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?
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:
Database will typically start a new transaction automatically when the current SQL statement requires one and no transaction is explicitly started before.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With