Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate Read-Only Transaction

Tags:

orm

hibernate

The Hibernate docs show this example:

session = sessionFactory.openSession();
session.beginTransaction();
List result = session.createQuery( "from Event" ).list();
for ( Event event : (List<Event>) result ) {
    System.out.println( "Event (" + event.getDate() + ") : " + 
        event.getTitle() );
}
session.getTransaction().commit();
session.close();

Why is it necessary to perform the session.getTransaction().commit() even though the Event list was merely printed out?

like image 273
Kevin Meredith Avatar asked Jul 06 '13 17:07

Kevin Meredith


1 Answers

SELECT also requires transaction. It is impossible to execute SELECT without any transaction. The fact that you do not have to explicitly start and end a transaction when selecting data from DB using some SQL GUI tools is that these tools are using autocommit mode . In autocommit mode ,database will automatically start and commit the transaction for each single SQL statement such that you don't have to explicitly declare the transaction boundary.

If you do not end (i.e commit or rollback) a transaction , the database connection used by this transaction will not be released and your database will run out of the available connections eventually.

For hibernate ,it uses non-autocommit mode by default (which is specified by the property hibernate.connection.autocommit) . So we must declare the transaction boundary and make sure the transaction ends.

But if you only query data using hibernate API , it is okay even you do not explicitly declare the transaction boundary because of the followings:

  1. Database will typically start a new transaction automatically when the current SQL statement requires one and no transaction is explicitly started before.

  2. Session.close() will close() the underlying Connection .According to the JDBC specification , if java.sql.Connection#close() is called and there is an active transaction , the result of this active transaction depends on the JDBC vendor 's implementation. Usually , JDBC driver will automatically commit or rollback this transaction . But in this case, it doesn't matter whether the transaction commits or rollbacks because you have already get the data you want.

like image 73
Ken Chan Avatar answered Jan 04 '23 16:01

Ken Chan