我尝试使用jdbcTemplate.batchUpdate
将多个数据添加到关系表中
我尝试从学生表中选择maxid
,并在插入查询中使用它作为id。
这是我的代码:
List<Relatives> relatives=student.getRelatives();
String sql3="Select Id,Name from Student where Id=(select Max(Id) from student)";
final Student student1= (Student) jdbcTemplate.query(sql3, new UserMapper5());
String sql4 = " INSERT INTO Relatives (StudentId,RelativeId,YearId,ClassId,SectionId,RelationshipId,IsDeleted,CreatedBy,CreatedDate) "+
" Values(?,?,?,?,?,?,?,?,GETDATE())";
int[][] updateCounts = jdbcTemplate.batchUpdate(sql4, relatives, relatives.size(),
new ParameterizedPreparedStatementSetter<Relatives>() {
public void setValues(PreparedStatement ps, Relatives relative) throws SQLException {
ps.setInt(1, student1.getId());
ps.setString(2, relative.getStudent().getName());
ps.setInt(3, relative.getStudent().getYear().getId());
ps.setInt(4, relative.getStudent().getClasss().getId());
ps.setInt(5, relative.getStudent().getSection().getId());
ps.setInt(6, relative.getRelationship().getId());
ps.setInt(7, 0);
ps.setInt(8,123);
}
}
);
当我试图将多个数据插入到关系表中时,我得到了以下错误:
java.lang.ClassCastException:不能将java.util.ArrayList强制转换为com.cloudnexus.spring.model.Student
发布于 2018-12-19 17:45:12
这将解决您的问题:
final Student student1= (Student) jdbcTemplate.queryForObject(sql3, new UserMapper5());
此外,您还可以将UserMapper5
设置为泛型,从而避免强制转换:
public class UserMapper5<T> implements RowMapper {
public T mapRow(ResultSet rs, int rowNum) throws SQLException {
/// ...
}
}
然后:
final Student student1= jdbcTemplate.queryForObject(sql3, new UserMapper5<Student>());
发布于 2018-12-19 16:16:42
带有RowMapper
的jdbcTemplate.query将返回一个列表,如果不为空,则获取学生:
List<Student> studentList = jdbcTemplate.query(...
if (!studentList.isEmpty()){
Student student1 = studentList.get(0);
返回:结果列表,包含映射对象
发布于 2018-12-19 17:04:08
改为使用jdbcTemplate.queryForObject
,它可以返回您所期望的对象。您正在使用的当前方法返回列表不是您所期望的(根据sql query
,它应该只返回一条记录)。
https://stackoverflow.com/questions/53846990
复制相似问题