繁体   English   中英

Spring Data Rest JPA - 无法延迟加载OneToMany双向关系

[英]Spring Data Rest JPA - Can't lazy load OneToMany bidirectional relationship

我有两个实体,Company和Job,具有OneToMany双向关系。 我的问题是我不能懒得加载公司的List<Job> jobs

例如,当我这样做时:

GET /api/companies/1这是JSON响应:

{
  "id": 1,
  "name": "foo",
  ...
  "_embedded": {
    "jobs": [
      {...},
       ...
      {...}
    ],
    "employees": [
      {...},
      {...}
    ]
  },
  "_links": {
    "self": {
      "href": "http://localhost:8080/api/companies/1"
    },
    "jobs": {
      "href": "http://localhost:8080/api/companies/1/jobs"
    },
    "employees": {
      "href": "http://localhost:8080/api/companies/1/employees"
    }
  }
}

我不想拥有_embedded因为我没有设置FetchType = EAGER。 这是我的模特:

Company.java

@Entity
public class Company {

    @Column(nullable = false, unique = true)
    private String name;


    @OneToMany(mappedBy = "company", fetch = FetchType.LAZY)
    private List<Job> jobs;

    ...

    public Company() {
    }

    ...

}

Job.java

@Entity
public class Job {

    @Column(nullable = false)
    public String title;

    @Column(length = 10000)
    public String description;

    @ManyToOne(fetch=FetchType.LAZY)
    private Company company;

    ...

    public Job() {
    }

    ...

}

正如您所看到的,其他OneToMany关系(员工)也会发生同样的事情。 我可以避免每次都返回整个职位空缺或员工名单吗?

编辑:从工作方面,懒惰负载工作正常! 我没有得到与工作相关的公司的回复。 我必须明确地做/api/jobs/123/company以获得公司。

EDIT2:预测仅适用于集合。 在这种情况下,它不是我需要的。 节选可行,但我想避免它们。 我不想明确做/api/companies/1?projection=MyProjection因为我不会使用多个。 我想更改默认行为,就像集合中的投影一样。

编辑3:我试过这个

@RestResource(exported = false)
@OneToMany(mappedBy = "company")
private List<Job> jobs;

我得到错误Detected multiple association links with same relation type! Disambiguate association Detected multiple association links with same relation type! Disambiguate association

真的很烦人 我只需要摆脱_embedded 什么?

您可以使用Entity Graph.Entity图用于在运行时覆盖属性映射的提取设置。例如

@Repository
public interface GroupRepository extends CrudRepository<GroupInfo, String> {

  @EntityGraph(attributePaths = { "members" })
  GroupInfo getByGroupName(String name);

}

从Spring Data Jpa文档“4.3.10。配置Fetch-和LoadGraphs” https://docs.spring.io/spring-data/jpa/docs/current/reference/html/

此外; 在此输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM