落葉J空間

          常用鏈接

          統計

          最新評論

          我的第一個hibernate

          經過幾天的調試,我終于把調試成功了我第一個 hibernate ,之前都是學習理論知識。由于我參考的教材后臺數據庫用的是 MYSQL, hbm2java 生成 java 源代碼,用 hbm2ddl 生成數據庫實 hbm2java 。我覺得太麻煩了,而且現在主要數據庫用的最多的是 ORACLE,SQL SERVER 。所以最近一段時間我用 SQL SERVER2000+MYECLIPSE 來構建我的 hibernate 程序。因為中間因為自己的大意,出現很多不該出現的問題,導致的程序調試不成功,為了讓大家少走彎路,我將自己的經驗完整寫下來:

          開發環境:

          Sql server 2000

          Eclipse3.1.1+Myeclipse4.1.1+hibernate2.0

          myeclipse 建立數據庫的連接

          依照下圖打開 myeclipse database explore



          新建數據連接


          進入下面頁面并填寫好 NAME


          點擊 configure database drive, 進入后,點擊 new, 出現下圖,并在 driver template 選擇如圖所示


          點擊 add jars, 找到自己所下的 mssql 驅動路徑


          按確定回到下圖,并按圖填寫好其他項, name,password 為你數據庫的登陸用戶名和密碼


          一直點擊下步,完成即可。然后點擊新建的連接,打開即可

          然后再數據庫中建立兩個表 CUSTOMER . ORDER? 數據庫名為 test



          文件

          / 新建 / 其他 / 出現以下畫面


          點擊 web project 下一步后在項目名寫 test2, 點擊完成即可 .

          完成后在 test2 項目點擊右鍵 , 如下圖


          然后進入下面頁面 ,( 記得選擇 hibernate2.1 jar library installation 選第二項 , 確保設置與下圖一致 )


          下一步 / 下一步 db profile 選擇為 MSSQL1 點擊下一步 下圖 ( class: 如下圖填寫 )

          點擊完成 .

          現在我們建立對象 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 >


          最后建立類

          BusinessService.java 放置 src/com

          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 點擊右建


          運行過程如下




          查看數據庫 就可看到數據庫中添加了相關記錄



          因為我也是初學 如果還有什么問題 可以和我聯系 一起學習

          我的 QQ397125569

          posted on 2006-08-09 20:08 黃暉 閱讀(349) 評論(1)  編輯  收藏

          評論

          # re: 我的第一個hibernate 2006-08-12 10:15 java技術

          圖片壞了  回復  更多評論   


          只有注冊用戶登錄后才能發表評論。


          網站導航:
           
          主站蜘蛛池模板: 浠水县| 东莞市| 股票| 高台县| 连江县| 岱山县| 碌曲县| 呼伦贝尔市| 新郑市| 鹤山市| 稷山县| 调兵山市| 翁源县| 峨山| 桦南县| 烟台市| 陕西省| 文水县| 南京市| 新昌县| 佳木斯市| 寿光市| 曲水县| 长沙县| 石渠县| 福州市| 建昌县| 洛浦县| 日喀则市| 修武县| 新营市| 蓬莱市| 莫力| 天台县| 区。| 津南区| 苏尼特左旗| 瓦房店市| 阳山县| 肇庆市| 类乌齐县|