views:

1827

answers:

2

Hey I am developing an desktop application using Spring and Hibernate, and I have a problem with lazy initiation. I looked in the web and every solution is related to the open session in view pattern, but I can't use this pattern. I've also tried to get the sessionfactory from the HibernateTemplate, but it returns to me a disconnected session.

Does anyone know other solution?

+3  A: 

I would suggest that you basically have two solutions:

  1. Make arrangements to keep a Hibernate session open when you access a lazy-initialized object or collection. That means you're going to have to carefully mark your transaction boundaries in your code, a la the "open session in view" pattern. Spring makes this possible, but in a desktop application it won't be as straightforward as a web application where the transaction boundaries are a little more obvious.

  2. Turn off all the lazy-initialization for your persisted objects in Hibernate.

Option 2 could lead to a lot of unnecessary database access, and option 1 means you have to seriously study your workflow and use cases.

Hope that helps!

Mojo
I done something similar to first option...I have changed the Application Context to make transaction boundaries in every business class methods. thanks mojo
Thiago Diniz
+1  A: 

One option is to call Hibernate.initialize() on the entities or collections to force initialize them. You'd want to do this before you return the data back to your view. I would consider this carefully, since it's going to generate a lot of SQL statements back to the database.

You may want to look into using "fetch" in your HQL queries or configuration the fetch mode to "eager" in your mappings (I believe it's FetchMode.EAGER in JPA or lazy="false" in hbm.xml).

@Jose: Don't manage the Session in your own ThreadLocal. Use SessionFactory.getCurrentSession() and configure Hibernate to use the "thread" SessionContext.

cliff.meyers
i have tried this way but i doesn't work.The spring works with one session per operation, so when i try to call any Hibernate methods it says that there is no session or the session is closed. any way thanks
Thiago Diniz