【问题标题】:How to use entity graph in spring data jpa如何在spring data jpa中使用实体图
【发布时间】:2018-09-18 01:16:03
【问题描述】:

我开始学习使用实体图来减少 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?

【问题讨论】:

标签: hibernate jpa


【解决方案1】:
  • 方法一:

我们可以使用 DISTINCT 关键字来删除重复数据

  • 方法二:

我们可以使用集合。我找到了一种以休眠形式remove duplicate data 的方法,这种方式为我们提供了休眠创建重复数据的原因。

【讨论】:

    猜你喜欢
    • 2012-08-06
    • 2016-12-03
    • 2020-08-19
    • 2019-10-01
    • 1970-01-01
    • 2015-09-11
    • 1970-01-01
    • 2020-02-21
    • 1970-01-01
    相关资源
    最近更新 更多