MySQL存储过程中的Hibernate JDBC
创始人
2024-04-19 21:30:20
0

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

【编辑推荐】

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

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

相关内容

热门资讯

如何允许远程连接到MySQL数... [[277004]]【51CTO.com快译】默认情况下,MySQL服务器仅侦听来自localhos...
如何利用交换机和端口设置来管理... 在网络管理中,总是有些人让管理员头疼。下面我们就将介绍一下一个网管员利用交换机以及端口设置等来进行D...
施耐德电气数据中心整体解决方案... 近日,全球能效管理专家施耐德电气正式启动大型体验活动“能效中国行——2012卡车巡展”,作为该活动的...
20个非常棒的扁平设计免费资源 Apple设备的平面图标PSD免费平板UI 平板UI套件24平图标Freen平板UI套件PSD径向平...
德国电信门户网站可实时显示全球... 德国电信周三推出一个门户网站,直观地实时提供其安装在全球各地的传感器网络检测到的网络攻击状况。该网站...
为啥国人偏爱 Mybatis,... 关于 SQL 和 ORM 的争论,永远都不会终止,我也一直在思考这个问题。昨天又跟群里的小伙伴进行...
《非诚勿扰》红人闫凤娇被曝厕所... 【51CTO.com 综合消息360安全专家提醒说,“闫凤娇”、“非诚勿扰”已经被黑客盯上成为了“木...
2012年第四季度互联网状况报... [[71653]]  北京时间4月25日消息,据国外媒体报道,全球知名的云平台公司Akamai Te...