Step 1: First Create the Stored Procedure in MySQL
Create procedure 'GetStudents' (INT student_id varchar(20))
Begin
select * from student where s_id = student_id;
End
call GetStudents('2');
Step:2 There are different way in Hibernate to call the stored procedure.
1). Native SQL - Call using createSQLQuery()
Query query = session.createQuery('CALL GetStudents(:s_id)').addEntity(Student.class).setParameter('s_id','2');
List result = query.list();
for(int i=0; i<result.size(); i++) {
Student student = result.get(i);
System.out.println(student.getName());
}
2). Call using the getNamedQuery() & Specify Sql-Query in hbm.xml files
<!--student.hbm.xml ---!>
<hibernate-mapping>
<class name="com.piyushr.student" table="student">
<id name="sid" type="java.lang.String">
<column name="s_id" />
<generator class="assigned" />
</id>
<property name="studentName" type="java.lang.String">
<column name="s_name" length=10 not-null="true" unique="true" />
</property>
</class>
<sql-query name="callStudentProcedure">
<return alias="student" class="com.piyushr.student" />
<![CDATA[CALL GetStudents(:s_id)]]>
</sql-query>
</hibernate-mapping>
Query query = session.getNamedQuery("callStudentProcedure").setParameter("s_id",'2');
List result = query.list();
for(int i=0; i<result.size(); i++) {
Student student = result.get(i);
System.out.println(student.getName());
}
Create procedure 'GetStudents' (INT student_id varchar(20))
Begin
select * from student where s_id = student_id;
End
call GetStudents('2');
Step:2 There are different way in Hibernate to call the stored procedure.
1). Native SQL - Call using createSQLQuery()
Query query = session.createQuery('CALL GetStudents(:s_id)').addEntity(Student.class).setParameter('s_id','2');
List result = query.list();
for(int i=0; i<result.size(); i++) {
Student student = result.get(i);
System.out.println(student.getName());
}
2). Call using the getNamedQuery() & Specify Sql-Query in hbm.xml files
<!--student.hbm.xml ---!>
<hibernate-mapping>
<class name="com.piyushr.student" table="student">
<id name="sid" type="java.lang.String">
<column name="s_id" />
<generator class="assigned" />
</id>
<property name="studentName" type="java.lang.String">
<column name="s_name" length=10 not-null="true" unique="true" />
</property>
</class>
<sql-query name="callStudentProcedure">
<return alias="student" class="com.piyushr.student" />
<![CDATA[CALL GetStudents(:s_id)]]>
</sql-query>
</hibernate-mapping>
Query query = session.getNamedQuery("callStudentProcedure").setParameter("s_id",'2');
List result = query.list();
for(int i=0; i<result.size(); i++) {
Student student = result.get(i);
System.out.println(student.getName());
}
No comments:
Post a Comment