Package xyz.zhouxy.jdbc
Class TransactionTemplate
java.lang.Object
xyz.zhouxy.jdbc.TransactionTemplate
事务模板,提供事务执行能力。
负责管理事务的生命周期:开启、提交、回滚、恢复自动提交。
事务内的 JDBC 操作通过 JdbcOperations 接口进行,
所有操作共享同一个数据库连接。
使用示例:
TransactionTemplate tx = new TransactionTemplate(dataSource);
// 消费者模式:无异常自动提交
tx.execute(ops -> {
ops.update("INSERT INTO ...", buildParams(...));
ops.update("UPDATE ...", buildParams(...));
});
// 谓词模式:返回 true 提交,false 回滚
tx.commitIfTrue(ops -> {
ops.update("UPDATE ...", buildParams(...));
return ops.queryBoolean("SELECT ...", buildParams(...));
});
- Since:
- 1.1.0
- Author:
- ZhouXY
-
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescription<E extends Exception>
voidcommitIfTrue(xyz.zhouxy.plusone.commons.function.ThrowingPredicate<JdbcOperations, E> operations) 执行事务。<E extends Exception>
voidexecute(xyz.zhouxy.plusone.commons.function.ThrowingConsumer<JdbcOperations, E> operations) 执行事务。
-
Constructor Details
-
TransactionTemplate
-
-
Method Details
-
execute
public <E extends Exception> void execute(@Nonnull xyz.zhouxy.plusone.commons.function.ThrowingConsumer<JdbcOperations, E> operations) throws TransactionException, SQLException执行事务。如果未发生异常,则提交事务;当有异常发生时,回滚事务operations 中使用 JdbcExecutor 实参进行 JDBC 操作,这些操作在一个连接中
- Type Parameters:
E- 异常类型- Parameters:
operations- 事务操作- Throws:
SQLException- SQL 异常TransactionException- 事务异常。事务中的异常会包装在该异常中。
-
commitIfTrue
public <E extends Exception> void commitIfTrue(@Nonnull xyz.zhouxy.plusone.commons.function.ThrowingPredicate<JdbcOperations, E> operations) throws SQLException, TransactionException执行事务。 如果operations返回true,则提交事务; 如果抛出异常,或返回false,则回滚事务- Type Parameters:
E- 事务中的异常- Parameters:
operations- 事务操作- Throws:
SQLException- 数据库异常TransactionException- 事务异常。事务中的异常会包装在该异常中。
-