MySQL存储过程中的Hibernate JDBC

开发 后端
本文将介绍MySQL存储过程中的Hibernate JDBC,存储过程是在数据库中预编译好的SQL语句,只需一次编译即可,大大提高了sql 语句执行的速度。

一、如何认识Hibernate JDBC存储过程

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

好处:提高了速度;

坏处:不便于移植。

二、存储过程的语法:

a) 创建一个存储过程

无参:    

  1. Create procedure creatp()   
  2.     Begin  

Sql 语句;

     End;

有参:

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

     Begin

         Sql 语句;

     End;

例如:

无参:

  1. DELIMITER $$   
  2. DROP PROCEDURE IF EXISTS `test`.`createp` $$   
  3. CREATE PROCEDURE `test`.`createp` ( idv int)   
  4. BEGIN   
  5.   select * from `table_test` where id=idv;   
  6. END $$   
  7. DELIMITER ;  

有参:

  1. DELIMITER $$   
  2. DROP PROCEDURE IF EXISTS `test`.`queryProV` $$   
  3. CREATE DEFINER=`root`@`localhost` PROCEDURE `queryProV`(tid integer)   
  4. BEGIN   
  5.   select * from table_test where id=tid;   
  6. END $$   
  7. DELIMITER ;  

b)     使用存储过程

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

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

例如:

call createp(2);

c)     删除存储过程

Drop procedure 存储过程名;

例如:

  1. drop procedure createp;  

三、Hibernate JDBC使用存储过程

  1. package com.test.dao;   
  2. import java.sql.CallableStatement;   
  3. import java.sql.Connection;   
  4. import java.sql.DriverManager;   
  5. import java.sql.PreparedStatement;   
  6. import java.sql.ResultSet;   
  7. import java.sql.SQLException;   
  8. import org.hibernate.Session;   
  9. import com.test.hibernate.HibernateSessionFactory;   
  10. /**   
  11.   * MySQl 存储过程___   
  12.   *   JDBC   
  13.   * @author Administrator   
  14.   *   
  15.   */   
  16. public class Test {   
  17.      /**    
  18.        * 获取数据库的连接对象   
  19.        * @return    数据库连接对象   
  20.        */   
  21.      private  Connection getConnection(){        
  22.          final String MYSQL_DRIVER="com.mysql.jdbc.Driver";// 数据库连接的驱动   
  23.          final String MYSQL_USERNAME="root";// 数据库连接的url   
  24.          final String MYSQL_PASSWORD="123456";// 数据库连接的密码   
  25.          final String MYSQL_URL="jdbc:mysql://localhost:3306/test";// 数据库连接的url           
  26.          try{   
  27.               Class.forName(MYSQL_DRIVER);   
  28.               return DriverManager.getConnection(MYSQL_URL, MYSQL_USERNAME, MYSQL_PASSWORD);   
  29.           }catch(Exception e){   
  30.               e.printStackTrace();   
  31.          }   
  32.         return null;   
  33.      }   
  34.      /**   
  35.      ===========================================   
  36. DELIMITER $$   
  37. DROP PROCEDURE IF EXISTS `test`.`queryPro` $$   
  38. CREATE DEFINER=`root`@`localhost` PROCEDURE `queryPro`()   
  39. BEGIN   
  40.   select * from table_test ;   
  41. END $$   
  42. DELIMITER ;   
  43.        ===========================================   
  44.        * 这是一个无参的存储过程jdbc 使用方法   
  45.        * @throws SQLException   
  46.        */   
  47.      public void testQuery() throws SQLException{   
  48.          Connection conn=null;   
  49.          CallableStatement cstmt=null;   
  50.          ResultSet rs=null;   
  51.          try{   
  52.               conn=this.getConnection();   
  53.               cstmt =conn.prepareCall("{call queryPro()}");   
  54.               rs=cstmt.executeQuery();   
  55.               while(rs.next()){   
  56.                    System.out.println("id:"+rs.getInt(1)+"||name:"+rs.getString(2));   
  57.               }   
  58.          }catch(Exception e){e.printStackTrace();}   
  59.          finally{   
  60.               if(rs!=null){   
  61.                    rs.close();   
  62.               }   
  63.               if(cstmt!=null){   
  64.                    cstmt.close();   
  65.               }   
  66.               if(conn!=null){   
  67.                    conn.close();   
  68.               }   
  69.          }   
  70.      }   
  71.      /**   
  72.        ===========================================   
  73. DELIMITER $$   
  74. DROP PROCEDURE IF EXISTS `test`.`queryProV` $$   
  75. CREATE DEFINER=`root`@`localhost` PROCEDURE `queryProV`(tid integer)   
  76. BEGIN   
  77.   select * from table_test where id=tid;   
  78. END $$   
  79. DELIMITER ;   
  80.        ===========================================   
  81.        * 这是一个有参的存储过程jdbc 使用方法   
  82.        * @throws SQLException   
  83.        */   
  84.      public void testQueryV() throws SQLException{   
  85.          Connection conn=null;   
  86.          CallableStatement cstmt=null;   
  87.           ResultSet rs=null;   
  88.          try{   
  89.               conn=this.getConnection();   
  90.               cstmt =conn.prepareCall("{call queryProV(?)}");   
  91.               cstmt.setInt(12);// 就是把上句中***个问号的值设为2   
  92.               rs=cstmt.executeQuery();   
  93.               while(rs.next()){   
  94.                    System.out.println("id:"+rs.getInt(1)+"||name:"+rs.getString(2));   
  95.               }   
  96.          }catch(Exception e){e.printStackTrace();}   
  97.          finally{   
  98.               if(rs!=null){   
  99.                    rs.close();   
  100.               }   
  101.               if(cstmt!=null){   
  102.                    cstmt.close();   
  103.               }   
  104.               if(conn!=null){   
  105.                    conn.close();   
  106.               }   
  107.         }   
  108.      }   
  109.      /**   
  110.       ===========================================   
  111. DELIMITER $$   
  112. DROP PROCEDURE IF EXISTS `test`.`delPro` $$   
  113. CREATE DEFINER=`root`@`localhost` PROCEDURE `delPro`(tid nteger)   
  114. BEGIN   
  115.   delete from table_test where id=tid;   
  116. END $$   
  117. DELIMITER ;   
  118.        ===========================================   
  119.        * 这是一个有参的存储过程jdbc 使用方法   
  120.        * @throws SQLException   
  121.        */   
  122.     public void testDel() throws SQLException{   
  123.          Connection conn=null;   
  124.          CallableStatement cstmt=null;   
  125.          try{   
  126.               conn=this.getConnection();   
  127.               cstmt =conn.prepareCall("{call delPro(?)}");   
  128.               cstmt.setInt(12);// 就是把上句中***个问号的值设为2   
  129.               boolean tag=cstmt.execute();       
  130.               System.out.println(" 删除成功");   
  131.          }catch(Exception e){e.printStackTrace();}   
  132.          finally{   
  133.                  if(cstmt!=null){   
  134.                    cstmt.close();   
  135.               }   
  136.               if(conn!=null){   
  137.                    conn.close();   
  138.               }   
  139.         }   
  140.      }   
  141.      public static void main(String [] args) throws SQLException{   
  142.      Test tset =new Test();   
  143.           }   
  144. }  

四、Hibernate  JDBC中使用

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

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

  1. <?xml version="1.0" encoding="utf-8"?>   
  2. <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"   
  3. "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">   
  4. <!--   
  5.      Mapping file autogenerated by MyEclipse Persistence Tools   
  6. -->   
  7. <hibernate-mapping>   
  8.      <class name="com.test.hibernate.TableTest" table="table_test"   
  9.          catalog="test">   
  10.          <id name="id" type="java.lang.Integer">   
  11.               <column name="id" />   
  12.               <generator class="assigned" />   
  13.          </id>   
  14.          <property name="name" type="java.lang.String">   
  15.              <column name="name" length="45" />   
  16.          </property>   
  17.          <property name="value" type="java.lang.String">   
  18.               <column name="value" length="45" />   
  19.          </property>   
  20.     </class>   
  21.      <!-- 无参数: Hibernate 存储过程配置 -->   
  22.     <!-- name: 查询语句在hibernate 中的名字, 随便取 -->      
  23.    <sql-query name="queryPro1" callable="true">   
  24.     <!-- alias: 查询返回的对象的别名, 随便取           
  25.     class 查询返回的类的全路径,否则会抱找不到类的错误 -->   
  26.     <return alias="t1" class="com.test.hibernate.TableTest">   
  27.          <!-- 查询中每一个参数的设置,name 表示为别名 -->   
  28.          <return-property  name="c1" column="id" />   
  29.         <return-property  name="c2" column="name" />   
  30.          <return-property  name="c3" column="value" />   
  31.     </return>   
  32.      <!-- mysql 中存储过程 -->   
  33.     { call queryPro()}   
  34.     </sql-query>   
  35.    <!-- 有参数: Hibernate 存储过程配置 -->   
  36.    <!-- name: 查询语句在hibernate 中的名字, 随便取 -->      
  37.     <sql-query name="queryPro2" callable="true">   
  38.     <!-- alias: 查询返回的对象的别名, 随便取           
  39.     class 查询返回的类的全路径,否则会抱找不到类的错误 -->   
  40.     <return alias="TableTest" class="com.test.hibernate.TableTest">   
  41.          <!-- 查询中每一个参数的设置,name 表示为别名 -->   
  42.          <return-property  name="id" column="id" />   
  43.          <return-property  name="name" column="name" />   
  44.          <return-property  name="value" column="value" />   
  45.     </return>   
  46.     <!-- mysql 中存储过程 -->   
  47.     {call queryProV(?)}   
  48.    </sql-query>   
  49. </hibernate-mapping>   
  50. 4.3. 使用   
  51. package com.test.dao;   
  52. import java.sql.CallableStatement;   
  53. import java.sql.Connection;   
  54. import java.sql.PreparedStatement;   
  55. import java.sql.ResultSet;   
  56. import java.sql.SQLException;   
  57. import java.util.List;   
  58. import org.hibernate.Query;   
  59. import org.hibernate.Session;   
  60. import com.test.hibernate.HibernateSessionFactory;   
  61. import com.test.hibernate.TableTest;   
  62. public class TestDao {   
  63.      /**   
  64.        * 无参数的hibernate 存储过程查询   
  65.        */   
  66.      public void query(){   
  67.         Session session=null;   
  68.         try{   
  69.               session=HibernateSessionFactory.getSession();             
  70.               Query qy=session.getNamedQuery("queryPro1");              
  71.               List<TableTest> list=qy.list();   
  72.               if(list!=null){   
  73.                    for(int i=0;i<list.size();i++){                      
  74.                        TableTest test=list.get(i);   
  75.                        System.out.println("id="+test.getId()+"||name:"+test.getName());   
  76.                    }   
  77.              }      
  78.          }catch(Exception e){e.printStackTrace();}   
  79.          finally{   
  80.               if(session!=null){   
  81.                    session.close();   
  82.              }   
  83.          }      
  84.      }   
  85.      /**   
  86.        * 有参数的hibernate 的存储过程之查询   
  87.        */   
  88.      public void queryV(){   
  89.         Session session=null;   
  90.          try{   
  91.               session=HibernateSessionFactory.getSession();             
  92.               Query qy=session.getNamedQuery("queryPro2");         
  93.               qy.setInteger(0, 3);// 设置指定位置的参数,注意参数从0 开始。   
  94.               List<TableTest> list=qy.list();   
  95.               if(list!=null){   
  96.                    for(int i=0;i<list.size();i++){                      
  97.                        TableTest test=list.get(i);   
  98.                        System.out.println("id="+test.getId()+"||name:"+test.getName());   
  99.                    }   
  100.               }      
  101.          }catch(Exception e){e.printStackTrace();}   
  102.          finally{   
  103.               if(session!=null){   
  104.                    session.close();   
  105.               }   
  106.          }      
  107.      }   
  108.     /**   
  109.       * 此种方法是jdbc 的方法   
  110.        * 优点:不用在在配置文件中进行配置   
  111.       * 缺点:无法返回对象   
  112.        * @throws SQLException   
  113.        */   
  114.      public void queryOther() throws SQLException{   
  115.          Session session=null;   
  116.          Connection conn=null;   
  117.          PreparedStatement pst=null;   
  118.          ResultSet rs=null;   
  119.          try{   
  120.               session=HibernateSessionFactory.getSession();   
  121.                 conn=session.connection();   
  122.                 pst=conn.prepareCall("{call queryProV(?)}");   
  123.               pst.setInt(1, 3);   
  124.                 rs=pst.executeQuery();   
  125.               while(rs.next()){   
  126.                    System.out.println("id="+rs.getInt(1)+"||name:"+rs.getString(2));   
  127.               }   
  128.                 
  129.         }catch(Exception e){e.printStackTrace();}   
  130.          finally{   
  131.               if(rs!=null){   
  132.                    rs.close();   
  133.               }   
  134.               if(pst!=null){   
  135.                   pst.close();   
  136.               }   
  137.               if(conn!=null){   
  138.                    conn.close();   
  139.               }   
  140.               if(session!=null){   
  141.                    session.close();   
  142.               }   
  143.          }      
  144.     }   
  145.      public static void main(String [] args) throws SQLException{   
  146.          TestDao td=new TestDao();   
  147.          td.queryOther();   
  148.      }   
  149. }  

【编辑推荐】

  1. 在Weblogic中实现JDBC的功能
  2. 详解JDBC与Hibernate区别
  3. JDBC连接MySQL数据库关键四步
  4. 五步精通SQL Server 2000 JDBC驱动安装与测试
  5. 详解JDBC驱动的四种类型
  6. JDBC存储过程在Oracle中的获取结果集

【责任编辑:彭凡 TEL:(010)68476606】

责任编辑:彭凡 来源: 网易空间
相关推荐

2010-05-31 16:57:09

2010-05-27 17:45:13

MySQL存储过程

2016-09-07 20:28:17

MySQL存储数据库

2010-05-27 17:56:39

MySQL存储过程

2010-11-26 16:18:13

MySQL变量定义

2011-04-11 17:28:50

oracle存储select语句

2022-08-26 16:28:41

MySQL存储只读语句

2009-06-17 10:33:17

Hibernate 存

2010-04-15 16:54:31

Oracle存储过程

2010-11-12 09:18:13

SQL Server存

2010-04-16 09:03:28

Oracle 存储过程

2011-08-15 15:56:31

SQL Server

2009-07-08 17:17:16

JDBC调用存储过程

2009-07-17 13:54:51

JDBC存储过程

2009-07-08 17:42:33

JDBC存储过程

2010-10-09 16:41:54

MYSQL存储过程

2010-05-07 18:44:28

Oracle存储过程

2010-05-05 14:55:15

Oracle存储过程

2010-04-26 10:09:22

Oracle存储过程

2011-08-11 14:35:47

SQL Server插入更新
点赞
收藏

51CTO技术栈公众号