[SOLVED] org.hibernate.ObjectNotFoundException: No row with the given identifier exists

1. Reason

This exception is thrown when we try to load an entity in hibernate with session.load() method and entity is not found. The exception trace looks like this:

Hibernate: select department0_.ID as ID0_0_, department0_.NAME as NAME0_0_ from DEPARTMENT department0_ where department0_.ID=?
org.hibernate.ObjectNotFoundException: No row with the given identifier exists: [hibernate.test.dto.DepartmentEntity#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.DepartmentEntity$$EnhancerByCGLIB$$deac2c14.getName()
at hibernate.test.TestHibernateEhcache.main(TestHibernateEhcache.java:21)
Random exceptions
Random exceptions

2. Solution

The correct way to solve this problem is to use session.get() method. Get method will return null if the entity with given identifier is not found.

DepartmentEntity department = (DepartmentEntity) session.get(DepartmentEntity.class, new Integer(11));

if(department == null) {
    //handle null case

Another solution is to wrap the session.load() call in try-catch block and handle exception accordingly.

Happy Learning !!

Leave a Reply

Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions, and frequently asked interview questions.

Our Blogs

REST API Tutorial