Hibernate: check if object exists


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);
 // do smth.....

Couldn't find it hibernate docs…

Best Solution

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.