I'm trying to understand how things work. I understand them separately but fail to get the whole picture.
At the lower level, there is what is executed inside the DataBase using SQL queries :
start transaction
insert A
insert B
commit
At a higher level, there is Hibernate or any other JPA provider. Things need to be managed manually (I didn't put try/catch/roolback to make thing easier to read) :
public saveAandB()
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
session.save(A);
session.save(B);
session.getTransaction().commit();
session.close();
Finally, at a higher level, there are Spring Transactions :
@Transactional
public void save(A,B) {
saveA(A);
saveB(B);
}
Ok I'm trying to understand now how all of them are related :
With @Transactional, Spring creates a transaction at the beginning of my service (with proxy created from business service).
With Hibernate, I no longer need to create a new session object. I need to use
getSession()
instead ofopenSession()
I can have separated saveA() and saveB() methods that will execute within the same transaction (becausegetSession()
will return the same session)
I don't need either to manager session.getTransaction().commit(); anymore inside Hibernate layer. When I complete saveA() method, I enter saveB() method which starts with getSession()
. I get back the exact same session from saveA() method.
When my save(A,B) method is finised, my transaction is committed thus terminating the session.
- Behind the scenes : Spring will create a Hibernate Transaction. I enter both saveA() and saveB() method within the same transaction. Then Hibernate will generate SQL transaction
start transaction
andcommit
when creating real SQL queries
Is this correct ?