使用什么:JPQL 还是 Criteria API?

发布于 2024-09-25 17:30:58 字数 1431 浏览 5 评论 0原文

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

遮云壑 2024-10-02 17:30:58

我很确定这已经在此处进行了介绍,但我找不到现有的问题。所以,这是我对这个问题的看法:

  • 我发现 JPQL 查询更容易编写/阅读。
  • 我发现 Criteria API 非常适合构建动态查询。

这基本上就是您在 Hibernate:Criteria 与 HQL 中找到的内容。

但是 JPA 2.0 Criteria API 和 Hibernate 的 Criteria API 之间有一个值得一提的主要区别:JPA 2.0 Criteria API 是一个类型安全的 API,因此提供编译时检查、代码完成和更好的重构支持等
然而,认为 JPQL 的好处并没有超过其易用性。

总而言之,除了动态查询(例如多条件搜索功能)之外,我更喜欢 JPQL。

相关问题

更多资源

I'm pretty sure this has already been covered here on SO but I couldn't find the existing question. So, here is my point of view on the question:

  • I find JPQL queries easier to write/read.
  • I find the Criteria API nice for building dynamic queries.

Which is basically what you'll find in Hibernate: Criteria vs. HQL.

But there is one major difference between the JPA 2.0 Criteria API and the Hibernate's Criteria API that is worth mentioning: the JPA 2.0 Criteria API is a typesafe API and thus gives compile time checks, code completion, better refactoring support, etc.
However, I don't find that the benefits outweighs the ease of use of JPQL.

To sum up, I would favor JPQL, except for dynamic queries (e.g. for multi criteria search features).

Related questions

More resources

能否归途做我良人 2024-10-02 17:30:58

我之前回答过类似的问题,为了社区的利益,我将在这里重新发布我的答案。我假设您正在使用应用程序服务器,而不是我下面的答案。

Criteria API 的存在是为了允许以类型安全的方式构造动态 SQL 查询,从而防止 SQL 注入。否则,您会将 SQL 字符串连接在一起,这既容易出错,又存在安全风险:即 SQL 注入。这是您唯一想要使用 Criteria API 的时候。

如果查询保持基本相同,但只需要接受不同的参数,您应该使用带注释的@NamedQueries,它更简单,预编译,可以缓存在二级缓存中,并可能在服务器启动期间进行验证。

这基本上是关于条件查询与 @NamedQueries 的经验法则。根据我的经验,您很少需要 Criteria API,但在极少数需要它的时候它的存在是件好事。

希望这有帮助。

I answered a similar question previously and I will re-post my answer here for the benefit of the community. I'm going to assume you are using an Application Server vis-a-vis my answer below.

The Criteria API exists to allow for the construction of dynamic SQL queries in a type-safe manner that prevents SQL injection. Otherwise you would be concatenating SQL strings together which is both error prone and a security risk: i.e. SQL Injection. That would be the only time you would want to use the Criteria API.

If the query remains basically the same but need only accept different parameters you should use annotated @NamedQueries which are simpler, precompiled, can be cached within the secondary cache and possibly validated during server startup.

That's basically the the rule of thumb concerning Criteria Queries versus @NamedQueries. In my experience rarely do you require the Criteria API but it is good that it exists for those rare times it is required.

Hope this helps.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文