【发布时间】:2017-05-11 08:52:46
【问题描述】:
我想知道是否可以使用具有结果集和多个输出参数的 Spring Data JPA 调用存储过程。
我发现同一 https://github.com/spring-projects/spring-data-examples/issues/80 的 Git 问题
如果解决了,有人可以提供一个 Spring Boot 的例子吗?
【问题讨论】:
标签: spring jpa stored-procedures
我想知道是否可以使用具有结果集和多个输出参数的 Spring Data JPA 调用存储过程。
我发现同一 https://github.com/spring-projects/spring-data-examples/issues/80 的 Git 问题
如果解决了,有人可以提供一个 Spring Boot 的例子吗?
【问题讨论】:
标签: spring jpa stored-procedures
我过去实现此目的的方法是将自定义行为添加到 Spring Data JPA 存储库 (link)。在里面我得到 EntityManager 并使用 java.sql.Connection 和 CallableStatement
编辑:添加高级示例代码。 Sample假设您正在使用Hibernate,但想法也应该适用于其他人
假设你有一个 EntityRepository
public interface EntityRepositoryCustom {
Result storedProcCall(Input input);
}
public class EntityRepositoryImpl implements EntityRepositoryCustom {
@PersistenceContext
private EntityManager em;
@Override
public Result storedProcCall(Input input) {
final Result result = new Result();
Session session = getSession();
// instead of anonymous class you could move this out to a private static class that implement org.hibernate.jdbc.Work
session.doWork(new Work() {
@Override
public void execute(Connection connection) throws SQLException {
CallableStatement cs = null;
try {
cs = connection.prepareCall("{call some_stored_proc(?, ?, ?, ?)}");
cs.setString(1, "");
cs.setString(2, "");
cs.registerOutParameter(3, Types.VARCHAR);
cs.registerOutParameter(4, Types.VARCHAR);
cs.execute();
// get value from output params and set fields on return object
result.setSomeField1(cs.getString(3));
result.setSomeField2(cs.getString(4));
cs.close();
} finally {
// close cs
}
}
});
return result;
}
private Session getSession() {
// get session from entitymanager. Assuming hibernate
return em.unwrap(org.hibernate.Session.class);
}
}
【讨论】: