3
I’m starting to study Hibernate
and wanted to "start the right way".
The doubt is as follows:
For any transaction I need to use the following code:
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
and to save
Empregado emp = new Empregado();
emp.setEmail("[email protected]");
emp.setNome("Jose");
emp.setSobenome("Alves");
session.save(emp);
session.getTransaction().commit();
I’m used to the pattern DAO
but using JDBC
.
I would like to know how best to use Sessions
along with the pattern DAO
.
If, for example, I had to open the Session
and close in all methods of DAO
, or if there was some other way not to allocate unnecessary resources.
If you could paste an example I’d appreciate it.
What is the question exactly? For a model class, you create a dao correspondent? If so, I see no problem with that. For example: suppose you have an employee.java class within the model, with its characteristics. On the dao, suppose you have Empregadodao.java with the method
save()
. In this method, you will put this code that you showed in the question. Every time you need to save an employee, just call the methodsave()
for that employee. That’s what you do?– Paulo
It would be more or less that. My real doubt is whether in all the methods of
DAO
I would have to keep opening theSession
and theTransaction
repeatedly or if there would be any better way to do it.– vlopes
Got it. I use it this way, having seen some code on the net. But I don’t know if it’s the best way.
– Paulo
You always have to open and close Session, and you always have to start and close the transaction. But it doesn’t make much sense to do this in each DAO method because you may want to use more than one method in the same transaction. Generally, you get Session and initialize the transaction at the beginning of each application service, and you can use frameworks to save service. The best way to do it, however, depends on more information about your system.
– Caffé