I have been reading for a while regarding Hibernate but I can’t seem to understand one concept regarding Transaction.
On some sites that I have visit, Select statements are in transaction mode like this.
public List<Book> readAll() {
Session session = HibernateUtil.getSessionFactory()
.getCurrentSession();
session.beginTransaction();
List<Book> booksList = session.createQuery("from Book").list();
session.getTransaction().commit();
return booksList;
}
While on some site, it does not advocate the use of transaction on Select statements:
public List<Book> readAll() {
Session session = HibernateUtil.getSessionFactory()
.getCurrentSession();
List<Book> booksList = session.createQuery("from Book").list();
return booksList;
}
I am thinking which one should I follow. Are transactions needed on Select Statements or not?
It depends on the use case.
In a typical CRUD style web application a common entity configuration is to use versioning and optimistic locking. (hibernate annotation docs) If the application is using optimistic locking, dirty reads are probably not that important, and there is no need to put the select in a transaction.
When dirty reads are not acceptable, then a transaction for the select is appropriate. Most of the time, with that kind of scenario, the select will be done in conjunction with some data modification that requires full consistency for a point in time.