在JPA中实现离线悲观锁

JPA规范并没有涉及悲观锁,如有需要,可以参考下面代码实现:

[b]在数据库中准备一张lock表[/b]
,[b]用户通过页面锁定某个entity时[/b]

java app向lock表插入一条记录,包含该entity实例的标识(如主键),该entity类型的标识(比如表的名字或实体Bean对应的java类的全路径名),锁定时间等。

如果java app发现lock表中已经存在相关记录,java app要判断其是否已经超时,如果已经超时,则更新锁定时间,锁定成功,如果未超时则返回锁定失败。


[b]用户通过UI修改、删除某个锁定的entity时[/b]
java app除了修改该entity的值外,同时删除lock表中相关记录,以释放entity上的锁。


LOCKS表

DROP TABLE LOCKS;

--==============================================================
-- Table: LOCKS
--==============================================================

CREATE TABLE LOCKS
(
TB_NAME VARCHAR(500) not null,
PK_VALUE VARCHAR(40) not null,
KEYWD VARCHAR(40),
LOCKING_TIME DECIMAL(20),
TIMEOUT BIGINT,
constraint "P_KEY_1" primary key (TB_NAME, PK_VALUE)
);


@Stateless
public class CommonDaoBean implements CommonDaoLocal, CommonDaoRemote {
@PersistenceContext
EntityManager em;

/**
* lock an entity using key
*/
public boolean lock(Employ emp, String key, long timeOutInMilli) {
LocksId id = new LocksId(Employ.class.getCanonicalName(),""+emp.getPk());
Locks lock = new Locks(id,key,System.currentTimeMillis(),timeOutInMilli);

// 查询该entity是否已经被锁定
Locks currLock = em.find(Locks.class, id);
if(currLock == null){
em.persist(lock);
em.flush();// 'flush' must be called
return true;

}else{
// 判断现有锁是否已经超时
boolean currLockDead = System.currentTimeMillis() > (currLock.getLockingTime() + currLock.getTimeout());
if(currLockDead){
currLock.setLockingTime(System.currentTimeMillis());
em.merge(currLock);
em.flush();
return true;
}else{
return false;
}
}
}

/**
* update entity using a key, then release lock
*/
public void update(Employ emp, String key) {
LocksId id = new LocksId(Employ.class.getCanonicalName(),""+emp.getPk());
Locks currLock = em.find(Locks.class, id);

if(currLock == null){
throw new PessimisticLockingException("Entity not locked, entity:"+emp);
}

if(!currLock.getKeywd().equals(key)){
throw new PessimisticLockingException("Key '"+key+"' cannot open the lock on entity:"+emp);
}
em.merge(emp);
em.remove(currLock);
em.flush();

}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值