Our application consists of three parts:
1. A core module, which contains model and DAO classes and the spring configuration.
2. A web module, which uses the core package and is executed in a (portal) web environment.
3. A tasks module, which also uses the core package and is executed as a scheduled task (no web context)
We try to introduce the OpenEntityManagerInView pattern with the Spring Filter for the web module. As far as I understand it, the DAOs must not close the EntityManager because the filter does it. Furthermore, I would inject an EntityManager with @PersistenceContext instead of EntityManagerFactory with @PersistenceUnit (is that right?).
But how can I reuse the same core package with these modifications in the tasks module? There is no Filter which controles the lifecycle of the EntityManager.
OpenEntityManagerInViewFilteris usually used to complement Spring transaction management, as follows:You define transaction boundaries in your code. Inside a transaction you can use
EntityManagerinjected with@PersistenceContext(or Hibernate session obtained fromgetCurrentSession()). Also transactions define JPA Units of Work, i.e. all changes to persistent object you made inside a transaction will be propageted to the database automatically.But sometimes you need to access the database outside of defined transaction (the most notable case is lazy loading when rendering a view). For this case you have
OpenEntityManagerInViewFilterthat allows you to access the database and use@PersistenceContextat any point during HTTP request processing.As you can see,
OpenEntityManagerInViewFilteracts as a substitute for absent transaction, therefore you can run the same code withoutOpenEntityManagerInViewFilterif you do it inside a scope of transaction. So, you need to define transactons appropriately to make sure that all persistence-related code in your tasks module runs inside a transaction.