Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Best practice to get EntityManagerFactory
- @Stateless
- public class FooService {
- @PersistenceContext
- private EntityManager em;
- public Foo find(Long id) {
- return em.find(Foo.class, id);
- }
- // ...
- }
- @WebListener
- public class EMF implements ServletContextListener {
- private static EntityManagerFactory emf;
- @Override
- public void contextInitialized(ServletContextEvent event) {
- emf = Persistence.createEntityManagerFactory("unitname");
- }
- @Override
- public void contextDestroyed(ServletContextEvent event) {
- emf.close();
- }
- public static EntityManager createEntityManager() {
- if (emf == null) {
- throw new IllegalStateException("Context is not initialized yet.");
- }
- return emf.createEntityManager();
- }
- }
- EntityManager em = EMF.createEntityManager();
- // ...
Add Comment
Please, Sign In to add comment