java 开启事务管理,保证数据一致性
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
@Service
public class ICStockBillServiceImpl extends ServiceImpl<ICStockBillDao, ICStockBillEntity> implements ICStockBillService {
@Resource
private DataSource dataSource;
public void TransactionExample () {
Connection connection = null;
PreparedStatement statement = null;
try {
connection = dataSource.getConnection();
System.out.println("connection"+connection);
// 设置自动提交为false,禁用事务自动提交
connection.setAutoCommit(false);
// 创建Statement
statement = connection.createStatement();
// 执行一系列操作
statement.executeUpdate("INSERT INTO YourTable (column1) VALUES ('value1')");
statement.executeUpdate("UPDATE YourTable SET column1 = 'newValue' WHERE column1 = 'value1'");
// 提交事务
connection.commit();
System.out.println("事务成功提交!");
} catch (SQLException e) {
try {
if (connection != null) {
// 出现异常,回滚事务
connection.rollback();
}
} catch (SQLException ex) {
// 处理回滚时的异常
}
// 处理其他异常
throw new RuntimeException("Error performing transaction", e);
} finally {
// 关闭资源
try {
if (statement != null) statement.close();
if (connection != null) connection.close();
} catch (SQLException e) {
// 处理资源关闭异常
return "处理资源关闭异常";
}
}
}
}
首先加载了数据源DataSource (我这里是通过application.yml配置的。接着,关闭了自动提交事务,以便可以手动控制事务的提交或回滚。在执行SQL操作时,如果出现异常,会进行回滚。最后,在finally块中关闭了所有的资源。这是一个简单的事务管理实践,确保了在发生错误时数据的一致性。
需要注意的是:如果报错信息,没有捕获到SQLException 异常,或者报错信息并非SQLException 异常,事务回滚机制是不会触发的。所以其他的异常需要单独处理完,确保只捕获SQLException异常。
java 开启事务管理,保证数据一致性
本文2024-09-16 21:56:27发表“eas cloud知识”栏目。
本文链接:https://wenku.my7c.com/article/kingdee-eas-44900.html
- 鼎捷EAI整合規範文件V3.1.07 (集團).pdf
- 鼎捷OpenAPI應用場景說明_基礎資料.pdf
- 鼎捷OpenAPI應用場景說明_財務管理.pdf
- 鼎捷T100 API設計器使用手冊T100 APIDesigner(V1.0).docx
- 鼎新e-GoB2雲端ERP B2 線上課程E6-2應付票據整批郵寄 領取.pdf
- 鼎新e-GoB2雲端ERP B2 線上課程A4使用者建立權限設定.pdf
- 鼎新e-GoB2雲端ERP B2 線上課程C3會計開帳與會計傳票.pdf
- 鼎新e-GoB2雲端ERP B2 線上課程E6-1應付票據.pdf
- 鼎新e-GoB2雲端ERP B2 線上課程A5-1進銷存參數設定(初階篇).pdf
- 鼎新e-GoB2雲端ERP B2 線上課程D2帳款開帳與票據開帳.pdf