Monday, August 3, 2015

Calling Stored procedure In Hibernate

Calling Stored procedure In Hibernate

You can easily call stored procedure in Hibernate.

Create Mapping file as usual and then in the main Hibernate Code Call the Stores procedure with the help of createSQLQuery of Hibernate Query.

import org.hibernate.Query;
import org.hibernate.SessionFactory; 
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.classic.Session;
public class HibernateTesting {

public static void main(String[] args) { 
// TODO Auto-generated method stub 

   Configuration cfg = new Configuration(); 
          cfg.configure();
          SessionFactory sfactory=cfg.buildSessionFactory();
          Session session=sfactory.openSession();
           Transaction trans=session.beginTransaction();
           System.out.println("before calling stored procedure"); 
       
         System.out.println("6");   
         Employee e=new Employee();
       
        //Query query=session.createSQLQuery("call procedure1(10)");
         
         Query query=session.createSQLQuery("call procedure1(:a)").setParameter("a", "10");
        
         //query.list();
         query.executeUpdate();
         
        System.out.println("after calling stored procedure");
        
        
        e.setEid(5657);
        e.setName("rdinesh");
        
        session.persist(e);
        
        System.out.println("Rec Saved");
   trans.commit();
   session.close();
}
}