-1

I am new in Hibernate, I still don't understand how does it work the Object import org.hibernate.Transaction;. Now I am writing CRUD operations for a Person Entity, I wrote this implementation, basing on what I found on web:

public void save(Person p) {
    Session session = this.sessionFactory.openSession();
    Transaction tx = session.beginTransaction();
    session.persist(p);
    tx.commit();
    session.close();
}

My question are, why I should use Transaction object? What happend if I don't use it? Finally, is required to use in every CRUD operations? I noticed that in read operations (so when we don't write in the DB and we got request only the list of Person object) developers don't put the code under transaction.

Szanownego
  • 239
  • 1
  • 11

1 Answers1

0

Why I should use Transaction object?

In Database management systems a transaction represents a Unit of work,and each of them needs to be independent of the others,so that in case of any types of failures the system can recover and the data that is already existing is not lost. Transaction object helps you achieve this.Data is persisted only when you commit the transaction in case of any failure before commit all changes will be rolled back.

Should I use it in every crud operation?

Normally for read operations you do not need a transaction object, But it is again debatable, refer to this for more info about transactions in read only operations. But for Create,Update and Delete operation you should always use transaction.

Community
  • 1
  • 1
Optimus
  • 697
  • 2
  • 8
  • 22