前言
之前写的一对一
这次写写多对一、一对多
准备
一个Hibernate环境的Java项目
这个之前的帖子有
就不再写了
一对多(多对一)
这里用老师和学生来做例子
一个老师有多个学生
一个学生只能属于一个老师
Teacher类
1 2 3 4 5 6 7
| public class Teacher { private int id; private String name; private Set<Student> list = new HashSet<>(); }
|
Teacher类对应的Teacher.hbm.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="pojo.Teacher"> <id name="id"> <generator class="native"></generator> </id> <property name="name"></property> <set name="list">
<key column="teacher_id"></key> <one-to-many class="pojo.Student"></one-to-many> </set> </class> </hibernate-mapping>
|
Student类
1 2 3 4 5 6
| public class Student { private int id; private String name; private Teacher teacher; }
|
Student类对应的Student.hbm.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="pojo.Student"> <id name="id"> <generator class="native"></generator> </id> <property name="name"></property> <many-to-one name="teacher" column="teacher_id"></many-to-one> </class> </hibernate-mapping>
|
写个测试类测试下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| public class HibernateTest {
@Test public void test01() { Session session = SessionUtil.getSession(); Transaction transaction = session.beginTransaction(); Teacher teacher = new Teacher(); teacher.setName("teacher"); Student student1 = new Student(); student1.setName("student1"); Student student2 = new Student(); student2.setName("student2"); teacher.getList().add(student1); teacher.getList().add(student2); student1.setTeacher(teacher); student2.setTeacher(teacher); session.save(teacher); session.save(student1); session.save(student2);
transaction.commit(); session.close(); SessionUtil.close(); } }
|
运行之后
就可以看到
Teacher表
Student表
Student表中的外键
后记
多对一还好
不是特别的难理解