引起:java.lang.ClassCastException:java.util.ArrayList无法强制转换为com.gridunity.core.bean.model.CommunicationBean

时间:2018-04-20 20:20:41

标签: java spring-jdbc jdbctemplate

我的Dao看起来像这样:

package com.gridunity.core.persistence.dao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;

import com.xxxx.core.bean.model.CommunicationInstanceBean;

@Repository
@Component
public class CommunicationInstanceDao extends JdbcDaoSupport {

@Autowired
public void setJT(JdbcTemplate jdbcTemplate) {
     setJdbcTemplate(jdbcTemplate);
}

public CommunicationInstanceBean findOne(int id) {
    String sql = "SELECT * FROM CommunicationInstance WHERE id = ?";
    return (CommunicationInstanceBean)getJdbcTemplate().query(sql, new BeanPropertyRowMapper<CommunicationInstanceBean>(CommunicationInstanceBean.class), id);

}
}

我一直收到这个错误:

 Caused by: java.lang.ClassCastException: java.util.ArrayList cannot be cast to com.gridunity.core.bean.model.CommunicationBean

我已经检查了数据库,并且只有一行发送了ID。我已经尝试了.query().queryForObject(),但两者都抛出相同的错误。

如果我&#34;知道&#34;只有一行(即db上的唯一约束)如何强制模板不返回和数组?

2 个答案:

答案 0 :(得分:1)

如果SELECT语句只返回一行(id = ?的公平假设),请使用
<T> T queryForObject(String sql, RowMapper<T> rowMapper, Object... args)
而不是 <T> List<T> query(String sql, RowMapper<T> rowMapper, Object... args)

你根本不需要演员:

public CommunicationInstanceBean findOne(int id) {
    String sql = "SELECT * FROM CommunicationInstance WHERE id = ?";
    return getJdbcTemplate().queryForObject(
              sql,
              new BeanPropertyRowMapper<>(CommunicationInstanceBean.class),
              id);
}

答案 1 :(得分:0)

return getJdbcTemplate()。queryForObject(sql,new BeanPropertyRowMapper&lt;&gt;(CommunicationInstanceBean.class),id);