一对一外键关联映射(单向)
一对一外键关联映射(双向)
一对一主键关联映射(在实际中很少使用) 使用@PrimaryKeyJoinColumn
一对一主键关联映射
主:
@OneToOne(Cascade={CascadeType.ALL},fetch=FetchType.LAZY,optional=false)
@JoinColumn(name="id",insertable=false,updatable=false)
public MokeTextbook getXXXX() {
return xxxx;
}
关联方:
@Id
public String getMokeId() {
return mokeId;
}
一对一外键关联映射(单向) Husband---->Wife
引用
public class Husband{
@OneToOne(Cascade={CascadeType.ALL})
@JoinColumn(name="wife_id",unique=true)
private Wife getWife(){
.........
}
@JoinColum设置了外键的名称为wife_id(数据库字段名),如果不设置,则默认为另一类的属性名+ _id
}
2)一对一外键关联映射(双向)Husband <---> Wife
引用
public class Husband{
private Wife wife;
@OneToOne(cascade=CascadeType.ALL)
@JoinColumn(name="wife_id",unique=true)
public Wife getWife(){…} ... }
public Class Wife{
private Husband husband;
@OneToOne(mappedBy="wife",cascade=CascadeType.ALL))
public Husband getHusband(){
//需要加上mappedBy="wife",如果不加上的话,Wife也会生成一个外键(husband_id)
/**
mappedby="wife"需要指向与他关联对象的一个属性(即Husband类里面的wife属性),这里的会在Husband表里面生成个外键wife_id字段,而Wife表里则不会生成。这里Husband作为维护端即主体端,Wife作为被维护端。
*/
}
}
多对一关联映射(单向) Students ---> Group
引用
public class Students {
private Group group;
@ManyToOne(targetEntity= Group.class)
@JoinColumn(name="group_id")
public Group getGroup(){…} … }
public class Group{ }
一对多关联映射(单向) Group----》Student
引用
一对多关联映射(单向)Group ---> Students public class Group{
private Set<Students> students = new HashSet<Students>(0);
@OneToMany
@JoinColumn(name="group_id")
public Set<Students>
getStudents() {…} … }
public class Students{ }
/**
如果只写@OneToMany的话,hibernate会建一张中间表来 维护他们之间的关系,
加上@JoinColumn(name="Group_id"),则不会建中间表,他会在 多的一端加上外键Group_id,来维护他们之间的关系
*/
一对多双向关联
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name="pid" ,nullable = true)
@NotFound(action=NotFoundAction.IGNORE)
public MokeStep getParent() {
return parent;
}
public void setParent(MokeStep parent) {
this.parent = parent;
}
@OneToMany(cascade =CascadeType.ALL,fetch = FetchType.LAZY,mappedBy="parent")
@OrderBy(value="sorts ASC")
public List<MokeStep> getChildren() {
return children;
}
多对多关联关系映射
多对多关联映射(单向)Teachers --->
Students public class Teachers{
private Set<Students> students = new HashSet<Students>(0);
@ManyToMany
@JoinTable(name="Teacher_Students",
joinColumns={@JoinColumn(name=" students_id")},
inverseJoinColumns={@JoinColumn(name="teachers_id ")} )
public Set<Students> getStudents() {…} … }
public class Students{ }
多对多关联映射(双向)
引用
多对多关联映射(双向) Teachers <---> Students
public class Teachers{
private Set<Students> students = new HashSet<Students>(0);
@ManyToMany
@JoinTable(name="Teacher_Students", joinColumns={@JoinColumn(name="teachers_id")}, inverseJoinColumns ={@JoinColumn(name="students_id")} )
public Set<Students> getStudents() {…} … }
public class Students{ private Set<Teachers>
teachers = new HashSet<Teachers>(0);
@ManyToMany(mappedBy="students")
public Set<Teachers> getTeachers() {…} }