简体   繁体   English

在Java中使用mysql回滚事务

[英]roll back transaction using mysql in java

I am inserting data into three table ie 我将数据插入三个表即

Transaction
TransactionEntry
Payment

First I insert the data in Transaction , and then get Transaction ID and then insert data in TransactionEntry , after this inserting in Payment 首先,我将数据插入Transaction中 ,然后获取Transaction ID ,然后在Payment中插入数据之后,将数据插入TransactionEntry中。

Suppose in first two table, data inserted successfully. 假设在前两个表中,数据已成功插入。 Then Server breakdown. 然后服务器崩溃。

How can we Roll Back all the entries? 我们如何回滚所有条目? can we control it programmatically or database has default feature to control this type of situation? 我们可以通过编程方式控制它还是数据库具有默认功能来控制这种情况?

How to achieve consistency and integrity? 如何实现一致性和完整性?

Which framwork, In java , can control this type of situation? 在Java中,哪个框架可以控制这种情况?

MySQL Java EE MySQL Java EE

mysql supports transactions the normal way. mysql以常规方式支持事务。 Open transaction at the beginning and commit at the end, if something happens in the middle nothing will be posted. 在开始时打开事务,在结束时提交,如果中间发生任何事情,则不会过帐。

Since you are using Java EE you have to investigate whether your java mysql client proposes or not built in statements. 由于您使用的是Java EE,因此必须调查Java mysql客户端是否建议内置语句。 If not, use 如果没有,请使用

SET AUTOCOMMIT=0;

... statements ...

COMMIT;

You need to disable autocommit and commit after your unit of work is done (or rollback when it failed). 您需要在工作单元完成后禁用自动提交和提交(或在失败时回滚)。

This should be something like: 这应该是这样的:

Connection con = ...; //set earlier
con.setAutoCommit(false);
...
try {
  //insert here
  ...
  con.commit();
} catch (Exception e) {
  con.rollback();
  // other exception handling
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM