Spring and Hibernate, Lazy initiation problem

做~自己de王妃 提交于 2019-12-07 12:29:48

问题


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?


回答1:


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!




回答2:


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.




回答3:


I had a very similar problem, and as I was not able to find any really appropriate solution to it. I came up with my own one combining a lot of different approaches found on the web and posted them to my blog.

Sorry, that I don't put it in all here, but it is to much work to do it over and over again in all the forums I found people having this or a similar problem

Remote Lazy Loading with Hibernate and Spring



来源:https://stackoverflow.com/questions/424312/spring-and-hibernate-lazy-initiation-problem

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!