Entering a Select statement in a Hibernate transaction

I read about Hibernate for a while, but I cannot understand one concept regarding Transaction .

On some sites I visited, 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 protect the use of a transaction in Select statements:

 public List<Book> readAll() { Session session = HibernateUtil.getSessionFactory() .getCurrentSession(); List<Book> booksList = session.createQuery("from Book").list(); return booksList; } 

I think with whom I should follow. Are transactions necessary for Select Statements or not?

+4
source share
4 answers

It depends on the use case.

In a typical CRUD style web application, the general configuration of entities is using version control and optimistic locking. (hibernate annotation docs) If the application uses optimistic locking, dirty reads are probably not that important, and there is no need to put the selection in a transaction.

If dirty reads are unacceptable, then suitable for selection. In most cases, in such a scenario, the choice will be made in combination with some modification of the data, which requires complete consistency at a certain point in time.

+7
source

session.getTransaction().commit() used to save your changes to the database, use it if you changed the database, for example, insert or update

+3
source

You have the choice to use the transaction here just as you can get the same result.

If you do not make some changes to the data, you do not need a transaction. some would like to have a transaction whenever they interact with the database, but this is just an agreement. In this case, you can use the read-only transaction using session.setFlushMode(FlushMode.NEVER);

You are also better off using

session.createCriteria (Book.class) .list ();

Like any refactoring will automatically change the request.

+1
source

As far as I remember, hibernate requires a transaction for everything. Try to run it without a transaction and see if it works.

I used it with spring and JPA recently, and if I forget to open a transaction (by annotation), a read-only transaction will start. But it can be spring specific.

0
source

Source: https://habr.com/ru/post/1334035/


All Articles