hibernate中one-to-many实例一

参考:http://hi.baidu.com/ohaozy/blog/item/ed486a33bc83cf48ac4b5f75.html

下面是我调试过的代码

通过简单的例子说明这几个关系:

以下测试都是在mysql5下完成,数据库表是由hibernate.cfg.xml里配置了。
one-to-many及many-to-one我以教师和学生的关系举例,一个教师对应多个学生,反过来多个学生对应一个教师。

  1. 建类

Teacher.java

[c-sharp]  view plain copy print ?
  1. package com.sjtu.xw.pojo;  
  2. import java.util.HashSet;  
  3. import java.util.Set;  
  4. public class Teacher {  
  5.     private long id;  
  6.     private String teaName;  
  7.     private Set students = new HashSet();  
  8.     public long getId() {  
  9.         return id;  
  10.     }  
  11.     public void setId(long id) {  
  12.         this.id = id;  
  13.     }  
  14.     public String getTeaName() {  
  15.         return teaName;  
  16.     }  
  17.     public void setTeaName(String teaName) {  
  18.         this.teaName = teaName;  
  19.     }  
  20.       
  21.     public Set getStudents() {  
  22.         return students;  
  23.     }  
  24.     public void setStudents(Set students) {  
  25.         this.students = students;  
  26.     }  
  27.     public String toString() {  
  28.         return "Teacher:[teacherId=" + this.id + "/tteacherName="  
  29.                 + this.teaName + "]";  
  30.     }  
  31. }  
 

Student.java

[c-sharp]  view plain copy print ?
  1. package com.sjtu.xw.pojo;  
  2. public class Student {  
  3.     private long id;  
  4.     private String stuName;  
  5.     public long getId() {  
  6.         return id;  
  7.     }  
  8.     public void setId(long id) {  
  9.         this.id = id;  
  10.     }  
  11.     public String getStuName() {  
  12.         return stuName;  
  13.     }  
  14.     public void setStuName(String stuName) {  
  15.         this.stuName = stuName;  
  16.     }  
  17.     public String toString() {  
  18.         return "student:[studentId=" + this.id + "/tstudentName="  
  19.                 + this.stuName + "]";  
  20.     }  
  21. }  
 

Student.hbm.xml

[c-sharp]  view plain copy print ?
  1. <?xml version="1.0"?>  
  2. <!DOCTYPE hibernate-mapping PUBLIC  
  3.         "-//Hibernate/Hibernate Mapping DTD 3.0//EN"  
  4.         "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">  
  5. <hibernate-mapping package="com.sjtu.xw.pojo">  
  6.     <class name="Student" table="student">  
  7.         <id name="id" column="id">  
  8.             <generator class="native"></generator>  
  9.         </id>  
  10.         <property name="stuName" column="studentName" length="30" />  
  11.     </class>  
  12. </hibernate-mapping>  
 

Teacher.hbm.xml

[c-sharp]  view plain copy print ?
  1. <?xml version="1.0"?>  
  2. <!DOCTYPE hibernate-mapping PUBLIC  
  3.         "-//Hibernate/Hibernate Mapping DTD 3.0//EN"  
  4.         "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">  
  5. <hibernate-mapping package="com.sjtu.xw.pojo">  
  6.     <class name="Teacher" table="teacher">  
  7.         <id name="id" column="id">  
  8.             <generator class="native"></generator>  
  9.         </id>  
  10.         <property name="teaName" column="teacherName" length="30" />  
  11.           
  12.         <set name="students" fetch="join" lazy="false">   
  13.         <!--   
  14.         <set name="students">  
  15.          -->  
  16.             <key column="teacherId"></key>  
  17.             <!--  
  18.                 这里的column="teacherId" 是指明了在student表里有一个teacherId的列名,是指向teacher表的外键  
  19.             -->  
  20.             <one-to-many class="Student" />  
  21.         </set>  
  22.     </class>  
  23. </hibernate-mapping>  
 

hibernate.cfg.xml

[c-sharp]  view plain copy print ?
  1. <?xml version='1.0' encoding='utf-8'?>  
  2. <!DOCTYPE hibernate-configuration PUBLIC  
  3.         "-//Hibernate/Hibernate Configuration DTD 3.0//EN"  
  4.         "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">  
  5. <hibernate-configuration>  
  6.     <session-factory>  
  7.         <!-- Database connection settings -->  
  8.         <property name="connection.driver_class">com.mysql.jdbc.Driver</property>  
  9.         <property name="connection.url">jdbc:mysql://localhost:3306/coursems</property>  
  10.         <property name="connection.username">root</property>  
  11.         <property name="connection.password">root</property>  
  12.         <property name="dialect">org.hibernate.dialect.MySQLDialect</property>  
  13.         <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>  
  14.         <property name="show_sql">false</property>  
  15.         <mapping resource="com/sjtu/xw/pojo/Student.hbm.xml"/>  
  16.         <mapping resource="com/sjtu/xw/pojo/Teacher.hbm.xml"/>  
  17.     </session-factory>  
  18. </hibernate-configuration>  
 

HibernateUtil.java

[c-sharp]  view plain copy print ?
  1. package com.sjtu.xw.util;  
  2.   
  3. import org.hibernate.SessionFactory;  
  4. import org.hibernate.cfg.Configuration;  
  5. public class HibernateUtil {  
  6.     private static final SessionFactory sessionFactory = buildSessionFactory();  
  7.     private static SessionFactory buildSessionFactory() {  
  8.         try {  
  9.             // Create the SessionFactory from hibernate.cfg.xml  
  10.             return new Configuration().configure().buildSessionFactory();  
  11.         }  
  12.         catch (Throwable ex) {  
  13.             // Make sure you log the exception, as it might be swallowed  
  14.             System.err.println("Initial SessionFactory creation failed." + ex);  
  15.             throw new ExceptionInInitializerError(ex);  
  16.         }  
  17.     }  
  18.     public static SessionFactory getSessionFactory() {  
  19.         return sessionFactory;  
  20.     }  
  21. }  
 

Test.java

[c-sharp]  view plain copy print ?
  1. package com.sjtu.xw.test;  
  2. import java.util.List;  
  3. import org.hibernate.Session;  
  4. import org.hibernate.SessionFactory;  
  5. import org.hibernate.Transaction;  
  6. import com.sjtu.xw.pojo.Student;  
  7. import com.sjtu.xw.pojo.Teacher;  
  8. import com.sjtu.xw.util.HibernateUtil;  
  9. public class Test {  
  10.     public static void main(String[] args)  
  11.     {  
  12.         Test test=new Test();  
  13.         //test.addStudent();  
  14.         //test.addTeacher();  
  15.         test.test();  
  16.     }  
  17.     public void addStudent() {  
  18.         Student student = new Student();  
  19.         student.setStuName("student6");  
  20.         SessionFactory sf = HibernateUtil.getSessionFactory();  
  21.         Session session = sf.openSession();  
  22.         Transaction tx = session.beginTransaction();  
  23.         session.save(student);  
  24.         tx.commit();  
  25.         session.close();  
  26.         sf.close();  
  27.     }  
  28.     public  void addTeacher() {  
  29.         Student student = new Student();  
  30.         student.setId(3);  
  31.         Teacher teacher = new Teacher();  
  32.         teacher.setTeaName("Teacher1");  
  33.         teacher.getStudents().add(student); // 把id为1的学生添加到教师对象  
  34.         // 保存这个教师的同时会更新student表  
  35.         SessionFactory sf = HibernateUtil.getSessionFactory();  
  36.         Session session = sf.openSession();  
  37.         Transaction tx = session.beginTransaction();  
  38.         session.save(teacher);  
  39.         tx.commit();  
  40.         session.close();  
  41.         sf.close();  
  42.     }  
  43.     public void test()   
  44.     {  
  45.         SessionFactory sf = HibernateUtil.getSessionFactory();  
  46.         Session session = sf.openSession();  
  47.         Transaction tx = session.beginTransaction();  
  48.           
  49.            List list = session.createQuery("from Teacher t where t.id=1").list();  
  50.          //List list = session.createQuery("from Teacher t left join fetch t.students where t.id=1").list();  
  51.           
  52.            Teacher t = (Teacher)list.get(0);  
  53.              
  54.            System.out.println(t);//  
  55.            System.out.println(t.getStudents().iterator().next());   
  56.            for(int i=0;i<list.size();i++)  
  57.            {  
  58.                Teacher tt = (Teacher)list.get(i);  
  59.                System.out.println(tt);//  
  60.                System.out.println(tt.getStudents().iterator().next());   
  61.            }  
  62.                   
  63.         /*//未明白什么意思,和session有什么关系呢? 
  64.          * 上面这句话放在session结束前,student在用到的时候将会自动被查询出来,否则查询语句应改为: 
  65.          * from Teacher t left join fetch t.students where t.id=1 
  66.          * 或者设置teacher.hbm.xml里的set属性,加上:fetch="join" lazy="false":  
  67.          * <set name="students" fetch="join" lazy="false">  
  68.          * <key column="teacherId"></key> <one-to-many class="model.Student"/> </set> 
  69.          */  
  70.         tx.commit();  
  71.         session.close();  
  72.         sf.close();  
  73.     }  
  74. }  

 





本文转自xwdreamer博客园博客,原文链接:http://www.cnblogs.com/xwdreamer/archive/2010/11/30/2297066.html,如需转载请自行联系原作者


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值