It's time for a good old discussion. About a year ago, I designed a webapplication which manages at testsystem for a company. This means a lot of settings, equipment, readings, setups - you name it - is persisted. This also means, that when a user for example wants to load a table with all tests, I really don't want to load 1.5 million readings alongside from the database.
So of course, I used lazy loading. When a user then chose a test, and wanted to see the results, all the results was loaded from the database then. At the time, I used Eclipselink. That worked - as I understand because Eclipselink automatically opens a new session when trying to fetch something that is annotated with lazy fetchtype.
Now, a year older and smarter, I'm doing some refactoring. A big change was leaving Eclipselink for Hibernate ( Also good to learn new stuff ). Suddenly, I get the good old LazyInitializationException. And yes, I now see that my DAO-structure is not working.
/**
* The Class DAO which all the other EntityDAOS extend
*/
public class DAO {
/** The entitymanager. */
private EntityManager entitymanager;
/**
* Gets the entitymanager
*
* @return the manager
*/
public EntityManager getManager(){
entitymanager = FactoryMaker.getFactory().createEntityManager();
entitymanager.getTransaction( ).begin( );
entitymanager.flush();
entitymanager.clear();
return entitymanager;
}
/**
* Commit and clear the manager.
*/
public void Close(){
if(entitymanager.isOpen()){
if(entitymanager.getTransaction().isActive()){
entitymanager.getTransaction().commit();
entitymanager.clear();
}
entitymanager.close();
}
}
@Override
protected void finalize() throws Throwable {
super.finalize();
}
}
As clearly seen in the save-example below, the session is closed immediatly.
public void SaveSomething(Something t){
EntityManager manager = getManager();
manager.merge(t);
manager.flush();
Close();
}
So this is clearly not a good solution. Now - in your oppinion - what is the best way of creating a Data Access Layer for a webapplication, where lazy loading is a requirement and data from the database is the base for the whole system?
Aucun commentaire:
Enregistrer un commentaire