hibernate调用mysql存储过程

hibernate调用mysql存储过程

  在mysql中创建两个存储过程,香港虚拟主机,如下:

1、根据id查找某条数据:

`findEmpById`(IN id INTEGER(11))emp where empId=id;4 end;

2、根据id查找某个字段,并返回

`getNameById`(in id integer(11),out eName varchar(50))empName into eName from emp where empId=id;4 end;

  在存储过程的参数列表里面,虚拟主机,香港服务器,in修饰的参数代表输入参数,out修饰的代表输出参数。

使用hibernate调用上面两个存储过程:

  (1)调用第一个存储过程

1 package com.test; java.sql.CallableStatement; 4 import java.sql.Connection; 5 import java.sql.ResultSet; 6 import java.sql.SQLException; org.hibernate.Session; 9 import org.hibernate.SessionFactory;10 import org.hibernate.cfg.Configuration; 调用存储过程 { args SQLException main(String[] args) throws SQLException {20Configuration cfg = new Configuration().configure();21SessionFactory factory = cfg.buildSessionFactory();22Session session = factory.openSession();23Connection con = session.connection();24String sql = “{call findEmpById(?)}”;25CallableStatement cs = con.prepareCall(sql);26cs.setObject(1, 2);27ResultSet rs = cs.executeQuery();28while(rs.next()){29int id = rs.getInt(“empId”);30String name = rs.getString(“empName”);31System.out.println(id+”\t”+name);32 }33 }34 35 }

 调用存储过程的sql语句为:call 存储过程名(参数…),不过在java中调用存储过程一般都加{}。调用存储过程使用的是CallableStatement。

  (2)调用第二个存储过程

1 package com.test; java.sql.CallableStatement; 4 import java.sql.Connection; 5 import java.sql.SQLException; org.hibernate.Session; 8 import org.hibernate.SessionFactory; 9 import org.hibernate.cfg.Configuration; 调用存储过程1 {main(String[] args) throws SQLException {15Configuration config = new Configuration().configure();16SessionFactory sessionFactory = config.buildSessionFactory();17Session session = sessionFactory.openSession();18Connection conn = session.connection();19String sql = “{call getNameById(?,?)}”;20CallableStatement cs = conn.prepareCall(sql); cs.registerOutParameter(2, java.sql.Types.VARCHAR); cs.execute(); String name = cs.getString(2);System.out.println(name);26 }27 28 }

  如果有输出参数,需要特别指出,如上面的代码22行。

posted on

在向山靠近一点,才发现这座山,好象一位诗人遥望远方,

hibernate调用mysql存储过程

相关文章:

你感兴趣的文章:

标签云: