我有一种情况,数据在事务中有并发性。
例子:
用户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;
}
我还需要应用悲观锁定吗?
也许有人可以帮助我,防止交易中的并发性?
提前谢谢你。