hibernate调用存储过程
一、建表
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`ID` int(11) NOT NULL auto_increment,
`NAME` varchar(16) NOT NULL default '',
`REMARK` varchar(16) NOT NULL default '',
PRIMARY KEY (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=24 DEFAULT CHARSET=utf8;
二、建立存储过程
1、获取用户信息
CREATE DEFINER=`root`@`localhost` PROCEDURE `getUserList`()
BEGIN
select * from user;
END;
2、通过传入参数创建用户
CREATE DEFINER=`root`@`localhost` PROCEDURE `insertUser`(nameVar varchar(16),remarkVar varchar(16))
BEGIN
insert into user(name,remark) values(nameVar,remarkVar);
END;
三、User.hbm.xml
<hibernate-mapping>
<class name="com.cj.proc.hibernate.User" table="user" catalog="temp">
<id name="id" type="java.lang.Integer">
<column name="ID" />
<generator class="native"></generator>
</id>
<property name="name" type="java.lang.String">
<column name="NAME" length="16" not-null="true" />
</property>
<property name="remark" type="java.lang.String">
<column name="REMARK" length="16" not-null="true" />
</property>
</class>
<sql-query name="getUserList" callable="true">
<return alias="aa" class="com.cj.proc.hibernate.User">
<return-property name="id" column="ID"></return-property>
<return-property name="name" column="NAME"></return-property>
<return-property name="remark" column="REMARK"></return-property>
</return>
{call getUserList()}
</sql-query>
</hibernate-mapping>
四、调用
1、获取用户信息
Session session = HibernateSessionFactory.getSession();
Query query = session.getNamedQuery("getUserList");
//query.setString(0, "");设置参数
List<User> list = query.list();
for(User user:list){
System.out.println(user.getName()+" "+user.getRemark());
}
2、通过传入参数创建用户
Session session = HibernateSessionFactory.getSession();
Transaction tx = session.beginTransaction();
Connection conn = session.connection();
String proc = "call insertUser(?,?)";
CallableStatement cs = conn.prepareCall(proc);
cs.setString(1, "LINRZ");
cs.setString(2, "REMARK");
cs.execute();
tx.commit();
调用查询存储过程时,调用session.getNamedQuery("…")方法来获得User.hbm.xml中配置的查询存储过程。其余存储过程的调用,先通过hibernate的session获得connection,然后调用connection对象的相应方法来实现存储过程的调用。
本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/trwhoya/archive/2009/09/14/4551598.aspx