A
A
Andrfas2015-03-06 13:41:52
Java
Andrfas, 2015-03-06 13:41:52

How to work with transactions in hibernate?

I'm familiar with hibernate and mySQL.
Suppose a DAO object is called in the service method, and on the latter a method is called that gets the database table object (simplified code):

void service() {
   Dao d = new Dao();
   Obj o = d.getObj();
}


Dao class
Obj getObj() {
   sessionFactory = HibernateUtil.getSessionFactory();
   Session session = factory.getCurrentSession();
   ransaction ta = session.beginTransaction();
   //manipulations to get object
   ta.commit();
   session.close();
}


After reading articles on the Internet, I realized that I was not working correctly with transactions (for example, with lazy fatching, problems arise in the service method).
I also saw @Transactional, and, as far as I understood, this annotation should solve my problem (to the point that I will not need to open and close transactions at all). I put this annotation before the service () method, but it did not work (when I try to pull lazy data from an object, I get errors).

I didn't write anything about TransactionManager in hibernate.cfg.xml, because I didn't find what to write.

Please direct me in the right direction - how to set it all up correctly and how to work with it correctly?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladimir Smirnov, 2015-03-10
@Andrfas

You have mixed everything together and confused yourself. First, there are Container-Managed Transactions (CMT) and Bean-Managed Transactions (see Google). Often, anything that can be specified with annotations (such as @Transactional ) refers to the CMT. When working with CMT in your application, there is no code for working with sessions and transactions, all this is implicitly done by the container (for example, the application server). Since you have this code, then you have Bean-Managed Transactions and the annotations are simply ignored.
Concerning lazy - a question generally separate. Typically, problems with lazy initialization occur when the entity's data is read, not when it is saved. So the above code and " trying to pull lazy data from an object - I get errors " have nothing to do with each other.
In general, if you want to get it right, stop coding and study the documentation.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question