使用Criteria或HQL的优点和缺点是什么?Criteria API是一种在Hibernate中表达查询的面向对象的好方法,但有时Criteria queries比HQL更难理解/构建。

什么时候使用标准,什么时候使用HQL?在哪些用例中您更喜欢什么?还是说这只是个人口味的问题?


当前回答

这里的大多数答案都是误导性的,并提到标准查询比HQL慢,但事实并非如此。

如果你深入研究并执行一些测试,你会发现标准查询比常规HQL执行得更好。

同样,通过Criteria Query,你可以得到HQL所没有的面向对象的控制。

更多信息请阅读这里的答案。

其他回答

Criteria Api是Hibernate的一个很好的概念。根据我的观点,这些是我们可以区分HQL和Criteria Api的少数点

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 than 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

我不想在这里白费口舌,但有一点很重要,那就是Criteria查询现在已被弃用。使用HQL。

这个帖子很老了。大多数答案谈论的是Hibernate标准,而不是JPA标准。JPA 2.1增加了CriteriaDelete/CriteriaUpdate和EntityGraph来控制获取什么。Criteria API更好,因为Java是面向对象的。这就是创建JPA的原因。当JPQL被编译时,它将被转换为AST树(OO模型),然后再转换为SQL。

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可能会导致SQL注入等安全问题。