Guest User

Untitled

a guest
Aug 18th, 2018
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.86 KB | None | 0 0
  1. Best practice to get EntityManagerFactory
  2. @Stateless
  3. public class FooService {
  4.  
  5. @PersistenceContext
  6. private EntityManager em;
  7.  
  8. public Foo find(Long id) {
  9. return em.find(Foo.class, id);
  10. }
  11.  
  12. // ...
  13. }
  14.  
  15. @WebListener
  16. public class EMF implements ServletContextListener {
  17.  
  18. private static EntityManagerFactory emf;
  19.  
  20. @Override
  21. public void contextInitialized(ServletContextEvent event) {
  22. emf = Persistence.createEntityManagerFactory("unitname");
  23. }
  24.  
  25. @Override
  26. public void contextDestroyed(ServletContextEvent event) {
  27. emf.close();
  28. }
  29.  
  30. public static EntityManager createEntityManager() {
  31. if (emf == null) {
  32. throw new IllegalStateException("Context is not initialized yet.");
  33. }
  34.  
  35. return emf.createEntityManager();
  36. }
  37.  
  38. }
  39.  
  40. EntityManager em = EMF.createEntityManager();
  41. // ...
Add Comment
Please, Sign In to add comment