首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >jdbcTemplate batchUpdate正在抛出java.lang.ClassCastException:无法强制转换java.util.ArrayList

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

Stack Overflow用户
提问于 2018-12-19 16:10:27
回答 3查看 160关注 0票数 2

我尝试使用jdbcTemplate.batchUpdate将多个数据添加到关系表中

我尝试从学生表中选择maxid,并在插入查询中使用它作为id。

这是我的代码:

代码语言:javascript
复制
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

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2018-12-19 17:45:12

这将解决您的问题:

代码语言:javascript
复制
final Student student1= (Student) jdbcTemplate.queryForObject(sql3, new UserMapper5());

此外,您还可以将UserMapper5设置为泛型,从而避免强制转换:

代码语言:javascript
复制
public class UserMapper5<T> implements RowMapper {

    public T mapRow(ResultSet rs, int rowNum) throws SQLException {
        /// ...
    }
}

然后:

代码语言:javascript
复制
final Student student1= jdbcTemplate.queryForObject(sql3, new UserMapper5<Student>());
票数 0
EN

Stack Overflow用户

发布于 2018-12-19 16:16:42

带有RowMapperjdbcTemplate.query将返回一个列表,如果不为空,则获取学生:

代码语言:javascript
复制
List<Student> studentList = jdbcTemplate.query(...
if (!studentList.isEmpty()){ 
   Student student1 = studentList.get(0);

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

票数 2
EN

Stack Overflow用户

发布于 2018-12-19 17:04:08

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53846990

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档