tags:

views:

3427

answers:

1

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...

+6  A: 

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.

Juanma
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."
Juanma