Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OpenSessionInView vs PersistentContext (Extended)

I'm working on an architecture Hibernate/JPA/Spring/Zk, and I multiply the questions these days because I have to learn a lot of framework.

I have a question that leaves me perplexed for several days.

I hear about the "pattern" OpenSessionInView to keep alive a Hibernate transaction to make lazy loading. Many also say that pattern is not very clean.

And on the other, it is said that PersistentContext extended is not thread safe, and is therefore not suitable for keeping alive the entityManager.

So, what is the real solution to these problems? I presume that these issues arise from the introduction of ajax which allows more possibilities especially with the use lazy loading to load some heavy Collections when necessary.

For moment, i tried @PersistenceContext in extended mode. It's working... I had to set it for my JUnit tests, et it's working too in my web application with lazy loading without more configurations.

Is that the evolution of framework (Spring, JPA 2.0) mean that it is now easier and more "clean" work with PersistentContext?

If this is not the case, should we use the OpenSessionInViewFilter from Spring and replace the PersistentContext in transactional mode?

Thank you.

like image 451
MychaL Avatar asked Nov 13 '22 00:11

MychaL


1 Answers

I hear you. I've implemented both patterns in several applications since 2008. Now, I abandon any statetful patterns altogether. When you introduce state to the client, you pose scalability and state management issues: do you merge in client, do you save in user session, what happens when you walk through a wizard and object must be transient before save? How would you synchronize client and serverside state? What happens when db changes--does the client break?

Look at the trend of existing technologies, including Spring MVC: the pattern is to build two projects: 1) restful webservices 2) user interfaces. State is shared through an immutable domain model. Sure you might end up maintain a set of dtos, but they're predictable, cheap, and scale infinitely.

My recommendation? Avoid sending proxied objects over the wire and deal with dtos on the client or a share a domain model with the client if you want to reuse serverside validations. Lazy collections can be loaded via fine-grained api calls through Ajax. That way, you give complete control to the client.

That's how the social web has scaled in the past five years.

like image 127
pri Avatar answered Dec 24 '22 16:12

pri