Hibernate3.x調(diào)用存儲(chǔ)過程

          原文出處:http://tech.it168.com/j/d/2007-05-14/200705141007843.shtml
          說明:該文不得轉(zhuǎn)載

          摘要:本文以詳盡的實(shí)例展示了hibernate3.x中調(diào)用存儲(chǔ)過程各步驟,從建立測(cè)試表、存儲(chǔ)過程的建立、工程的建立以及類的編寫和測(cè)試一步一步引導(dǎo)用戶學(xué)習(xí)hibernate3.x中調(diào)用存儲(chǔ)過程的方法.

          如果底層數(shù)據(jù)庫(eg. Oraclemysqlsqlserver)等支持存儲(chǔ)過程,可通過存儲(chǔ)過程執(zhí)行批量刪除、更新等操作。本文以實(shí)例說明在hibernate3.x中如何調(diào)用存儲(chǔ)過程。

            說明:本例hibernate所用版本為3.0mysql所用版本為5.0,所用數(shù)據(jù)庫驅(qū)動(dòng)為mysql-connector-java-5.0.4-bin.jar

          一.             建表與初始化數(shù)據(jù)

           mysqltest數(shù)據(jù)庫中建立一張新表:tbl_user,建表語句如下:

           DROP TABLE IF EXISTS `user`;

          CREATE TABLE `tbl_user` (

            `userid` varchar(50) NOT NULL,

            `name` varchar(50) default '',

            `blog` varchar(50) default '',

            PRIMARY KEY (`userid`)

          ) ENGINE=InnoDB DEFAULT CHARSET=gb2312;

           

           建表成功后,在該表中插入如下4條初始數(shù)據(jù),對(duì)應(yīng)的sql語句如下:

          INSERT INTO `tbl_user` (`userid`,`name`,`blog`) VALUES ('ant', '螞蟻', 'http://www.aygfsteel.com/qixiangnj');

          INSERT INTO `tbl_user` (`userid`,`name`,`blog`) VALUES ('beansoft', 'bean', 'http://www.aygfsteel.com/beansoft');

          INSERT INTO `tbl_user` (`userid`,`name`,`blog`) VALUES ('sterning', '似水流年', 'http://www.aygfsteel.com/sterning');

          INSERT INTO `tbl_user` (`userid`,`name`,`blog`) VALUES ('tom', 'tom' , 'http://www.aygfsteel.com/tom');

           

          二.             建立存儲(chǔ)過程

          為測(cè)試hibernate3.x中存儲(chǔ)過程的調(diào)用,我們?cè)?span>user表中建立getUserListcreateUserupdateUserdeleteUser這四個(gè)存儲(chǔ)過程,在mysql中建立存儲(chǔ)過程的語句如下:

          1. 獲得用戶信息列表的存儲(chǔ)過程--getUserList

          DROP PROCEDURE IF EXISTS `getUserList`;

          CREATE PROCEDURE `getUserList`()

          begin

               select * from tbl_user;

          end;

           

          2. 通過傳入的參數(shù)創(chuàng)建用戶的存儲(chǔ)過程--createUser

          DROP PROCEDURE IF EXISTS `createUser`;

          CREATE PROCEDURE `createUser`(IN userid varchar(50), IN name varchar(50), IN blog varchar(50))

          begin

              insert into tbl_user values(userid, name, blog);

          end;

           

          3. 通過傳入的參數(shù)更新用戶信息的存儲(chǔ)過程--updateUser

          DROP PROCEDURE IF EXISTS `updateUser`;

          CREATE PROCEDURE `updateUser`(IN nameValue varchar(50), IN blogValue varchar(50), IN useidValue varchar(50))

          begin

              update tbl_user set name = nameValue, blog = blogValue where userid = useridValue;

          end;

           

          4. 刪除用戶信息的存儲(chǔ)過程--deleteUser

          DROP PROCEDURE IF EXISTS `deleteUser`;

          CREATE PROCEDURE `deleteUser`(IN useridValue int(11))

          begin

              delete from tbl_user where userid = useridValue;

          end;

          三.             編程前準(zhǔn)備工作

          1.    建立工程

          在進(jìn)入代碼編寫前,建立新的java工程proc, 目錄結(jié)構(gòu)如下:

          proc

             -lib

              -bin

              -src

                -com

                  -amigo

                    -proc

                      -model

          2.    引入所需包

             hibernate3.0的包以及其相關(guān)包放入編譯路徑中,另注意:還需將mysql的數(shù)據(jù)庫驅(qū)動(dòng)jarmysql-connector-java-5.0.4-bin.jar放入編譯路徑中。

           

          四.             編碼與測(cè)試

          在準(zhǔn)備工作完成后,進(jìn)入編碼與測(cè)試階段,本例演示了在hibernate3.0中調(diào)用mysql的存儲(chǔ)過程的方法。

          1hibernate的配置文件

          hibernate的配置文件中包含數(shù)據(jù)庫的連接信息,以及加入OR mappingxml格式的映射文件,該文件如下(部分內(nèi)容略):

          ……

                  
          <property name="connection.url">jdbc:mysql://localhost:3306/test</property>

                  
          <property name="connection.username">root</property>

                  
          <property name="connection.password">root</property>

                  
          <property name="connection.driver_class">com.mysql.jdbc.Driver</property>

                  
          <property name="dialect">org.hibernate.dialect.MySQLDialect</property>

                  
          <property name="show_sql">true</property>

                  
          <mapping resource="com/amigo/proc/model/User.hbm.xml"/> 

              ……

          2OR Mapping文件

          產(chǎn)生的OR Mapping文件有User.java以及其對(duì)應(yīng)的hibernate映射文件User.hbm.xml。其中User.java的內(nèi)容如下:

          package com.amigo.proc.model;

           

          /**

           * 用戶信息對(duì)象

           
          */


          public class User implements java.io.Serializable {

              
          private static final long serialVersionUID = 1L;

              
          /** 用戶id*/

              
          private String userid;

              
          /** 用戶姓名*/

              
          private String name;

              
          /** 用戶blog*/

              
          private String blog;

          //省略get/set方法

          }

          User.hbm.xml文件的內(nèi)容如下:

          <?xml version="1.0"?>

          <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"

          "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"
          >

           

          <hibernate-mapping package="com.amigo.proc.model">

              
          <class name="User" table="tbl_user">

                  
          <id name="userid" column="userid">

                      
          <generator class="assigned"/>

                  
          </id>

                  
          <property name="name" column="name" type="string" />

                  
          <property name="blog" column="blog" type="string" />

              
          </class>

              

              
          <sql-query name="getUserList" callable="true">

                  
          <return alias="user" class="User">

                      
          <return-property name="userid" column="userid"/>

                      
          <return-property name="name" column="name"/>

                      
          <return-property name="blog" column="blog" />

                  
          </return>

                  {call getUserList()}

              
          </sql-query>

          </hibernate-mapping>

          在該文件中需注意<sql-query…></sql-query>中的這段代碼,調(diào)用的存儲(chǔ)過程在其中定義,并定義了調(diào)用存儲(chǔ)過程后將記錄組裝成User對(duì)象,同時(shí)對(duì)記錄的字段與對(duì)象的屬性進(jìn)行相關(guān)映射。

          3.    管理hibernatesession以及事務(wù)的類HibernateSessionFactory

          該類包括打開session等方法,主要用于管理hibernatesession和事務(wù)。該類的內(nèi)容如下(部分內(nèi)容略):

           

          package com.amigo.proc;

          import java.io.ByteArrayOutputStream;

          import java.io.OutputStreamWriter;

           

          import org.hibernate.HibernateException;

          import org.hibernate.Session;

          import org.hibernate.SessionFactory;

          import org.hibernate.Transaction;

          import org.hibernate.cfg.Configuration;

          /**

           * Hibernate相關(guān)控制

           
          */


          public class HibernateSessionFactory {

              
          /** Hibernate配置文件 */

              
          private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";

           

              
          /** 存儲(chǔ)一個(gè)單獨(dú)的session實(shí)例 */

              
          private static final ThreadLocal threadLocal = new ThreadLocal();

           

              
          /** Hibernate配置相關(guān)的一個(gè)實(shí)例 */

              
          private static Configuration configuration = null;

           

              
          /** Hibernate SessionFactory的一個(gè)實(shí)例 */

              
          private static SessionFactory sessionFactory;

           

              
          /** Hibernate的字符編碼集*/

              
          private static String charSet;

              
          /** 若Hibernate未設(shè)置字符編碼集時(shí),采用的字符編碼集*/

              
          private static final String encoding = (new OutputStreamWriter(

                      
          new ByteArrayOutputStream())).getEncoding();

           

              
          /**

               * 默認(rèn)構(gòu)造函數(shù)

               
          */


              
          public HibernateSessionFactory() {

              }


           

              
          /**

               * 打開Hibernate的數(shù)據(jù)庫連接

               
          */


              
          public static final synchronized void open() {

                  
          if (sessionFactory != null)

                      
          return;

                  
          try {

                      sessionFactory 
          = getConfiguration().buildSessionFactory();

                      charSet 
          = configuration.getProperty("hibernate.connection.charSet");

                      
          if (charSet == null)

                          charSet 
          = encoding;

                      
          return;

                  }
           catch (Throwable throwable) {

                      
          throw new ExceptionInInitializerError(throwable);

                  }


              }


           

              
          /**

               * 配置Hibernate數(shù)據(jù)庫,并將其打開

               
          */


              
          private static synchronized void configure() throws HibernateException {

                  
          if (sessionFactory == null{

                      
          if (configuration == null{

                          getConfiguration().configure(CONFIG_FILE_LOCATION);

                      }


                      open();

                  }


              }


           

              
          /**

               * 獲得配置實(shí)例

               
          */


              
          public static synchronized final Configuration getConfiguration() {

                  
          if (configuration == null{

                      configuration 
          = new Configuration();

                  }


                  
          return configuration;

              }


           

              
          /**

               * 功能說明:獲得SessionFactory

               
          */


              
          public static final SessionFactory getSessionFactory() {

                  
          return sessionFactory;

              }


           

              
          /**

               * 功能說明:獲得session

               
          */


              
          public static final Session getSession() throws HibernateException {

                  configure();

                  Session session 
          = null;

                  
          if (threadLocal.get() == null{

                      session 
          = getSessionFactory().openSession();

                      threadLocal.set(session);

                  }
           else {

                      
          try {

                          session 
          = (Session)threadLocal.get();

                      }
           catch(Exception ex) {

                          session 
          = getSessionFactory().openSession();

                          threadLocal.set(session);

                      }


                  }


                  
          return session;

              }


              
          //其余方法略

          }


           4hibernate調(diào)用存儲(chǔ)過程的測(cè)試類

          本類是該例的核心類,在本類中,以實(shí)例清楚地說明了在hibernate中如何調(diào)用存儲(chǔ)過程,例示了hibernate調(diào)用查詢、更新、插入和刪除這四類存儲(chǔ)過程的方法,該類的內(nèi)容如下:

          package com.amigo.proc;

           

          import java.sql.CallableStatement;

          import java.sql.Connection;

          import java.sql.PreparedStatement;

          import java.util.List;

           

          import com.amigo.proc.model.User;

           

          import org.hibernate.Session;

          import org.hibernate.Transaction;

           

          /**

           * hibernate調(diào)用存儲(chǔ)過程

           * 
          @author Amigo Xie(xiexingxing1121@126.com)

           * 
          @since 2007/04/30

           
          */


          public class ProcTest {

           

              
          /**

               * 
          @param args

               
          */


              
          public static void main(String[] args) throws Exception {

                  ProcTest proc 
          = new ProcTest();

                  Session session 
          = HibernateSessionFactory.getSession();

                  proc.testProcQuery(session);

                  proc.testProcUpdate(session);

                  System.out.println(
          "update successfully");

                  

                  proc.testProcInsert(session);

                  System.out.println(
          "insert successfully");

                  

                  proc.testProcDelete(session);

                  System.out.println(
          "delete successfully");

                  session.close();

              }


              

              
          /**

               * 測(cè)試實(shí)現(xiàn)查詢的存儲(chǔ)過程

               * 
          @throws Exception

               
          */


              
          private void testProcQuery(Session session) throws Exception {

                  
          //查詢用戶列表

                  List list 
          = session.getNamedQuery("getUserList").list();

                  
          for (int i = 0; i < list.size(); i++{

                      User user 
          = (User) list.get(i);    

                      System.out.print(
          "序號(hào): " + (i+1));

                      System.out.print(
          ", userid: " + user.getUserid());

                      System.out.print(
          ", name: " + user.getName());

                      System.out.println(
          ", blog: " + user.getBlog());

                  }


              }


              

              
          /**

               * 測(cè)試實(shí)現(xiàn)更新的存儲(chǔ)過程

               * 
          @throws Exception

               
          */


              
          private void testProcUpdate(Session session) throws Exception {

                  
          //更新用戶信息

                  Transaction tx 
          = session.beginTransaction(); 

                  Connection con 
          = session.connection(); 

                  String procedure 
          = "{call updateUser(?, ?, ?)}"

                  CallableStatement cstmt 
          = con.prepareCall(procedure); 

                  cstmt.setString(
          1"陳xx");

                  cstmt.setString(
          2"http://www.aygfsteel.com/sterningChen");

                  cstmt.setString(
          3"sterning");

                  cstmt.executeUpdate(); 

                  tx.commit();

              }


           

              
          /**

               * 測(cè)試實(shí)現(xiàn)插入的存儲(chǔ)過程

               * 
          @throws Exception

               
          */


              
          private void testProcInsert(Session session) throws Exception {

                  
          //創(chuàng)建用戶信息

                  session.beginTransaction();

                  PreparedStatement st 
          = session.connection().prepareStatement("{call createUser(?, ?, ?)}");

                  st.setString(
          1"amigo");

                  st.setString(
          2"阿蜜果");

                  st.setString(
          3"http://www.wblogjava.net/amigoxie");

                  st.execute();

                  session.getTransaction().commit(); 

              }


              

              
          /**

               * 測(cè)試實(shí)現(xiàn)刪除的存儲(chǔ)過程

               * 
          @throws Exception

               
          */


              
          private void testProcDelete(Session session) throws Exception {

                  
          //刪除用戶信息

                  session.beginTransaction();

                  PreparedStatement st 
          = session.connection().prepareStatement("{call deleteUser(?)}");

                  st.setString(
          1"amigo");

                  st.execute();

                  session.getTransaction().commit();

              }


          }


          http://www.aygfsteel.com/amigoxie/archive/2007/08/15/136828.html

          posted on 2008-11-15 22:08 smallfa 閱讀(250) 評(píng)論(0)  編輯  收藏 所屬分類: hibernate/ibatis

          <2008年11月>
          2627282930311
          2345678
          9101112131415
          16171819202122
          23242526272829
          30123456

          導(dǎo)航

          統(tǒng)計(jì)

          公告

          smallfa
          博客園
          C++博客
          博客生活
          Blogjava
          足球博客
          微博
          Redsaga

          常用鏈接

          留言簿(2)

          隨筆分類

          隨筆檔案

          文章分類

          文章檔案

          相冊(cè)

          Ajax

          Blogs

          DB

          java

          Open source

          ORM

          Tools/Help

          vedio Tech

          搜索

          最新評(píng)論

          閱讀排行榜

          評(píng)論排行榜

          主站蜘蛛池模板: 精河县| 彭州市| 仲巴县| 泰兴市| 延吉市| 常熟市| 彰化县| 钟祥市| 苗栗县| 三门县| 舞阳县| 通海县| 威宁| 三门峡市| 吉首市| 安宁市| 科尔| 清水河县| 苏尼特右旗| 都兰县| 虹口区| 阳山县| 汉川市| 镇赉县| 塔城市| 瑞丽市| 梧州市| 崇明县| 沙湾县| 郑州市| 康平县| 新疆| 苗栗县| 皮山县| 五河县| 宣威市| 辽中县| 舟山市| 嘉鱼县| 德格县| 屯留县|