我需要通过 SQL 查询数据库的函数,就像这样简单
@Query("SELECT random()")
如何实现实现此目的的 domain/repository 或 service 方法?
有多种方法可以将存储过程与 Spring Data JPA 绑定(使用 JPA 2.1)。
最简单的例子:
@Procedure("random")
Integer randomStoredProcedure();
@Repository
public class YourRepository {
private final EntityManager entityManager;
public(EntityManager entityManager) {
this.entityManager = entityManager;
}
public List<YourObject> findObjects() {
List<Object[]> columns = entityManager
.createStoredProcedureQuery("your_sql_func")
.getResultList();
return columns.stream().map(this::toYourObject).collect(Collectors.toList());
}
private YourObject toYourObject(Object[] columns) {
return new YourObject((int)columns[0], (String)columns[1]);
}
}
class YourObject {
private int number;
private String name;
public YourObject(int number, String name) {
this.number = number;
this.name = name;
}
// getters/setters or use Lombok
}
如果您的函数中有任何参数,那么您的查询应该如下所示,
List<Object[]> columns = entityManager
.createStoredProcedureQuery("your_sql_func")
.registerStoredProcedureParameter("param1Name", String.class, ParameterMode.IN)
.setParameter("param1Name", param1Value)
.getResultList();
您也可以使用本机查询,
List<Object[]> columns = entityManager
.createNativeQuery("SELECT * FROM your_sql_func(:param1Name)")
.setParameter("param1Name", param1Value)
.getResultList();