I have a couple questions regarding using the entity manager in a JavaSE environment.
I'm using the repository pattern to perform my CRUD operations on the database. There will be a base repository class like so:
public class Repository<T> implements IRepository<T> {
private EntityManager em;
private String persistenceUnitName;
public Repository(String persistenceUnitName) {
this.persistenceUnitName = persistenceUnitName;
}
@Override
public T find(Class<T> type, Object id) {
return em.find(type, id);
}
private EntityManager getEntityManager() {
if (this.em == null) {
EntityManagerFactory emf = Persistence.createEntityManagerFactory(persistenceUnitName);
em = emf.createEntityManager();
}
return em;
}
...
...
}
I will then have classes like EmployeeRepository that will inherit Repository. These repository classes will be created in my service layer.
Is this a good way of initializing the entity manager? I'm starting to think that it's not - it seems like you should only have one entity manager per persistence unit? Where as in this case you would have an entity manager for every repository you create... How would you go about ensuring you only have one entity manager per persistence unit? Also, I noticed that the entity manager and entity manager factory methods have a close method - when should these be called? On a server terminate event?
If you know of any good sources about using JPA in JavaSE I would appreciate the info.
Thanks!