user3198603
user3198603

Reputation: 5836

Is begining the transaction mandatory while create/update/delete?

I have below code in my hello world program for learning hibernate

Configuration cfg=new Configuration();
cfg.configure("hibernate.cfg.xml");

SessionFactory factory = cfg.buildSessionFactory();
Session session = factory.openSession();

Transaction  tx = session.beginTransaction();// line1
College college= new College();
session.saveOrUpdate(college);
tx.commit();//line2
session.close();
factory.close();

Above code successfully saves the college entity in DB but if i drop line1 and line2, it does not. Is beginning the transaction mandatory while create/update/delete?

If yes, in another application, i see

session.update(entity)

works successfully without beginning/end transaction. I just see session.flush() after session.update(entity) I am not sure why it works at one place without transaction boundary but not at other?

UPDATE :-

As per RADIM answer i tried below

Configuration cfg=new Configuration();
cfg.configure("hibernate.cfg.xml");

SessionFactory factory = cfg.buildSessionFactory();
Session session = factory.openSession();

College college= new College();
session.saveOrUpdate(college);
session.flush();
session.close();
factory.close();

But it did not also persisted the college in DB

Upvotes: 1

Views: 72

Answers (1)

Radim Köhler
Radim Köhler

Reputation: 123901

The good is, that there is nothing exceptional or surprising.
Just - if we won't use explicit transaction, the implicit transaction of each separated write operation will be used.

Without explicit transaction begin() commit():
The session.flush() will execute each WRITE operation as expected. Each change will be persisted or not on its own. It won't be treated as a batch of operation.
BUT what won't be as expected is the result. It could happen that some WRITE statements will fail and some will succeed. Not what we would like...

With explicit transaction:
all WRITE statements will succeed if there is no error, else all will fail.
That should be marked as only expected behavior in fact...

Of course, while there is nothing surprising - that WRITE operation is working even without explicit transaction - it is not suggested approach.

SUGGESTION: we should use explicit transactions, to be sure, that the session.flush() will end in consistent DB state.

Upvotes: 1

Related Questions