2
votes

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 :

  1. With @Transactional, Spring creates a transaction at the beginning of my service (with proxy created from business service).

  2. With Hibernate, I no longer need to create a new session object. I need to use getSession() instead of openSession() I can have separated saveA() and saveB() methods that will execute within the same transaction (because getSession() 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.

  1. 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 and commit when creating real SQL queries

Is this correct ?

1

1 Answers

0
votes

More or less, yes. Note though, that JDBC uses transactions by default i.e. every statement runs in a transaction, so there is no explicit "start transaction" call necessary.