开发者

Fight LazyInitializationException without Spring

I'm using Hibernate and have a problem with LazyInitializationException in my app. This problem can be simply solved by Spring framework(some annotations,config or something) but I just dont know this framework and dont want to learn it now(I'm just the beginner).

This pro开发者_JS百科blem is pretty old and so I found how it can be solved with OpenSessioninView pattern, but I bet there is an easer way to do it.

My app is running on latest glassfish appliation server so I want to know what the typical way to work with lazy initialization in EJB container?


You can set everything as EAGER and use session.get instead of session.load, but I bet that open session in view is better approach.

By the way This is exactly what SPring is doing. you can see Spring OpenSessionInView implementation here:

http://static.springsource.org/spring/docs/3.0.6.RELEASE/javadoc-api/org/springframework/orm/hibernate3/support/OpenSessionInViewFilter.html


this is your problem:

"but I just dont know this framework and dont want to learn it now(I'm just the beginner)."

It would be nice if things just happened automatically, and we didn't even need to write code, but alas, things aren't always nice. It doesn't make any sense to use a technology but not want to put in the effort/learn to use its mechanisms.

There are a bunch of options.

1) Open session in view. Spend the time to do this. It's not hard. What it does is keep the session open for the life of the request, so if you access a lazy relationship, the session is there and the data can be loaded. @Danny.lesnik's answer is incorrect -- from what I read, he is implying that OSiV just makes associations eager, which is not what it does. If you don't want to use Spring, you can probably find an example of implementing the OSiV pattern by hand, it shouldn't be too bad, and is probably a good learning experience.

2) Write custom mappings/hql so you load all the data you need for a given scenario. This is not to say load all the objects; you can load certain fields off of tables to make the fetch as lean as possible. For example, you can make your hibernate/jpa mappings/annotations lazy, and then write a custom DAO method that fetches only certain fields off columns across tables in a join. That can be really fast with some tuning/caches/indexes.

Of both options, 1 is easier, you just need to look at the documentation, its mostly config. Note that OSiV has its own complications, for example, if you modify data but have an exception presenting the results to the user, and your transactions are configured a certain way, your modification will be rolled back. Option 2 has the advantage of not needing OSiV, with all of its attendant complications, and has the benefit of giving you more control of your interaction with your database, with the tradeoff of having to do more work.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜