Lets assume, I have a db design with the following relationship.
University table contains university details.
Course table contains course details along with an association to university.
Instructor table contains instructor details, this table also has an association with university.
In my hibernate mapping files, especially on the university table, I have a one to many association to course and instructor records with lazy loading enabled.
On my GUI, Whenever the user searches for an university and opens it, I am displaying all the information related to university like courses,instructors associated with this university.
As per hibernate documentation, We can retrieve the collection objects only if the session in in open state(Lazy loading enabled).
Assuming a layered architecture, my model objects has to be transferred to the form objects and send it back to the jsp page to be displayed.
I am doing this transfer of objects when the session is open state,So all the collection objects are transferred to form objects, but during this step, Hibernate goes in and executes the SQL's to get the collection objects.
Now coming to the problem. Assume that an university has 100 courses and 100 instructors, so when i want to view the information of this university, system is taking too long to respond because, hibernate usually executes only 1 select statement to retrieve the university record, but when i transfer the objects from model to form with hibernate session in open state,hibernate is executing select statements to retrieve course and instructor records.
Please let me know, how to solve this kind of performance problem with hibernate.
I am not a fan of the Open Session In View (anti) pattern.
Quoting from this site:
Open Session In View should be regarded as an anti-pattern; not only because it breaks the encapsulation of data access from the web tier, but because it allows for inefficient data access if not used sparingly. Reliance on Open Session in View can easily result in large number of SQL selects being executed from the web tier, a reappearance of the N+1 Selects problem. If used, the Open Session In View should be considered a last resort, with resulting data access in the web tier considered a bug in the application. Do not place too much reliance on the Open Session in View pattern. Use it only as a last resort to avoid more embarrassing user interface bugs.
Look here for some alternatives.
Some also choose to create DTO's and map their entities to those using a library like Dozer. Either way I would not hold the session open.