Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate: check if object exists

Tags:

hibernate

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.


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.


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;
   }
}

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;
}