注册后如何解决将实体添加到ManyToMany的问题

时间:2019-11-06 10:39:35

标签: java spring spring-security nullpointerexception spring-data

我需要检查用户的电子邮件是否已添加到学生列表中,如果已添加,请将该用户与课程联系起来。

我已经检查了所有引用和其他引用,但是我仍然得到NullPointer

用户实体

    private String name;
    private String password;
    private String email;

@ManyToMany(cascade = {CascadeType.MERGE})
    @JoinTable(
            name = "Student_Courses",
            joinColumns = {@JoinColumn(name = "student_id")},
            inverseJoinColumns = {@JoinColumn(name = "course_id")}
    )
    private Set<Course> availableCourses;

课程实体

@ManyToMany(mappedBy = "availableCourses")
    private Set<User> users = new HashSet<>();

CourseStudentEmails(课程中的学生电子邮件条目

@ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.MERGE)
    @JoinColumn(name = "course_id", nullable = false)
    private Course course;

    private String email;

CourseService

public void bindStudentWithCoursesAfterRegistration(String email) {

        User user = userRepo.findFirstByEmail(email);
        List<CourseStudentEmails> studentEntriesInCourses = courseStudentEmailsRepo.findAllByEmail(email);

        if (studentEntriesInCourses != null){
            Set<Course> availableCourses = new HashSet<>();

            for (CourseStudentEmails entry : studentEntriesInCourses) {
                availableCourses.add(entry.getCourse());
            }
            user.setAvailableCourses(availableCourses);//nullpointer is here
            userRepo.save(user);
        }
    }

1 个答案:

答案 0 :(得分:0)

您应该在使用之前初始化Set,尝试:

+------+--------+
|  ID  | Gender |
+------+--------+
| 1001 | MENS   |
| 1002 | MENS   |
| 1001 | WOMENS |
| 1002 | WOMENS |
| 1001 | KIDS   |
+------+--------+

requestMessage.Properties[WebAssemblyHttpMessageHandler.FetchArgs] = new
        {
            credentials = "include"
        };