Hibernate Criteria examples by mkyong
2015-10-13 14:42
351 查看
http://www.mkyong.com/hibernate/hibernate-criteria-examples/
Hibernate Criteria 标准查询 API 是可用来替代HQL的, 更高一级面向对象的一种查询.
如果应用中有很多灵活可配置的查询需要, Criteria API 是一个好的选择.
HQL和Criteria的例子
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.
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注入的风险。
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进行格式化。
不仅减少了代码量,而且也更加优化且面向对象。
Let go through some popular Criteria API functions.
让我们看看常用的Criteria API方法.
基本查询
Create a criteria object and retrieve all the ‘StockDailyRecord’ records from database.
创建一个查询对象,将StockDailyRecord的所有数据从db中查询出来.
The result is sort by ‘date’ in ascending order.
结果以date进行asc排序.
The result is sort by ‘date’ in descending order.
结果集以date倒叙排序
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的数据
Restrictions.lt, le, gt, ge
Make sure the volume is less than 10000. 小于
Make sure the volume is less than or equal to 10000. 小等于
Make sure the volume is great than 10000.大于
Make sure the volume is great than or equal to 10000.大等于
Restrictions.like
Make sure the stock name is start with ‘MKYONG’ and follow by any characters.
Restrictions.between
Make sure the date is between start date and end date.
Restrictions.isNull, isNotNull
Make sure the volume is null.
Make sure the volume is not null.
Many other Restrictions functions can find here.
https://www.hibernate.org/hib_docs/v3/api/org/hibernate/criterion/Restrictions.html
分页
Criteria provide few functions to make pagination extremely easy. Starting from the 20th record, and retrieve the next 10 records from database.
The Criteria API do bring some disadvantages.
Criteria API也带来一些问题.
1 性能问题: 没法控制Hibernate生成的SQL. 如果SQL的性能比较慢, 将难以在SQL语句层面进行调试优化.
2 维护调试问题: 所有的SQL通过java代码进行拼接.如果查询不理想, 调试可能需要更多时间. 在Hibernate mapping文件中的预定义查询更容易维护.
总结: 没有完美的解决方案, 合适最重要.
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.
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.
Nothing is perfect, do consider your project needs and use it wisely.
Criteria exampBy mkyong | February 20, 201
Hibernate Criteria API is a more object oriented and elegant alternative to Hibernate Query Language (HQL). It’s always a good solution to an application which has many optional search criteria.
Hibernate Criteria 标准查询 API 是可用来替代HQL的, 更高一级面向对象的一种查询.如果应用中有很多灵活可配置的查询需要, Criteria API 是一个好的选择.
Example in HQL and Criteria
HQL和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 anderror-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 elegantand 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 inthe Hibernate mapping files are much more easier to maintain.
Conclusion
Nothing is perfect, do consider your project needs and use it wisely.
相关文章推荐
- cookie,session与浏览器关系,application
- Ubuntu登录界面输入正确密码依然无法登陆
- 获取字体的长度(宽度)和高度,字体尺寸决定控件尺寸
- zzuli OJ 1111: 多个整数的逆序输出(函数专题)
- 如何在OS X Yosemite 配置php web站点及虚拟主机?
- Tiptop二二次开发系列
- linux下JsonServer启动
- ASP.NET MVC 分部页 PartialViewResult
- 马良建模学习笔记——软包制作十四
- Win10系统BMR模式怎么无损转换为UEFI+GPT【图文教程】
- poj 2019 Cornfields(二维RMQ)
- Spring+SpringMVC+Mybatis整合系列(三)SSM框架整合
- Handler引起的内存泄露
- 让我们来FirePHP
- 点击事件
- IOPS 使用FIO工具测试
- 遍历Map的四种方法
- eclipse中注释出现乱码的情况
- JPA和hibernate的缓存关系
- QCustomPlot demo version1.3.0