[SOLVED] 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. Exception trace look 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

Solution:

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

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

//This will throw NullPointerException if entity is not found.

System.out.println(department.getName());

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

Happy Learning !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

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 its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.