Search code examples
hibernatejpaentitymanager

JPA EntityManager, how does it work?


Sorry for the noob question, but I'm having problems with JPA+Hibernate so I thought that something is not clear in my mind. I have some entities, say A, B, C, D and I have coded AMethods, BMethods, CMethods, DMethods. Each of the *Methods classes contain EntityManager initialization via EntityManagerFactory and some methods that basically execute queries. I don't know if I should use a singleton pattern (so that I have an EntityManager per *Method class) or if I need to open and close the EntityManager each time I execute a query or I persist/remove an entity... can you help me??


Solution

  • In a typical JPA/Hibernate application, you don't put persistence logic in the entity classes themselves. This is a big change in design philosophy compared to older EJB 2.x applications. Instead, many applications create a layer of Data Access Objects--separate from the entities--that use EntityManager instances to query, load, and save entities. Often, these are singletons, and the entity manager instances inside the DAOs are local to the thread.

    If you use a framework like Spring, the management of the EntityManager instances and transactions is completely automatic. Same with EJB 3, although I have not used that on a large project. I would suggest reading the Spring documentation's chapter on Object-Relational Mapping data access. Even if you don't end up using Spring in your application, the chapter gives some good tips on how to structure your application in a layered way that separates persistence concerns from the entities being persisted. Good luck!