原因:java.lang.ClassCastException:java.util.ArrayList 无法转换为 com.gridunity.core.bean.model.CommunicationBean

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

我的道是这样的:

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(),但都抛出相同的错误。

如果我 "know" 只有一行(即数据库上的唯一约束),我如何强制模板不 return 和数组?

如果 SELECT 语句只会 return 一行(与 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);
}

return getJdbcTemplate().queryForObject(sql, new BeanPropertyRowMapper<>(CommunicationInstanceBean.class), id);