Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select entities by calling a stored procedure with Spring Data

Let's say I have a MySQL stored procedure that contains the following select:

select * from users;

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();
}
like image 618
tzortzik Avatar asked Sep 28 '22 18:09

tzortzik


1 Answers

Let's say this is your procedure:

CREATE PROCEDURE get_users()
BEGIN
    SELECT * FROM USERS;
END

You define a @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();
like image 109
Vlad Mihalcea Avatar answered Oct 18 '22 10:10

Vlad Mihalcea