I have Compnay and Branch with one-to-many relationship
Company
@Entity
@Table(name = "tbl_company")
public class Company {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "company_id")
private long companyId;
...
@OneToMany(mappedBy = "company", cascade = CascadeType.ALL, fetch = LAZY)
private Set<Branch> branches;
...
}
Branch:
@Entity
@Table(name = "tbl_branch")
public class Branch {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "branch_id")
private long branchId;
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="branchcompany_id")
private Company company;
@Override
public int hashCode() {
int hash = 3;
hash = 59 * hash + (int) (this.branchId ^ (this.branchId >>> 32));
return hash;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Branch other = (Branch) obj;
if (this.branchId != other.branchId) {
return false;
}
return true;
}
}
I get following JSON for adding company + branch which does not have ID (my equals and hash is based upon ID). When I try to attach below 2 branches to company's branches set, I get only 1 branch because by default ID is 0 for both.
{
"companyName": "Cynosure Company",
"address": "Nashik",
"branches": [
{
"branchName": "my branch"
},
{
"branchName": "my second branch"
}
]
}
Some options may be 1) Convert into list (not possible in my case) 2) Save branches separately after saving company (no cascade) - not preferable
Else 3) Remove equals/hashcode - Currently there is no detachment and re-attachment. There are multiple users using the website and making simultaneous POST/PUT requests but no multiple session for one single user. So is it safe to go with option 3? would like to understand the risks involved.
Thanks in advance.