org.hibernate.ObjectNotFoundException: No row with the given identifier exists Solution

(96 Views)

This Exception occurs when Session.load() fails to select a row with the given primary key (identifier value). This exception might not be thrown when load() is called, even if there was no row on the database, because load() returns a proxy if possible. Applications should use Session.get() to test if a row or particular record exists in the database for particular primary key.

In this article, we are discussing the hibernate org.hibernate. ObjectNotFoundException: No row with the given identifier exists.

Reason

This exception is thrown when you try to load an entity in hibernate with session.load() method and entity is not found, which means instance of particular entity is not found in the current hibernate seesion context.

Exception trace look like this:

Hibernate: select employee0_.ID as ID0_0_, employee0_.NAME as NAME0_0_ from employee employee0_ where employee0_.ID=?
org.hibernate.ObjectNotFoundException: No row with the given identifier exists: [hibernate.test.dto.EmployeeEntity#11]
at org.hibernate.impl.SessionFactoryImpl$1.handleEntityNotFound(SessionFactoryImpl.java:375)
at org.hibernate.proxy.AbstractLazyInitializer.checkTargetState(AbstractLazyInitializer.java:79)
at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:68)
at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:111)
at org.hibernate.proxy.pojo.cglib.CGLIBLazyInitializer.invoke(CGLIBLazyInitializer.java:140)
at hibernate.test.dto.EmployeeEntity$$EnhancerByCGLIB$$deac2c14.getName()
at hibernate.test.TestHibernateEhcache.main(TestHibernateEhcache.java:17)

Solution

The correct way to solve this problem is to use session.get() method. Get method will return null if there is no record peresent for that entity or if record is not found.