「Java入門」 hibernateでMySQLのプロシージャ (procedure)を呼び出すプログラム1
1.プロシージャ
CREATE PROCEDURE `findEmpById`(IN id INTEGER(11))
begin
select * from emp where empId=id;
end;
2.procedureを呼び出すサンプル
package com.startnews24_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 CallProcedure {
/**
* @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);
}
}
}