原文出處:http://tech.it168.com/j/d/2007-05-14/200705141007843.shtml
說(shuō)明:該文不得轉(zhuǎn)載
摘要:本文以詳盡的實(shí)例展示了hibernate3.x中調(diào)用存儲(chǔ)過(guò)程各步驟,從建立測(cè)試表、存儲(chǔ)過(guò)程的建立、工程的建立以及類的編寫和測(cè)試一步一步引導(dǎo)用戶學(xué)習(xí)hibernate3.x中調(diào)用存儲(chǔ)過(guò)程的方法.
如果底層數(shù)據(jù)庫(kù)(eg. Oracle、mysql、sqlserver)等支持存儲(chǔ)過(guò)程,可通過(guò)存儲(chǔ)過(guò)程執(zhí)行批量刪除、更新等操作。本文以實(shí)例說(shuō)明在hibernate3.x中如何調(diào)用存儲(chǔ)過(guò)程。
說(shuō)明:本例hibernate所用版本為3.0,mysql所用版本為5.0,所用數(shù)據(jù)庫(kù)驅(qū)動(dòng)為mysql-connector-java-5.0.4-bin.jar。
一. 建表與初始化數(shù)據(jù)
在mysql的test數(shù)據(jù)庫(kù)中建立一張新表:tbl_user,建表語(yǔ)句如下:
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語(yǔ)句如下:
INSERT INTO `tbl_user` (`userid`,`name`,`blog`) VALUES ('ant', '螞蟻', 'http://www.tkk7.com/qixiangnj');
INSERT INTO `tbl_user` (`userid`,`name`,`blog`) VALUES ('beansoft', 'bean', 'http://www.tkk7.com/beansoft');
INSERT INTO `tbl_user` (`userid`,`name`,`blog`) VALUES ('sterning', '似水流年', 'http://www.tkk7.com/sterning');
INSERT INTO `tbl_user` (`userid`,`name`,`blog`) VALUES ('tom', 'tom' , 'http://www.tkk7.com/tom');
二. 建立存儲(chǔ)過(guò)程
為測(cè)試hibernate3.x中存儲(chǔ)過(guò)程的調(diào)用,我們?cè)?span>user表中建立getUserList、createUser、updateUser和deleteUser這四個(gè)存儲(chǔ)過(guò)程,在mysql中建立存儲(chǔ)過(guò)程的語(yǔ)句如下:
1. 獲得用戶信息列表的存儲(chǔ)過(guò)程--getUserList
DROP PROCEDURE IF EXISTS `getUserList`;
CREATE PROCEDURE `getUserList`()
begin
select * from tbl_user;
end;
2. 通過(guò)傳入的參數(shù)創(chuàng)建用戶的存儲(chǔ)過(guò)程--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. 通過(guò)傳入的參數(shù)更新用戶信息的存儲(chǔ)過(guò)程--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ǔ)過(guò)程--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ù)庫(kù)驅(qū)動(dòng)jar包mysql-connector-java-5.0.4-bin.jar放入編譯路徑中。
四. 編碼與測(cè)試
在準(zhǔn)備工作完成后,進(jìn)入編碼與測(cè)試階段,本例演示了在hibernate3.0中調(diào)用mysql的存儲(chǔ)過(guò)程的方法。
1、hibernate的配置文件
在hibernate的配置文件中包含數(shù)據(jù)庫(kù)的連接信息,以及加入OR mapping的xml格式的映射文件,該文件如下(部分內(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"/>

……

2、OR 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ǔ)過(guò)程在其中定義,并定義了調(diào)用存儲(chǔ)過(guò)程后將記錄組裝成User對(duì)象,同時(shí)對(duì)記錄的字段與對(duì)象的屬性進(jìn)行相關(guān)映射。
3. 管理hibernate的session以及事務(wù)的類HibernateSessionFactory
該類包括打開session等方法,主要用于管理hibernate的session和事務(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ù)庫(kù)連接

*/


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ù)庫(kù),并將其打開

*/


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;

}



/** *//**

* 功能說(shuō)明:獲得SessionFactory

*/


public static final SessionFactory getSessionFactory()
{

return sessionFactory;

}



/** *//**

* 功能說(shuō)明:獲得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;

}

//其余方法略

}


4. hibernate調(diào)用存儲(chǔ)過(guò)程的測(cè)試類
本類是該例的核心類,在本類中,以實(shí)例清楚地說(shuō)明了在hibernate中如何調(diào)用存儲(chǔ)過(guò)程,例示了hibernate調(diào)用查詢、更新、插入和刪除這四類存儲(chǔ)過(guò)程的方法,該類的內(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ǔ)過(guò)程

* @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ǔ)過(guò)程

* @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ǔ)過(guò)程

* @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.tkk7.com/sterningChen");

cstmt.setString(3, "sterning");

cstmt.executeUpdate();

tx.commit();

}



/** *//**

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

* @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ǔ)過(guò)程

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

}

}


在本類中,調(diào)用查詢類存儲(chǔ)過(guò)程時(shí),調(diào)用session.getNamedQuery("…")方法來(lái)獲得User.hbm.xml中配置的查詢存儲(chǔ)過(guò)程。在其余的存儲(chǔ)過(guò)程調(diào)用的測(cè)試中,首先通過(guò)hibernate的session獲得connection,然后調(diào)用connection對(duì)象的相應(yīng)方法來(lái)實(shí)現(xiàn)存儲(chǔ)過(guò)程的調(diào)用。
該類的執(zhí)行結(jié)果如下:
Hibernate: {call getUserList()}
序號(hào): 1, userid: ant, name: 螞蟻, blog: http://www.tkk7.com/qixiangnj
序號(hào): 2, userid: beansoft, name: bean, blog: http://www.tkk7.com/beansoft
序號(hào): 3, userid: sterning, name: 似水流年, blog: http://www.tkk7.com/sterning
序號(hào): 4, userid: tom, name: tom, blog: http://www.tkk7.com/tom
update successfully
insert successfully
delete successfully
五.總結(jié)
本例提出了在hibernate3中調(diào)用mysql的存儲(chǔ)過(guò)程的實(shí)現(xiàn)方案,從本例可以看出,hibernate提供了在*.hbm.xml中配置調(diào)用存儲(chǔ)過(guò)程,并通過(guò)向用戶提供session.getNamedQuery(“…”)方法來(lái)調(diào)用配置的調(diào)用查詢相關(guān)的存儲(chǔ)過(guò)程的方法,另外,hibernate還提供了取得sql的connection的方法,從而能夠通過(guò)connection中存儲(chǔ)過(guò)程調(diào)用相關(guān)的方法來(lái)實(shí)現(xiàn)存儲(chǔ)過(guò)程的調(diào)用。
posted on 2007-09-17 22:09
Ke 閱讀(2123)
評(píng)論(2) 編輯 收藏 所屬分類:
hibernate