Is it possible to execute SQL Server stored procedure using JPA @Query() like given below
@Query(nativeQuery = true, value = "exec [dbo].[uspGetVinorUserInfo] =:vin")
List<Object> findCommandStatusByVinOrderByCreatedTimestampDesc(@Param("vin") String vin);
It is possible since JPA 2.1 version, please read about NamedStoredProcedureQuery anotation. But it seems to me that you use some specific JPA implementation or some framework (possibly Spring Data JPA ?), because @Query
annotation is not a part of JPA specification ; so it's difficult to me to provide concrete code snippet for your case.
I am not able to find a way to use @Query to execute MS-SQL SP, but I used the below code to execute the MS-SQL Stored Procedure and it is working fine.
package com.ford.cevs.scheduler.repository;
import org.springframework.stereotype.Repository;
import javax.persistence.EntityManager;
import javax.persistence.ParameterMode;
import javax.persistence.PersistenceContext;
import javax.persistence.StoredProcedureQuery;
@Repository
public class CommandStatusRepositoryImpl implements CommandStatusRepository {
@PersistenceContext
protected EntityManager em;
@Override
public String executeCommandStatusPurge(Integer minutes) {
StoredProcedureQuery storedProcedure = em.createStoredProcedureQuery("MyProcedureName");
// set parameters
storedProcedure.registerStoredProcedureParameter("minutes", Integer.class, ParameterMode.IN);
storedProcedure.setParameter("minutes", minutes);
storedProcedure.execute();
String result = (String)storedProcedure.getSingleResult();
return result;
}
}
MS-SQL Store Procedure
ALTER PROCEDURE [dbo].[MyProcedureName] @minutes int
AS
SET nocount ON
DECLARE @Message VARCHAR(40);
SET @Message = ' Completed, '
-- <Your code> --- @minutes
SELECT @Message
The below link shows different ways: https://www.programcreek.com/java-api-examples/index.php?api=javax.persistence.StoredProcedureQuery
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.