What is the best approach to get EntityManagerFactory in web app(jsp/servlets)? Is this a good way When should EntityManagerFactory instance be created/opened?, or is it better to get it from JNDI, or something else?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
They're heavyweight and they're supposed to be in the application scope. So, you need to open them on application startup and close them on application shutdown.
How to do that depends on your target container. Does it support EJB 3.x (Glassfish, JBoss AS, etc)? If so, then you don't need to worry about opening/closing them (neither about transactions) at all if you just do the JPA job in EJBs with
@PersistenceContext
the usual way:If your target container doesn't support EJBs (e.g. Tomcat, Jetty, etc) and an EJB add-on like OpenEJB is also not an option for some reason, and you're thus manually fiddling with creating
EntityManager
s (and transactions) yourself, then your best bet is aServletContextListener
. Here's a basic kickoff example:(note: before Servlet 3.0, this class needs to be registered by
<listener>
inweb.xml
instead of@WebListener
)Which can be used as: