我正在尝试使用 CriteriaUpdate 更新多对多关系。
以下是实体;
@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...
}
下面是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();
}
上面的代码抛出以下异常
java.lang.IllegalArgumentException: Attribute path for assignment must represent a singular attribute [null.courses]
如何使用 CriteriaUpdate 进行更新?