下边是简单的Hibernate存储过程
Java代码:
- create PROCEDURE proc()
- begin
- select * from proctab;
- end ; create PROCEDURE proc()
- begin
- select * from proctab;
- end ;
Hibernate存储过程调用的一种方法是通过Hibernate传统的xml映射方式去调用。
Java代码:
- <class name="com.test.User" table="proctab">
- <id name="id" column="id">
- <generator class="native"/>
- </id>
- <property name="name" column="name" type="string" />
- <property name="age" column="age" type="integer" />
- </class>
- <sql-query name="getUser" callable="true">
- <return alias="user" class="com.test.User">
- <return-property name="id" column="id" />
- <return-property name="name" column="name" />
- <return-property name="age" column="age" />
- </return>
- {call proc()}
- </sql-query>
- <class name="com.test.User" table="proctab">
- <id name="id" column="id">
- <generator class="native"/>
- </id>
- <property name="name" column="name" type="string" />
- <property name="age" column="age" type="integer" />
- </class>
- <sql-query name="getUser" callable="true">
- <return alias="user" class="com.test.User">
- <return-property name="id" column="id" />
- <return-property name="name" column="name" />
- <return-property name="age" column="age" />
- </return>
- {call proc()}
- </sql-query>
调用方法 Java代码:
- Session ss= HibernateSessionFactory.getSession()
- List li=ss.getNamedQuery("getUser").list();
- ss.close();
- Session ss= HibernateSessionFactory.getSession()
- List li=ss.getNamedQuery("getUser").list();
- ss.close();
及其类似jdbc的方法 Java代码:
- Session session =HibernateSessionFactory.getSession();
- Connection conn = session.connection();
- ResultSet rs =null;
- CallableStatement call = conn.prepareCall("{Call proc()}");
- rs = call.executeQuery();
- rs.close();
- session.close();
- Session session =HibernateSessionFactory.getSession();
- Connection conn = session.connection();
- ResultSet rs =null;
- CallableStatement call = conn.prepareCall("{Call proc()}");
- rs = call.executeQuery();
- rs.close();
- session.close();
这种方法基本上就是jdbc,不过很简单,总是感觉怪怪的~还有就是通过强大的createSQLQuery来实现,o(∩_∩)o...哈哈 个人比较喜欢这种方法
Java代码:
- Session session =HibernateSessionFactory.getSession();
- SQLQuery query = session.createSQLQuery("{Call proc()}");
- List list =query.list();
- session.close();
- Session session =HibernateSessionFactory.getSession();
- SQLQuery query = session.createSQLQuery("{Call proc()}");
- List list =query.list();
- session.close();
如果没有返回值 直接用execute的方法就可以了,(*^__^*) 忘了一个重要的问题就是Hibernate存储过程的传参问题
Java代码:
- CallableStatement call = conn.prepareCall("{Call proc(?)}");
- call.setString(1, 参数);
- rs = call.executeQuery();
- CallableStatement call = conn.prepareCall("{Call proc(?)}");
- call.setString(1, 参数);
- rs = call.executeQuery();
Java代码:
- SQLQuery query = session.createSQLQuery("{Call proc(?)}");
- query.setString(0, 参数);
- List list =query.list();
以上便是对Hibernate存储过程调用的认识,粗陋之处还请指正。
【编辑推荐】