How can i call stored procedure using spring with jpa

前端 未结 3 529
温柔的废话
温柔的废话 2020-12-17 04:54

Am new to SPRING with JPA techniques.

am trying to call the stored procedure which is written in mysql 5. when i am trying to get the data using stored procedure cal

相关标签:
3条回答
  • 2020-12-17 05:26

    JPA 2.1 introduced support for stored procedures. You might want to give it a try instead of a native queries.

    http://docs.oracle.com/javaee/7/api/javax/persistence/EntityManager.html#createStoredProcedureQuery%28java.lang.String%29

    0 讨论(0)
  • 2020-12-17 05:29

    Use EntityManager.createNativeQuery() instead. I don't think it's possible to call a stored procedure through a JPA query.

    public List doInJpa(EntityManager em) throws PersistenceException {
      javax.persistence.Query query=em.createNativeQuery("call st_proc_getusers()"); 
      return query.getResultList(); 
    }
    

    You could also use @NamedNativeQuery.

    0 讨论(0)
  • 2020-12-17 05:36

    Calling a stored procedure means executing some SQL statement. You can't do that with with a JPQL query (what you get in your code when you do em.createQuery(...)). You must create a native query that allows you to send native SQL to the database, execute it and get the results:

     String query = "call st_proc_getusers(?)";
     NativeQuery nq = em.createNativeQuery(query);
     //the following line is necessary only if your stored procedure accepts a parameter:
     nq.setParameter(1, "paramValue");
     List<?> results = em.createNativeQuery(query).getResultList();
    
    0 讨论(0)
提交回复
热议问题