悲观锁的实现,通常依赖于数据库机制,在整个过程中将数据锁定,其它任何用户都不能读取或修改
1
package com.bjsxt.hibernate;2

3
import org.hibernate.LockMode;4
import org.hibernate.Session;5

6
import junit.framework.TestCase;7

8

public class PessimisticLockingTest extends TestCase
{9

10

public void testLoad1()
{11
Session session = null;12

try
{13
session = HibernateUtils.getSession();14
session.beginTransaction();15
16
Inventory inv = (Inventory)session.load(Inventory.class, 1, LockMode.UPGRADE);17
System.out.println("itemName=" + inv.getItemName());18
System.out.println("quantity=" + inv.getQuantity());19
inv.setQuantity(inv.getQuantity() - 200);20
session.update(inv);21
session.getTransaction().commit();22

}catch(Exception e)
{23
e.printStackTrace();24
session.getTransaction().rollback();25

}finally
{26
HibernateUtils.closeSession(session);27
} 28
}29
30

public void testLoad2()
{31
Session session = null;32

try
{33
session = HibernateUtils.getSession();34
session.beginTransaction();35
36
Inventory inv = (Inventory)session.load(Inventory.class, 1, LockMode.UPGRADE);37
System.out.println("itemName=" + inv.getItemName());38
System.out.println("quantity=" + inv.getQuantity());39
inv.setQuantity(inv.getQuantity() - 200);40
session.update(inv);41
session.getTransaction().commit();42

}catch(Exception e)
{43
e.printStackTrace();44
session.getTransaction().rollback();45

}finally
{46
HibernateUtils.closeSession(session);47
} 48
}49
50
}51

posted on
浙公网安备 33010602011771号