hibernate之OneToMany和ManyToOne

hibernate一对多,多对一双向关联

假设一个老师对应多门课程,一门课程只对应一个老师

 

 

@OneToMany(mappedBy="teacher",fetch=FetchType.LAZY,cascade={CascadeType.MERGE,CascadeType.REMOVE})
private Set<Course> courses = new HashSet<Course>();

@ManyToOne(cascade={CascadeType.MERGE})
@JoinColumn(name = "teacher_id")
private Teacher teacher;

对于一对多,如果要在一的这一端维持关系,则需要删除mappedBy配置,如下

 

 

@OneToMany(fetch=FetchType.LAZY,cascade={CascadeType.MERGE,CascadeType.REMOVE})
@JoinColumn(name = "teacher_id")
private Set<Course> courses = new HashSet<Course>();

@ManyToOne(cascade={CascadeType.MERGE})
@JoinColumn(name = "teacher_id",insertable=false,updatable=false)
private Teacher teacher;

 这种方案得不到什么优化,反而会产生大量的update语句,推荐使用对一种方案

 

你可能感兴趣的:(Hibernate)