简体   繁体   中英

How to manage EntityManager/Session in JSF?

I have a JSF application running on tomcat, using hibernate. Until now, everytime I needed an EntityManager to do somethink, eg. some select query, i was oppening the connection, then doing the query, then closing it. Yesterday i've discovered that the correct way to do it was to begin a transaction, then do the query, and finally commit or rollback the transaction (even if it's a read only statement). So, today i spent most of the day tracking down every single occurence of EntityManager, and change the code to include the begins and commits where they were needed.

Is there a way to somehow keep the EntityManager opening/closing/commiting operations hidden from the developer, something like, when some request starts, the EntityManager is opened, when the request finishes, it automatically closes... Something like this, so it decreases the chance of distracted developers to make mistakes?

You could create a base abstract class that does the basics for you and the subclass implements only the specific stuff. The problem is that you would end up needing many methods to be enclosed by the base class mechanisms.

Another way to do this is to implement this with a Generics template and during implementation you will put only the specifics.

A more esoteric way could be to use AOP to intercept the call and prepare the environment for your code to run.

Cheers

Spring's OpenEntityManagerInViewFilter (and OpenSessionInViewFilter if you are using Hibernate API not JPA API) do the thing you need.

You add the filter to your web.xml, and define EntityManagerFactory as bean in Spring context, now creates and opens a new EntityManager in each HttpServletRequest passing through the filter, and closes it after request handling.

You can do Transaction management with Spring Transaction API. Spring keeps a single transaction if you do both JPA, Hibernate, and JDBC queries in a single transaction.

In Java EE version 5 or later, assuming that you are using the application server's implementation of JPA, you can inject an EntityManager by annotating a private field with @Resource, and that EM will then be managed by the app server.

If you are using Spring, this facility is available if you are using Spring-managed transactions, and those are properly configured. There is another Stackoverflow question available for that, and this is widely covered in the Spring documentation .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM