I have been doing some courses and all the material I have read so far exemplifies the use of JPA / Hibernate in small examples, however, when we are developing something more concrete as a project, some questions arise.
For example, before any operation with the database, you must start the EntityManager operation and commit after the operation.
entityManager.getTransaction().begin();
entityManager.persist(Estado);
entityManager.getTransaction().commit();
1st Doubt: Do I need to close the EntityManager at some point? In this case, I initiated a transaction before performing my operations: "entityManager.getTransaction (). begin ()". Should I terminate this transaction in any way? as? through the entityManager.close ()?
2nd Doubt: Should each DAO method start and commit the transaction?
public void inserir(Cidade cidade){
entityManager.getTransaction().begin();
entityManager.persist(cidade);
entityManager.getTransaction().commit();
}
public void remover(Cidade cidade){
entityManager.getTransaction().begin();
entityManager.remove(cidade);
entityManager.getTransaction().commit();
}
3rd QUESTION: How to pass the EntityManager more efficiently to the DAO layer?
The examples I had access worked with a DAO layer that did the database operations, however, these DAO's were given an EntityManager instance via the constructor.
Something like:
public class CidadeDAO implements DAOInterface<Cidade>{
private EntityManager em;
public CidadeDAO(EntityManager em){
this.em = em;
}
}
But this ends up confusing me when working with this implementation format when I'm developing my pages with JSF, because I end up creating a coupling that I do not know how to handle. For example, I feel the need to retrieve an EntityManager instance in each @ManagedBean to be able to inject my DAO's, and consequently makes me declare an entityManager within ManagedBean and I think this is incongruent to the context of the class , since it would be the right thing to have all the tools, objects and methods of persistence in the classes that are reserved in order to perform transactions in databases.
To illustrate my question:
@ManagedBean
public class EnderecoBean{
private EntityManager em;
public EnderecoBean(){
this.em = JPAUtil.getEntityManager();
}
public void operacaoExemplo(){
EstadoDAO dao = new EstadoDAO(em);
List<Cidade> listaCidades = dao.listar();
}
}
I find this strange, because if I have multiple DAO's I'm going to need multiple instances of EntityManager and this seems wrong to me. Any solution on how to work the entityManager pass for my DAO layer?