In the Hibernate we can check whether an object is managed by the persistence context. It can be done through the below given methods:
entityManager.get(Student.class, studentId);
...
boolean isIn = entityManager.contains(student);
assert isIn;
Here below code tells us also check whether an object, an association or a property is lazy or not. You can do that independently of the underlying persistence provider:
PersistenceUtil jpaUtil = Persistence.getPersistenceUtil();
if ( jpaUtil.isLoaded( customer.getAddress() ) {
//display address if loaded
}
if ( jpaUtil.isLoaded( customer.getOrders ) ) {
//display orders if loaded
}
if (jpaUtil.isLoaded(customer, "detailedBio") ) {
//display property detailedBio if loaded
}
When we have access to the entityManagerFactory, we recommend you to use:
PersistenceUnitUtil jpaUtil = entityManager.getEntityManagerFactory().getPersistenceUnitUtil();
Customer customer = entityManager.get( Customer.class, customerId );
if ( jpaUtil.isLoaded( customer.getAddress() ) {
//display address if loaded
}
if ( jpaUtil.isLoaded( customer.getOrders ) ) {
//display orders if loaded
}
if (jpaUtil.isLoaded(customer, "detailedBio") ) {
//display property detailedBio if loaded
}
log.debug( "Customer id {}", jpaUtil.getIdentifier(customer) );
The performances are likely to be slightly better and you can get the identifier value from an object (using getIdentifier()).
We have to always remember is that the These are roughly the counterpart methods of Hibernate.isInitialize.