例如:
EXISTS ( SELECT * FROM [table] WHERE ... )
如何使用 Hibernate 进行这样的查询?
HQL不允许使用exists
陈述。UPD从 Hibernate 5 开始它支持将其作为 WHERE 中的谓词 https://docs.jboss.org/hibernate/orm/5.1/userguide/html_single/Hibernate_User_Guide.html#hql-exists-predicate
您可以使用多种方法:
- 对于 Hibernate 5:您可以对同一个表使用子查询
boolean exists = session.createQuery("select 1 from PersistentEntity where exists (select 1 from PersistentEntity p where ...)").uniqueResult() != null;
。感谢以下作者。
-
count(*) > 0
但这对性能不利当可以使用 EXISTS() 时,避免在 SQL 中使用 COUNT() https://blog.jooq.org/2016/09/14/avoid-using-count-in-sql-when-you-could-use-exists/
- Use
boolean exists = session.createQuery("from PersistentEntity where ...").setMaxResults(1).uniqueResult() != null;
但这将迫使 Hibernate 加载所有字段并使水合作用为对象,即使您只需要检查 null 也是如此。
- Use
session.get(PersistentEntity.class, id) != null
如果您启用二级缓存,这会工作得更快,但如果您需要更多标准,这将是一个问题id
.
- 您可以使用以下方法:
getSession().createQuery("select 1 from PersistentEntity where ...").uniqueResult() != null)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)