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

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


当前回答

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

其他回答

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

为了两全其美,HQL的表达性和简洁性以及Criteria的动态特性可以考虑使用Querydsl。

Querydsl支持JPA/Hibernate, JDO, SQL和Collections。

我是Querydsl的维护者,所以这个答案是有偏见的。

HQL和criteriaQuery在性能上是有区别的,每次你使用criteriaQuery发起查询时,它会为表名创建一个新的别名,这个别名不会反映在任何DB的最后一个查询缓存中。这会导致编译生成的SQL的开销,需要更多的时间来执行。

关于抓取策略[http://www.hibernate.org/315.html]

Criteria respects the laziness settings in your mappings and guarantees that what you want loaded is loaded. This means one Criteria query might result in several SQL immediate SELECT statements to fetch the subgraph with all non-lazy mapped associations and collections. If you want to change the "how" and even the "what", use setFetchMode() to enable or disable outer join fetching for a particular collection or association. Criteria queries also completely respect the fetching strategy (join vs select vs subselect). HQL respects the laziness settings in your mappings and guarantees that what you want loaded is loaded. This means one HQL query might result in several SQL immediate SELECT statements to fetch the subgraph with all non-lazy mapped associations and collections. If you want to change the "how" and even the "what", use LEFT JOIN FETCH to enable outer-join fetching for a particular collection or nullable many-to-one or one-to-one association, or JOIN FETCH to enable inner join fetching for a non-nullable many-to-one or one-to-one association. HQL queries do not respect any fetch="join" defined in the mapping document.

Criteria api提供了一个SQL和HQL都不提供的独特特性。ie。它允许对查询进行编译时检查。

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

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

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

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