Java – spring data rest JPA – unable to delay loading of onetomany bidirectional relationship
I have two entities, company and job, with one to many two-way relationship My problem is that I can't be lazy to load the company's list < job > work
For example, when I do this:
Get / API / companies / 1 this is the JSON response:
{ "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" } } }
I don't want to have_ Embedded, because I didn't set fetchtype = eagle This is my model:
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() { } ... }
As you can see, the same thing happens to other onetomany relationships (employees) Can I avoid returning to the entire job opening or employee list every time?
Edit: in terms of work, lazy load works normally! I didn't get a reply from the company related to my work I must definitely do / API / jobs / 123 / company to get the company
Edit2: forecast is only applicable to the set In this case, it's not what I need Excerpts work, but I want to avoid them I don't want to explicitly do / API / companies / 1? Projection = myprojection because I won't use multiple I want to change the default behavior, just like the projection in the collection
Editor 3: I tried this
@RestResource(exported = false) @OneToMany(mappedBy = "company") private List<Job> jobs;
I got an error. Multiple associated links with the same relationship type were detected! Disambiguation of association
It's really annoying. I just need to get rid of it_ embedded. what?
Solution
You can use entity graph Entity graph is used to override the extraction settings of attribute mapping at run time for example
@Repository public interface GroupRepository extends CrudRepository<GroupInfo,String> { @EntityGraph(attributePaths = { "members" }) GroupInfo getByGroupName(String name); }
From the spring data JPA document "4.3.10. Configure fetch - and loadgraphs" https://docs.spring.io/spring-data/jpa/docs/current/reference/html/
In addition;