hibernate的createSQLQuery调用存储过程

连接数据库工具类

import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;

/**
 * Hibernate Utility class with a convenient method to get Session Factory
 * object.
 *
 */
public class NewHibernateUtil {
   
    private static SessionFactory msSessionFactory;
    private static SessionFactory pgSessionFactory;
    private static SessionFactory oracleSessionFactory;
    private static SessionFactory mysqlSessionFactory;
   
    @SuppressWarnings("deprecation")
 public static SessionFactory getSessionFactory(String type) {
       
            if (SqlType.MS.toString().equals(type)) {
                if (msSessionFactory==null) {
                 msSessionFactory = new AnnotationConfiguration().configure("hibernate.ms.cfg.xml").buildSessionFactory();
                }
                return msSessionFactory;
            } else if (SqlType.PG.toString().equals(type)) {
                if (pgSessionFactory==null) {
                    pgSessionFactory = new AnnotationConfiguration().configure("hibernate.pg.cfg.xml").buildSessionFactory();
                }
                return pgSessionFactory;
            } else if (SqlType.ORACLE.toString().equals(type)) {
                if (oracleSessionFactory==null) {
                 oracleSessionFactory = new AnnotationConfiguration().configure("hibernate.oracle.cfg.xml").buildSessionFactory();
                }
                return oracleSessionFactory;
               
            } else if (SqlType.MYSQL.toString().equals(type)) {
                if (mysqlSessionFactory==null) {
                 mysqlSessionFactory = new AnnotationConfiguration().configure("hibernate.mysql.cfg.xml").buildSessionFactory();
                }
                return mysqlSessionFactory;
            }
      
        return null;
    }
}

1.存储过程

--带出参存储过程
CREATE OR REPLACE PROCEDURE demo_proc(id number,name varchar2) as
BEGIN
      delete from demo2 where id=id;
      insert into demo2(id,name) values(id,name);
END;

2.hibernate调用存储过程

static Session oracleSession = NewHibernateUtil.getSessionFactory(SqlType.ORACLE.toString()).openSession();

 

public void insertDemo(){

  oracleSession.getTransaction().begin();
  SQLQuery query = oracleSession.createSQLQuery("{Call demo_proc(?,?)}"); 
  query.setInteger(0, 2);
  query.setString(1, "12312");
  query.executeUpdate();
  oracleSession.getTransaction().commit();
  oracleSession.close();

}

你可能感兴趣的:(数据库,hibernate)