PDA

View Full Version : OpenSessionInView good or evil?



bullgod
Sep 27th, 2004, 04:26 AM
Hi All,

what is the ultimate approach for Hibernate and lazy collections with Spring? I've read loads of different opinions about the OpenSessionInView pattern/interceptor. Some say it's a very good thing to to - other say it's a no-no. Now what is the proper approach for web app using all spring (dao, mvc, transactions) and hibernate?

Should I touch collections manuall in my service objects? This can be rather expensive, memory and code wise. I'd need many service methods for all kinds of view cenarios in my service methods (not all views need all lazy data). Plus there's plenty of iteration that needs to be coded in the service methods that need to provide lists of data (i.e. load a list of users via DAO, loop through it and touch the lazy collections).

Or should I rely on open session in view which loads basically the same stuff upon requirement, but I don't have to take care of all different kinds of view scenarios, hence a tighter service class. Yes, it causes a bit more setup hassel in some situations but it think it's simpler to maintain once it works. You don't have full controll over when which query is issued, but who needs that? I can run the app with sql output, run through all use-cases in the app, grap the quiers and optimize them (db wise or hibernate wise using named queries).

Best,
Andi

Colin Sampaleanu
Sep 27th, 2004, 08:32 AM
OpenSessionInViewFillter can be used in two modes...

I do not like (at all) the OpenSessionFilter original mode (singleSession=true). I think it is potentially dangerous, as it makes it easy to use a damaged/invalid Session, and makes it easy to mix objects different transactions when they shouldn't be. I would always use the touch approach over this.

On the other hand, I think the newer (introduced with Spring 1.1) singleSession=false mode is pretty clean, and would probably use it over the touch approach. All this does is defer closing of Sessions, so you don't have to touch lazy relationships. You still have multiple sessions and should generally structure your view code so that operations are done through one call down into a transactionally wrapped service layer method that does a complete operation and returns a complete object graph (same as if you didn't use the filter), but now the service layer no longer has to worry about touching lazy relationships.

jsissom
Sep 29th, 2004, 04:05 PM
Has there been any discussion on a similar thing for OJB? We have similar issues there, but there isn't a filter for OJB.

Thanks
Jay

davidnewcomb
Oct 12th, 2009, 10:36 AM
There is a more extensive discussion here:

http://forum.springsource.org/showthread.php?t=24174