Using Hibernate, I have bi-directional association between person/address. Person entity can have too many addresses and I want to add and remove to address collection without loading entire collection.
Below is a example depicting my case, in my real case, number of address entities are huge that i want to avoid loading all of them when doing add/remove.
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) {
addresses.add(address);
address.setPerson(this);
return this;
}
public Person removeAddress(Address address) {
// though i want to remove one specific address entity association,
// it loads all addresses which is a lot impacting perf
addresses.remove(address);
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; ...
}
}
When i want to dissassociate a address from Person entity, i call person.removeAddress(address) which loads all the addresses of this person. In my case there are 100s of them and i want to avoid loading all of them into memory.
Once my modifications are done on entity, i call personRepository.flush()
and don’t do any manual HQL query.
Are there any solutions to avoid loading all addresses of this person, when i only want to remove one given address association?