4

I would like to know

Is session.getTransaction().commit(); required in hibernate while fetching data

private List listEvents() {
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        session.beginTransaction();
        List result = session.createQuery("from Event").list();
        session.getTransaction().commit();
        return result;
    }

This example is taken from http://docs.jboss.org/hibernate/orm/4.1/manual/en-US/html_single/#tutorial-firstapp-firstclass

xrcwrn
  • 5,339
  • 17
  • 68
  • 129

2 Answers2

3

Yes, you need a transaction even for read operation and it should be committed as per the hibernate documentation.

Here are the details:

13.2. Database transaction demarcation

Database, or system, transaction boundaries are always necessary. No communication with the database can occur outside of a database transaction (this seems to confuse many developers who are used to the auto-commit mode). Always use clear transaction boundaries, even for read-only operations. Depending on your isolation level and database capabilities this might not be required, but there is no downside if you always demarcate transactions explicitly. Certainly, a single database transaction is going to perform better than many small transactions, even for reading data.

In case of plain JDBC, the auto-commit is enabled by default. Here are the details for it:

Disabling Auto-Commit Mode

When a connection is created, it is in auto-commit mode. This means that each individual SQL statement is treated as a transaction and is automatically committed right after it is executed. (To be more precise, the default is for a SQL statement to be committed when it is completed, not when it is executed. A statement is completed when all of its result sets and update counts have been retrieved. In almost all cases, however, a statement is completed, and therefore committed, right after it is executed.)

Chaitanya
  • 15,403
  • 35
  • 96
  • 137
1

AFAIK: in most cases it doesn't matter. Both approaches (commit/ rollback) are valid.

But the recommended way is to commit, because that relational databases are performance optimized for the most common expected case which is commit, not rollback.


UPDATE:
You can take a look at following similar post if you are wondering why to start transaction at all.

Community
  • 1
  • 1
G. Demecki
  • 10,145
  • 3
  • 58
  • 58
  • But why it is needed in fetch – xrcwrn Oct 08 '14 at 07:00
  • It varies. Good practice is to open transaction for every DB operation. Also transaction is useful to ensure that no other transaction added data that makes your view inconsistent. – G. Demecki Oct 08 '14 at 07:12