[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 !!

Was this post helpful?

Join 7000+ Awesome Developers

Get the latest updates from industry, awesome resources, blog updates and much more.

* We do not spam !!

4 thoughts on “[SOLVED] org.hibernate.ObjectNotFoundException: No row with the given identifier exists”

  1. I had that same exception using get() method. Do you know what could make it?
    I have a generic repository class that calls: getSessionFactory().getCurrentSession().get(getType(), id)
    My domain class is something like follows:
    public class MyClass{

    private MySecondClass mySecondClass;
    ………….

    }

    When I get a MyClass object and try to use mySecondClass’s getter in it, I get that exception. That happens when mySecondClass object is supposed to be null but it is a proxyfied class named something javaassist.

    Reply

Leave a Comment

HowToDoInJava

A blog about Java and related technologies, the best practices, algorithms, and interview questions.