参考:http://hi.baidu.com/ohaozy/blog/item/ed486a33bc83cf48ac4b5f75.html
下面是我调试过的代码
通过简单的例子说明这几个关系: 以下测试都是在mysql5下完成,数据库表是由hibernate.cfg.xml里配置了。 |
- 建类
Teacher.java
- package com.sjtu.xw.pojo;
- import java.util.HashSet;
- import java.util.Set;
- public class Teacher {
- private long id;
- private String teaName;
- private Set students = new HashSet();
- public long getId() {
- return id;
- }
- public void setId(long id) {
- this.id = id;
- }
- public String getTeaName() {
- return teaName;
- }
- public void setTeaName(String teaName) {
- this.teaName = teaName;
- }
- public Set getStudents() {
- return students;
- }
- public void setStudents(Set students) {
- this.students = students;
- }
- public String toString() {
- return "Teacher:[teacherId=" + this.id + "/tteacherName="
- + this.teaName + "]";
- }
- }
Student.java
- package com.sjtu.xw.pojo;
- public class Student {
- private long id;
- private String stuName;
- public long getId() {
- return id;
- }
- public void setId(long id) {
- this.id = id;
- }
- public String getStuName() {
- return stuName;
- }
- public void setStuName(String stuName) {
- this.stuName = stuName;
- }
- public String toString() {
- return "student:[studentId=" + this.id + "/tstudentName="
- + this.stuName + "]";
- }
- }
Student.hbm.xml
- <?xml version="1.0"?>
- <!DOCTYPE hibernate-mapping PUBLIC
- "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
- "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
- <hibernate-mapping package="com.sjtu.xw.pojo">
- <class name="Student" table="student">
- <id name="id" column="id">
- <generator class="native"></generator>
- </id>
- <property name="stuName" column="studentName" length="30" />
- </class>
- </hibernate-mapping>
Teacher.hbm.xml
- <?xml version="1.0"?>
- <!DOCTYPE hibernate-mapping PUBLIC
- "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
- "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
- <hibernate-mapping package="com.sjtu.xw.pojo">
- <class name="Teacher" table="teacher">
- <id name="id" column="id">
- <generator class="native"></generator>
- </id>
- <property name="teaName" column="teacherName" length="30" />
- <set name="students" fetch="join" lazy="false">
- <!--
- <set name="students">
- -->
- <key column="teacherId"></key>
- <!--
- 这里的column="teacherId" 是指明了在student表里有一个teacherId的列名,是指向teacher表的外键
- -->
- <one-to-many class="Student" />
- </set>
- </class>
- </hibernate-mapping>
hibernate.cfg.xml
- <?xml version='1.0' encoding='utf-8'?>
- <!DOCTYPE hibernate-configuration PUBLIC
- "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
- "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
- <hibernate-configuration>
- <session-factory>
- <!-- Database connection settings -->
- <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
- <property name="connection.url">jdbc:mysql://localhost:3306/coursems</property>
- <property name="connection.username">root</property>
- <property name="connection.password">root</property>
- <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
- <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
- <property name="show_sql">false</property>
- <mapping resource="com/sjtu/xw/pojo/Student.hbm.xml"/>
- <mapping resource="com/sjtu/xw/pojo/Teacher.hbm.xml"/>
- </session-factory>
- </hibernate-configuration>
HibernateUtil.java
- package com.sjtu.xw.util;
- import org.hibernate.SessionFactory;
- import org.hibernate.cfg.Configuration;
- public class HibernateUtil {
- private static final SessionFactory sessionFactory = buildSessionFactory();
- private static SessionFactory buildSessionFactory() {
- try {
- // Create the SessionFactory from hibernate.cfg.xml
- return new Configuration().configure().buildSessionFactory();
- }
- catch (Throwable ex) {
- // Make sure you log the exception, as it might be swallowed
- System.err.println("Initial SessionFactory creation failed." + ex);
- throw new ExceptionInInitializerError(ex);
- }
- }
- public static SessionFactory getSessionFactory() {
- return sessionFactory;
- }
- }
Test.java
- package com.sjtu.xw.test;
- import java.util.List;
- import org.hibernate.Session;
- import org.hibernate.SessionFactory;
- import org.hibernate.Transaction;
- import com.sjtu.xw.pojo.Student;
- import com.sjtu.xw.pojo.Teacher;
- import com.sjtu.xw.util.HibernateUtil;
- public class Test {
- public static void main(String[] args)
- {
- Test test=new Test();
- //test.addStudent();
- //test.addTeacher();
- test.test();
- }
- public void addStudent() {
- Student student = new Student();
- student.setStuName("student6");
- SessionFactory sf = HibernateUtil.getSessionFactory();
- Session session = sf.openSession();
- Transaction tx = session.beginTransaction();
- session.save(student);
- tx.commit();
- session.close();
- sf.close();
- }
- public void addTeacher() {
- Student student = new Student();
- student.setId(3);
- Teacher teacher = new Teacher();
- teacher.setTeaName("Teacher1");
- teacher.getStudents().add(student); // 把id为1的学生添加到教师对象
- // 保存这个教师的同时会更新student表
- SessionFactory sf = HibernateUtil.getSessionFactory();
- Session session = sf.openSession();
- Transaction tx = session.beginTransaction();
- session.save(teacher);
- tx.commit();
- session.close();
- sf.close();
- }
- public void test()
- {
- SessionFactory sf = HibernateUtil.getSessionFactory();
- Session session = sf.openSession();
- Transaction tx = session.beginTransaction();
- List list = session.createQuery("from Teacher t where t.id=1").list();
- //List list = session.createQuery("from Teacher t left join fetch t.students where t.id=1").list();
- Teacher t = (Teacher)list.get(0);
- System.out.println(t);//
- System.out.println(t.getStudents().iterator().next());
- for(int i=0;i<list.size();i++)
- {
- Teacher tt = (Teacher)list.get(i);
- System.out.println(tt);//
- System.out.println(tt.getStudents().iterator().next());
- }
- /*//未明白什么意思,和session有什么关系呢?
- * 上面这句话放在session结束前,student在用到的时候将会自动被查询出来,否则查询语句应改为:
- * from Teacher t left join fetch t.students where t.id=1
- * 或者设置teacher.hbm.xml里的set属性,加上:fetch="join" lazy="false":
- * <set name="students" fetch="join" lazy="false">
- * <key column="teacherId"></key> <one-to-many class="model.Student"/> </set>
- */
- tx.commit();
- session.close();
- sf.close();
- }
- }
本文转自xwdreamer博客园博客,原文链接:http://www.cnblogs.com/xwdreamer/archive/2010/11/30/2297066.html,如需转载请自行联系原作者