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

原因:java.lang.ClassCastException:java.util.ArrayList无法强制转换为com.gridunity.core.bean.model.CommunicationBean,java,spring-jdbc,jdbctemplate,Java,Spring Jdbc,Jdbctemplate,我的刀是这样的: 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.springframe

我的刀是这样的:

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

}
}
我已经检查了数据库,只有一行发送了id。我尝试了.query和.queryForObject,但都抛出了相同的错误

如果我知道db上只有一行,即唯一约束,如何强制模板不返回和数组?

如果SELECT语句只返回一行id为的公平假设,请使用 而不是

您也完全不需要演员阵容:

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

返回getJdbcTemplate.queryForObjectsql,新BeanPropertyRowMapperCommunicationInstanceBean.class,id

你看过文件了吗返回值是一个列表。您是否阅读了我指出的问题,我还尝试了queryForObject,其中返回类型where根据我没有阅读的文档返回TqueryForObject不会导致有关强制转换ArrayList的异常,因此您错了。可能您正在读取先前尝试中的旧日志条目。再试一次。哦,对不起,你是对的,你错了。您是对的,将该调用更改为queryForObject不会解决问题,因为您对错误发生的位置的认识是错误的。错误表示无法转换为CommunicationBean,但该行代码正在转换为CommunicationInstanceBean。你的错误在别处,在你没有共享的代码中-很抱歉,我们应该强制您向我们显示完整的stacktrace,它会显示这个,因为它显示的是导致错误的语句的行号,而不是那个语句。@Andreas,您完全正确。我认为错误在其他地方,如果有一个完整的堆栈跟踪,答案就会明显得多。抱歉。不必要的强制转换。是否有一个一般的经验法则,何时以及何时不将类名添加到BeanPropertyRowMapper?@mmaceachran如果编译器可以推断,您可以忽略它。如果您使用一个好的IDE,您可以在不需要的地方发出警告消息。例如,在Eclipse中,它被称为不必要的类型参数或类似的东西。如果您没有使用一个好的IDE,您应该这样做,但在其他情况下尝试不使用IDE,并添加编译器抱怨的内容。在这种情况下,可以从实际参数CommunicationInstanceBean.class派生类型参数。
public CommunicationInstanceBean findOne(int id) {
    String sql = "SELECT * FROM CommunicationInstance WHERE id = ?";
    return getJdbcTemplate().queryForObject(
              sql,
              new BeanPropertyRowMapper<>(CommunicationInstanceBean.class),
              id);
}