繁体   English   中英

jdbcTemplate batchUpdate抛出java.lang.ClassCastException:无法强制转换java.util.ArrayList

[英]jdbcTemplate batchUpdate is throwing java.lang.ClassCastException: java.util.ArrayList cannot be cast

我尝试使用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

使用RowMapper jdbcTemplate.query返回一个List,然后如果不为空,则获取该学生:

List<Student> studentList = jdbcTemplate.query(...
if (!studentList.isEmpty()){ 
   Student student1 = studentList.get(0);

返回:结果列表,包含映射的对象

使用jdbcTemplate.queryForObject代替,它可以返回所需的对象。 您正在使用的当前方法返回的列表不是您所期望的(根据sql query它应该仅返回一条记录)。

这将解决您的问题:

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>());

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM