eclipselink mysql_EclipseLink JPA MySQL防止事务并发

我有一种情况,数据在事务中有并发性。

例子:

用户1使用第1项数量3和第2项数量5创建事务处理1。

用户2使用第1项数量6和第2项数量7创建事务处理2。

每件商品都有自己的余额(比如进仓、出仓)。

如果事务1和事务2在FrutsUn用户同时运行,则如何防止从项目1和项目2平衡项的正确性?

由于覆盖,项1的余额应为9(3+6),而不是3或6。

项目2的余额应为12(5+7)。

我在冷饮方面有经验。当我使用函数cftransaction时,每个sql查询都将锁定数据和表(不是所有表,仅在cftransaction中),直到调用commit或rollback(如果我误解了,请更正我)。

到目前为止,我申请的是:

在persistence.xml中

value="com.sft.FlexiSessionCustomizer" />

在Java文件中:

public class FlexiSessionCustomizer implements SessionCustomizer {

@Override

public void customize(Session session) throws Exception {

DatabaseLogin databaseLogin = (DatabaseLogin) session

.getDatasourceLogin();

databaseLogin

.setTransactionIsolation(DatabaseLogin.TRANSACTION_SERIALIZABLE);

}

}

insert方法(纯插入数据库):

public boolean insertDataBean(Object data) {

if (data == null) {

logger.error("Data is not valid.");

return false;

}

boolean result = true;

EntityManager em = this.createEntityManager();

data.setCreatedDate(new Timestamp((new Date()).getTime()));

EntityTransaction entr = em.getTransaction();

try {

entr.begin();

em.persist(data);

entr.commit();

} catch (Exception e) {

logger.error("ERROR INSERT : " + data.getClass().getName() + " | "

+ e.getMessage());

result = false;

}

em.close();

return result;

}

调用insert方法:

insertDataBean(transaction1); // from user 1

insertDataBean(transaction2); // from user 2

这足以防止并发吗?

我想,也许,我应该更改插入代码如下:

public boolean insertDataBean(Object data) {

if (data == null) {

logger.error("Data is not valid.");

return false;

}

boolean result = true;

EntityManager em = this.createEntityManager();

data.setCreatedDate(new Timestamp((new Date()).getTime()));

EntityTransaction entr = em.getTransaction();

try {

entr.begin();

// all code, like read item balance and calculation item balance?

// should query use the same entity manager (em) or new entity manager will be the same?

em.persist(data);

// Other code transaction

entr.commit();

} catch (Exception e) {

logger.error("ERROR INSERT : " + data.getClass().getName() + " | "

+ e.getMessage());

result = false;

}

em.close();

return result;

}

我还需要应用悲观锁定吗?

也许有人可以帮助我,防止交易中的并发性?

提前谢谢你。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值