AFF
AFF

Reputation: 1575

how to call a sql server function from hibernate with return parameter?

I have a function in SQL server and I want to call it from hibernate. I have tested these 2 methods but no one was successful. First method:

Session sixSession=HibernateUtil.getSessionFactory().openSession();
Query q2=sixSession.createQuery("from dbo.old_remaining(?)").setParameter("paymentVcode", p_Vcode);
        q2.getNamedParameters();
        List list=sixSession.getNamedQuery("{dbo.old_remaining(?)}").setString(1,"p_Vcode").list();

dbo.old_remaining is my function and p_Vcode is an int

the error is:

unexpected token: ( near line 1, column 23 [from dbo.old_remaining(?)]

Second method:

Float var;
List li=session.getNamedQuery("{dbo.old_remaining(?)}")  
    .setString(1, var).list();

The error is: org.hibernate.MappingException: Named query not known: {dbo.old_remaining(?)}

Please Help me...

Upvotes: 1

Views: 6896

Answers (2)

Snake Eye
Snake Eye

Reputation: 535

try following code

session.doWork(new Work() {
    public void execute(Connection conn) throws SQLException {
        PreparedStatement pstmt = conn.prepareStatement("SELECT dbo.old_remaining(?)");
        pstmt.setString(1,p_Vcode);
        ResultSet rs = pstmt.executeQuery();
        while( rs.next() )
        System.out.println( rs.getFloat(1) ) ;
    }
});

Upvotes: 0

alexey28
alexey28

Reputation: 5230

Can propose one work around based on CallableStatement. This standard jdbc statement to call functions:

session.doWork(new Work() {
    public void execute(Connection connection) throws SQLException {
        CallableStatement callable = connection.prepareCall("{? = call dbo.old_remaining(?)}");
        callable.registerOutParameter( 1, Types.FLOAT );
        callable.setString(2, "your string parameter");
        callable.execute();
        float functionResult = callable.getFloat(1);
    }
});

Upvotes: 1

Related Questions