`

hibernate原生sql封装,报错信息:could not find setter for rownum_

 
阅读更多
报错信息:could not find setter for rownum_

还原现场:在mysql环境下,以下代码,在mysql下运行正常,但是切换到oralce,报出找不到STUDENTNAME属性的错误。
List resultWithAliasedBean = s.createSQLQuery(
  "SELECT st.name as studentName, co.description as courseDescription " +
  "FROM Enrolment e " +
  "INNER JOIN Student st on e.studentId=st.studentId " +
  "INNER JOIN Course co on e.courseCode=co.courseCode")
  .setResultTransformer( Transformers.aliasToBean(StudentDTO.class))
  .list();


分析:原来是oracle自动将列映射的studentName转换为大写的STUDENTNAME,所以不能映射,报类找不到STUDENTNAME的set方法。
解决办法:添加addScalar方法,代码如下:

List resultWithAliasedBean = s.createSQLQuery(
  "SELECT st.name as studentName, co.description as courseDescription " +
  "FROM Enrolment e " +
  "INNER JOIN Student st on e.studentId=st.studentId " +
  "INNER JOIN Course co on e.courseCode=co.courseCode")
  .addScalar("studentName")
  .addScalar("courseDescription")
  .setResultTransformer( Transformers.aliasToBean(StudentDTO.class))
  .list();


Tip: the addScalar() calls were required on HSQLDB to make it match a property name since it returns column names in all uppercase (e.g. "STUDENTNAME"). This could also be solved with a custom transformer that search the property names instead of using exact match - maybe we should provide a fuzzyAliasToBean() method ;

还有一种方式解决,就是使用双引号将别名包裹起来,感觉不是很优雅。像这样
String sql = "select id as \"id\",iata as \"iata\",flight as \"flight\",dest as \"dest\",domint as \"domint\" " + 
            " ,sdt as \"sdt\",task_nature as \"taskNature\",est_date as \"estDate\",act_date as \"actDate\",remark as \"remark\" " + 
            " from FIDS_DEPF";



createSQLQuery  setFirstResult设置起始记录,setMaxResult设置结束记录 sql里有用分组函数,返回非持久化对象  当firstResult=0,正常,当firstResult>0时,报错。  大家是否遇到过?
public List findBySql(String sql, List params, int pageNo, int pageSize,
Class clazz) {
SQLQuery sqlQuery = getCurrentSession().createSQLQuery(sql);
if (params != null && !params.isEmpty()) {
for (int i = 0, size = params.size(); i < size; i++) {
sqlQuery.setParameter(i, params.get(i));
}
}
sqlQuery.setFirstResult((pageNo - 1) * pageSize);
sqlQuery.setMaxResults(pageSize);
sqlQuery.setResultTransformer(Transformers.aliasToBean(clazz));
return sqlQuery.list();
}

问题补充:报错信息:could not find setter for rownum_

用createSQLQuery的方式,查询的结果setResultTransformer()了一下。
并且设置了firstResult和MaxResult.

现象:
当firstResult为0的时候,一切正常,当firstResult不为0的时候报 “could not find setter for rownum_”的错误
如果不setResultTransformer,设置的firstResult和MaxResult不受影响。

主要是改sql
1、别名要大写
如:select day DAY,count(id) COUNT from t_name group by day
像楼下给的链接的解释,oracle自动将别名大写,但是如果自己设置了小写的,就会出现上面的问题。 为了避免addScalar多个,建议将别名直接大写。
2、当然你可以采用多个addScalar,这样只会,你就不能封装为通用的dao了。 

2
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics