0

I begin to learn to use entity-graph to reduce N+1 problem.but I face a problem that findAll method return duplicate data.

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<>();

I create a 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>

what's wrong about my code? the method findAll can not use EntityGraph?

qiabigin
  • 45
  • 7
  • 1
    Possible duplicate of [JPA 2.1 Entity Graph returns duplicated results](https://stackoverflow.com/questions/27170142/jpa-2-1-entity-graph-returns-duplicated-results) – K.Nicholas Apr 08 '18 at 19:08

1 Answers1

0
  • Method 1:

we can use the DISTINCT keyword to remove duplicate data

  • Method 2:

we can use the set collection. I find that a way to remove duplicate data in hibernate form, and this way give us a reason that why hibernate create duplicate data.

Maraboc
  • 10,550
  • 3
  • 37
  • 48
qiabigin
  • 45
  • 7