5

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();
}
Cœur
  • 37,241
  • 25
  • 195
  • 267
tzortzik
  • 4,993
  • 9
  • 57
  • 88

1 Answers1

3

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();
Vlad Mihalcea
  • 142,745
  • 71
  • 566
  • 911
  • Can't I do something similar in the Repository? – tzortzik Jun 01 '15 at 21:51
  • It will definitely work. I was searching for a way to put it in the repository because everything I have related to database transactions is there – tzortzik Jun 02 '15 at 04:35
  • Hello again, I tried the solution you proposed and I keep encountering different issues. I tried the last 8 hours to find why this is not working and I hope you may help me. I opened another topic here. http://stackoverflow.com/questions/31097667/illegalargumentexception-type-cannot-be-null – tzortzik Jun 28 '15 at 16:38
  • As usual, your solution doesn't work at all – Alex Feb 04 '22 at 05:27