如何通过使用Spring Data调用存储过程来选择实体 [英] How to select entities by calling a stored procedure with Spring Data
本文介绍了如何通过使用Spring Data调用存储过程来选择实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有一个包含以下选择的MySQL存储过程:
Let's say I have a MySQL stored procedure that contains the following select:
select * from users;
如何在JpaRepository
中使用@Procedure
批注,以便获得结果?像这样:
How to use the @Procedure
annotation in a JpaRepository
so that I can get the results? Something like:
public UserRepository extenda JpaRepository<User, Long>{
@Procedure('get_users')
List<User> getUsers();
}
推荐答案
让我们说这是您的过程:
Let's say this is your procedure:
CREATE OR REPLACE PROCEDURE get_users(data out SYS_REFCURSOR)
AS
BEGIN
OPEN data FOR SELECT * FROM USERS;
END;
您定义@NamedStoredProcedureQuery
:
@NamedStoredProcedureQuery(
name="getUsers",
procedureName="get_users",
resultClass=User.class, parameters={
@StoredProcedureParameter(queryParameter="data", name="data", direction=Direction.OUT_CURSOR)
}
)
@Entity
public class User {
...
}
然后您可以像这样调用过程:
And then you can call your procedure like this:
public UserRepository extends JpaRepository<User, Long>{
@Procedure('User.getUsers')
List<User> getUsers();
}
您还可以使用EntityManager对此进行检查,如下所示:
You can also check this using your EntityManager like this:
Query query = entitymanager.createNamedQuery("getUsers");
List users = query.getResultList();
这篇关于如何通过使用Spring Data调用存储过程来选择实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文