Hibernate在单个事务中自动更新

时间:2015-09-20 03:07:56

标签: java hibernate orm

我有两个实体 - PersonAddress,它们具有多对一的关系。因此,在尝试使用级联和自动更新时,我看到了一些有趣的事情(对我来说):

    @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会通过插入address来更新Persons,但它只会更新第一个<?php $servername = "myservername"; $username = "myusername"; $password = "mypassword"; $dbname = "mydbname"; try { $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password); // set the PDO error mode to exception $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $stmt = $conn->prepare("SELECT (SELECT g_balance FROM balance WHERE user_id = :userid) + (SELECT rewards FROM reward WHERE user_id = :userid)"); $stmt->bindParam(':userid', $userid); $userid = $_POST['userid']; $stmt->execute(); while($row=$stmt->fetch()){ echo $result; }} catch(PDOException $e) { echo "Error: " . $e->getMessage(); } $conn = null; ?> 。有谁知道这里发生了什么?提前谢谢。

1 个答案:

答案 0 :(得分:1)

编辑:初始答案不正确,这里是正确答案:

经过评论中的一些讨论后,我们发现作者已在其对象中覆盖equalshashCodeHere是关于此的文章。简而言之:如果我们覆盖,我们会覆盖基于equals实体的hashCodeid方法,而不是将对象添加到Set时,它的ID为null,当我们添加第二个对象时 - 它具有相同的ID,因此它被认为是重复的,并且没有被添加到集合中,因此,不会被持久保存到DB。