MYSQL 存储过程 jdbc hibernate

存储过程

一、        如何认识存储过程

存储过程是在数据库中预编译好的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;

 

三、        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 integer)

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 中使用

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();

     }

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值