Charlessmori
Charlessmori

Reputation: 217

BeginTransaction Hibernate necessary?

Is it really necessary to start a transaction when you are going to execute only one query, without deleting or updating data?

I'm currently using Hibernate 4.1.9 with C3p0

Example,

session session = hibernateutil.getsessionfactory().opensession();
Transaction tx = session.beginTransaction();
List messages = session.createQuery("from Message m order by m.text asc").list();  
tx.commit();
session.close();

regards

Upvotes: 10

Views: 11115

Answers (1)

JB Nizet
JB Nizet

Reputation: 692181

The documentation says:

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.

(emphasis mine)

Upvotes: 8

Related Questions