Tuesday, 15 March 2016

How to Call Stored Procedure through Hibernate + JPA

Following code will help to call the procedure through preparecall

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Types;


import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.hibernate.Session;
import org.hibernate.engine.spi.SessionImplementor;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

public class TravelDetailsDAOImpl{
@PersistenceContext
private EntityManager entityManager;

   @Transactional
public void getTravelDetails(String place,Date date) {

Session session = entityManager.unwrap(Session.class);
SessionImplementor sessionImplementor = (SessionImplementor) session;
Connection cc = sessionImplementor.getJdbcConnectionAccess().obtainConnection();
 
 CallableStatement callableStatement = cc.prepareCall("{call stored_procedure(?,?,?,?)}");
 callableStatement.setString(1, "Mount Alps");//Parameter #1 - place
 callableStatement.setString(2, "20/02/2015");////Parameter #2 - travel date

 callableStatement.registerOutParameter(3, Types.INTEGER); //Output # 1
 callableStatement.registerOutParameter(4, Types.INTEGER); //Output # 2
 
 callableStatement.execute();

 Integer outputValue = callableStatement.getInt(3);
 Integer outputValue1 = callableStatement.getInt(4);

 }
}

No comments:

Post a Comment