5.1 一对一映射
双向一对一关系需要在关系维护端(owner side)的one2one Annotition定义mappedBy属性。建表时在关系被维护端(inverse side)建立外键列指向关系维护端的主键列。
假设Country 和 Capital 是双向一对一的关系,具体元数据声明如下:
public class Country {
@OneToOne(optional = true,cascade = CascadeType.ALL, mappedBy = "country")
private Capital capital;
}
public class Capital {
@OneToOne(optional = false, cascade = CascadeType.ALL)
@JoinColumn(name = "COUNTRY_ID", referencedColumnName = "id")
private Country country;
代码中元数据的说明:
元数据描述:
@OneToOne(optional = true,cascade = CascadeType.ALL, mappedBy = "country")
optional声明关系是否是必须存在的,即是否允许其中一端为null。
cascade声明级联操作。
@JoinColumn(name = "COUNTRY_ID", referencedColumnName = "id")
name声明外键列的名字,referencedColumnName声明外键指向列的列名。
5.2 一对多映射
双向一对多关系,一是关系维护端(owner side),多是关系被维护端(inverse side)。 建表时在关系被维护端建立外键列指向关系维护端的主键列。
假设Father 和 Child 是双向一对多的关系,具体元数据声明如下:
public class Father {
@OneToMany(targetEntity = Child.class, cascade = CascadeType.ALL, mappedBy = "father")
public List<Child> getChildren() {
return children; }
}
public class Child {
@ManyToOne
@JoinColumn(name = "FATHER_ID", referencedColumnName = "id")
public Father getFather() {
return father;
}
}
代码中元数据的说明:元数据描述:
@OneToMany(targetEntity = Child.class, cascade = CascadeType.ALL, mappedBy = "father")
targetEntity = Child.class表明关系另一端的实体类型
cascade声明级联操作。
mappedBy声明关系维护端的字段(field)名。
@ManyToOne
@JoinColumn(name = "FATHER_ID", referencedColumnName = "id")
name声明外键列的名字,referencedColumnName声明外键指向列的列名。
5.3 多对多映射
多对多映射采取中间表连接的映射策略,建立的中间表将分别引入两边的主键作为外键。
EJB3对于中间表的元数据提供了可配置的方式,用户可以自定义中间表的表名,列名。
假设Teacher 和 Student是多对多的关系,具体元数据声明如下:
pubic class Teacher{
@ManyToMany(targetEntity = Student.class, cascade = CascadeType.PERSIST)
@JoinTable(table = @Table(name = "M2M_TEACHER_STUDENT"),
joinColumns = @JoinColumn(name = "TEACHER_ID", referencedColumnName = "ID"),
inverseJoinColumns = @JoinColumn(name = "STUDENT_ID", referencedColumnName = "ID"))
public List<Student> getStudents() {
return students;
}
}
public class Student{
@ManyToMany(targetEntity = Teacher.class, mappedBy = "students")
public List<Teacher> getTeachers() {
return teachers; }
}
代码中元数据的说明:
元数据描述:
@ManyToMany(targetEntity = Student.class, cascade = CascadeType.PERSIST)
targetEntity = Student.class表明关系另一端的实体类型。cascade声明级联操作。
@JoinTable(table = @Table(name = "M2M_TEACHER_STUDENT"),
joinColumns = @JoinColumn(name = "TEACHER_ID", referencedColumnName = "ID"),
inverseJoinColumns = @JoinColumn(name = "STUDENT_ID", referencedColumnName = "ID"))
JoinTable配置中间表信息,它由3个部分组成:
1) table = @Table(name = "M2M_TEACHER_STUDENT") ,声明中间表的名字
2) joinColumns ,定义中间表与关系维护端的外键关系。
3) inverseJoinColumns,定义中间表与inverse端的外键关系.
本文来自CSDN博客,出处:http://blog.csdn.net/senton/archive/2007/03/15/1529969.aspx