Hibernate:如何进行 EXISTS 查询? (不是子查询)

发布于 2024-11-01 11:25:34 字数 111 浏览 1 评论 0原文

例如:

EXISTS ( SELECT * FROM [table] WHERE ... )

如何使用 Hibernate 进行这样的查询?

For example:

EXISTS ( SELECT * FROM [table] WHERE ... )

How to make such query using Hibernate?

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

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

发布评论

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

评论(8

甜尕妞 2024-11-08 11:25:34

HQL 不允许使用 exists 语句。
UPD 从 Hibernate 5 开始 它支持将其作为 WHERE 中的谓词

您可以使用多种方法:

  1. 对于 Hibrnate 5:您可以对同一个表使用子查询 boolean contains = session.createQuery("select 1 from PersistentEntity where isn't (从 PersistentEntity p 中选择 1,其中 ...)").uniqueResult() != null;。感谢以下作者。
  2. <代码>计数(*)> 0 但这对性能不利 当您可以使用 EXISTS() 时,请避免在 SQL 中使用 COUNT()
  3. 使用 boolean contains = session.createQuery("from PersistentEntity where ...").setMaxResults( 1).uniqueResult() != null; 但这将强制 Hibernate 加载所有字段并对对象进行水合作用,即使您只需要检查 null 也是如此。
  4. 使用 session.get(PersistentEntity.class, id) != null 如果您启用二级缓存,这会工作得更快,但如果您需要更多的条件而不仅仅是 id<,这将是一个问题/代码>。
  5. 您可以使用以下方法:getSession().createQuery("select 1 from PersistentEntity where ...").uniqueResult() != null)

HQL doesn't allow to use exists statement.
UPD Starting from Hibernate 5 it supports it as a predicate in WHERE

You can use several approaches:

  1. For Hibrnate 5: you can use subquery with the same table boolean exists = session.createQuery("select 1 from PersistentEntity where exists (select 1 from PersistentEntity p where ...)").uniqueResult() != null;. Thank to author bellow.
  2. count(*) > 0 but this is bad for performance Avoid Using COUNT() in SQL When You Could Use EXISTS()
  3. Use boolean exists = session.createQuery("from PersistentEntity where ...").setMaxResults(1).uniqueResult() != null; but this will force Hibernate to load all fields and make hydration to object even if you need just to check for a null.
  4. Use session.get(PersistentEntity.class, id) != null and this will work faster if you enabled second level cache but it will be a problem if you need more criteries than just id.
  5. You can use the following method: getSession().createQuery("select 1 from PersistentEntity where ...").uniqueResult() != null)
抚笙 2024-11-08 11:25:34

如果您的目标是检查某些空集,您可以使用简单的 HQL 查询:

boolean exists = (Long) session.createQuery("select count(*) from PersistentEntity where ...").uniqueResult() > 0

If your goal is inspect some set on emptiness, you may use simple HQL query:

boolean exists = (Long) session.createQuery("select count(*) from PersistentEntity where ...").uniqueResult() > 0
海的爱人是光 2024-11-08 11:25:34

如果我们使用WHERE子句,数据库可能必须扫描整个表来统计符合我们条件的记录,但我们可以限制只搜索一条记录,这足以说明空了。

如果没有任何搜索过滤器,则先前的查询将被接受,因为数据库将使用索引进行一些优化。

所以我想与前一个查询相比,以下查询会提高一些性能:

boolean exists = session.createQuery("from PersistentEntity where ...").setMaxResults(1).uniqueResult() != null;

If we are using WHERE clause, the database may have to scan the whole table to count records that matches our criteria, but we can limit to search only for one record, it is enough to say about emptiness.

If there wasn't any search filters the previous query would be admissible as the database would do some optimisation with the use of an index.

so I suppose following query will increase some perfomance comparing to previous one:

boolean exists = session.createQuery("from PersistentEntity where ...").setMaxResults(1).uniqueResult() != null;
慈悲佛祖 2024-11-08 11:25:34

有一些关于使用 EXISTS 的很好的评论,但没有示例。这是我在 Hibernate 5.2 中的解决方案:

boolean exists = session.createQuery( 
                    "SELECT 1 FROM PersistentEntity WHERE EXISTS (SELECT 1 FROM PersistentEntity p WHERE ...)")
            .uniqueResult() != null;

There's some nice comments about using EXISTS but no examples. Here is my solution in Hibernate 5.2:

boolean exists = session.createQuery( 
                    "SELECT 1 FROM PersistentEntity WHERE EXISTS (SELECT 1 FROM PersistentEntity p WHERE ...)")
            .uniqueResult() != null;
把梦留给海 2024-11-08 11:25:34

另外,如果您使用 JpaRepository,您可以通过 ORM 轻松检查实体是否存在。这是一个 Kotlin 示例:

interface UserRepository : JpaRepository<User, Long> {
    fun existsByUsername(username: String): Boolean
}

Also, if you use JpaRepository, you can easily check entity existence via ORM. Here is a Kotlin example:

interface UserRepository : JpaRepository<User, Long> {
    fun existsByUsername(username: String): Boolean
}
魂ガ小子 2024-11-08 11:25:34

如果您使用JpaRepository,如果存在标准很简单,例如:
,那么这可能会很简单:

Boolean existsByName(String name);

如果不是,则此解决方案可能就是您要寻找的解决方案。
编写一个如下所示的查询:

SELECT CASE WHEN count(attr) > 0 THEN TRUE ELSE FALSE
FROM entity
WHERE <condition>

示例:

SELECT CASE count(pr_id) > 0 THEN TRUE ELSE FALSE
FROM product
WHERE pr_name LIKE 'a__%'

测试您的查询,然后将其添加到您的存储库中

@Repository
public interface FooRepository extends JpaRepository<FooEntity,UUID>{

    @Query(value = "<tested_query_here>", nativeQuery = true)
    Boolean existsByConditionYouWrote(<args>);

}

If you use JpaRepository, this could be simple if the existence criteria is simple like:

Boolean existsByName(String name);

If not, this solution may be the one you look for.
Write a query that looks like:

SELECT CASE WHEN count(attr) > 0 THEN TRUE ELSE FALSE
FROM entity
WHERE <condition>

Example:

SELECT CASE count(pr_id) > 0 THEN TRUE ELSE FALSE
FROM product
WHERE pr_name LIKE 'a__%'

test your query, then add it into your repo

@Repository
public interface FooRepository extends JpaRepository<FooEntity,UUID>{

    @Query(value = "<tested_query_here>", nativeQuery = true)
    Boolean existsByConditionYouWrote(<args>);

}
疧_╮線 2024-11-08 11:25:34

我使用了以下内容:SELECT COUNT(e) FROM Entity e。在 Spring Data JPA 中工作得非常好。

I used the following: SELECT COUNT(e) FROM Entity e. Worked perfectly fine in Spring Data JPA.

勿忘初心 2024-11-08 11:25:34

尝试:

"select count(e) > 0 from Entity e where..."

与 Spring Data 配合良好。

Try:

"select count(e) > 0 from Entity e where..."

Works fine with Spring Data.

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