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

问题描述 投票:0回答:1

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

我已经检查了所有引用和其他引用,但仍然得到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;

//I`ve got nullpointer here 
    public void addAvailableCourse(Course course){
        this.availableCourses.add(course);
        course.getUsers().add(this);
    }

课程实体

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

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){
            for (CourseStudentEmails entry : studentEntriesInCourses) {
                Course course = entry.getCourse();
                user.addAvailableCourse(course);
            }
        }
    }

我需要检查用户的电子邮件是否已添加到学生列表中,如果已添加,请将该用户与课程联系起来。我已经检查了所有引用和其他引用,但仍然得到NullPointer用户实体...

java spring spring-security nullpointerexception spring-data
1个回答
0
投票

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

private Set<Course> availableCourses = new HashSet<>();
© www.soinside.com 2019 - 2024. All rights reserved.