hibernate的常见错误

1.查询记录总数

错误:HQL:select count(1) from ....

正确:HQL:select count(*) from ....

2.Criteria的同一个条件不能复用,

例如

错误:

Criteria criteria = session.createCriteria(A.class);
criteria.add(Restrictions.eq("field1","xx");
criteria.list();


criteria.add(Restrictions.eq("field1","yy");//出错
criteria.list();

正确:

Criteria criteria = session.createCriteria(A.class);
criteria.add(Restrictions.eq("field1","xx");
criteria.list();


criteria=session.createCriteria(A.class);
criteria.add(Restrictions.eq("field1","yy");
criteria.list();

3.criteria的rowcount返回的是Integer

错误:

Criteria criteria = XXDAO.getCriteria(XX.class);
criteria.setProjection(Projections.rowCount());
int count = ((Long)procriteria.uniqueResult()).intValue();//错误
 

正确:

Criteria criteria = XXDAO.getCriteria(XX.class);
criteria.setProjection(Projections.rowCount());
int count = ((Integer)procriteria.uniqueResult()).intValue();//正确
 

4.HQL对聚合函数count,sum返回的类型却是Long,这点要注意和3区分开。

相关推荐