您的位置:首页 > 产品设计 > UI/UE

Hibernate学习之createSQLQuery与createQuery的区别及使用

2013-09-03 19:30 519 查看
hibernate中createQuery与createSQLQuery:前者用的hql语句进行查询,后者可以用sql语句查询,前者以hibernate生成的Bean为对象装入list返回,后者则是以对象数组进行存储。

在有时查询部分字段,或实现一些统计查询时很方便。如要统计一个表中各个专业的状态:

public List<Object[]> statisticTitileNum(String instituteNumber, String yearTime) {

int[] ns;
List<Object[]> list = HibernateUtil
.getSession()
.createSQLQuery(
"select count(id),sum(status>1),sum(status=4) "
+",major,instituteNumber from t_liti where instituteNumber=:instituteNumber and yearTime=:yearTime group by major")
.setString("instituteNumber", instituteNumber)
.setString("yearTime", yearTime).list();
return list;
}

如果使用createSQLQuery有时候也想以hibernate生成的Bean为对象装入list返回,就不是很方便,不过createSQLQuery有这样一个方法可以直接转换对象

Query query = session.createSQLQuery(sql).addEntity(XXXXXXX.class);

XXXXXXX 代表以hibernate生成的Bean的对象,也就是数据表映射出的Bean。

呵呵以后多注意,还是时不时的要看看hibernate各个对象方法的使用。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: