blogjava's web log

          blogjava's web log
          ...

          hibernate一對多例子-已更新(二)

          先看由滿江紅翻譯團隊(RedSaga Translate Team)翻譯的一對多配置說明
          然后在看例子
          ?一對多關聯(One-to-many Associations)

          一對多關聯 通過外鍵 連接兩個類對應的表,而沒有中間集合表。 這個關系模型失去了一些Java集合的語義:

          • 一個被包含的實體的實例只能被包含在一個集合的實例中

          • 一個被包含的實體的實例只能對應于集合索引的一個值中

          一個從ProductPart的關聯需要關鍵字字段,可能還有一個索引字段指向Part所對應的表。 <one-to-many>標記指明了一個一對多的關聯。

          <one-to-many 
                  class="ClassName"                                  (1)
                  not-found="ignore|exception"                       (2)
                  entity-name="EntityName"                           (3)
                  node="element-name"
                  embed-xml="true|false"
              />
          (1)

          class(必須):被關聯類的名稱。

          (2)

          not-found (可選 - 默認為exception): 指明若緩存的標示值關聯的行缺失,該如何處理: ignore 會把缺失的行作為一個空關聯處理。

          (3)

          entity-name (可選): 被關聯的類的實體名,作為class的替代。

          例子

          <set name="bars">
              <key column="foo_id"/>
              <one-to-many class="org.hibernate.Bar"/>
          </set>

          注意:<one-to-many>元素不需要定義任何字段。 也不需要指定表名。

          重要提示 :如果一對多關聯中的外鍵字段定義成NOT NULL,你必須把<key>映射聲明為not-null="true",或者使用雙向關聯,并且標明inverse="true"

          詳細請看http://www.huihoo.com/framework/hibernate/reference-v3_zh-cn/collections.html



          1 先建表

          create ? table ?student
          (sid?
          varchar ( 32 )? not ? null ? primary ? key ,
          ?sname?
          varchar ( 16 ),
          ?sage?
          varchar ( 16 ),
          )
          create ? table ?book
          (bid?
          varchar ( 32 )? not ? null ? primary ? key ,
          bname?
          varchar ( 16 ),
          bprice?
          varchar ( 16 ),
          sid?
          varchar ( 32 )
          )
          2.寫vo
          ? Student.java
          package?com.test;

          import?java.util.Set;

          public?class?Student
          {
          ????
          private?String?sid;
          ????
          private?String?sname;
          ????
          private?String?sage;
          ????
          private?Set?book;
          ????
          public?Student()
          ????
          {
          ????}

          ??
          //?寫上get?set
          Book.JAVA
          package?com.test;

          public?class?Book
          {
          ????
          private?String?bid;
          ????
          private?String?bname;
          ????
          private?String?bprice;
          ????
          public?Book()
          ????
          {
          ????}

          ???
          //寫上get?set
          3.寫對應的映射文件
          Student.hbm.xml
          <?xml?version="1.0"?>
          <!DOCTYPE?hibernate-mapping
          ????PUBLIC?"-//Hibernate/Hibernate?Mapping?DTD//EN"
          ????"http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd"
          >

          <hibernate-mapping>

          ????
          <class?name="com.test.Student"?table="student"?>

          ????????
          <id?name="sid"?type="string"?unsaved-value="null"?>
          ????????????
          <column?name="sid"?sql-type="char(32)"?not-null="true"/>
          ????????????
          <generator?class="uuid.hex"/>
          ????????
          </id>

          ????????
          <property?name="sname">
          ????????????
          <column?name="sname"?sql-type="varchar(16)"?not-null="true"/>
          ????????
          </property>

          ????????
          <property?name="sage">
          ????????????
          <column?name="sage"?sql-type="varchar(16)"?not-null="true"/>
          ????????
          </property>

          ????????
          <set?name="book"?cascade="all"?outer-join="true">
          ????????????
          <key?column="sid"/>
          ????????????
          <one-to-many?class="com.test.Book"?/>
          ????????
          </set>

          ????
          </class>

          </hibernate-mapping>

          Book.hbm.xml
          <?xml?version="1.0"?>
          <!DOCTYPE?hibernate-mapping
          ????PUBLIC?"-//Hibernate/Hibernate?Mapping?DTD//EN"
          ????"http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd"
          >

          <hibernate-mapping>

          ????
          <class?name="com.test.Book"?table="book"?>

          ????????
          <id?name="bid"?type="string"?unsaved-value="null"?>
          ????????????
          <column?name="bid"?sql-type="char(32)"?not-null="true"/>
          ????????????
          <generator?class="uuid.hex"/>
          ????????
          </id>

          ????????
          <property?name="bname">
          ????????????
          <column?name="bname"?sql-type="varchar(16)"?not-null="true"/>
          ????????
          </property>

          ????????
          <property?name="bprice">
          ????????????
          <column?name="bprice"?sql-type="varchar(16)"?not-null="true"/>
          ????????
          </property>

          ????
          </class>

          </hibernate-mapping>

          接著把下面的hibernate.properties文件拷到classes目錄下。。這里用的是mysql
          hibernate.query.substitutions?true?1,?false?0,?yes?'Y',?no?'N'
          ##?MySQL
          hibernate.dialect?net.sf.hibernate.dialect.MySQLDialect
          hibernate.connection.driver_class?org.gjt.mm.mysql.Driver
          hibernate.connection.url?jdbc:mysql://localhost:3306/wjcms
          hibernate.connection.username?root
          hibernate.connection.password?wujun
          hibernate.connection.pool_size?1
          hibernate.proxool.pool_alias?pool1
          hibernate.show_sql?true
          hibernate.jdbc.batch_size?0
          hibernate.max_fetch_depth?1
          hibernate.cache.use_query_cache?true?
          4.寫測試類了..
          package?com.test;

          import?net.sf.hibernate.Session;
          import?net.sf.hibernate.SessionFactory;
          import?net.sf.hibernate.cfg.Configuration;
          import?net.sf.hibernate.*;
          import?java.util.Set;
          import?java.util.HashSet;
          import?java.sql.*;
          import?java.util.List;
          import?java.util.Iterator;

          public?class?TestOneToMany
          {
          ????SessionFactory?sf;
          ????Session?session;
          ????
          public?TestOneToMany()
          ????
          {
          ????????
          try
          ????????
          {
          ????????????Configuration?cfg?
          =?new?Configuration();
          ????????????sf?
          =?cfg.addClass(Student.class).addClass(Book.class).buildSessionFactory();
          ????????}

          ????????
          catch(HibernateException?ex)
          ????????
          {
          ????????????ex.printStackTrace();
          ????????}

          ????}

          ????
          //插入
          ????public?void?doCreate()
          ????
          {
          ????????
          try
          ????????
          {
          ????????????session?
          =?sf.openSession();

          ????????????Student?student?
          =?new?Student();
          ????????????student.setSname(
          "小王");
          ????????????student.setSage(
          "22");

          ????????????Set?bookSet?
          =?new?HashSet();
          ????????????Book?book?
          =?null;
          ????????????
          for(int?i=0;i<2;i++)
          ????????????
          {
          ????????????????book?
          =?new?Book();
          ????????????????book.setBname(
          "java?"+i);
          ????????????????book.setBprice(
          "50");
          ????????????????bookSet.add(book);
          ????????????}

          ????????????student.setBook(bookSet);

          ????????????session.save(student);
          ????????????session.flush();
          ????????????session.connection().commit();

          ????????}

          ????????
          catch(HibernateException?ex)
          ????????
          {
          ????????????ex.printStackTrace();
          ????????}

          ????????
          catch(SQLException?ex1)
          ????????
          {
          ????????????ex1.printStackTrace();
          ????????}

          ????????
          finally
          ????????
          {
          ????????????????
          try{
          ????????????????????session.close();
          ????????????????}

          ????????????????
          catch(HibernateException?ex2){
          ????????????????}

          ????????}


          ????}

          ????
          //查詢
          ????public?void?doQuery()
          ????
          {
          ????????
          try{
          ????????????session?
          =?sf.openSession();
          ????????????Query?q?
          =?session.createQuery("select?s?from?Student?as?s");
          ????????????List?l?
          =?q.list();
          ????????????Student?s?
          =?null;
          ????????????Book?book?
          =?null;
          ????????????
          for(int?i=0;i<l.size();i++)
          ????????????
          {
          ????????????????s?
          =?(Student)l.get(i);
          ????????????????System.out.println(
          "姓名:?"+s.getSname());
          ????????????????System.out.println(
          "年齡:?"+s.getSage());
          ????????????????System.out.println(
          "所有的書:");
          ????????????????Iterator?it?
          =?s.getBook().iterator();
          ????????????????
          while(it.hasNext())
          ????????????????
          {
          ????????????????????book?
          =?(Book)it.next();
          ????????????????????System.out.println(
          "書名:?"+book.getBname());
          ????????????????????System.out.println(
          "價格:?"+book.getBprice());
          ????????????????}



          ????????????}


          ????????}

          ????????
          catch(HibernateException?ex){
          ????????????ex.printStackTrace();
          ????????}

          ????????
          finally{
          ????????????
          try{
          ????????????????session.close();
          ????????????}

          ????????????
          catch(HibernateException?ex2){
          ????????????}

          ????????}

          ????}

          ????
          public?static?void?main(String[]?args)
          ????
          {
          ????????TestOneToMany?t?
          =?new?TestOneToMany();
          ????????
          //t.doCreate();
          ????????t.doQuery();
          ????}

          }


          好了。。

          在這里把這些例子幾下來。。方便查閱。。

          也是很適合象我們這樣的出學者。。。

          posted on 2006-04-07 00:07 record java and net 閱讀(20679) 評論(9)  編輯  收藏 所屬分類: java

          評論

          # re: hibernate一對多例子-方便以后查看(二) 2006-04-13 11:48 foreverjiang

          一對一,一對多,多對多概念不理解,簡單描述一下好吧  回復  更多評論   

          # re: hibernate一對多例子-方便以后查看(二) 2006-04-13 14:44 吳某人-不斷地學習

          概念上的東西,我建議你還是買一本 夏昕的那本<<深入淺出hibernate>>吧。這本書講的很詳細的。


          那些配置文件概念上的東西,你在blogjava搜索一下,有很多人寫了這些基礎的東西。

          http://www.aygfsteel.com/georgehill/category/1286.html
            回復  更多評論   

          # re: hibernate一對多例子-已更新(二) 2006-06-05 15:59 williem

          為什么我在枚舉BOOK是會沒有值?
          我稍稍修改了你的代碼為:
          Set set=s.getBook();
          System.out.println(set.size());
          測試set的長得是0  回復  更多評論   

          # re: hibernate一對多例子-已更新(二) [未登錄] 2008-08-04 11:18 Michael

          net.sf.hibernate.這個是一什么包  回復  更多評論   

          # re: hibernate一對多例子-已更新(二) [未登錄] 2008-12-08 12:31 韓振超

          在doCreate()中 for(int i=0;i<2;i++)
          {
          book = new Book();
          book.setBname("java "+i);
          book.setBprice("50");
          bookSet.add(book);
          }
          student.setBook(bookSet);

          session.save(student);
          我和你做了一個相似的例子,但是在上面的代碼段出錯了。
          錯誤:
          Caused by: java.sql.SQLException: 違反了 PRIMARY KEY 約束 'PK_ORDER'。不能在對象 'CUSORDER' 中插入重復鍵。
          即:在插入兩個book的時候,hibernate給他們生成了相同的主鍵。
          不知道為什么!!!!  回復  更多評論   

          # re: hibernate一對多例子-已更新(二) [未登錄] 2008-12-08 16:40 韓振超

          樓主 你的 <set name="book" cascade="all" outer-join="true">
          <key column="sid"/>
          <one-to-many class="com.test.Book" />
          </set>
          中的column的值應該對應的是book中的一個column吧。
          book中的這個column儲存著student的主鍵的值。  回復  更多評論   

          # re: hibernate一對多例子-已更新(二) 2009-04-09 17:57 bb

          非常感謝,添加成功,要代碼的發郵件到lwl@cgrs.com.cn  回復  更多評論   

          # re: hibernate一對多例子-已更新(二) 2012-06-04 14:59 34

          Connection cannot be null when 'hibernate.dialect' not set  回復  更多評論   

          # re: hibernate一對多例子-已更新(二) 2013-05-07 11:11 luchas

          @bb
          麻煩發一份代碼到 526230531@qq.com , 研究學習,謝謝  回復  更多評論   

          導航

          常用鏈接

          留言簿(44)

          新聞檔案

          2.動態語言

          3.工具箱

          9.文檔教程

          友情鏈接

          搜索

          最新評論

          主站蜘蛛池模板: 花莲县| 镇江市| 舟山市| 巫溪县| 岳西县| 革吉县| 迁安市| 嘉峪关市| 永安市| 凤阳县| 右玉县| 杂多县| 博客| 铜梁县| 彭山县| 泉州市| 陇南市| 怀远县| 永吉县| 苍梧县| 南昌县| 云阳县| 页游| 锦州市| 珠海市| 甘德县| 阳曲县| 永丰县| 原阳县| 弥渡县| 长子县| 政和县| 郓城县| 四会市| 滦平县| 延边| 甘孜| 普格县| 六安市| 宣武区| 双流县|