我的第一個hibernate
經(jīng)過幾天的調試,我終于把調試成功了我第一個 hibernate ,之前都是學習理論知識。由于我參考的教材后臺數(shù)據(jù)庫用的是 MYSQL, 用 hbm2java 生成 java 源代碼,用 hbm2ddl 生成數(shù)據(jù)庫實 hbm2java 。我覺得太麻煩了,而且現(xiàn)在主要數(shù)據(jù)庫用的最多的是 ORACLE,SQL SERVER 。所以最近一段時間我用 SQL SERVER2000+MYECLIPSE 來構建我的 hibernate 程序。因為中間因為自己的大意,出現(xiàn)很多不該出現(xiàn)的問題,導致的程序調試不成功,為了讓大家少走彎路,我將自己的經(jīng)驗完整寫下來:
開發(fā)環(huán)境:
Sql server 2000
Eclipse
用 myeclipse 建立數(shù)據(jù)庫的連接
依照下圖打開 myeclipse database explore
新建數(shù)據(jù)連接
進入下面頁面并填寫好 NAME
點擊 configure database drive, 進入后,點擊 new, 出現(xiàn)下圖,并在 driver template 選擇如圖所示
點擊
add jars,
找到自己所下的
mssql
驅動路徑
按確定回到下圖,并按圖填寫好其他項,
name,password
為你數(shù)據(jù)庫的登陸用戶名和密碼
一直點擊下步,完成即可。然后點擊新建的連接,打開即可
然后再數(shù)據(jù)庫中建立兩個表
CUSTOMER . ORDER?
數(shù)據(jù)庫名為
test
文件
點擊 web project 下一步后在項目名寫 test2, 點擊完成即可 .
完成后在 test2 項目點擊右鍵 , 如下圖
然后進入下面頁面
,(
記得選擇
hibernate2.1 jar library installation
選第二項
,
確保設置與下圖一致
)
下一步
/
下一步
將
db profile
選擇為
MSSQL1
點擊下一步
如
下圖
( class:
如下圖填寫
)
點擊完成 .
現(xiàn)在我們建立對象 Customer.java Order.java
文件 / 新建 / 類 ? 在彈出的窗口中 源文件夾為 test2/src 包為 com 名字為 Customer, 點擊完成即可 .
建立 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();
??? }
}
建立兩個映射文件 Customer.hbm..xml?? Order.hbm.xml
文件 / 新建 選擇如下圖
選擇第一個
下一步
在下一步中
父文件夾為
test2/src/com?
文件名為
Customer.hbm.xml
下一步
選擇如下圖
點擊下一步 完成 ?
建立 Order.hbm.xml 方法一致 .
將兩個 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();
? }
}
運行
: BusinessService.java
在文件
BusinessService.java
點擊右建
運行過程如下
查看數(shù)據(jù)庫
就可看到數(shù)據(jù)庫中添加了相關記錄
因為我也是初學 如果還有什么問題 可以和我聯(lián)系 一起學習