You should not use any Spring filters or templates if you use Java Persistence (or you should ask in a Spring forum how their proprietary stuff works).
If the EntityManager is the primary interface you use, there are two ways to implement "Open Session (persistence context) in view":
- Use an EJB 3.0 container and scope the persistence context to a stateful session bean that is available when your view is rendering
- Use JBoss Seam, which can manage persistence contexts for you even with plain JavaBeans as application components
With EJB 3.0:
Code:
@Stateless
public class GenericDAO {
@PersistenceContext
EntityManager em;
}
With EJB 3.0, you can give the EM an extended life by binding it to a SFSB:
Code:
@Stateful
public class MyAction {
@PersistenceContext(EXTENDED)
EntityManager em;
@EJB
MyDAO myDAO;
public void doSomething() {
myDAO.loadStuff();
}
}
The same persistence context is now available when the view after doSomething() is rendered. It is also propagated into the myDAO.loadStuff() call and injected into that DAO.
With Seam and JavaBeans it looks like this:
Code:
@Name("mySeamComponent")
public class MyAction {
@In
MyDAO myDAO;
public void doSomething() {
myDAO.loadStuff();
}
}
Code:
public class GenericDAO {
@In
EntityManager em;
}
Code:
Name("myDAO")
public class MyDAO extends GenericDAO {
}
In both environments you can easily call em.getDelegate() to get a Session interface when needed.
I recommend you first drop the chapter 16 in Java Persistence with Hibernate and read chapters 9, 10, and 11, which give you the background to understand all of this.