【发布时间】:2021-07-17 17:46:13
【问题描述】:
我正在使用带有 Spring-data-jpa 的 Spring Boot
我有两个实体 Category 和 Course。它们通过@ManyToMany 关联。
public class Course {
@Id
@GeneratedValue(generator = "inc")
@GenericGenerator(name = "inc", strategy = "increment")
private int courseId;
@NotBlank(message = "Add the course's title!")
private String title;
@ManyToMany(mappedBy = "courses", fetch = FetchType.EAGER)
private Set<Category> categories;
}
public class Category {
@Id
@GeneratedValue(generator = "inc")
@GenericGenerator(name = "inc", strategy = "increment")
private int categoryId;
@NotBlank(message = "category's name must be not empty!")
private String name;
@ManyToMany(cascade = CascadeType.PERSIST)
@JoinTable(
name="course_category",
joinColumns = @JoinColumn(name = "category_id"),
inverseJoinColumns = @JoinColumn(name = "course_id")
)
private Set<Course> courses;
当我下载一个类别时,我也想下载它的所有课程(没有fetchType.EAGER,因为我不想在下载所有类别的同时获取课程)。这是我在CategoryRepository (JpaRepository) 中覆盖的查询:
@Override
@Query("SELECT cat FROM Category cat JOIN FETCH cat.courses")
Optional<Category> findById(Integer id);
因为我想从两个表中发送我的客户数据,所以我创建了一个 DTO:
public class CategoryAndCourses {
private Category category;
private List<Course> courses;
public CategoryAndCourses(Category category, List<Course> courses) {
this.category = category;
this.courses = courses;
}
还有一个地方,我实际上是通过 DTO 发送课程和类别:
public CategoryAndCourses getCourses(int id) {
var category = repository.findById(id)
.orElseThrow(() -> new IllegalArgumentException("No category with given id"));
var result = new CategoryAndCourses(category, new ArrayList<>(category.getCourses()));
return result;
}
使用这样的代码我得到这个错误:
javax.persistence.NonUniqueResultException: query did not return a unique result: 8
如何解决?
【问题讨论】:
标签: java hibernate spring-data-jpa