xrcwrn
xrcwrn

Reputation: 5325

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

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

Upvotes: 4

Views: 8018

Answers (2)

Learner
Learner

Reputation: 21393

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.)

Upvotes: 3

G. Demecki
G. Demecki

Reputation: 10586

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.

Upvotes: 1

Related Questions