在JDBC和Hibernat中的使用存储过程

在JDBC和Hibernat中的使用存储过程
1.在SQLServer中新建数据库BUSINESS
create database BUSINESS

2.在BUSINESS数据库中新建表CUSTOMERS,包含字段ID、NAME
use BUSINESS
create table CUSTOMERS(
  ID bigint primary key,
  NAME varchar(10) not null
)
并加入一条或多条记录
insert into CUSTOMERS (ID,NAME) values (1,'cheumen')

3.建立对应的Bean文件Customers.java,如下:
package com.hibernate;
public class Customers implements java.io.Serializable {
 private Long id;
 private String name;
 public Customers() {
 }
 public Customers(String name) {
  this.name = name;
 }
 public Long getId() {
  return this.id;
 }
 public void setId(Long id) {
  this.id = id;
 }
 public String getName() {
  return this.name;
 }
 public void setName(String name) {
  this.name = name;
 }
}

4.建立对应的Customers.hbm.xml文件,如下(以后再根据需要一步一步增加相应内容):
这里需要注意的是OID生成器,我们采用increment类

xml 代码
  1. <hibernate-mapping>  
  2.     <class name="com.hibernate.Customers" table="CUSTOMERS" lazy="true">  
  3.         <id name="id" type="java.lang.Long">  
  4.             <column name="ID" />  
  5.             <generator class="increment"></generator>  
  6.         </id>           
  7.         <property name="name" type="java.lang.String">  
  8.             <column name="NAME" length="10" not-null="true" />  
  9.         </property>  
  10.      </class>  
  11. </hibernate-mapping>  

5.创建各种要求的存储过程(与下面的存储过程使用顺序相对应)
①创建一个无输入参数多返回值的查询存储过程
CREATE PROCEDURE selectAllCustomer   AS
    select * from CUSTOMERS
GO
②创建一个有输入参数多返回值的查询存储过程
CREATE PROCEDURE selectNameById @id bigint,@name varchar(15) output  AS
select @name= NAME  from CUSTOMERS where ID=@id
if @name='cheumen'
select ID,NAME from CUSTOMERS where NAME=@name
else
select ID,NAME from CUSTOMERS where ID=@id
GO
③创建一个插入一条新纪录的存储过程(要注意要讲ID放在后面)
CREATE PROCEDURE insertCustomer @name varchar(10),@id bigint   AS
insert into CUSTOMERS (NAME,ID) VALUES (@name,@id)
GO
④创建一个更新记录的存储过程
CREATE PROCEDURE updateCustomer @name varchar(10) , @id bigint  AS
update CUSTOMERS set NAME=@name where ID=@id
GO
⑤创建一个删除记录的存储过程
CREATE PROCEDURE delCustomerById @id bigint AS
delete   CUSTOMERS where ID=@id
GO

6.首先介绍在JDBC中的应用(在Hibernate中通过session.connection()得到connection对象也是一样使用,Deprecated. To be replaced with a SPI for performing work against the connection; scheduled for removal in 4.x )
在这里,无需在Customers.hbm.xml中加入任何东西

 CallableStatement ctmt=con.prepareCall("{call selectAllCustomer()}",ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
 ResultSet rs=ctmt.executeQuery();
 while(rs.next()){
    Long id=rs.getLong(1);
    String name=rs.getString(2);
    System.out.print(id+" "+name);
 }

CallableStatement  cstm=con.prepareCall("{call selectNameById(?,?)}");
cstm.registerOutParameter(2, java.sql.Types.LONGVARCHAR);
cstm.setLong(1,new Long(1));
cstm.execute();
String name=cstm.getString(2);
if(name!=null){
 System.out.println(name);
}

CallableStatement  stmt=con.prepareCall("{call insertCustomer(?,?)}");
stmt.setString(1,"P_cheumen");
stmt.setLong(2,new Long(5));
stmt.execute();

CallableStatement cstm=con.prepareCall("{call updateCustomer(?,?)}");
cstm.setString(1,"pcw-100");
cstm.setLong(2,new Long(1));
cstm.execute();

CallableStatement cstm=con.prepareCall("{call delCustomerById(?)}");
cstm.setLong(1,new Long(1));
cstm.execute();

7.在Hibernate中的使用
在这里就要根据需要来在Customers.hbm.xml中增加相应的东西了

在<hibernate-mapping></hibernate-mapping>元素中增加子元素<sql-query></sql-query>,即在之间增加以下内容:

xml 代码
  1. <sql-query name="selectAllCustomer" callable="true">  
  2.     <return alias="customer" class="com.hibernate.Customers">  
  3.         <return-property name="id" column="ID"/>  
  4.         <return-property name="name" column="NAME"/>               
  5.     </return>  
  6.     {call selectAllCustomer()}   
  7. </sql-query>  


<return class="com.hibernate.Customers" alias="customer"></return>
<return-property name="id" column="ID"></return-property>
<return-property name="name" column="NAME"></return-property>

下面的是测试代码:
Query query=session.getNamedQuery("selectAllCustomer");
List list=query.list();
Iterator it=list.iterator();
while(it.hasNext()){
 Customers customer=(Customers)it.next();
 System.out.println(customer.getId()+" "+customer.getName());
}

在<hibernate-mapping></hibernate-mapping>元素中增加子元素<sql-query></sql-query>,即在之间增加以下内容:
<sql-query name="selectNameById" callable="true"></sql-query>

xml 代码
  1. <sql-query name="selectNameById" callable="true">  
  2.     <return alias="customer" class="com.hibernate.Customers">  
  3.         <return-property name="id" column="ID"/>  
  4.         <return-property name="name" column="NAME"/>               
  5.     </return>  
  6.     {call selectNameById(?,?)}   
  7. </sql-query>  



以下是测试代码:
Query query=session.getNamedQuery("selectNameById");
query.setLong(0,new Long(1));
query.setString(1,new String());
List list=query.list();
Iterator it=list.iterator();
while(it.hasNext()){
 Customers customer=(Customers)it.next();
 System.out.println(customer.getId()+" "+customer.getName());
}

在<class></class>元素中增加子元素<sql-insert></sql-insert>,即在之间加上以下内容:
<sql-insert callable="true"></sql-insert>

xml 代码
  1. <sql-insert callable="true">{call insertCustomer(?,?)}</sql-insert>  


以下是测试代码:(注意控制台的信息,看看是不是调用存储过程)
Customers customer=new Customers();
customer.setName("cheumen");
session.save(customer);

在<class></class>元素中增加子元素<sql-update></sql-update>,即在之间加上以下内容:
注意在这里多了个"?="
<sql-update callable="true"></sql-update>

xml 代码
  1. <sql-update callable="true">{?=call updateCustomer(?,?)}</sql-update>  


以下是测试代码:(注意控制台的信息,看看是不是调用存储过程)
Customers customer=(Customers)session.get(Customers.class,new Long(1));
customer.setName("cheumen");
session.saveOrUpdate(customer);
⑤在<class></class>元素中增加子元素<sql-delete></sql-delete>,即在之间加上以下内容:
注意在这里多了个"?="
<sql-delete callable="true"></sql-delete>

xml 代码
  1. <sql-delete callable="true">{?=call delCustomerById(?)}</sql-delete>  

下面是测试代码:(注意控制台的信息,看看是不是调用存储过程)
Customers customer=(Customers)session.get(Customers.class ,new Long(1));
if(customer!=null)
session.delete(customer);

8.
综上所述,Customers.hbm.xml中的内容如下:

xml 代码
  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. <hibernate-mapping>  
  5.     <class name="com.hibernate.Customers" table="CUSTOMERS" lazy="true">  
  6.         <id name="id" type="java.lang.Long">  
  7.             <column name="ID" />  
  8.             <generator class="increment"></generator>  
  9.         </id>           
  10.         <property name="name" type="java.lang.String">  
  11.             <column name="NAME" length="10" not-null="true" />  
  12.         </property>  
  13.          <sql-insert callable="true">{call insertCustomer(?,?)}</sql-insert>  
  14.          <sql-update callable="true">{?=call updateCustomer(?,?)}</sql-update>  
  15.          <sql-delete callable="true">{?=call delCustomerById(?)}</sql-delete>  
  16.      </class>  
  17.         
  18. <sql-query name="selectNameById" callable="true">  
  19.     <return alias="customer" class="com.hibernate.Customers">  
  20.         <return-property name="id" column="ID"/>  
  21.         <return-property name="name" column="NAME"/>               
  22.     </return>  
  23.     {call selectNameById(?,?)}   
  24. </sql-query>  
  25.   
  26. <sql-query name="selectAllCustomer" callable="true">  
  27.     <return alias="customer" class="com.hibernate.Customers">  
  28.         <return-property name="id" column="ID"/>  
  29.         <return-property name="name" column="NAME"/>               
  30.     </return>  
  31.     {call selectAllCustomer()}   
  32. </sql-query>  
  33. </hibernate-mapping>  

测试程序内容如下:
public class businessMain {
 public static void main(String[] args) {
  Session session=HibernateSessionFactory.getSession();
  Transaction tx=null;
  try{
      tx=session.beginTransaction();
      java.sql.Connection con=session.connection();     

      /*①
      Query query=session.getNamedQuery("selectAllCustomer");
      List list=query.list();
      Iterator it=list.iterator();
      while(it.hasNext()){
       Customers customer=(Customers)it.next();
       System.out.println(customer.getId()+" "+customer.getName());
      }
           
      CallableStatement ctmt=con.prepareCall("{call selectAllCustomer()}",ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
      ResultSet rs=ctmt.executeQuery();
      while(rs.next()){
       Long id=rs.getLong(1);
       String name=rs.getString(2);
       System.out.print(id+" "+name);
      }*/

      /*②
      java.sql.CallableStatement  cstm=con.prepareCall("{call selectNameById(?,?)}");
      cstm.registerOutParameter(2, java.sql.Types.LONGVARCHAR);
      cstm.setLong(1,new Long(1));
      cstm.execute();
      String name=cstm.getString(2);
      if(name!=null){
       System.out.println(name);
      }
     
      Query query=session.getNamedQuery("selectNameById");
      query.setLong(0,new Long(1));
      query.setString(1,new String());
      List list=query.list();
      Iterator it=list.iterator();
      while(it.hasNext()){
       Customers customer=(Customers)it.next();
       System.out.println(customer.getId()+" "+customer.getName());
      }*/      
     

      /*③
      java.sql.CallableStatement  stmt=con.prepareCall("{call insertCustomer(?,?)}");
      stmt.setString(1,"cheumen");
      stmt.setLong(2,new Long(5));
      stmt.execute();
     
     
   //在存储过程中一定要将ID字段放在最后
      Customers customer=new Customers();
      customer.setName("cheumen");
      session.save(customer);*/     

      /*④
      CallableStatement cstm=con.prepareCall("{call updateCustomer(?,?)}");
      cstm.setString(1,"cheumen");
      cstm.setLong(2,new Long(1));
      cstm.execute();
     
      Customers customer=(Customers)session.get(Customers.class,new Long(1));
      customer.setName("cheumen");
      session.saveOrUpdate(customer);*/     
     
      /*⑤
      CallableStatement cstm=con.prepareCall("{call delCustomerById(?)}");
      cstm.setLong(1,new Long(5));
      cstm.execute();
     
      Customers customer=(Customers)session.get(Customers.class ,new Long(1));
      if(customer!=null)
      session.delete(customer);*/
     
   tx.commit();
  }
  catch(Exception ex){
   if(tx!=null)
    tx.rollback();
   ex.printStackTrace();
  }
  finally{
   session.close();
  }
 }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值