MySQL存储过程中的Hibernate JDBC

(转载:http://developer.51cto.com/art/200907/138824.htm
本文将介绍MySQL存储过程中的Hibernate JDBC,存储过程是在数据库中预编译好的SQL语句,只需一次编译即可,大大提高了sql 语句执行的速度。
AD:
一、如何认识Hibernate JDBC存储过程

存储过程是在数据库中预编译好的SQL语句,只需一次编译即可,大大提高了sql 语句执行的速度。

好处:提高了速度;

坏处:不便于移植。

二、存储过程的语法:

a) 创建一个存储过程

无参:    

Create procedure creatp()   
    Begin  
Sql 语句;

End;

有参:

Create procedure creatp( 参数名1 参数类型1 ,参数名2 参数类型2 )

Begin

Sql 语句;

End;

例如:

无参:

DELIMITER $$   
DROP PROCEDURE IF EXISTS `test`.`createp` $$   
CREATE PROCEDURE `test`.`createp` ( idv int)   
BEGIN   
  select * from `table_test` where id=idv;   
END $$   
DELIMITER ;  
有参:

DELIMITER $$   
DROP PROCEDURE IF EXISTS `test`.`queryProV` $$   
CREATE DEFINER=`root`@`localhost` PROCEDURE `queryProV`(tid integer)   
BEGIN   
  select * from table_test where id=tid;   
END $$   
DELIMITER ;  
b)     使用存储过程

无参:Call 存储过程名();

有参:Call 存储过程名( 参数值) ;

例如:

call createp(2);

c)     删除存储过程

Drop procedure 存储过程名;

例如:

drop procedure createp;  
三、Hibernate JDBC使用存储过程

package com.test.dao;   
import java.sql.CallableStatement;   
import java.sql.Connection;   
import java.sql.DriverManager;   
import java.sql.PreparedStatement;   
import java.sql.ResultSet;   
import java.sql.SQLException;   
import org.hibernate.Session;   
import com.test.hibernate.HibernateSessionFactory;   
/**   
  * MySQl 存储过程___   
  *   JDBC   
  * @author Administrator   
  *   
  */   
public class Test {   
     /**    
       * 获取数据库的连接对象   
       * @return    数据库连接对象   
       */   
     private  Connection getConnection(){        
         final String MYSQL_DRIVER="com.mysql.jdbc.Driver";// 数据库连接的驱动   
         final String MYSQL_USERNAME="root";// 数据库连接的url   
         final String MYSQL_PASSWORD="123456";// 数据库连接的密码   
         final String MYSQL_URL="jdbc:mysql://localhost:3306/test";// 数据库连接的url           
         try{   
              Class.forName(MYSQL_DRIVER);   
              return DriverManager.getConnection(MYSQL_URL, MYSQL_USERNAME, MYSQL_PASSWORD);   
          }catch(Exception e){   
              e.printStackTrace();   
         }   
        return null;   
     }   
     /**   
     ===========================================   
DELIMITER $$   
DROP PROCEDURE IF EXISTS `test`.`queryPro` $$   
CREATE DEFINER=`root`@`localhost` PROCEDURE `queryPro`()   
BEGIN   
  select * from table_test ;   
END $$   
DELIMITER ;   
       ===========================================   
       * 这是一个无参的存储过程jdbc 使用方法   
       * @throws SQLException   
       */   
     public void testQuery() throws SQLException{   
         Connection conn=null;   
         CallableStatement cstmt=null;   
         ResultSet rs=null;   
         try{   
              conn=this.getConnection();   
              cstmt =conn.prepareCall("{call queryPro()}");   
              rs=cstmt.executeQuery();   
              while(rs.next()){   
                   System.out.println("id:"+rs.getInt(1)+"||name:"+rs.getString(2));   
              }   
         }catch(Exception e){e.printStackTrace();}   
         finally{   
              if(rs!=null){   
                   rs.close();   
              }   
              if(cstmt!=null){   
                   cstmt.close();   
              }   
              if(conn!=null){   
                   conn.close();   
              }   
         }   
     }   
     /**   
       ===========================================   
DELIMITER $$   
DROP PROCEDURE IF EXISTS `test`.`queryProV` $$   
CREATE DEFINER=`root`@`localhost` PROCEDURE `queryProV`(tid integer)   
BEGIN   
  select * from table_test where id=tid;   
END $$   
DELIMITER ;   
       ===========================================   
       * 这是一个有参的存储过程jdbc 使用方法   
       * @throws SQLException   
       */   
     public void testQueryV() throws SQLException{   
         Connection conn=null;   
         CallableStatement cstmt=null;   
          ResultSet rs=null;   
         try{   
              conn=this.getConnection();   
              cstmt =conn.prepareCall("{call queryProV(?)}");   
              cstmt.setInt(1, 2);// 就是把上句中第一个问号的值设为2   
              rs=cstmt.executeQuery();   
              while(rs.next()){   
                   System.out.println("id:"+rs.getInt(1)+"||name:"+rs.getString(2));   
              }   
         }catch(Exception e){e.printStackTrace();}   
         finally{   
              if(rs!=null){   
                   rs.close();   
              }   
              if(cstmt!=null){   
                   cstmt.close();   
              }   
              if(conn!=null){   
                   conn.close();   
              }   
        }   
     }   
     /**   
      ===========================================   
DELIMITER $$   
DROP PROCEDURE IF EXISTS `test`.`delPro` $$   
CREATE DEFINER=`root`@`localhost` PROCEDURE `delPro`(tid nteger)   
BEGIN   
  delete from table_test where id=tid;   
END $$   
DELIMITER ;   
       ===========================================   
       * 这是一个有参的存储过程jdbc 使用方法   
       * @throws SQLException   
       */   
    public void testDel() throws SQLException{   
         Connection conn=null;   
         CallableStatement cstmt=null;   
         try{   
              conn=this.getConnection();   
              cstmt =conn.prepareCall("{call delPro(?)}");   
              cstmt.setInt(1, 2);// 就是把上句中第一个问号的值设为2   
              boolean tag=cstmt.execute();       
              System.out.println(" 删除成功");   
         }catch(Exception e){e.printStackTrace();}   
         finally{   
                 if(cstmt!=null){   
                   cstmt.close();   
              }   
              if(conn!=null){   
                   conn.close();   
              }   
        }   
     }   
     public static void main(String [] args) throws SQLException{   
     Test tset =new Test();   
          }   
}  
四、Hibernate  JDBC中使用

4.1 在数据库中创建存储过程;

4.2 在hibernate 中配置存储过程,以及返回的对象

<?xml version="1.0" encoding="utf-8"?>   
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"   
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">   
<!--   
     Mapping file autogenerated by MyEclipse Persistence Tools   
-->   
<hibernate-mapping>   
     <class name="com.test.hibernate.TableTest" table="table_test"   
         catalog="test">   
         <id name="id" type="java.lang.Integer">   
              <column name="id" />   
              <generator class="assigned" />   
         </id>   
         <property name="name" type="java.lang.String">   
             <column name="name" length="45" />   
         </property>   
         <property name="value" type="java.lang.String">   
              <column name="value" length="45" />   
         </property>   
    </class>   
     <!-- 无参数: Hibernate 存储过程配置 -->   
    <!-- name: 查询语句在hibernate 中的名字, 随便取 -->      
   <sql-query name="queryPro1" callable="true">   
    <!-- alias: 查询返回的对象的别名, 随便取           
    class 查询返回的类的全路径,否则会抱找不到类的错误 -->   
    <return alias="t1" class="com.test.hibernate.TableTest">   
         <!-- 查询中每一个参数的设置,name 表示为别名 -->   
         <return-property  name="c1" column="id" />   
        <return-property  name="c2" column="name" />   
         <return-property  name="c3" column="value" />   
    </return>   
     <!-- mysql 中存储过程 -->   
    { call queryPro()}   
    </sql-query>   
   <!-- 有参数: Hibernate 存储过程配置 -->   
   <!-- name: 查询语句在hibernate 中的名字, 随便取 -->      
    <sql-query name="queryPro2" callable="true">   
    <!-- alias: 查询返回的对象的别名, 随便取           
    class 查询返回的类的全路径,否则会抱找不到类的错误 -->   
    <return alias="TableTest" class="com.test.hibernate.TableTest">   
         <!-- 查询中每一个参数的设置,name 表示为别名 -->   
         <return-property  name="id" column="id" />   
         <return-property  name="name" column="name" />   
         <return-property  name="value" column="value" />   
    </return>   
    <!-- mysql 中存储过程 -->   
    {call queryProV(?)}   
   </sql-query>   
</hibernate-mapping>   
4.3. 使用   
package com.test.dao;   
import java.sql.CallableStatement;   
import java.sql.Connection;   
import java.sql.PreparedStatement;   
import java.sql.ResultSet;   
import java.sql.SQLException;   
import java.util.List;   
import org.hibernate.Query;   
import org.hibernate.Session;   
import com.test.hibernate.HibernateSessionFactory;   
import com.test.hibernate.TableTest;   
public class TestDao {   
     /**   
       * 无参数的hibernate 存储过程查询   
       */   
     public void query(){   
        Session session=null;   
        try{   
              session=HibernateSessionFactory.getSession();             
              Query qy=session.getNamedQuery("queryPro1");              
              List<TableTest> list=qy.list();   
              if(list!=null){   
                   for(int i=0;i<list.size();i++){                      
                       TableTest test=list.get(i);   
                       System.out.println("id="+test.getId()+"||name:"+test.getName());   
                   }   
             }      
         }catch(Exception e){e.printStackTrace();}   
         finally{   
              if(session!=null){   
                   session.close();   
             }   
         }      
     }   
     /**   
       * 有参数的hibernate 的存储过程之查询   
       */   
     public void queryV(){   
        Session session=null;   
         try{   
              session=HibernateSessionFactory.getSession();             
              Query qy=session.getNamedQuery("queryPro2");         
              qy.setInteger(0, 3);// 设置指定位置的参数,注意参数从0 开始。   
              List<TableTest> list=qy.list();   
              if(list!=null){   
                   for(int i=0;i<list.size();i++){                      
                       TableTest test=list.get(i);   
                       System.out.println("id="+test.getId()+"||name:"+test.getName());   
                   }   
              }      
         }catch(Exception e){e.printStackTrace();}   
         finally{   
              if(session!=null){   
                   session.close();   
              }   
         }      
     }   
    /**   
      * 此种方法是jdbc 的方法   
       * 优点:不用在在配置文件中进行配置   
      * 缺点:无法返回对象   
       * @throws SQLException   
       */   
     public void queryOther() throws SQLException{   
         Session session=null;   
         Connection conn=null;   
         PreparedStatement pst=null;   
         ResultSet rs=null;   
         try{   
              session=HibernateSessionFactory.getSession();   
                conn=session.connection();   
                pst=conn.prepareCall("{call queryProV(?)}");   
              pst.setInt(1, 3);   
                rs=pst.executeQuery();   
              while(rs.next()){   
                   System.out.println("id="+rs.getInt(1)+"||name:"+rs.getString(2));   
              }   
                
        }catch(Exception e){e.printStackTrace();}   
         finally{   
              if(rs!=null){   
                   rs.close();   
              }   
              if(pst!=null){   
                  pst.close();   
              }   
              if(conn!=null){   
                   conn.close();   
              }   
              if(session!=null){   
                   session.close();   
              }   
         }      
    }   
     public static void main(String [] args) throws SQLException{   
         TestDao td=new TestDao();   
         td.queryOther();   
     }   
}  
原文地址:https://www.cnblogs.com/OOAbooke/p/2381580.html