The Hibernate docs show this example:
session = sessionFactory.openSession();
session.beginTransaction();
List result = session.createQuery( \"from Event\" )
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.