How will you call a stored procedure in Hibernate?

Hibernate supports executing not only simple queries but also stored procedure of database. There are three ways to call a stored procedure in Hibernate:

  • XML mapping file:
    We can declare the store procedure inside XML Mapping file.


We can call it with getNamedQuery().

Query query = session.getNamedQuery(“callEmployeeStoreProcedure”)
.setParameter(“employeeId”, “1234”);
List result = query.list();
for(int i=0; i<result.size(); i++){
Employee employee = (Employee)result.get(i);
System.out.println(employee.getEmployeeCode());
}

  • Native SQL: We can use Native SQL to call a store procedure query directly. In this example GetEmployees() stored procedure is being called.

Query query = session.createSQLQuery(
“CALL GetEmployees(:employeeId)”)
.addEntity(Employee.class)
.setParameter(“employeeId”, “1234);

List result = query.list();
for(int i=0; i<result.size(); i++){
Employee employee = (Employee) result.get(i);
System.out.println(employee.getEmployeeCode());
}

  • Use annotation:
    We can also mark out stored procedure with @NamedNativeQueries annotation.

//Employee.java

@NamedNativeQueries({
@NamedNativeQuery(
name = “callEmployeeStoreProcedure”,
query = “CALL GetEmployees(:employeeId)”,
resultClass = Employee.class
)
})
@Entity
@Table(name = “employee”)
public class Employee implements java.io.Serializable {

Call it with getNamedQuery().

Query query = session.getNamedQuery(“callEmployeeStoreProcedure”)
.setParameter(“employeeId”, “1234”);
List result = query.list();
for(int i=0; i<result.size(); i++){
Employee employee = (Employee)result.get(i);
System.out.println(employee.getEmployeeCode());
}

Read the full book at www.amazon.com
Posted in Hibernate, Hibernate Interview Questions

Leave a Reply

Your email address will not be published. Required fields are marked *

*