Reputation: 1675
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) { ... }
Upvotes: 0
Views: 3583
Reputation: 12368
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.
Upvotes: 1