public class TransactionTemplate extends Object
负责管理事务的生命周期:开启、提交、回滚、恢复自动提交。
事务内的 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(...));
});
| Constructor and Description |
|---|
TransactionTemplate(DataSource dataSource)
构造一个
TransactionTemplate 实例 |
| Modifier and Type | Method and Description |
|---|---|
<E extends Exception> |
commitIfTrue(ThrowingPredicate<JdbcOperations,E> operations)
执行事务。
|
<E extends Exception> |
execute(ThrowingConsumer<JdbcOperations,E> operations)
执行事务。
|
public TransactionTemplate(DataSource dataSource)
TransactionTemplate 实例dataSource - 数据源,用于获取数据库连接;不可为 nullpublic <E extends Exception> void execute(@Nonnull ThrowingConsumer<JdbcOperations,E> operations) throws TransactionException, SQLException
operations 中使用 JdbcExecutor 实参进行 JDBC 操作,这些操作在一个连接中
E - 异常类型operations - 事务操作SQLException - SQL 异常TransactionException - 事务异常。事务中的异常会包装在该异常中。public <E extends Exception> void commitIfTrue(@Nonnull ThrowingPredicate<JdbcOperations,E> operations) throws SQLException, TransactionException
operations 返回 true,则提交事务;
如果抛出异常,或返回 false,则回滚事务E - 事务中的异常operations - 事务操作SQLException - 数据库异常TransactionException - 事务异常。事务中的异常会包装在该异常中。Copyright © 2026. All rights reserved.