Reputation: 393
In general I have idea that select queries does not require transaction. Only the Create and Update operations require transaction. But the hibernate latest documentation example use transaction for select query. Can someone clarify the reason for this ? The code below is from the following link
http://docs.jboss.org/hibernate/orm/5.0/quickstart/html/
entityManager = entityManagerFactory.createEntityManager();
entityManager.getTransaction().begin();
List<Event> result = entityManager.createQuery( "from Event", Event.class).getResultList();
for ( Event event : result )
{
System.out.println( "Event (" + event.getDate() + ") : " + event.getTitle() );
}
entityManager.getTransaction().commit();
entityManager.close();
Upvotes: 1
Views: 819
Reputation: 844
Yes indeed it works without defining transaction boundaries and hence it may seem a bit redundant at the first glance.
The question is what can happen if you don't use transactions? In this blog post you can read up on transaction properties, isolation levels and "phenomena" that may occur while (not) using transactions. Such phenomena are "dirty read", "phantom read", "non-repeatable" read. By using transactions (and the right isolation levels) you can make sure that you don't come across these problems.
TL;DR Using transactions while querying the database has significance once multiple people/processes are using the database at the same time. (i.e. concurrency) With using transaction boundaries you are eliminating (at least some of) the problems that are introduced by concurrent database usage.
Upvotes: 2