30

Suppose, objects of type A are stored in DB. Here's the way I load specific one from DB using hibernate:

org.hibernate.Session session = ...;
long id = 1;
A obj = session.load(A.class, id);

If object with id=1 doesn't exist I will get ObjectNotFoundException. But is there a way to check if such object exists without having to catch the exception? What I would like to have is smth like:

org.hibernate.Session session = ...;
long id = 1;
boolean exists = session.exists(A.class, id);
if(exists){
 // do smth.....
}

Couldn't find it hibernate docs...

4 Answers 4

49

you can use HQL for checking object existence:

public Boolean exists (DTOAny instance) {
    Query query = getSession().             
    createQuery("select 1 from DTOAny t where t.key = :key");
        query.setString("key", instance.getKey() );
    return (query.uniqueResult() != null);
}

Hibernates uniqueResult() method returns null if no data was found. By using HQL you can create more complex query criterium.

Sign up to request clarification or add additional context in comments.

Comments

27

You can use session.get:

public Object get(Class clazz,
                  Serializable id)
           throws HibernateException

It will return null if the object does not exist in the database. You can find more information in Hibernate API Documentation.

5 Comments

Hmm... I still get the same thing (ObjectNotFoundException) no matter whether I use "load" or "get".
Maybe you are getting an exception from a previous session.load()? From the docs for ObjectNotFoundException: "This exception might not be thrown when load() is called because load() returns a proxy if possible. Use Session.get() to test if a row exists in the db."
get works but it is a slow approach since Hibernate will have to fetch all the columns and affect them to the new object and store it in the session. If you don't want to waste resources uselessly, consider the HQL approach instead.
you should not use this method! Because it load all entity with all fields, instead you can check only id.
for new users, AFAIK you can use jparepository.exists(id) in hibernate. check hibenate jpa documentation for more info.
11

Hibernate

Fetches only key for optimal performance:

public boolean exists(Class clazz, String idKey, Object idValue) {
    return getSession().createCriteria(clazz)
            .add(Restrictions.eq(idKey, idValue))
            .setProjection(Projections.property(idKey))
            .uniqueResult() != null;
}

JPA

Since Hibernate is an implementation of JPA, it is possible to inject an EntityManager. This method also has good performance because it lazily fetches the instance:

public boolean exists(Class clazz, Object key) {
   try {
      return entitymanager.getReference(Entity.class, key) != null;
   } catch (EntityNotFoundException.class) {
      return false;
   }
}

1 Comment

You do not need a conditional for the last line: You can use .uniqueResult() != null;
6

A bit simplified method of @Journeycorner

public boolean exists(Class<?> clazz, Object idValue) {
    return getSession().createCriteria(clazz)
            .add(Restrictions.idEq(idValue))
            .setProjection(Projections.id())
            .uniqueResult() != null;
}

A below method can be useful also. Keep in mind, that this method can be used only with the criteria that can produce not more than one record (like Restrictions.idEq() criteria)

public static boolean uniqueExists(Criteria uniqueCriteria) {
    uniqueCriteria.setProjection(Projections.id());
    return uniqueCriteria.uniqueResult() != null;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.