简体   繁体   中英

How to get the execution result from SQL Server stored procedure using Hibernate?

I need to get the result of stored procedure execution assuming that I'm using exactly this interface: org.hibernate.SQLQuery.

Currently the code looks like that:

SQLQuery query = s.createSQLQuery("exec myProc :list, :out);                                
query.setString("list", list);
query.setInteger("out", out);
try {
    query.executeUpdate();
} catch (HibernateException e) { ... }

If I'll change it to this: - will it work?

 SQLQuery query = s.createSQLQuery("DECLARE @totalRes INT ; exec myProc
 :list, @myInnerParam=@totalRes OUTPUT; select @totalRes");

 query.setString("list", list);query.setInteger("out", out); try {
     Object result = query.uniqueResult(); } catch (HibernateException e) { ... }

Here is an example of a stored procedure from Hibernate.

I haven't used all the techniques suggested here, but I usually use the NamedQuery Approach

Stored procedure: (this will change depending on the underlying database)

ALTER PROCEDURE [dbo].[CL_ServiceHoursImport]
    @orderId int = 0  
AS
   select Id, Name from OrderProducts where OrderId = @orderId;

Defining Named Query : (there are different ways you can define it)

<sql-query name="myProcNamedQuery">
<return alias="output" class="com.stackoverflow.StoredProcedureOutput"/>
<![CDATA[exec GetStocks :orderId]]>
</sql-query>

Output class

public class StoredProcedureOutput{
     private int Id;
     private String Name;

     @Override 
      public String toString(){
         return Id + " " + Name + "\n";
      }

    //  getter setters
}

Calling the NamedQuery : (taken from the example in the blog post)

Query query = session.getNamedQuery("myProcNamedQuery")
    .setParameter("orderId", orderId);

for(int i=0; i<result.size(); i++){
    StoredProcedureOutput output = (StoredProcedureOutput)result.get(i);
    System.out.println(output);
}

Updates

Using NamedQuery is just a personal choice.

I would suggest the method which best suits the project you are working on.

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