HIbernate transaction concurrency pessimistic locking && optimistic locking

Transaction concurrency problems

1. dirty read (dirty read): a read transaction to another uncommitted transaction
2. The non-repeatable read (non-repeatable read): a transaction data in the same line is read twice, but this data is not read twice Like
3. magic reading (phantom read): a transaction query twice, but the second query than the first query has more or fewer lines or columns of data

There are four transaction isolation levels:
1 - the Read-Uncommitted
2 - the Read-committed
4 - Repeatable the Read
8- Serializable
in order to solve the problem using the second level of the general isolation method under consideration of efficiency. But it can not solve the non-repeatable read, but can be used to solve the optimistic and pessimistic locking in hibernate species.

Pessimistic locking

Pessimistic locking assumes that the current transaction will be simultaneously accessed by other transactions, to avoid the operation of the current transaction is disturbed to lock resources.
It is a lock database use. In the method of load types is provided such that LockMode.UPCRADE ddl for update statement to add later.

@Test
	public void testPessimisticLock() {
		Session session = sf.openSession();
		session.beginTransaction();
		
		Account a = (Account)session.load(Account.class, 1, LockMode.UPGRADE);
		int balance = a.getBalance();
		//do some caculation
		balance = balance - 10;
		a.setBalance(balance);
		session.getTransaction().commit();
		session.close();
	}

Optimistic locking

Optimistic locking assumes that the current transaction will not do other things simultaneously access, when access to other transactions re-use program logic to solve.
The current transaction plus the Version field, when the end of the transaction, version 1. contrast value plus the value of the start and commit time, not as an error. In the process of adding @Version Version hosts to above. `

private int version;
	@Version
	public int getVersion() {
		return version;
	}

Test

@Test
	public void testOptimisticLock() {
		Session session = sf.openSession();

		Session session2 = sf.openSession();

		
		
		
		session.beginTransaction();
		Account a1 = (Account) session.load(Account.class, 1);
		

		session2.beginTransaction();
		Account a2 = (Account) session2.load(Account.class, 1);
		
		a1.setBalance(900);
		a2.setBalance(1100);

		session.getTransaction().commit();
		System.out.println(a1.getVersion());

		session2.getTransaction().commit();
		System.out.println(a2.getVersion());

		session.close();
		session2.close();
	}

The results will session2.getTransaction () commit (); if a fault occurs.

发布了47 篇原创文章 · 获赞 5 · 访问量 2049

Guess you like

Origin blog.csdn.net/OVO_LQ_Start/article/details/104120344