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

标签 java spring

我尝试使用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 cannot be cast to com.cloudnexus.spring.model.Student

最佳答案

jdbcTemplate.query with RowMapper 返回一个列表,然后如果不为空则获取学生:

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

Returns: the result List, containing mapped objects

关于java - jdbcTemplate batchUpdate 抛出 java.lang.ClassCastException : java. util.ArrayList 无法转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53846990/

相关文章:

Java android 10 创建文件的问题

java - 是否真的可以使用原型(prototype)调用 HTTP PUT

java - Spring项目不自动创建数据库(MYSQL)

Spring Boot 无法从资源文件夹提供静态图像

java - mongo java 驱动程序 2.14.0。更改已弃用的代码

spring - 当我在 Spring Boot 应用程序中使用 CommonsMultipartResolver 时,MultipartFile 为 null

java - Spring + Maven + .properties 文件

java - Gradle - 运行 junit 测试找不到我的 xml 文件

java - 简单 Java 序列化的错误代码

java - Apache Commons Math 的标准偏差