使用Set而不是List时发生JsonMappingException

Dan*_*nda 5 javascript java spring json hibernate

我有一个带有某些实体的spring boot项目,具体来说,我有一个带有DesiredCourses列表的Student Class,该列表应该是Set <>。

当我使用时:

@OneToMany(mappedBy = "student", cascade = CascadeType.ALL)
public List<StudentDesiredCourseEntity> getStudentDesiredCourses() {
    return studentDesiredCourses;
}

public void setStudentDesiredCourses(List<StudentDesiredCourseEntity> studentDesiredCourses) {
    this.studentDesiredCourses = studentDesiredCourses;
}
Run Code Online (Sandbox Code Playgroud)

一切正常,但是当我使用

@OneToMany(mappedBy = "student", cascade = CascadeType.ALL)
public Set<StudentDesiredCourseEntity> getStudentDesiredCourses() {
    return studentDesiredCourses;
}

public void setStudentDesiredCourses(Set<StudentDesiredCourseEntity> studentDesiredCourses) {
    this.studentDesiredCourses = studentDesiredCourses;
}
Run Code Online (Sandbox Code Playgroud)

我懂了

org.springframework.http.converter.HttpMessageNotReadableException",
"message":"Could not read JSON: (was java.lang.NullPointerException) (through reference chain: edu.cs6310.project4.entities.StudentEntity[\"studentDesiredCourses\"]->java.util.HashSet[0]); nested exception is com.fasterxml.jackson.databind.JsonMappingException: (was java.lang.NullPointerException) (through reference chain: edu.cs6310.project4.entities.StudentEntity[\"studentDesiredCourses\"]->java.util.HashSet[0])
Run Code Online (Sandbox Code Playgroud)

是否有我想念的东西或需要做的其他事情?

根据要求,等于和哈希码

@Override
public boolean equals(Object o) {
    if (this == o) return true;
    if (!(o instanceof StudentDesiredCourseEntity)) return false;

    StudentDesiredCourseEntity that = (StudentDesiredCourseEntity) o;

    if (!course.equals(that.course)) return false;
    if (!priority.equals(that.priority)) return false;
    if (!student.equals(that.student)) return false;

    return true;
}

@Override
public int hashCode() {
    int result = priority.hashCode();
    result = 31 * result + course.hashCode();
    result = 31 * result + student.hashCode();
    return result;
}
Run Code Online (Sandbox Code Playgroud)

Dan*_*nda 4

正如 alexwen 在评论中提到的,这不起作用的原因是没有处理 hashcode/equals 方法中的空值