关于关系的一些基本知识点,请查看总结篇:Hibernate 关系映射
对象模型:
teacher 和student,多对多。且可以由teacher找到student,即teacher中含有student的集合。 此时会产生中间表。
表结构为:teacher(id, name); student(id, name); tea_stu(tea_id, stu_id);
其中tea_id为外键参考teacher的id,stu_id为外键,参考student的id。 tea_id, stu_id为联合主键
Annotation方式:
由于是teacher为主导,所以配置方式如下:在getStudents()方法上注解:
@ManyToMany
@JoinTable(
name="tea_stu", //表示中间表的名称是tea_stu
joinColumns={@JoinColumn(name="tea_id")}, //表示中间表中参考本类id的外键名称是tea_id
inverseJoinColumns={@JoinColumn(name="stu_id")} //表示中间表中参考另一个类id的外键名称是stu_id
)
其中如果是联合主键的情况,joinColumns或inverseJoinColumns应该是多个字段的集合
具体代码如下:
package com.zyh.hibernate;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
@Entity
@Table(name="teacher")
public class Teacher {
private int id;
private String name;
private Set<Student> students = new HashSet<Student>();
@Id
@GeneratedValue
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@ManyToMany
@JoinTable(
name="tea_stu",//表示中间表的名称
joinColumns={@JoinColumn(name="tea_id")},//表示中间表中参考本类id的外键名称
inverseJoinColumns={@JoinColumn(name="stu_id")}//表示中间表中参考另一个类id的外键名称
)
public Set<Student> getStudents() {
return students;
}
public void setStudents(Set<Student> students) {
this.students = students;
}
}
package com.zyh.hibernate;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="student")
public class Student {
private int id;
private String name;
@Id
@GeneratedValue
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
xml方式:
在teacher.hbm.xml中配置: <!-- 中间表名称为"t_s" -->
<set name="students" table="t_s">
<!-- 表示中间表中参考本类id的外键名称为"tea_id" -->
<key column="tea_id"></key>
<!-- 表示中间表中参考另一个类id的外键名称是"stu_id" -->
<many-to-many class="com.zyh.hibernate.Student" column="stu_id" ></many-to-many>
</set>
详细配置如下:
Teacher.hbm.xml:
<hibernate-mapping>
<class name="com.zyh.hibernate.Teacher" table="_teacher">
<id name="id" column="id">
<generator class="native"></generator>
</id>
<property name="name" column="name" />
<!-- 中间表名称为"t_s" -->
<set name="students" table="t_s">
<!-- 表示中间表中参考本类id的外键名称为"tea_id" -->
<key column="tea_id"></key>
<!-- 表示中间表中参考另一个类id的外键名称是"stu_id" -->
<many-to-many class="com.zyh.hibernate.Student" column="stu_id" ></many-to-many>
</set>
</class>
</hibernate-mapping>
Student.hbm.xml:
<hibernate-mapping>
<class name="com.zyh.hibernate.Student" table="_stu">
<id name="id" column="id">
<generator class="native"></generator>
</id>
<property name="name" column="name" />
</class>
</hibernate-mapping>