我有两个具有多对一关系的实体 - Person
和 Address
。因此,在尝试尝试级联和自动更新时,我看到了一些有趣的事情(对我来说):
@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
}
如您所见,我获得了 Address
实例(之前已保存)并向其添加了两个新的 Person
-s。我期望 Hibernate 会通过插入此 Persons
-s 来更新 address
,但它只更新第一个。有谁知道这是怎么回事?提前致谢。
最佳答案
编辑:最初的答案不正确,这是正确的答案:
经过评论中的一些讨论,我们发现作者已经覆盖了 equals
和hashCode
在他的物体中。 Here是关于这个的文章。简而言之:如果我们重写,我们就会重写 equals
和hashCode
方法基于id
实体的 - 与我们将对象添加到 Set
时相比它的 ID 为 null
,当我们添加第二个对象时 - 它具有相同的 id,因此它被认为是重复的并且不会被添加到集合中,因此不会被持久化到数据库中。
关于java - Hibernate 在单个事务中自动更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32675368/