java调用存储过程:java调用存储过程博文地址
mybaits调用存储过程:mybaits调用存储过程博文地址
hibernate调用存储过程 :hibernate调用存储过程博文地址
在mysql中创建两个存储过程,如下:
1、根据id查找某条数据:
CREATE PROCEDURE `findEmpById`(IN id INTEGER(11))
begin
select * from emp where empId=id;
end;
2、根据id查找某个字段,并返回
CREATE PROCEDURE `getNameById`(in id integer(11),out eName varchar(50))
begin
select empName into eName from emp where empId=id;
end;
在存储过程的参数列表里面,in修饰的参数代表输入参数,out修饰的代表输出参数。
使用hibernate调用上面两个存储过程:
(1)调用第一个存储过程
package com.test;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class CallProduced1 {
/**
* @param args
* @throws SQLException
*/
public static void main(String[] args) throws SQLException {
Configuration cfg = new Configuration().configure();
SessionFactory factory = cfg.buildSessionFactory();
Session session = factory.openSession();
Connection con = session.connection();
String sql = "{call findEmpById(?)}";
CallableStatement cs = con.prepareCall(sql);
cs.setObject(1, 2);
ResultSet rs = cs.executeQuery();
while(rs.next()){
int id = rs.getInt("empId");
String name = rs.getString("empName");
System.out.println(id+"\t"+name);
}
}
}
调用存储过程的sql语句为:call 存储过程名(参数...),不过在java中调用存储过程一般都加{}。调用存储过程使用的是CallableStatement。
(2)调用第二个存储过程
package com.test;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.SQLException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class CallProduced2 {
public static void main(String[] args) throws SQLException {
Configuration config = new Configuration().configure();
SessionFactory sessionFactory = config.buildSessionFactory();
Session session = sessionFactory.openSession();
Connection conn = session.connection();
String sql = "{call getNameById(?,?)}";
CallableStatement cs = conn.prepareCall(sql);
cs.setObject(1, 3); //设置输出参数
cs.registerOutParameter(2, java.sql.Types.VARCHAR); //设置第二个参数为输出参数
cs.execute(); //调用存储过程
String name = cs.getString(2);//获取输出参数
System.out.println(name);
}
}
原文地址:
原博文地址,谢谢残剑。