hibernate中调用存储过程hibernate中调用存储过程

    技术2022-05-11  124

    如果底层数据库(如Oracle)支持存储过程,也可以通过存储过程来执行批量更新。存储过程直接在数据库中运行,速度更加快。在Oracle数据库中可以定义一个名为batchUpdateStudent()的存储过程,代码如下:

    create or replace procedure batchUpdateStudent(p_age in number) asbeginupdate STUDENT set AGE=AGE+1 where AGE>p_age;end;

    以上存储过程有一个参数p_age,代表学生的年龄,应用程序可按照以下方式调用存储过程:

    tx = session.beginTransaction();Connection con=session.connection();

    String procedure = "{call batchUpdateStudent(?) }";CallableStatement cstmt = con.prepareCall(procedure);cstmt.setInt(1,0); //把年龄参数设为0cstmt.executeUpdate();tx.commit();

    public void fun(){ SessionFactory sessionFactory = new Configuration().configure("hibernate11.cfg.xml").buildSessionFactory(); Session session = sessionFactory.openSession(); Transaction tx = session.beginTransaction(); System.out.print("---begin---"); Connection con=session.connection(); String procedure = "{call batchUpdate (?)}"; try { CallableStatement cstmt = con.prepareCall(procedure); cstmt.setInt(1,15); //把年龄参数设为0 cstmt.executeUpdate(); } catch (Exception e) { e.printStackTrace(); // TODO: handle exception } tx.commit(); session.close(); sessionFactory.close(); } }  

    最新回复(0)