Reputation: 1225
I want to store workers in an Organization object, For this, I have an Organization class having One to Many Mapping for workers.
@OneToMany(cascade=CascadeType.ALL,fetch = FetchType.EAGER)
@JoinTable(name = "ORGANIZATION_WORKER", joinColumns = { @JoinColumn(name = "orgIdPK") }, inverseJoinColumns = { @JoinColumn(name = "id") })
public Set<Worker> workerList;
"ORGANIZATION_WORKER is a temporary table that holds the mapping"
Then I have a Worker class where I have Many to One Mapping as follow.
@ManyToOne(cascade=CascadeType.ALL,fetch = FetchType.LAZY)
@JoinColumn(name = "orgIdPK")
public Organization organization;
Now when I save the organization after inserting workers into it using hibernate session, i-e
session.saveOrUpdate(org);
insert query runs twice (N+1 issue). `
Hibernate: insert into ORGANIZATION_WORKER (orgIdPK, id) values (?, ?)
Hibernate: insert into ORGANIZATION_WORKER (orgIdPK, id) values (?, ?)
So when I expose Organization data on rest API, all records are shown twice because of which pagination gets wrong on the rest API. Anyone knows how to solve this issue?
Upvotes: 0
Views: 135
Reputation: 221
The problem is that you are creating a circular reference. You are inserting a organization which has workers in it, and those workers have that same organization as a parameter, so it is inserting twice.
To solve this issue, Hibernate has some keywords applicable to columns: "insertable" and "updatable", that specify whether or not the value of that column will be inserted or updated in DB.
In general, the proper thing to do is to make the OneToMany relationship non-insertable and non-updatable; if you want to change the Organization of a Worker, you will probably do it from that Worker; the class responsible for updating that value is the Worker itself, that is, the class with the ManyToOne association.
So you need to do this:
@OneToMany(cascade=CascadeType.ALL,fetch = FetchType.EAGER, insertable=false, updatable=false)
This way all changes in this column will be ignored when the entity inserts or updates in DB.
Upvotes: 2
Reputation: 1611
Remove the annotations from Worker.
@ManyToOne(cascade=CascadeType.ALL,fetch = FetchType.LAZY) @JoinColumn(name = "orgIdPK")
Upvotes: 1