在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 代碼
< sql-query   name = "selectAllCustomer"   callable = "true" >         < return   alias = "customer"   class = "com.hibernate.Customers" >             < return-property   name = "id"   column = "ID" />             < return-property   name = "name"   column = "NAME" />                      </ return >        {call selectAllCustomer()}    </ 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 代碼
< sql-query   name = "selectNameById"   callable = "true" >         < return   alias = "customer"   class = "com.hibernate.Customers" >             < return-property   name = "id"   column = "ID" />             < return-property   name = "name"   column = "NAME" />                      </ return >        {call selectNameById(?,?)}    </ 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 代碼
< 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 代碼
< 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 代碼
< 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 代碼
<? 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" >    < hibernate-mapping >         < class   name = "com.hibernate.Customers"   table = "CUSTOMERS"   lazy = "true" >             < id   name = "id"   type = "java.lang.Long" >                 < column   name = "ID"   />                 < generator   class = "increment" > </ generator >             </ id >                      < property   name = "name"   type = "java.lang.String" >                 < column   name = "NAME"   length = "10"   not-null = "true"   />             </ property >              < sql-insert   callable = "true" > {call insertCustomer(?,?)} </ sql-insert >              < sql-update   callable = "true" > {?=call updateCustomer(?,?)} </ sql-update >              < sql-delete   callable = "true" > {?=call delCustomerById(?)} </ sql-delete >          </ class >             < sql-query   name = "selectNameById"   callable = "true" >         < return   alias = "customer"   class = "com.hibernate.Customers" >             < return-property   name = "id"   column = "ID" />             < return-property   name = "name"   column = "NAME" />                      </ return >        {call selectNameById(?,?)}    </ sql-query >       < sql-query   name = "selectAllCustomer"   callable = "true" >         < return   alias = "customer"   class = "com.hibernate.Customers" >             < return-property   name = "id"   column = "ID" />             < return-property   name = "name"   column = "NAME" />                      </ return >        {call selectAllCustomer()}    </ sql-query >    </ 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();
  }
 }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章