Reputation: 2009
I have two entities — Person
and Address
that have many-to-one relationship. So while trying to experiment with cascading and autoupdating i saw some interesting thing(for me):
@Transactional
public void run() {
Address address = new Address("UK", "London", "221B Baker Street");
Person person = new Person("Sherlock", "Homes", address);
personRepository.save(person); //saves address also because of cascading
address = addressRepository.findByCity("London");
Set<Person> persons = address.getPersons();
persons.add(new Person("John", "Watson", address)); //insert fires
persons.add(new Person("Mary", "Morstan", address)); //nothing happens
}
As you can see i get Address
instance(previously saved) and add two new Person
-s to it. What i expected is that Hibernate would update the address
by inserting this Persons
-s but it only updates the first one. Do anyone know what is going on here? Thanks in advance.
Upvotes: 0
Views: 66
Reputation: 2931
EDIT: initial answer was incorrect, here is correct one:
After some discussion in comments we've found that author has overriden equals
and hashCode
in his objects. Here is article about this. Briefly: if we override we override equals
and hashCode
method based on id
of entity — than when we add object to Set
it has id of null
, when we add second object - it has same id, so it's considered to be a duplicate and isn't being added to collection, and, consequently, isn't being persisted to DB.
Upvotes: 1