修复向ManyToMany添加实体的问题

时间:2019-11-06 18:17:26

标签: java spring hibernate spring-mvc spring-data-jpa

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

java.lang.UnsupportedOperationException
    at java.util.Collections$1.remove(Collections.java:4684)
    at java.util.AbstractCollection.clear(AbstractCollection.java:436)
    at org.hibernate.collection.internal.PersistentSet.clear(PersistentSet.java:318)
    at org.hibernate.type.CollectionType.replaceElements(CollectionType.java:581)
    at org.hibernate.type.CollectionType.replace(CollectionType.java:757)
    at org.hibernate.type.TypeHelper.replace(TypeHelper.java:167)

用户实体

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

课程实体

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

UserService

public void bindStudentWithCoursesAfterRegistration(String email) {
        User user = userRepo.findFirstByEmail(email);
        List<CourseStudentEmails> studentEntriesInCourses = courseStudentEmailsRepo.findAllByEmail(email);

        if (studentEntriesInCourses.size() != 0){
            for (CourseStudentEmails entry : studentEntriesInCourses) {
                Course course = entry.getCourse();
                user.getAvailableCourses().add(course);
            }
        }
        userRepo.save(user);//Exception throws here
    }

注册控制器

    @PostMapping("/registration")
    public String addUser(User user, @RequestParam(value = "checkboxTeacher", required = false) String checkboxValue, Model model) {
 [//chek if user is already registered]
            userRepo.save(user);
            courseService.bindStudentWithCoursesAfterRegistration(user);
            return "redirect:/login";

    }

1 个答案:

答案 0 :(得分:0)

我想您缺少适当的查询来找到合适的CourseStudentEmails

如果您在实体(CourseStudentEmails)中保留字符串形式的电子邮件作为电子邮件的集合,则可以根据以下特定电子邮件来查询实体:

@Query("SELECT c FROM CourseStudentEmails c WHERE ?1 member of c.emails")
List<CourseStudentEmails> findAllByEmail(String email);