Hello. Please help me, JPA 2.
The question is:

Suppose I have some class that works with the database. Different objects create it, use it, etc. So that there are not many "dead" connections, they should always be closed.

EntityManagerFactory emf = Persistence.createEntityManagerFactory("commonStorage"); EntityManager em = emf.createEntityManager(); // операции em.close(); emf.close(); 

But creating a new EntityManager takes time. Maybe there is something that I missed? Maybe you need to use one EntityManagerFactory for the whole application? Or other options.

  • Perhaps, of course, I misunderstand something in php, for example (normal), everything that relates to the database is a singleton ... Actually, what's stopping you from using it? <br> <small> <i> (Except java religion, what's static the method should only be one ...) </ i> </ small> - Zowie
  • PHP script does not work forever. It starts and ends as soon as the page is generated. Java web applications run in a container and the application is loaded all the time and all requests come in one process, whereas in the case of PHP, requests generate new interpreter processes running in different contexts. In this regard, for PHP it is not relevant. - cy6erGn0m
  • Safe from creating unnecessary objects is not relevant? O_O <br> I am extremely saddened by your post ... <br> <br> And I know the difference between compiled and scripting languages, thank you ... - Zowie

1 answer 1

Yes, EntityManagerFactory is a heavy object and you should not create it with each request. It is better to use a strategy - one EntityManager per request.

  • Maybe the opposite? :) <br> One for all requests? - Zowie
  • Those. Is it best to create a singleton? Those. once initialize EntityManager use it with a constant retention of the connection to the database? - Anton Mukhin
  • What do the others think? - Anton Mukhin
  • one
    @Artem Prigoda is right, EntityManager is easy and should be created for every unit of work (<a href=" docs.jboss.org/hibernate/entitymanager/3.5/reference/en/…. Second paragraph <</a> is for Hibernate) In addition, according to the above docks, it is not thread-safe in the general case, however there are exceptions: for example, an EntityManager that was connected from the context of the spring via @PersistenceContext will be thread-safe, since in reality a proxy will be connected that redirects requests to the current EntityManager or creating a new one. - yozh
  • one
    JPA 2 Spec .: "It’s not a matter of course." - so this is true for all implementations, not just Hibernate. - yozh