MyObject myObject = repositoryHibernateImpl.getMyObjectFromDatabase();
//transaction is finished, and no, there is not an option to reopen it
ThirdPartyUtility.doStu
If you don't want to couple your domain to Hibernate, another possibility is to have your DAO instantiate your own instance of the entity from inside getMyObjectFromDatabase() and populate that with the appropriate fields from Hibernate's proxy. I've done this and it works well.
Obviously this is more code, but you're guaranteed a "pure" instance of your entity (complete with null uninitialized values) if that's what you want.
Let's say you have a field, in the getter you could:
MyField getMyField() {
if (Hibernate.isInitialized(myField)) {
return myField;
}
return null;
}
From the javadoc of org.hibernate.Hibernate:
public static boolean isInitialized(Object proxy): check if the proxy or persistent collection is initialized.
check my solution.
Minimal example:
I do not load the property from the object but from the controller.
Code:
{..}
MyProp prop = employeeController.getMyProp(employee);
{..}
This initiaqlizes the property via repository object and returns it.
EmployeeController.java:
public Set<MyProp> getMyProp(Employee employee) {
if (this.employeeRepository.InitMyProp(employee)){
return employee.getMyProp();
}
return null;
}
Repository get/open the session, reload employee object ! and initialize lazy loaded field
EmployeeRepository.java:
public boolean InitMyProp(Employee employee) {
if (Hibernate.isInitialized(employee.getMyProp())){
return true;
}
try {
Session session = getSession();
session.refresh(employee);
Hibernate.initialize(employee.getMyProp());
} catch (Exception ex) {
return false;
}
return true;
}
private Session getSession(){
if (session == null || !session.isConnected() || !session.isOpen()){
session = HibernateUtil.getSessionFactory().getCurrentSession();
}
if (!session.getTransaction().isActive()) {
session.beginTransaction();
}
return session;
}
I have in my solution a TableView with several thousand records and 2 further TableViews with details on the selected record in the first TableView.
hope it helps.