我有以下表格:
学生
Student_Course
场
现在,当我创建学生时,我只想创建一个用户并向student_course添加一行。 我遇到的“问题”是,当我在Student中设置课程集合为cascade =“save-update”时,也会在课程中调用更新。我想知道是否有办法阻止这种情况。
答案 0 :(得分:0)
如果确实需要这种行为,则应将@ManyToMany关系拆分为@ OneToMany-ManyToOne关系
obs:别忘了实施setter的
public class Student {
private Integer id;
public Set<StudentCourse> studentCourseSet = new HashSet<StudentCourse>();
@Id
@GeneratedValue
public Integer getId() {
return this.id;
}
/**
* Because you are using a Set collection
* You must provide equals and hashcode implementation in StudentCourse class
*/
@OneToMany(cascade=CascadeType.ALL)
@JoinColumn(name="STUDENT_ID", insertable=false, updatable=false)
public Set<StudentCourse> getStudentCourseSet() {
return this.studentCourseSet;
}
/**
* add convenience method
*/
public void addCourse(Course course) {
getStudentCourseSet().add(new StudentCourseId(getId(), course.getId()));
}
/**
* Feel free to implement your StudentCourse class outside Student one
*/
@Entity
@Table(name="<TABLE_NAME_GOES_HERE>")
public static class StudentCourse {
private StudentCourseId studentCourseId;
public Student student;
public Course course;
/**
* required no-arg constructor
*/
public StudentCourse() {}
public StudentCourse(StudentCourseId studentCourseId) {
this.studentCourseId = studentCourseId;
}
@EmbeddedId
public StudentCourseId getStudentCourseId() {
return this.studentCourseId;
}
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="STUDENT_ID", insertable=false, updatable=false)
public Student getStudent() {
return this.student;
}
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="COURSE_ID", insertable=false, updatable=false)
public Course getCourse() {
return this.course;
}
@Embeddable
public static class StudentCourseId implements Serializable {
private Integer studentId;
private Integer courseId;
/**
* required no-arg constructor
*/
public StudentCourseId() {}
public StudentCourseId(Integer studentId, Integer courseId) {
this.studentId = studentId;
this.courseId = courseId;
}
@Column(name="STUDENT_ID", nullable=false)
public Integer getStudentId() {
return this.studentId;
}
@Column(name="COURSE_ID", nullable=false)
public Integer getCourseId() {
return this.courseId;
}
// required equals and hashcode
public boolean equals(Object o) {
if(o == null)
return false;
if(!(o instanfeof StudentCourseId))
return false;
StudentCourseId other = (StudentCourseId) o;
if(!(getStudentId().equals(o.getStudentId())))
return false;
if(!(getCourseId().equals(o.getCourseId())))
return false;
return false;
}
public int hashcode() {
// hashcode impl goes here
}
}
}
}