zoukankan      html  css  js  c++  java
  • Hibernate一对多实例

    本文向大家介绍Hibernate实例一对多的情况,可能好多人还不了解Hibernate实例一对多,没有关系,下面通过一个实例来帮助您理解Hibernate实例一对多,希望本文能教会你更多东西。

    先看由满江红翻译团队(RedSaga Translate Team)翻译的一对多配置说明,然后在看例子
    一对多关联(One-to-many Associations)

    一对多关联 通过外键 连接两个类对应的表,而没有中间集合表。 这个关系模型失去了一些Java集合的语义:

    一个被包含的实体的实例只能被包含在一个集合的实例中

    一个被包含的实体的实例只能对应于集合索引的一个值中

    一个从Product到Part的关联需要关键字字段,可能还有一个索引字段指向Part所对应的表。标记指明了一个一对多的关联。

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

    (1) class(必须):被关联类的名称。 
    (2) not-found (可选 - 默认为exception): 指明若缓存的标示值关联的行缺失,该如何处理: ignore 会把缺失的行作为一个空关联处理。 
    (3) entity-name (可选): 被关联的类的实体名,作为class的替代。 
    例子

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

    注意:元素不需要定义任何字段。 也不需要指定表名。

    重要提示

    如果Hibernate实例一对多关联中的外键字段定义成NOT NULL,你必须把映射声明为not-null="true",或者使用双向关联,并且标明inverse="true"。

    1 先建表

    1.  create   table  student  
    2. (sid  varchar ( 32 )  not   null   primary   key ,  
    3.  sname  varchar ( 16 ),  
    4.  sage  varchar ( 16 ),  
    5. )  
    6.  create   table  book  
    7. (bid  varchar ( 32 )  not   null   primary   key ,  
    8. bname  varchar ( 16 ),  
    9. bprice  varchar ( 16 ),  
    10. sid  varchar ( 32 )  
    11. )  
    12.   

    2.写vo Student.java

    1. package com.test;  
    2.  
    3. import java.util.Set;  
    4.  
    5. public class Student  
    6. {  
    7.     private String sid;  
    8.     private String sname;  
    9.     private String sage;  
    10.     private Set book;  
    11.     public Student()  
    12.     {  
    13.     }  
    14.   // 写上get set 

    Book.JAVA

    1. package com.test;  
    2.  
    3. public class Book  
    4. {  
    5.     private String bid;  
    6.     private String bname;  
    7.     private String bprice;  
    8.     public Book()  
    9.     {  
    10.     }  
    11.    //写上get set 

    3.写对应的映射文件Student.hbm.xml

    1. xml version="1.0"?> 
    2.     PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN"  
    3.     "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd"> 
    4.  
    5. <hibernate-mapping> 
    6.  
    7.     <class name="com.test.Student" table="student" > 
    8.  
    9.         <id name="sid" type="string" unsaved-value="null" > 
    10.             <column name="sid" sql-type="char(32)" not-null="true"/> 
    11.             <generator class="uuid.hex"/> 
    12.         id 
    13.  
    14.         <property name="sname"> 
    15.             <column name="sname" sql-type="varchar(16)" not-null="true"/> 
    16.         property 
    17.  
    18.         <property name="sage"> 
    19.             <column name="sage" sql-type="varchar(16)" not-null="true"/> 
    20.         property 
    21.  
    22.         <set name="book" cascade="all" outer-join="true"> 
    23.             <key column="sid"/> 
    24.             <one-to-many class="com.test.Book" /> 
    25.         set 
    26.  
    27.     class 
    28.  
    29. hibernate-mapping 

    Book.hbm.xml

    1. xml version="1.0"?> 
    2.     PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN"  
    3.     "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd"> 
    4.  
    5. <hibernate-mapping> 
    6.  
    7.     <class name="com.test.Book" table="book" > 
    8.  
    9.         <id name="bid" type="string" unsaved-value="null" > 
    10.             <column name="bid" sql-type="char(32)" not-null="true"/> 
    11.             <generator class="uuid.hex"/> 
    12.         id 
    13.  
    14.         <property name="bname"> 
    15.             <column name="bname" sql-type="varchar(16)" not-null="true"/> 
    16.         property 
    17.  
    18.         <property name="bprice"> 
    19.             <column name="bprice" sql-type="varchar(16)" not-null="true"/> 
    20.         property 
    21.  
    22.     class 
    23.  
    24. hibernate-mapping 

    接着把下面的hibernate.properties文件拷到classes目录下。。这里用的是mysql

    1. hibernate.query.substitutions true 1, false 0, yes 'Y', no 'N'  
    2. ## MySQL  
    3. hibernate.dialect net.sf.hibernate.dialect.MySQLDialect  
    4. hibernate.connection.driver_class org.gjt.mm.mysql.Driver  
    5. hibernate.connection.url jdbc:mysql://localhost:3306/wjcms  
    6. hibernate.connection.username root  
    7. hibernate.connection.password wujun  
    8. hibernate.connection.pool_size 1  
    9. hibernate.proxool.pool_alias pool1  
    10. hibernate.show_sql true  
    11. hibernate.jdbc.batch_size 0  
    12. hibernate.max_fetch_depth 1  
    13. hibernate.cache.use_query_cache true  

    4.写测试类了..

      1. package com.test;  
      2.  
      3. import net.sf.hibernate.Session;  
      4. import net.sf.hibernate.SessionFactory;  
      5. import net.sf.hibernate.cfg.Configuration;  
      6. import net.sf.hibernate.*;  
      7. import java.util.Set;  
      8. import java.util.HashSet;  
      9. import java.sql.*;  
      10. import java.util.List;  
      11. import java.util.Iterator;  
      12.  
      13. public class TestOneToMany  
      14. {  
      15.     SessionFactory sf;  
      16.     Session session;  
      17.     public TestOneToMany()  
      18.     {  
      19.         try  
      20.         {  
      21.             Configuration cfg = new Configuration();  
      22.             sf = cfg.addClass(Student.class).addClass(Book.class).buildSessionFactory();  
      23.         }  
      24.         catch(HibernateException ex)  
      25.         {  
      26.             ex.printStackTrace();  
      27.         }  
      28.     }  
      29.     //插入  
      30.     public void doCreate()  
      31.     {  
      32.         try  
      33.         {  
      34.             session = sf.openSession();  
      35.  
      36.             Student student = new Student();  
      37.             student.setSname("小王");  
      38.             student.setSage("22");  
      39.  
      40.             Set bookSet = new HashSet();  
      41.             Book book = null;  
      42.             for(int i=0;i<2;i++)  
      43.             {  
      44.                 book = new Book();  
      45.                 book.setBname("java "+i);  
      46.                 book.setBprice("50");  
      47.                 bookSet.add(book);  
      48.             }  
      49.             student.setBook(bookSet);  
      50.  
      51.             session.save(student);  
      52.             session.flush();  
      53.             session.connection().commit();  
      54.  
      55.         }  
      56.         catch(HibernateException ex)  
      57.         {  
      58.             ex.printStackTrace();  
      59.         }  
      60.         catch(SQLException ex1)  
      61.         {  
      62.             ex1.printStackTrace();  
      63.         }  
      64.         finally  
      65.         {  
      66.                 try{  
      67.                     session.close();  
      68.                 }  
      69.                 catch(HibernateException ex2){  
      70.                 }  
      71.         }  
      72.  
      73.     }  
      74.     //查询  
      75.     public void doQuery()  
      76.     {  
      77.         try{  
      78.             session = sf.openSession();  
      79.             Query q = session.createQuery("select s from Student as s");  
      80.             List l = q.list();  
      81.             Student s = null;  
      82.             Book book = null;  
      83.             for(int i=0;i<l.size();i++)  
      84.             {  
      85.                 s = (Student)l.get(i);  
      86.                 System.out.println("姓名: "+s.getSname());  
      87.                 System.out.println("年龄: "+s.getSage());  
      88.                 System.out.println("所有的书:");  
      89.                 Iterator it = s.getBook().iterator();  
      90.                 while(it.hasNext())  
      91.                 {  
      92.                     book = (Book)it.next();  
      93.                     System.out.println("书名: "+book.getBname());  
      94.                     System.out.println("价格: "+book.getBprice());  
      95.                 }  
      96.  
      97.  
      98.             }  
      99.  
      100.         }  
      101.         catch(HibernateException ex){  
      102.             ex.printStackTrace();  
      103.         }  
      104.         finally{  
      105.             try{  
      106.                 session.close();  
      107.             }  
      108.             catch(HibernateException ex2){  
      109.             }  
      110.         }  
      111.     }  
      112.     public static void main(String[] args)  
      113.     {  
      114.         TestOneToMany t = new TestOneToMany();  
      115.         //t.doCreate();  
      116.         t.doQuery();  
      117.     }  
      118. }  
  • 相关阅读:
    自动轮播
    哈夫曼树的应用-金条划分
    计算两个日期相差的天数
    数据结构之算术表达式
    动态规划-矩阵最短路径
    动态规划-换钱最少货币数
    字母数字密码破解
    荷兰国旗问题
    集合并集
    进制数位幸运数
  • 原文地址:https://www.cnblogs.com/zydzyd/p/5629266.html
Copyright © 2011-2022 走看看