Java 如何修复注册后向多个实体添加实体的问题
我需要检查用户的电子邮件是否已添加到学生列表中,如果已添加,请将此用户与课程连接 我已经检查了所有引用和其他引用,但仍然得到空指针 用户实体Java 如何修复注册后向多个实体添加实体的问题,java,spring,spring-security,nullpointerexception,spring-data,Java,Spring,Spring Security,Nullpointerexception,Spring Data,我需要检查用户的电子邮件是否已添加到学生列表中,如果已添加,请将此用户与课程连接 我已经检查了所有引用和其他引用,但仍然得到空指针 用户实体 private String name; private String password; private String email; @ManyToMany(cascade = {CascadeType.MERGE}) @JoinTable( name = "Student_Courses",
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<>();
课程服务
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);
}
}
public void bindstudents with courses注册后(字符串电子邮件){
User User=userRepo.findFirstByEmail(电子邮件);
List Studentriesincourses=courseStudentEmailsRepo.findAllByEmail(电子邮件);
如果(学生入学人数!=null){
Set availableCourses=new HashSet();
用于(课程测试学生邮件输入:学生输入课程){
add(entry.getCourse());
}
user.setAvailableCourses(availableCourses);//此处有空指针
userRepo.save(用户);
}
}
您应该在使用前初始化设备,请尝试:
private Set<Course> availableCourses = new HashSet<>();
private Set availableCourses=new HashSet();
或
public void addAvailableCourse(课程){
this.availableCourses=new HashSet();
this.availableCourses.add(课程);
course.getUsers().add(此);
}
我已经做了,但仍然不起作用。检查我编辑的问题,然后您的用户为空,因此可能数据库中没有email
值。检查您的方法userRepo.findfirstbymail(电子邮件)代码>如果您的问题已解决,那么您能否回答并关闭该问题?
private Set<Course> availableCourses = new HashSet<>();
public void addAvailableCourse(Course course){
this.availableCourses = new HashSet<>();
this.availableCourses.add(course);
course.getUsers().add(this);
}