Understanding of transactions in hibernate

Source: Internet
Author: User
1. Concepts of database transactions
A database transaction is a unit of work composed of one or more SQL statements. The SQL statements in this unit are mutually dependent. If an SQL statement fails to be executed, the whole unit of work must be revoked.
In a concurrent environment, when multiple transactions access the same data resource at the same time, various concurrency problems may occur, which can be avoided by setting the transaction isolation level of the database, pessimistic locks and optimistic locks can also be used to solve the problem of missing updates.
Database transactions must have acid features:
A: Atomic atomicity, the entire transaction is inseparable, either successful or all are revoked.
C: consistency. transactions cannot undermine the integrity of the relational data and the consistency of the business logic. For example, the transfer should ensure that the total deposits of the two accounts remain unchanged after the transaction ends.
I: Isolation isolation. When multiple transactions manipulate the same data at the same time, each transaction has its own complete data space D: Durability persistence, as long as the transaction ends successfully, database updates must be permanently saved, even if
System crash. After the database is restarted, the database can be restored to the State at the end of the successful transaction.
2. Transaction boundary Declaration
Once a transaction is declared, the database system automatically guarantees the acid feature of the transaction.

Declared transactions include:
Start boundary of a transaction
Normal transaction end boundary (COMMIT): Submit the transaction and save it permanently.
Transaction exception termination boundary (rollback): cancels the transaction, and the database rolls back to the status before the transaction is executed.

The Database supports two transaction modes:
Automatic commit mode: Each SQL statement is an independent transaction. After the database executes an SQL statement, the transaction is automatically committed.
Manual submission mode: the database customers must Program Explicitly specify the start and end boundary of the transaction

The transaction control method of JDBC connection class:
Setautocommit (Boolean autocommit) sets whether to automatically submit transactions.
Commit a transaction
Rollback () cancels a transaction
How does hibernate control transactions:
1. Call the opensession method without parameters in sessionfactory to obtain a connection from the connection pool. The session automatically sets the connection to the manual transaction commit mode.
Session session = sessionfactory. opensession ();
If you call opensession with the connection parameter, you need to set the manual submission by yourself:
Connection. setautocommit (false );
Session session = sessionfactory. opensession (connection );
2. Declare the start boundary of the transaction
Transaction Tx = session. begintransaction ();
3. Submit the transaction
TX. Commit ();
4. Cancel the transaction:
TX. rollback ();
A session can correspond to multiple transactions, but a session should be prioritized to correspond to only one transaction. When a transaction ends or is canceled, the session will be closed.
Whether the transaction is successful or not, you should call session close to close the session.
At any time, a session only allows one uncommitted transaction and cannot start two transactions at the same time.
3. Concurrent transactions
When multiple transactions run simultaneously to access the same data, five types of concurrency problems may occur:
1. Type 1 lost update: overwrite the committed update of other transactions when you cancel a transaction.
2. Dirty read: one transaction reads the uncommitted update data of another transaction.
3. Virtual read: one transaction reads the newly inserted data committed by another transaction.
4. Read-Only: one transaction reads the updated data committed by another transaction.
5. The second type of update loss: A transaction overwrites the updated data committed by another transaction and cannot be read repeatedly.

1. The first type of loss update:
Start transaction T1
Start transaction T2
T3 query deposit balance is 1000 yuan
T4 query deposit balance is 1000 yuan
T5 transfers 100 yuan, and changes the deposit balance to 1100 yuan
T6 commit transaction
T7 fetch 100 yuan and change the deposit balance to 900 yuan
T8 revokes the transaction, and the account balance is restored to 1000 yuan
2. Dirty read:
Start transaction T1
Start transaction T2
T3 query deposit balance is 1000 yuan
T4
T5 extracts 100 yuan and changes the deposit balance to 900 yuan
Account balance of T6 query is 900 RMB (dirty read)
T7 cancel the transaction, and the account balance is restored to 1000 yuan
T8 is transferred to 100 RMB, and the deposit balance is changed to 1000 RMB
T9 commit transactions
3. Virtual read:
Start transaction T1
Start transaction T2
T3 statistics the number of registrants of the website is 1000
T4 registers a new user
T5 commit transactions
T6 count the number of registrants on the website as 1000 (Virtual read)
Which of the following statistics is valid for T7?
4. Non-repeated read:
Start transaction T1
Start transaction T2
T3 query account balance is 1000 yuan
T4 query account balance is 1000 yuan
T5 took out 100 yuan, and changed the balance to 900 yuan
T6 commit transaction
T7 query account balance is 900 yuan
Is the T8 balance 1100 yuan or 900 + 100 yuan?
5. Type 2 lost updates:
Start transaction T1
Start transaction T2
T3 query account balance is 1000 yuan
T4 query account balance is 1000 yuan
T5 took out 100 yuan, and changed the balance to 900 yuan
T6 commit transaction
T7 remitted 100 yuan and changed the deposit balance to 1100 yuan
T8 commit transaction

4. database lock
The database must have the ability to isolate concurrent transactions. The database uses locks to isolate transactions.
Isolation.
The following locks are available based on the resources that can be locked by the database:
Database-Level Lock
Table-Level Lock
Level Lock
Page lock
Key-value lock: Lock a row of data with indexes in the database table
Row-Level Lock: Lock a single row record in a database table
The larger the lock granularity, the higher the isolation, and the lower the concurrency
Lock upgrade refers to adjusting the lock granularity and replacing multiple low-granularity locks with higher-granularity locks to reduce system load.
Locks can be divided:
Shared lock: used to read data. It is not exclusive. It allows other transactions to read the locked resources at the same time, but does not allow it
His transaction updates.
Lock: When a SELECT statement is executed, the database allocates a shared lock to the transaction to lock the queried data.
Unlock: release immediately after the data is read.
Compatibility: Shared locks and update locks can also be placed.
Exclusive lock:
It is also called exclusive lock, which is used to modify data. Locked resources cannot be read or modified by other transactions.
Locking condition: exclusive locks are automatically used when a transaction executes the insert update Delete statement. If other locks exist, they cannot be exclusive.
Unlock condition: the transaction can be unbound until the transaction ends.
Compatibility: it cannot be compatible with other locks and cannot be placed with any other locks.
Concurrency performance: poor. Only one transaction is allowed to access the locked data. to access other transactions, read and wait until the previous transaction ends and the exclusive lock is lifted.
Update lock:
It is used to lock resources that may be modified during the initialization phase of the update operation to avoid the use of shared locks.
Lock phenomenon.
If a shared lock is used, the data update operation is divided into two steps:
1. Obtain a shared lock and read a record
2. Upgrade the shared lock to an exclusive lock before performing the update operation.
If multiple transactions update the data at the same time, each transaction obtains a share lock first.
These transactions must first upgrade the shared lock to an exclusive lock. Because exclusive locks cannot coexist with other locks,
Therefore, every transaction enters the waiting state and waits for other transactions to release the shared lock, resulting in a deadlock.
If an update lock is used, perform the following steps to update data:
1. Obtain an update lock and read a record.
2. Upgrade the update lock to an exclusive lock before performing the update operation.
Update lock features:
Locking condition: when a transaction executes an update statement, the database first assigns an update lock to the transaction.
Unlock condition: After the data is read, the update lock is upgraded to an exclusive lock when the update operation is performed.
Compatibility: Update locks are compatible with shared locks and can be placed at the same time, but only one update lock can be put at most to ensure that only one transaction can obtain the update lock when updating data for multiple transactions, upgrade the update lock to an exclusive lock. Other transactions can obtain the update lock only after the previous transaction ends. This avoids deadlocks.
Concurrent performance: Allows multiple transactions to read the locked resources at the same time, but does not allow other transactions to modify it.
Deadlock and prevention:
A deadlock occurs when multiple transactions lock one resource and attempt to lock the resources that the other party has locked.
A lock request ring causes multiple transactions to wait for the other party to release the locked resources.
Prevention:
Arrange table access order reasonably
Use short transactions
Dirty read allowed
Staggered execution time
Use the lowest possible transaction isolation level
5. transaction isolation level
The lock mechanism can solve various concurrency problems, but it will affect the concurrency performance.
Make a reasonable balance between the isolation and concurrency of transactions. The database system provides four transaction isolation levels for users to choose from:
8 serializable
4 Repeatable read
2 read commited: Read committed data transactions, you can see the new insert records committed by other transactions, and the updates committed by other transactions to existing records.
1 read uncommited: when reading uncommitted data transactions, you can see the newly inserted records not committed by other transactions, and the updates to existing records not committed by other transactions.
The isolation level is read commited, which can avoid dirty reads and has good concurrent performance, which may lead to non-repeated reads, virtual reads, and second type loss updates, however, pessimistic or optimistic locks can be used for control.

Set the transaction isolation level in hibernate:
Hibernate. Connection. Isolation = 2 (read commited)
6. pessimistic lock and optimistic lock
Pessimistic lock: first lock the resource to prevent loss of updates and repeated read failures, but it affects concurrent performance.
Optimistic lock: automatic lock management relies entirely on the database isolation level. version control can be used to avoid concurrency issues.
Pessimistic lock implementation:
Explicitly specify an exclusive lock to lock Resources
The SELECT statement uses a shared lock by default.
Select... for update can be used to explicitly specify the exclusive lock to lock the query records
Hibernate uses lockmode to implement lock mode
2. Add a lock Field
Hibernate uses <version> and <timestamp> to implement version control.
Optimistic lock implementation:
<Class name = "" table = "" optimistic-lock = "all" dynamic-update = "true">

 

This article is transferred from www.35java.com

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.