众所周知,当过多的使用存储过程,触发器等 数据库方言相关的应用时,应用程序的移植性会变差,特别是在Hibernate中使用这些,简直是讽刺,但是当今中国又有哪家公司做项目会关心应用程序的移植性呢?
现在看看Hibernate中对Oracle存储过程的调用.
1.plsql 代码
proc.plsql
create Procedure proc() begin select * from proctab; end;
1 create procedure proc1(v_no number(4)) 2 begin 3 select * from proc1 4 where id=v_no; 5 end;
2.Hibernate 存储过程调用的一种方法是,通过XML传统的映射方式去调用。
-》存储过程映射和领域模型中的实体的对应关系
xml映射文件
1 <class name="com.test.User" table="proctab"> 2 <id name="id" column="id"> 3 <generator class="native"/> 4 </id> 5 <property name="name" column="name" type="string" /> 6 <property name="age" column="age" type="integer" /> 7 </class> 8 <sql-query name="getUser" callable="true"> 9 <return alias="user" class="com.test.User"> 10 <return-property name="id" column="id" /> 11 <return-property name="name" column="name" /> 12 <return-property name="age" column="age" /> 13 </return> 14 {call proc()} 15 </sql-query>
-》Hibernate API 对存储过程的调用
Hibernate API code1 Session ss= HibernateSessionFactory.getSession() 2 List li=ss.getNamedQuery("getUser").list(); 3 ss.close(); 4 5 Session ss= HibernateSessionFactory.getSession() 6 List li=ss.getNamedQuery("getUser").list(); 7 ss.close();
-》JDBC API 对存储过程的调用
jdbc 调用1 Session session =HibernateSessionFactory.getSession(); 2 Connection conn = session.connection(); 3 ResultSet rs =null; 4 CallableStatement call = conn.prepareCall("{Call proc()}"); 5 rs = call.executeQuery(); 6 rs.close(); 7 session.close(); 8 9 Session session =HibernateSessionFactory.getSession(); 10 Connection conn = session.connection(); 11 ResultSet rs =null; 12 CallableStatement call = conn.prepareCall("{Call proc()}"); 13 rs = call.executeQuery(); 14 rs.close(); 15 session.close();
-》直接使用 Hibernate createQuerySql调用存储过程
createSqlQuery1 Session session =HibernateSessionFactory.getSession(); 2 SQLQuery query = session.createSQLQuery("{Call proc()}"); 3 List list =query.list(); 4 session.close(); 5 6 Session session =HibernateSessionFactory.getSession(); 7 SQLQuery query = session.createSQLQuery("{Call proc()}"); 8 List list =query.list(); 9 session.close();
-》通过Hibernate API或者JDBC,API给存储过程传参
传参11 CallableStatement call = conn.prepareCall("{Call proc(?)}"); 2 call.setString(1, 参数); 3 rs = call.executeQuery(); 4 5 CallableStatement call = conn.prepareCall("{Call proc(?)}"); 6 call.setString(1, 参数); 7 rs = call.executeQuery();
1 SQLQuery query = session.createSQLQuery("{Call proc(?)}"); 2 query.setString(0, 参数); 3 List list =query.list();
来源:https://www.cnblogs.com/jerryxing/archive/2012/04/28/2475762.html