2009年8月5日 星期三

Hibernate 3使用Eclipse開發之方法

說明:此範例是Hibernate3搭配MySql資料庫使用Eclipse 3.4並使用JBoss Tools3.0.1 GA之Plugin來製作Mapping File(*.hbm.xml)及Code Gen產生POJO之類別。最後配合JUnit來測試Hibernate是否work?

2.使用Eclipse建立一個HibernateTest Project(File-->New-->Java Project)
3.在Hibernate Project 下建立一個lib目錄,並將Hibernate3.2.5ga內之hibernate3.jar及lib目錄下之所有檔案皆解壓縮到此目錄下之後按F5 refresh使此Project可以看到剛解壓縮之jar檔。別忘了,要加入Mysql Connector之Jar檔(mysql-connector-java-5.1.5-bin.jar)
4.將lib目錄下之jar檔加到User Library:
4.1.在HibernateTest Project上按滑鼠右鍵-->選Properties則會跳出一個Properties視窗
4.2.選擇Java Build Path-->Libraries-->Add Library...-->選擇User Library-->Next-->User Libraries...-->New...-->輸入Library名稱(HibernateTest)-->Add JARs...-->選擇所有jar檔-->OK-->Finish
5.安裝JBoss Tool Plugin:
5.1.Help-->Software Updates...-->Add Site...-->OK-->選擇JBoss Tools3.0.1GA-->Install
http://download.jboss.org/jbosstools/updates/stable/
6.建立一個hibernate.cfg.xml檔案:
6.1.於Mysql資料庫中建立t_user表格
C:\Users\Nelson Chen>mysql -u manning -p
Enter password: ******
mysql> use manning
Database changed
create table t_user(
id int(11) auto_increment,
name varchar(100) not null default '',
primary key(id));
mysql> desc t_user;
6.2.HibernateTest Project按右鍵-->New-->Other...-->選擇Hibernate-->Hibernate Configuration File(cfg.xml)-->Next-->將hibernate.cfg.xml放置到HibernateTest/src目錄下-->Next-->設定參數
Database Dialect:MySQL 5
Driver Class:org.gjt.mm.mysql.Driver
Connection URL:jdbc:mysql://localhost:3306/manning
Username:manning
Password:action
-->Finish
7.建立Hibernate Console configuration:
7.1.HibernateTest Project按右鍵-->New-->Other...-->選擇Hibernate-->Hibernate Console Configuration-->Next-->設定參數:
Database Connection:MySQL
-->Finish
8.設定Code Generation configuration:
8.1.Run-->Hibernate Code Generation...->Hibernate Code Generation configurations...-->
設定Main Tag:
Output Directory:\HibernateTest\src
打勾Reverse engineer from JDBC Connection
Package:org.redsaga.quickstart
reveng.xml:\HibernateTest\src\hibernate.reveng.xml
設定Exporter Tag:
打勾Domain code(.java)
打勾Hibernate XML Mappings(.hbm.xml)
設定Common Tag:

打勾Hibernate Code Generation
打勾Hibernate Console Configuration
9.產生Mapping File及Domain Class:
Run-->Hibernate Code Generation...-->POJO Code Generation
自動產生TUser.hbm.xml及TUser.java兩個檔案,其內容如下:

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated 2009/8/5 ?U?? 09:09:18 by Hibernate Tools 3.2.4.GA -->
<hibernate-mapping>
<class name="org.redsaga.quickstart.TUser" table="t_user" catalog="manning">
<id name="id" type="java.lang.Integer">
<column name="id" />
<generator class="identity" />
</id>
<property name="name" type="string">
<column name="name" length="100" not-null="true" />
</property>
</class>
</hibernate-mapping>
=========================================
package org.redsaga.quickstart;
// Generated 2009/8/5 下午 09:09:18 by Hibernate Tools 3.2.4.GA
/**
* TUser generated by hbm2java
*/
public class TUser implements java.io.Serializable {
private Integer id;
private String name;
public TUser() {
}
public TUser(String name) {
this.name = name;
}
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
}
=====================================
9.1.mapping file產生後之目錄結構如下圖:
10.修改Hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">org.gjt.mm.mysql.Driver</property>
<property name="hibernate.connection.password">action</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/manning</property>
<property name="hibernate.connection.username">manning</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
<!-- 將SQL輸出到Console -->
<property name="hibernate.show_sql">true</property>
<!-- 使用JDBC Transaction -->
<property name="hibernate.transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</property>
<!-- 將TUser.hbm.xml加到Hibernate.cfg.xml檔案中 -->
<mapping resource="org/redsaga/quickstart/TUser.hbm.xml"/>
</session-factory>
</hibernate-configuration>
====================================
11.將Hibernate壓縮檔內之etc/log4j.properties解壓縮到src目錄下:
修改log4j.logger.org.hibernate=debug為
log4j.logger.org.hibernate=error
12.建立JUnit測試程式:
12.1修改HibernateTest.java之單元測試程式
package org.redsaga.test;
import java.util.List;
import junit.framework.Assert;
import junit.framework.Test;
import org.eclipse.hyades.test.common.junit.DefaultTestArbiter;
import org.eclipse.hyades.test.common.junit.HyadesTestCase;
import org.eclipse.hyades.test.common.junit.HyadesTestSuite;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.redsaga.quickstart.TUser;
/**
* Generated code for the test suite <b>HibernateTest</b> located at
* <i>/HibernateTest/src/org/redsaga/HibernateTest.testsuite</i>.
*/
public class HibernateTest extends HyadesTestCase {
/**
* Constructor for HibernateTest.
* @param name
*/
Session session = null;
public HibernateTest(String name) {
super(name);
}
/**
* Returns the JUnit test suite that implements the <b>HibernateTest</b> definition.
*/
public static Test suite() {
HyadesTestSuite hibernateTest = new HyadesTestSuite("HibernateTest");
hibernateTest.setArbiter(DefaultTestArbiter.INSTANCE).setId(
"A1DE81C3C77C1FE0EAC1B03036333535");
hibernateTest.addTest(new HibernateTest("testInsert").setId(
"A1DE81C3CF791B80EAC1B03036333535").setTestInvocationId(
"A1DE81C45D1BCE10EAC1B03036333535"));
hibernateTest.addTest(new HibernateTest("testSelect").setId(
"A1DE81C422514C60EAC1B03036333535").setTestInvocationId(
"A1DE81C468D9C950EAC1B03036333535"));
return hibernateTest;
}
/**
* @see junit.framework.TestCase#setUp()
*
*/
protected void setUp() throws Exception {
try{
Configuration config = new Configuration().configure();
SessionFactory sessionFactory = config.buildSessionFactory();
session = sessionFactory.openSession();
}catch(HibernateException e){
e.printStackTrace();
}
}
/**
* @see junit.framework.TestCase#tearDown()
*/
protected void tearDown() throws Exception {
try{
session.close();
}catch(HibernateException e){
e.printStackTrace();
}
}
/**
* test Insert 物件持久化(Insert)測試方法
* @throws Exception
*/
public void testInsert() throws Exception {
Transaction tran = null;
try{
tran = session.beginTransaction();
TUser user = new TUser();
user.setName("Emma");
session.save(user);
session.flush();
tran.commit();
Assert.assertEquals(user.getId().intValue()>0, true);
}catch(HibernateException e){
e.printStackTrace();
Assert.fail(e.getMessage());
if(tran!=null){
try{
tran.rollback();
}catch(HibernateException he){
he.printStackTrace();
}
}
}
}
/**
* testSelect 對象讀取(Select)測試 請保證運行之前資料庫中已經存在name='Emma'的記錄
* @throws Exception
*/
public void testSelect() throws Exception {
String hql = " from TUser where name='Emma'";
try{
List userList = session.createQuery(hql).list();
TUser user = (TUser)userList.get(0);
Assert.assertEquals(user.getName(), "Emman");
}catch(HibernateException e){
e.printStackTrace();
Assert.fail(e.getMessage());
}
}
}
======================================
12.2.測試結果:選擇HibernateTest.java按滑鼠右鍵-->Run As-->2 JUnit Test

沒有留言:

張貼留言