Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate: how to make EXISTS query? (not subquery)

Tags:

hibernate

hql

For example:

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

How to make such query using Hibernate?

like image 462
Ron Avatar asked Apr 13 '11 21:04

Ron


2 Answers

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)
like image 82
Sergey Ponomarev Avatar answered Sep 20 '22 07:09

Sergey Ponomarev


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
like image 37
user and Avatar answered Sep 18 '22 07:09

user and