How are the Spring @Transactional and the Hibernate @LockMode annotations related

后端 未结 2 1873
深忆病人
深忆病人 2021-01-31 04:56

I wish to know the relation between transactions and locks.

To be more specific, how is Spring\'s @Transactional related to Hibernate\'s LockMode. https://d

2条回答
  •  Happy的楠姐
    2021-01-31 05:49

    Spring's @Transactional and Hibernate's LockMode class are different.

    Spring Transaction Management

    @Transactional is a Spring annotation for declarative transaction management, i.e. defining what SQL statements are executed together inside of a database transaction. Using the readOnly attribute allows Spring to throw an exception if you attempt to insert rows inside of a read-only transaction, for example.

    With respect to locking, however, you'll most likely be using a read/write (readOnly = false) transaction, because you'll be attempting to modify data.

    Pessimistic Locking

    Hibernate's LockMode is used for pessimistic locking, e.g. LockMode.UPGRADE actually executes a SELECT...FOR UPDATE statement, and locks the row in the database corresponding to the entity.

    Pessimistic locking assumes that concurrent transactions will conflict with each other, and requires resources to be locked after they are read and only unlocked after the application has finished using the data.

    Optimistic Locking

    Optimistic concurrency control in Hibernate typically uses a version or timestamp column in the database. The idea here is that if multiple transactions attempt to modify a row concurrently, all but the first committed transaction will detect that the version number has changed and perform a rollback.

    Optimistic locking assumes that multiple transactions can complete without affecting each other, and that therefore transactions can proceed without locking the data resources that they affect. Before committing, each transaction verifies that no other transaction has modified its data. If the check reveals conflicting modifications, the committing transaction rolls back.

    Quotes above are from: https://docs.jboss.org/hibernate/orm/4.0/devguide/en-US/html/ch05.html

提交回复
热议问题