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

时间:2015-10-11 16:56:26

标签: java spring spring-data-jpa spring-data-rest

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

例如当我这样做时:

获取/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,因为我不会使用多个。{1}}我想更改默认行为,就像集合中的投影一样。

EDIT3:我试过这个

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

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

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

1 个答案:

答案 0 :(得分:0)

您可以使用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/

另外; enter image description here