I'm trying to update a ManyToMany relationship using CriteriaUpdate.
The following are the entities;
@Entity
@Table(name = "COURSE")
public class Course {
@Id
@GeneratedValue
private String id;
private String name;
// Getters and setter...
}
@Entity
@Table(name = "STUDENT")
public class Student {
@Id
@GeneratedValue
private String id;
private String name;
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(name = "STUDENT_COURSE", joinColumns = {@JoinColumn(name = "STUDENT_ID")}, inverseJoinColumns = {@JoinColumn(name = "COURSE_ID")})
private Set<Course> courses = new HashSet<>();
// Getters and setter...
}
Below is the code in the DAO
void updateCourses(String studentId, Set<Course> courses){
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
CriteriaUpdate<Student> criteriaUpdate = criteriaBuilder.createCriteriaUpdate(Student.class);
Root<Student> studentRoot = criteriaUpdate.from(Student.class);
criteriaUpdate.where(criteriaBuilder.equal(studentRoot.get("id"), studentId));
criteriaUpdate.set("courses", courses);
entityManager.createQuery(criteriaUpdate).executeUpdate();
}
The above code throws the following exception
java.lang.IllegalArgumentException: Attribute path for assignment must represent a singular attribute [null.courses]
How can I update using CriteriaUpdate?