可以发现,添加一个教师的同时指定一个学生,这种方式相当糟糕,合理的方式应该是在添加学生的时候指定教师。即在学生类里指
定教师对象,配置文件里配置成many-to-one。
单纯只使用many-to-one:在Student类里加入Teacher teacher属性。注释掉teacher.hbm.xml里的<set ...></set>内容在student.hbm.xml里入many-to-one属性:
<?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.pojo2"> <class name="Student" table="student"> <id name="id" column="id"> <generator class="native"></generator> </id> <property name="stuName" column="studentName" length="30" /> <many-to-one name="teacher" column="teacherId" class="Teacher" fetch="join" lazy="false" /> <!-- 这里的column="teacherId"是指明了自身(student表)表里的teacherId属性,指向teacher表的外键 --> </class> </hibernate-mapping>
做完上述工作即可进行测试了:
Test2.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.pojo2.Student; import com.sjtu.xw.pojo2.Teacher; import com.sjtu.xw.util.HibernateUtil; public class Test2 { public static void main(String[] args) { Test2 test = new Test2(); // test.addStudent();//通过 //test.addTeacher();//通过 test.test(); } public void addStudent() { Teacher teacher = new Teacher(); teacher.setId(1); Student student = new Student(); student.setStuName("student8"); student.setTeacher(teacher); SessionFactory sf = HibernateUtil.getSessionFactory(); Session session = sf.openSession(); Transaction tx = session.beginTransaction(); session.save(student); tx.commit(); session.close(); sf.close(); } public void addTeacher() { Teacher teacher = new Teacher(); teacher.setTeaName("Teacher5"); 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 Student s where s.id=1").list(); Student s = (Student) list.get(0);//找student的id为1的学生,并获取老师的信息。 // System.out.println(s); System.out.println(s.getTeacher()); System.out.println(s.getTeacher().getTeaName()); tx.commit(); session.close(); sf.close(); } }