Using Hibernate, I have bi-directional association between parent/child. Parent entity can have too many children and I want to add and remove to “children” (has mappedBy) collection without loading entire collection.
Below is a example depicting my case, in my case number of children entities are huge that i want to avoid loading all of them when doing add/remove. Considering my collection is a set, i might not be able to avoid initialization in add, but want to avoid for remove at least. Parent=Person, children = addresses.
Java class:
public class Person
{
private UUID id;
@OneToMany(mappedBy = "person", fetch = FetchType.LAZY, cascade= {CascadeType.PERSIST, CascadeType.MERGE})
private Set<Address> addresses = new HashSet<>();
public Person addAddress(Address address) {
getAddresses().add(address);
address.setPerson(this);
return this;
}
public Person removeAddress(Address address) {
getAddresses().remove(address); // though i want to remove a specific address association, it loads all addresses which is a lot
address.setPerson(null);
return this;
}
}
public class Address {
@ManyToOne(cascade={CascadeType.PERSIST}, fetch = FetchType.LAZY)
@NotNull
private Person person;
public void setPerson(Person person) {
this.person = person; ...
}
}
Are there any solutions to avoid loading all addresses of this person, when i only want to remove one given address association.