我的第一個(gè)hibernate
經(jīng)過(guò)幾天的調(diào)試,我終于把調(diào)試成功了我第一個(gè) hibernate ,之前都是學(xué)習(xí)理論知識(shí)。由于我參考的教材后臺(tái)數(shù)據(jù)庫(kù)用的是 MYSQL, 用 hbm2java 生成 java 源代碼,用 hbm2ddl 生成數(shù)據(jù)庫(kù)實(shí) hbm2java 。我覺得太麻煩了,而且現(xiàn)在主要數(shù)據(jù)庫(kù)用的最多的是 ORACLE,SQL SERVER 。所以最近一段時(shí)間我用 SQL SERVER2000+MYECLIPSE 來(lái)構(gòu)建我的 hibernate 程序。因?yàn)橹虚g因?yàn)樽约旱拇笠?,出現(xiàn)很多不該出現(xiàn)的問題,導(dǎo)致的程序調(diào)試不成功,為了讓大家少走彎路,我將自己的經(jīng)驗(yàn)完整寫下來(lái):
開發(fā)環(huán)境:
Sql server 2000
Eclipse
用 myeclipse 建立數(shù)據(jù)庫(kù)的連接
依照下圖打開 myeclipse database explore
新建數(shù)據(jù)連接
進(jìn)入下面頁(yè)面并填寫好 NAME
點(diǎn)擊 configure database drive, 進(jìn)入后,點(diǎn)擊 new, 出現(xiàn)下圖,并在 driver template 選擇如圖所示
點(diǎn)擊
add jars,
找到自己所下的
mssql
驅(qū)動(dòng)路徑
按確定回到下圖,并按圖填寫好其他項(xiàng),
name,password
為你數(shù)據(jù)庫(kù)的登陸用戶名和密碼
一直點(diǎn)擊下步,完成即可。然后點(diǎn)擊新建的連接,打開即可
然后再數(shù)據(jù)庫(kù)中建立兩個(gè)表
CUSTOMER . ORDER?
數(shù)據(jù)庫(kù)名為
test
文件
點(diǎn)擊 web project 下一步后在項(xiàng)目名寫 test2, 點(diǎn)擊完成即可 .
完成后在 test2 項(xiàng)目點(diǎn)擊右鍵 , 如下圖
然后進(jìn)入下面頁(yè)面
,(
記得選擇
hibernate2.1 jar library installation
選第二項(xiàng)
,
確保設(shè)置與下圖一致
)
下一步
/
下一步
將
db profile
選擇為
MSSQL1
點(diǎn)擊下一步
如
下圖
( class:
如下圖填寫
)
點(diǎn)擊完成 .
現(xiàn)在我們建立對(duì)象 Customer.java Order.java
文件 / 新建 / 類 ? 在彈出的窗口中 源文件夾為 test2/src 包為 com 名字為 Customer, 點(diǎn)擊完成即可 .
建立 Order.java 操作一樣 .
添加代碼 :
Customer.java
package com;
import java.io.Serializable;
import org.apache.commons.lang.builder.ToStringBuilder;
/** @author Hibernate CodeGenerator */
public class Customer implements Serializable {
??? /** identifier field */
??? private Long id;
??? /** nullable persistent field */
??? private String name;
??? /** full constructor */
??? public Customer(String name) {
??????? this.name = name;
??? }
??? /** default constructor */
??? public Customer() {
??? }
??? 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;
??? }
??? public String toString() {
??????? return new ToStringBuilder(this)
??????????? .append("id", getId())
??????????? .toString();
??? }
}
Order.java
package com;
import java.io.Serializable;
import org.apache.commons.lang.builder.ToStringBuilder;
/** @author Hibernate CodeGenerator */
public class Order implements Serializable {
??? /** identifier field */
??? private Long id;
??? /** nullable persistent field */
??? private String orderNumber;
??? /** persistent field */
??? private com.Customer customer;
??? /** full constructor */
??? public Order(String orderNumber,Customer customer) {
??????? this.orderNumber = orderNumber;
??????? this.customer = customer;
??? }
???
???
??? /** default constructor */
??? public Order() {
??? }
??? /** minimal constructor */
??? public Order(com.Customer customer) {
??????? this.customer = customer;
??? }
??? public Long getId() {
??????? return this.id;
??? }
??? public void setId(Long id) {
??????? this.id = id;
??? }
??? public String getOrderNumber() {
??????? return this.orderNumber;
??? }
??? public void setOrderNumber(String orderNumber) {
??????? this.orderNumber = orderNumber;
??? }
??? public com.Customer getCustomer() {
??????? return this.customer;
??? }
??? public void setCustomer(com.Customer customer) {
??????? this.customer = customer;
??? }
??? public String toString() {
??????? return new ToStringBuilder(this)
??????????? .append("id", getId())
??????????? .toString();
??? }
}
建立兩個(gè)映射文件 Customer.hbm..xml?? Order.hbm.xml
文件 / 新建 選擇如下圖
選擇第一個(gè)
下一步
在下一步中
父文件夾為
test2/src/com?
文件名為
Customer.hbm.xml
下一步
選擇如下圖
點(diǎn)擊下一步 完成 ?
建立 Order.hbm.xml 方法一致 .
將兩個(gè) xml 文件修改一下 修改部分粗體顯示了
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping
PUBLIC "-//Hibernate/Hibernate Mapping DTD 2.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">
編輯 Customer.hbm..xml?? Order.hbm.xml
Customer.hbm..xml??
<?
xml
version
=
"1.0"
?>
<!
DOCTYPE
hibernate-mapping
PUBLIC
"-//Hibernate/Hibernate Mapping DTD 2.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd"
>
<
hibernate-mapping
>
?
<
class
name
=
"com.Customer"
table
=
"CUSTOMER"
>
???
<
id
name
=
"id"
type
=
"long"
column
=
"ID"
>
?????
<
generator
class
=
"increment"
/>
???
</
id
>
???
<
property
name
=
"name"
type
=
"string"
>
???????
<
column
name
=
"NAME"
length
=
"15"
/>
???
</
property
>
?????
?
</
class
>
</
hibernate-mapping
>
Order.hbm.xml
<?
xml
version
=
"1.0"
?>
<!
DOCTYPE
hibernate-mapping
PUBLIC
"-//Hibernate/Hibernate Mapping DTD 2.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd"
>
<
hibernate-mapping
>
??
<
class
name
=
"com.Order"
table
=
"[ORDER]"
>
????
?????
<
id
name
=
"id"
type
=
"long"
column
=
"ID"
>
???????
<
generator
class
=
"increment"
/>
?????
</
id
>
??
?????
<
property
name
=
"orderNumber"
type
=
"string"
>
???????
<
column
name
=
"ORDER_NUMBER"
length
=
"15"
/>
?????
</
property
>
????
<
many-to-one
???????
name
=
"customer"
?????
??
column
=
"CUSTOMER_ID"
???????
class
=
"com.Customer"
???????
not-null
=
"true"
???????
cascade
=
"save-update"
?????
????
/>
<!-- mapping with cascade -->
<!--
????? <many-to-one
??????? name="customer"
??????? column="CUSTOMER_ID"
??????? class="mypack.Customer"
??????? cascade="save-update"?
??????? not-null="true" />
?-->
?
???
</
class
>
?
</
hibernate-mapping
>
最后建立類

package com;
//import net.sf.hibernate.*;
import net.sf.hibernate.*;
import net.sf.hibernate.SessionFactory;
import net.sf.hibernate.cfg.Configuration;
import java.util.*;
//import net.sf.hibernate.cfg.Configuration;
import java.util.*;
public class BusinessService{
? public static SessionFactory sessionFactory;
? static{
???? try{
????? // Create a configuration based on the properties file we've put
?????? Configuration config = new Configuration();
?????? config.addClass(Customer.class)
???????????? .addClass(Order.class);
????? // Get the session factory we can use for persistence
????? sessionFactory = config.buildSessionFactory();
??? }catch(Exception e){e.printStackTrace();}
? }
? public List findOrdersByCustomer(Customer customer) throws Exception{
??? Session session = sessionFactory.openSession();
??? Transaction tx = null;
??? try {
????? tx = session.beginTransaction();
????? List orders=(List)session.find("from Order as o where o.customer.id="+customer.getId());
????? tx.commit();
????? return orders;
??? }catch (Exception e) {
????? if (tx != null) {
??????? tx.rollback();
????? }
????? throw e;
??? } finally {
????? session.close();
??? }
? }
? public Customer findCustomer(long customer_id) throws Exception{
??? Session session = sessionFactory.openSession();
??? Transaction tx = null;
??? try {
????? tx = session.beginTransaction();
????? Customer customer=(Customer)session.load(Customer.class,new Long(customer_id));
????? tx.commit();
????? return customer;
??? }catch (Exception e) {
????? if (tx != null) {
??????? // Something went wrong; discard all partial changes
??????? tx.rollback();
????? }
????? throw e;
??? } finally {
????? // No matter what, close the session
????? session.close();
?? ?}
? }
? public void saveCustomerAndOrderWithCascade() throws Exception{
??? Session session = sessionFactory.openSession();
??? Transaction tx = null;
??? try {
????? tx = session.beginTransaction();
????? Customer customer=new Customer("Jack");
????? Order order1=new Order("Jack_Order001",customer);
????? Order order2=new Order("Jack_Order002",customer);
????? session.save(order1);
????? session.save(order2);
????? tx.commit();
??? }catch (Exception e) {
????? if (tx != null) {
??????? tx.rollback();
????? }
????? e.printStackTrace();
??? } finally {
????? // No matter what, close the session
????? session.close();
??? }
? }
? public void saveCustomerAndOrder() throws Exception{
? ??? ??// Ask for a session using the JDBC information we've configured
?
?????? ?
? Session session = sessionFactory.openSession();
?????? ?? Transaction tx = null;
?????? ?? try {
????? tx = session.beginTransaction();
?????
?????? Customer customer=new Customer("Tom");
?????? ?? session.save(customer);
?????? ?
??? Order order1=new Order("Tom_Order001",customer);
???? Order order2=new Order("Tom_Order002",customer);
??? session.save(order1);
???? session.save(order2);
????? // We're done; make our changes permanent
????? tx.commit();
?????? ?? /*?????
*/
??? }catch (Exception e) {
???? if (tx != null) {
??????? // Something went wrong; discard all partial changes
???? tx.rollback();
????? }
????? throw e;
??
??? } finally {
? // No matter what, close the session
????? session.close();
?
??? }
???
?
? }
? public void printOrders(List orders){
????? for (Iterator it = orders.iterator(); it.hasNext();) {
???????? Order order=(Order)it.next();
???????? System.out.println("OrderNumber of "+order.getCustomer().getName()+ " :"+order.getOrderNumber());
????? }
? }
?? public void test() throws Exception{
????? //saveCustomerAndOrder();
???? // saveCustomerAndOrderWithCascade();
????? Customer customer=findCustomer(1);
????? List orders=findOrdersByCustomer(customer);
???? printOrders(orders);
? }
? public static void main(String args[]) throws Exception {
??? new BusinessService().test();
??? sessionFactory.close();
? }
}
運(yùn)行
: BusinessService.java
在文件
BusinessService.java
點(diǎn)擊右建
運(yùn)行過(guò)程如下
查看數(shù)據(jù)庫(kù)
就可看到數(shù)據(jù)庫(kù)中添加了相關(guān)記錄
因?yàn)槲乙彩浅鯇W(xué) 如果還有什么問題 可以和我聯(lián)系 一起學(xué)習(xí)
我的 QQ397125569
posted on 2006-08-09 20:08 黃暉 閱讀(351) 評(píng)論(1) 編輯 收藏