简体   繁体   中英

Getting select statement results from a stored procedure using JPA?

Using JPA, I'm calling a MS SQL Server 2008 R2 stored procedure that looks like this

procedure [dbo].[testProc]
    @param1 varchar(max),
    @param2 datetime
as
begin
EXEC sessionProc

DECLARE @reportData varbinary(max)

EXEC aThirdPartyProc
     @reportData out,
     @parameter1 = @param1,
     @date = @param2

SELECT col1, col2
FROM fFunction(@reportData)

end

When trying to get the results from the select statement

StoredProcedureQuery q = em.createNamedStoredProcedureQuery("reportData");
q.setParameter("param1", "val1");
q.setParameter("param2", new Date());
return (List<ReportData>) q.getResultList();

I get

java.lang.IllegalStateException: Current CallableStatement ou was not a ResultSet, but getResultList was called
    at org.hibernate.jpa.internal.StoredProcedureQueryImpl.getResultList(StoredProcedureQueryImpl.java:319)

How can I get the select statement results?

Note: The JPA code works if I reduce testProc to a simple select (remove the two EXEC statements).

Also, here's the ReportData entity class:

@Entity
@NamedStoredProcedureQuery(name = "reportData", procedureName = "testProc", resultClasses = ReportData.class, parameters = {
        @StoredProcedureParameter(mode = ParameterMode.IN, name = "param1", type = String.class),
        @StoredProcedureParameter(mode = ParameterMode.IN, name = "param2", type = Date.class)
          })
public class ReportData {
    @Id
    private String col1;
    private String col2;
    // getter and setter for col1 and col2
}

I've tested the proc in SQL Server Management Studio and it works fine returning results from the select statement.

Feedback from multiple queries within SPs throw JPA off unless SET NOCOUNT ON; is used.

Insert SET NOCOUNT ON; after BEGIN in your SP.

Using SET NOCOUNT ON is a general best practice .

Introduce a parameter with mode = ParameterMode.REF_CURSOR and let your stored procedure return refcursor.

and then use

q.execute();
return (List<ReportData>) q.getResultList();

See here section Stored procedures with REF_CURSOR

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM