我有一个带有cooperator
和student
模型(以及其他模型)的spring boot应用程序。他们在合作者方面有@oneToMany关系,在学生方面有@ManyToOne
合作伙伴类:
@Entity
public class Cooperator{
private Integer id;
public void setId(Integer value) {
this.id = value;
}
@Id
public Integer getId() {
return this.id;
}
private Set<Student> student;
@OneToMany(mappedBy="cooperator", cascade={CascadeType.ALL})
public Set<Student> getStudent() {
return this.student;
}
public void setStudent(Set<Student> students) {
this.student = students;
}
public void addStudent(Student student) {
try {
this.student.add(student);
}
catch(Exception e) {
this.student = new HashSet<Student>();
this.student.add(student);
}
}
}
学生班:
@Entity
public class Student{
private String studentID;
public void setStudentID(String value) {
this.studentID = value;
}
@Id
public String getStudentID() {
return this.studentID;
}
private Cooperator cooperator;
@ManyToOne(optional=false)
public Cooperator getCooperator() {
return this.cooperator;
}
public void setCooperator(Cooperator cooperator) {
this.cooperator = cooperator;
}
}
我正在通过以下方式测试这种关系:
@Test
public void cooperatorStudent() {
String studentID = "260632353";
String firstname = "Saleh";
String lastname = "Bakhit";
Student student1 = service.createStudent(studentID, firstname, lastname, cooperator);
assertEquals(cooperator, student1.getCooperator());
studentID = "260632350";
firstname = "testFirst";
lastname = "testLast";
Student student2 = service.createStudent(studentID, firstname, lastname, cooperator);
assertEquals(cooperator, student2.getCooperator());
Set<Student> cooperatorStudents = cooperator.getStudent();
assertTrue(cooperatorStudents.contains(student1));
assertTrue(cooperatorStudents.contains(student2));
}
问题是即使cooperatorStudents
实际上包含两个student
对象,assertTrue语句也会失败。
非常感谢为什么提供帮助。
EDIT
我将student
添加到cooperator
中Set<Student> student
的{{1}}中,这是它的代码:
createStudent
在创建第二个学生时,还添加@override哈希码和equals会产生stackoverflow
答案 0 :(得分:0)
然后,您要比较对象,则必须覆盖“等于”和“哈希码”方法。默认情况下,每个类实例“对象”都是唯一的,尽管它们的字段相同。很好的解释:https://dzone.com/articles/working-with-hashcode-and-equals-in-java
答案 1 :(得分:0)
据我所知,您没有在测试方法中将学生对象添加到合作者中。
在测试方法中调用addStudent()
方法应该可以解决问题。
@Test
public void cooperatorStudent() {
String studentID = "260632353";
String firstname = "Saleh";
String lastname = "Bakhit";
Student student1 = service.createStudent(studentID, firstname, lastname, cooperator);
assertEquals(cooperator, student1.getCooperator());
studentID = "260632350";
firstname = "testFirst";
lastname = "testLast";
Student student2 = service.createStudent(studentID, firstname, lastname, cooperator);
assertEquals(cooperator, student2.getCooperator());
cooperator.addStudent(student1);
cooperator.addStudent(student2);
Set<Student> cooperatorStudents = cooperator.getStudent();
assertTrue(cooperatorStudents.contains(student1));
assertTrue(cooperatorStudents.contains(student2));
}