我开始学习使用实体图来减少N + 1问题。但是我遇到了一个问题,即findAll方法返回重复数据。
person
@Entity
public class Person {
@Id
@GeneratedValue
public long id;
public String name;
@ManyToOne(fetch = FetchType.LAZY,cascade = CascadeType.ALL)
@JoinColumn(name = "department_id")
@JsonIgnore
public Department department;
department
@Entity
@NamedEntityGraph(name = "department.p",attributeNodes =
@NamedAttributeNode(value = "people"))
public class Department {
@Id
@GeneratedValue
@Column(name = "department_id")
private long id;
private String name;
@OneToMany(fetch = FetchType.LAZY,cascade =
CascadeType.ALL,mappedBy = "department")
private List<Person> people = new ArrayList<>();
我创建了一个departmentrepo
interface DepartmentRepository extends CrudRepository<Department,Long> {
@EntityGraph(value = "department.p", type =
EntityGraph.EntityGraphType.LOAD)
List<Department> findAll();
}
pom.xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
我的代码有什么问题?方法findAll
不能使用EntityGraph?
答案 0 :(得分:0)
我们可以使用DISTINCT关键字删除重复数据
我们可以使用set集合。我找到了一种以休眠形式访问remove duplicate data的方法,并且这种方法为我们提供了一个原因,使休眠方式创建重复数据。