3
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, certain doubts arise.
For example, before any operation with the database you need to start the Entitymanager operation and commit after the execution of the operation.
entityManager.getTransaction().begin();
entityManager.persist(Estado);
entityManager.getTransaction().commit();
1st question : You must close 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? how? through entityManager.close() ?
2º Doubt : Each DAO method must 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();
}
3º Doubt (COUPLING) : How to pass the Entitymanager more efficiently to the DAO layer?
The examples I had access to worked with a DAO layer that did database operations, however, these DAO’s received an instance from Entitymanager via constructor.
Something like :
public class CidadeDAO implements DAOInterface<Cidade>{
private EntityManager em;
public CidadeDAO(EntityManager em){
this.em = em;
}
}
But this confuses me when working with this implementation format when I’m developing my pages with JSF, because I end up creating a coupling that I don’t know how to deal with. For example, I feel the need to recover an instance of Entitymanager 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 incongruous to the class context, since the right thing would be to have all the tools, persistence objects and methods in the classes that are reserved for the purpose of conducting transactions in databases.
To illustrate my doubt:
@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 will need multiple instances of Entitymanager and this seems wrong. Some solution for how to work the transition from entityManager to my DAO layer ?