从Hibernate 4升级到5遇QueryException问题求助
问题分析
你遇到的错误提示看似指向参数格式问题,但实际是查询结果集列数与DTO构造函数参数不匹配导致的:你的查询用select *返回了3个字段(对应表的config_for、config_value、config_description),但CustConfigDTO的构造函数仅接收2个参数,Hibernate在映射结果时内部解析异常,抛出了错误的提示信息。此外,你的DTO构造函数还存在语法错误(参数列表末尾多余的逗号)。
修复方案
以下两种方案任选其一即可:
方案1:调整查询语句匹配构造函数
修改查询语句,仅查询构造函数对应的2个字段,确保返回列数与构造参数数量一致:
public List<CustConfigDTO> getCustConfigDetails() throws DAOException { try { // 只查询构造函数需要的两个字段 String sectionQuery = "select config_for, config_value from cust_config"; Query<?> query = getSession().createNativeQuery(sectionQuery, CustConfigDTO.class); return (List<CustConfigDTO>) query.list(); } catch( Exception ex ) { LOGGER.error( ex ); throw new DAOException(); } }
同时修复DTO构造函数的语法错误,去掉参数列表末尾的多余逗号:
public CustConfigDTO(String config_for, String config_value) { this.config_for = config_for; this.config_value = config_value; }
方案2:完善DTO构造函数与字段映射
如果需要获取config_description字段,补充DTO的构造函数、getter和setter,并修正语法错误:
public class CustConfigDTO implements java.io.Serializable { private String config_for; private String config_value; private String config_description; // 补充第三个参数,修正语法错误 public CustConfigDTO(String config_for, String config_value, String config_description) { this.config_for = config_for; this.config_value = config_value; this.config_description = config_description; } // 可选:添加无参构造函数,部分Hibernate场景下需要 public CustConfigDTO() {} // 原有getter/setter public String getConfig_for() { return this.config_for; } public void setConfig_for(String config_for) { this.config_for = config_for; } public String getConfig_value() { return this.config_value; } public void setConfig_value(String config_value) { this.config_value = config_value; } // 添加config_description的getter/setter public String getConfig_description() { return config_description; } public void setConfig_description(String config_description) { this.config_description = config_description; } }
此时查询语句可保持select * from cust_config不变,返回的3个字段能与构造函数参数一一匹配。
内容的提问来源于stack exchange,提问作者Christopher Chua
相关产品推荐
相关产品推荐

