2

I am unable to call my stored procedure from java hibernate using session factory

I have written a sql procedure which takes 5 parameters and return a result set which works fine in MS SQL studio

EXEC SlaGrid @appID=245,@fromYear=2012,@toYear=2013,@fromMon=1,@toMon=12   --- sql

EXEC SlaGrid @applID=:applID,@fromYear=:fromYear,@toYear=:toYear,@fromMon=:fromMon,@toMon=:toMon  --hibernate

i am setting the parameters for the above query

String queryString = "EXEC SlaGrid @applID=:applID,@fromYear=:fromYear,@toYear=:toYear,@fromMon=:fromMon,@toMon=:toMon"

Query query = sessionFactory.getCurrentSession().createSQLQuery(queryString);

//set query parameters here

query.list()    --- giving sql grammer exception

4 Answers 4

7

You can use callable statement on hibernate session.

Connection con = getSessionFactory().getCurrentSession().connection();  

/**
* Amend to include your parameters and proc
*/          
CallableStatement cs = con.prepareCall( "{ call myprocedure }");

cs.execute();
Sign up to request clarification or add additional context in comments.

1 Comment

Do we need to close the callablestatement? Or will session takes care of closing the callable statement.?
6

create a SessionFactory and Open a session then

CallableStatement callableStatement = session.connection().prepareCall("call GetMarketDataCDS(?,?)");
callableStatement.setString(1,"JPM");
callableStatement.registerOutParameter(1, OracleTypes.CURSOR);
callableStatement.execute();
ResultSet resultSet=(ResultSet) callableStatement.getObject(1);

here i am using oracle and my first param is IN Parameter and second is OUT which is nothing but a resultset returning multiple rows. Then in last line we get the ResultSet with all row and then you can iterate through the rows.

2 Comments

connection() method is deprecated, isn't it?
@Tony, use session.doWork(...)
3

I solved it simply by the following code...Just pass the parameters in CSV.Thanks for the help guys..

String queryString = "SlaGrid 245,2012,2013,1,12"

Query query = sessionFactory.getCurrentSession().createSQLQuery(queryString);

query.list();

Works Perfect :)

2 Comments

'query.list();' did not work for me in Hibernate 4, instead I used 'query.executeUpdate()'
Does this work independently of database type or is this MySQL specific?
0

Try this

Query query = sessionFactory.getCurrentSession().createSQLQuery(
    "CALL SlaGrid(:appID, :fromYear, :toYear, :fromMon, :toMon)")
    .setParameter("appID", 245)
    .setParameter("fromYear", 2012)
    .setParameter("toYear", 2013)
    .setParameter("fromMon", 1)
    .setParameter("toMon", 12);

1 Comment

i have tried this already ..this syntax is for mysql not mssql

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.