springboot 主动提交pg存过
时间: 2023-07-17 16:59:22 浏览: 62
在 Spring Boot 中执行 PostgreSQL 存储过程并主动提交事务,可以使用 JdbcTemplate 或者 NamedParameterJdbcTemplate 来执行存储过程的调用,并在调用之后手动提交事务。下面是一个示例:
```java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
public class MyService {
private final JdbcTemplate jdbcTemplate;
@Autowired
public MyService(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
@Transactional
public void executeStoredProc() {
// 执行存储过程的调用
jdbcTemplate.execute("CALL my_stored_procedure();");
// 手动提交事务
jdbcTemplate.getDataSource().getConnection().commit();
}
}
```
在上述示例中,首先通过构造函数注入了一个 JdbcTemplate 对象。然后,使用 @Transactional 注解标记了 executeStoredProc() 方法,使其成为一个事务方法。
在 executeStoredProc() 方法中,通过 jdbcTemplate.execute() 方法执行了存储过程的调用。然后,通过 jdbcTemplate.getDataSource().getConnection().commit() 手动提交事务。
需要注意的是,在执行存储过程调用之前,必须确保当前的事务已经启动。这可以通过在方法上添加 @Transactional 注解或者在调用该方法的上层方法中定义事务来实现。
另外,你需要根据实际情况修改代码中的 "my_stored_procedure()" 为你要执行的存储过程的名称。
这样,当调用 executeStoredProc() 方法时,会执行存储过程的调用,并在调用之后手动提交事务。