使用Criteria或HQL的优点和缺点是什么?Criteria API是一种在Hibernate中表达查询的面向对象的好方法,但有时Criteria queries比HQL更难理解/构建。
什么时候使用标准,什么时候使用HQL?在哪些用例中您更喜欢什么?还是说这只是个人口味的问题?
使用Criteria或HQL的优点和缺点是什么?Criteria API是一种在Hibernate中表达查询的面向对象的好方法,但有时Criteria queries比HQL更难理解/构建。
什么时候使用标准,什么时候使用HQL?在哪些用例中您更喜欢什么?还是说这只是个人口味的问题?
当前回答
Criteria是一个面向对象的API,而HQL意味着字符串连接。这意味着面向对象的所有好处都适用:
All else being equal, the OO version is somewhat less prone to error. Any old string could get appended into the HQL query, whereas only valid Criteria objects can make it into a Criteria tree. Effectively, the Criteria classes are more constrained. With auto-complete, the OO is more discoverable (and thus easier to use, for me at least). You don't necessarily need to remember which parts of the query go where; the IDE can help you You also don't need to remember the particulars of the syntax (like which symbols go where). All you need to know is how to call methods and create objects.
由于HQL非常像SQL(大多数开发人员已经非常了解SQL),因此这些“不必记住”参数就没有那么重要了。如果HQL有更大的不同,那么这就更重要了。
其他回答
对于动态查询,我更喜欢使用条件查询。例如,根据某些参数,动态地添加一些排序或保留一些部分(例如限制)要容易得多。
另一方面,我使用HQL进行静态和复杂的查询,因为它更容易理解/阅读HQL。此外,我认为HQL更强大一些,例如对于不同的连接类型。
Criteria是一个面向对象的API,而HQL意味着字符串连接。这意味着面向对象的所有好处都适用:
All else being equal, the OO version is somewhat less prone to error. Any old string could get appended into the HQL query, whereas only valid Criteria objects can make it into a Criteria tree. Effectively, the Criteria classes are more constrained. With auto-complete, the OO is more discoverable (and thus easier to use, for me at least). You don't necessarily need to remember which parts of the query go where; the IDE can help you You also don't need to remember the particulars of the syntax (like which symbols go where). All you need to know is how to call methods and create objects.
由于HQL非常像SQL(大多数开发人员已经非常了解SQL),因此这些“不必记住”参数就没有那么重要了。如果HQL有更大的不同,那么这就更重要了。
HQL is to perform both select and non-select operations on the data, but Criteria is only for selecting the data, we cannot perform non-select operations using criteria HQL is suitable for executing Static Queries, where as Criteria is suitable for executing Dynamic Queries HQL doesn’t support pagination concept, but we can achieve pagination with Criteria Criteria used to take more time to execute then HQL With Criteria we are safe with SQL Injection because of its dynamic query generation but in HQL as your queries are either fixed or parametrized, there is no safe from SQL Injection.
源
HQL更容易阅读,更容易使用Eclipse Hibernate插件等工具进行调试,也更容易记录日志。条件查询更适合构建动态查询,其中许多行为都是在运行时确定的。如果你不知道SQL,我可以理解使用Criteria查询,但总的来说,如果我知道我想要什么,我更喜欢HQL。
为了两全其美,HQL的表达性和简洁性以及Criteria的动态特性可以考虑使用Querydsl。
Querydsl支持JPA/Hibernate, JDO, SQL和Collections。
我是Querydsl的维护者,所以这个答案是有偏见的。