Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate and transactions and table locking

Tags:

java

hibernate

If I have code that looks like the following:

beginTransaction();
// lots of stuff happens, can take anywhere from a minute to several minutes.
// it will read from several tables via calling getter methods on lazy relationships.
commitTransaction();

In between the begin and commit, are the tables that are being read from being locked and subsequently will this cause problems in a multi-user environment where issues will occur when the same code above is called by another user?

If the above is problematic, should we always try and keep transactions short? and to facilitate this, instead of calling getter methods on lazy relationships, does that mean its best to keep the transactions short and do finds manually for the children of the parents?

like image 905
digiarnie Avatar asked Dec 04 '10 00:12

digiarnie


People also ask

Does Hibernate lock table during transaction?

Hibernate does not lock objects in memory. Your application can expect the behavior as defined by the isolation level of your database transactions.

Does spring @transactional lock table?

"@Transactional" as itself on any isolation level doesn't enabling any locking. To achieve locking behaviour you should use "@Lock" annotation or use " for update" in your query.

What is transactional locking?

Once Transaction lock in enabled, all transactions before the set date cannot be Edited or Deleted. Addition of new transactions are also restricted before the set date.

Does a transaction lock the table SQL Server?

Locks are held on SQL Server resources, such as rows read or modified during a transaction, to prevent concurrent use of resources by different transactions. For example, if an exclusive (X) lock is held on a row within a table by a transaction, no other transaction can modify that row until the lock is released.


1 Answers

Hibernate is not going to do anything to explicitly lock tables you read from. The answer really depends on what Database you're using and what your isolation levels are set to. Locking an entire table by reading rows shouldn't happen in any full featured database written in this century. For any multiversioning database, nothing is going to get locked unless you explicitly lock the row yourself.

Your transactions should be whatever length they need to be for your atomic unit of work. There's no right or wrong length. Ask yourself "does everything that happens here succeed or fail as a single unit and all get rolledback together if any one piece fails?" That's the scope you set a transaction for.

Remember, you do not need a transaction to have lazy loading! You just need an open Session. The two are not linked. You can commit your transaction and keep your session open to keep lazy loading working.

like image 98
Affe Avatar answered Sep 28 '22 00:09

Affe