Example in HQL and Criteria
Criteria
Criteria AP
Here’s a case study to retrieve a list of StockDailyRecord, with optional search criteria – start date, end date and volume, order by date.
这是一个例子, 展示了如何检索查询一个StockDailyRecord的list. 例子中使用了可选的过滤criteria 项: start date, end date and volume, order by date.
1. HQL example
In HQL, you need to compare whether this is the first criteria to append the ‘where’ syntax, and format the date to a suitable format. It’s work, but the long codes are ugly, cumbersome and error-prone string concatenation may cause security concern like SQL injection.
在HQL中,你需要使用append将第一个查询过滤项前面加上where. 如果是date类型,需要将其进行格式转换.
HQL的写法可以实现需求,但是代码冗长且丑陋、笨重,字符串连接的这种方式容易出错,甚至还有SQL注入的风险。
public static List getStockDailtRecord(Date startDate,Date endDate,
Long volume,Session session){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");boolean isFirst = true;
StringBuilder query = new StringBuilder("from StockDailyRecord ");if(startDate!=null){if(isFirst){query.append(" where date >= '" + sdf.format(startDate) + "'");}else{
query.append(" and date >= '" + sdf.format(startDate) + "'");}
isFirst = false;}if(endDate!=null){if(isFirst){
query.append(" where date <= '" + sdf.format(endDate) + "'");}else{
query.append(" and date <= '" + sdf.format(endDate) + "'");}
isFirst = false;}if(volume!=null){if(isFirst){
query.append(" where volume >= " + volume);}else{
query.append(" and volume >= " + volume);}
isFirst = false;}
query.append(" order by date");
Query result = session.createQuery(query.toString());return result.list();}
2. Criteria example
In Criteria, you do not need to compare whether this is the first criteria to append the ‘where’ syntax, nor format the date. The line of code is reduce and everything is handled in a more elegant and object oriented way.
在Criteria标准查询中, 你不需要判断查询项是否是第一个,而去添加where,也不用对date进行格式化。
不仅减少了代码量,而且也更加优化且面向对象。
public static List getStockDailyRecordCriteria(Date startDate,Date endDate,
Long volume,Session session){
Criteria criteria = session.createCriteria(StockDailyRecord.class);if(startDate!=null){criteria.add(Expression.ge("date",startDate));}if(endDate!=null){
criteria.add(Expression.le("date",endDate));}if(volume!=null){
criteria.add(Expression.ge("volume",volume));}
criteria.addOrder(Order.asc("date"));return criteria.list();}
Criteria API
Let go through some popular Criteria API functions.
让我们看看常用的Criteria API方法.
1. Criteria basic query
Create a criteria object and retrieve all the ‘StockDailyRecord’ records from database.
创建一个查询对象,将StockDailyRecord的所有数据从db中查询出来.
Criteria criteria = session.createCriteria(StockDailyRecord.class);
2. Criteria ordering query
The result is sort by ‘date’ in ascending order.
结果以date进行asc排序.
Criteria criteria = session.createCriteria(StockDailyRecord.class).addOrder( Order.asc("date") );
The result is sort by ‘date’ in descending order.
结果集以date倒叙排序
Criteria criteria = session.createCriteria(StockDailyRecord.class).addOrder( Order.desc("date") );
3. Criteria restrictions query 使用条件过滤
The Restrictions class provide many methods to do the comparison operation.
Restrictions.eq
Make sure the valume is equal to 10000.
Restrictions(限制条件) 类提供了很多方法进行比较匹配操作. 比如estrictions.eq 相当比较.
例子: 获取volume=10000的数据
Criteria criteria = session.createCriteria(StockDailyRecord.class).add(Restrictions.eq("volume", 10000));
Restrictions.lt, le, gt, ge
Make sure the volume is less than 10000. 小于
Criteria criteria = session.createCriteria(StockDailyRecord.class).add(Restrictions.lt("volume", 10000));
Make sure the volume is less than or equal to 10000. 小等于
Criteria criteria = session.createCriteria(StockDailyRecord.class).add(Restrictions.le("volume", 10000));
Make sure the volume is great than 10000.大于
Criteria criteria = session.createCriteria(StockDailyRecord.class).add(Restrictions.gt("volume", 10000));
Make sure the volume is great than or equal to 10000.大等于
Criteria criteria = session.createCriteria(StockDailyRecord.class).add(Restrictions.ge("volume", 10000));
Restrictions.like
Make sure the stock name is start with ‘MKYONG’ and follow by any characters.
Criteria criteria = session.createCriteria(StockDailyRecord.class).add(Restrictions.like("stockName", "MKYONG%"));
Restrictions.between
Make sure the date is between start date and end date.
Criteria criteria = session.createCriteria(StockDailyRecord.class).add(Restrictions.between("date", startDate, endDate));
Restrictions.isNull, isNotNull
Make sure the volume is null.
Criteria criteria = session.createCriteria(StockDailyRecord.class).add(Restrictions.isNull("volume"));
Make sure the volume is not null.
Criteria criteria = session.createCriteria(StockDailyRecord.class).add(Restrictions.isNotNull("volume"));
Many other Restrictions functions can find here.
https://www.hibernate.org/hib_docs/v3/api/org/hibernate/criterion/Restrictions.html
3. Criteria paging the result
Criteria provide few functions to make pagination extremely easy. Starting from the 20th record, and retrieve the next 10 records from database.
Criteria criteria = session.createCriteria(StockDailyRecord.class);
criteria.setMaxResults(10);
criteria.setFirstResult(20);
Why not Criteria !?
The Criteria API do bring some disadvantages.
Criteria API也带来一些问题.
1 性能问题: 没法控制Hibernate生成的SQL. 如果SQL的性能比较慢, 将难以在SQL语句层面进行调试优化.
2 维护调试问题: 所有的SQL通过java代码进行拼接.如果查询不理想, 调试可能需要更多时间. 在Hibernate mapping文件中的预定义查询更容易维护.
总结: 没有完美的解决方案, 合适最重要.
1. Performance issue
You have no way to control the SQL query generated by Hibernate, if the generated query is slow, you are very hard to tune the query, and your database administrator may not like it.
1. Maintainece issue
All the SQL queries are scattered through the Java code, when a query went wrong, you may spend time to find the problem query in your application. On the others hand, named queries stored in the Hibernate mapping files are much more easier to maintain.
Conclusion
Nothing is perfect, do consider your project needs and use it wisely.
本文对比了Hibernate Query Language (HQL) 和 Criteria API 的使用场景和优劣,并通过实例介绍了Criteria API的基本用法,包括查询、排序、条件过滤及分页等功能。
498

被折叠的 条评论
为什么被折叠?



