3

I am using Hibernate 4, with lazy loading enabled. I have a basic entity that contains references to other objects. Below is a simple example:

    @Entity
    public class Employee{
        public int id;
        public String name;
        public Employee boss;
        //more code follows
    }

When I load the Employee entity from the database the boss object is represented by a Hibernate proxy object, due to lazy loading. Later I need to access the boss property, which may or may not be in the same session it was loaded in. If I try to use the boss object and it hasn't been loaded and I am in a different seesion I will get the following error:

Cause: org.hibernate.LazyInitializationException: could not initialize proxy - no Session

How can I tell if the Employee entity the boss property is returning is a proxy or the actual entity?

I really want an answer so I can do something like the following code:

    public Strin getBossName(Employee emp){
        Employee boss;
        if(isProxy(emp){
            boss = getBossFromDatabase(emp);
        }else{
            boss = emp.getBoss();
        }enter code here
        return boss.getName();
    }

Thanks in advance!

1 Answer 1

2

Hibernate provides such a facility in the Hibernate class:

Hibernate.isInitialized(emp)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.