How to select entities by calling stored procedure using Spring data
Let's say I have a MySQL stored procedure that contains the following selection:
select * from users;
How do I use annotation @Procedure
in JpaRepository
so I can get the results? Something like:
public UserRepository extenda JpaRepository<User, Long>{
@Procedure('get_users')
List<User> getUsers();
}
+3
source to share
1 answer
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;
You define @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();
}
You can also check this using your EntityManager like this:
Query query = entitymanager.createNamedQuery("getUsers");
List users = query.getResultList();
+3
source to share