Hibernate调用存储过程

来源:互联网 发布:透明名片生成器软件 编辑:程序博客网 时间:2024/06/03 15:46

hibernate提供了两种方式执行存储过程。但是还是觉得直接使用JDBC调用储存过程比较方便吧!
Hibernate 对于JDBC的封装,还是给我们提供了原始的Connection的接口,我们可以很方便的使用,以前能在JDBC中使用的功能。
看看你就懂啦!

Connection connection = getSession().connection();

调用存储过程的SQL语句

String procedure = "{call chargeday_statistics(?, ?, ?)}";     
  • Creates a CallableStatement object for calling database storedprocedures. The CallableStatement object provides methods for setting
    up its IN and OUT parameters, and methods for executing the call to astored procedure.
    CallableStatement prepareCall(String sql) throws SQLException; 这个是Connection接口中的内容!
public interface CallableStatement extends PreparedStatementpublic interface PreparedStatement extends Statement public interface Statement extends Wrapper, AutoCloseable{   ResultSet executeQuery(String sql) throws SQLException;   int executeUpdate(String sql) throws SQLException;}

直接就去调用哦~

        CallableStatement cstmt = connection.prepareCall(procedure);                     cstmt.setString(1, startime);                     cstmt.setString(2, endtime);        cstmt.registerOutParameter(3, Types.INTEGER); //存储过程输出参数         cstmt.executeUpdate();        return cstmt.getInt(3);
   Session session =HibernateSessionFactory.getSession(); //获取hibernate会话   Connection conn = session.connection(); // 用session对象获取连接   ResultSet rs =null;    try    {    CallableStatement call = conn.prepareCall("{Call pro_getManager(?,?)}");    call.setString(1, "admin");    call.setString(2, "admin");    rs = call.executeQuery();    }    catch (Exception e)    {        e.printStackTrace();    }finally  {    rs.close();//关闭    session.close();//关闭连接    HibernateSessionFactory.closeSession(); //关闭会话 }
0 0