Hi all!
We are having the exactly same problem when creating Windows desktop application (Swing UI, POJOs as Domain Objects, DAOs using Hibernate to get persistence for to DOs).
We have a big Test class and in the beginning of the program we would like to list all Tests in the system so that user can open one of them. Of course to get the Tests to the list, there is no need to load all the data from the Test (it would be hundreds of megabytes) but only the name, type etc..
I read the
http://www.hibernate.org/41.html and we could propably use this pattern, but at the moment I'd like to look for more general solution. (I'm not yet sure that the listing of Tests would be our only problem spot)
At the moment our DAOs are created in the way Hibernate documentation suggest. (One Session is created in the beginning of the method, and closed when the database transaction is done) Here is the example code:
Code:
public Set getAllTests() throws DataManagerException {
try {
Session session = sessions.openSession();
Query q = session.createQuery("from domainobjects.Test");
session.close();
return new HashSet(q.list());
} catch (HibernateException e) {
log.error("Couldn't load all Tests. ", e);
throw new DataManagerException("Couldn't load all Tests. " + e.getMessage(), e);
}
}
Now, when I afterwards try to use lazy collections of the acquired Test object, I, of course, get the LazyInitializationException since Session is closed.
As I see it at the moment (after reading this forum) it seems that we have two possibilities:
1. Reconnect the Test object somehow to a new Session before accessing collections.
2. Keeping the Session open all the time we are using the Test.
Now I'd like to know if anyone has a good design pattern for the first case, since I haven't been able to figure out any nice way to do it. Any ideas?
Another question is for the second option. Hibernate documentation states that Sessions should not be used as a long time object. What are the actual cons of this? Will something be broken if I create one Session when the program starts and use it all the time when the program is running (I could of course flush it etc during its lifespan). Ideas about this?
Or is there some third way to do the thing? :)
Sincerely,
-Jouni Hartikainen