使用Set而不是List时出现JsonMappingException

5

我有一个Spring Boot项目,其中包含一些实体。具体来说,我有一个“学生”类,其中包含一个“期望课程列表”,应该是一个Set<>。

当我使用以下代码时:

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

public void setStudentDesiredCourses(List<StudentDesiredCourseEntity> studentDesiredCourses) {
    this.studentDesiredCourses = studentDesiredCourses;
}

一切正常,但当我使用

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

public void setStudentDesiredCourses(Set<StudentDesiredCourseEntity> studentDesiredCourses) {
    this.studentDesiredCourses = studentDesiredCourses;
}

我获取

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])

我是否漏掉了什么或需要额外做些什么?

根据要求,需要编写equals和hashcode方法。

@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;
}

1
我在想HashCode或Equals方法是否可能是罪魁祸首,你有StudentDesiredCourseEntity的HashCode和Equals吗? - alexwen
发布了等于和哈希码。 - Daniel Esponda
啊,你知道吗,我从来没有考虑过我的学生或课程可能返回为空……我敢打赌这就是问题所在。 - Daniel Esponda
非常感谢 @alexwen,就是这样! - Daniel Esponda
2个回答

4

如评论中的alexwen所述,这个方法没有起作用是因为在hashcode/equals方法中没有处理null值。


2

1
我认为这是一个足够常见的请求,应该可以自动处理... - Daniel Esponda
1
Jackson支持集合,我认为这里可能发生了其他事情。 - alexwen

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接