【问题标题】:Unidirectional one to many association in Hibernate / spring-data-jpaHibernate / spring-data-jpa中的单向一对多关联
【发布时间】:2015-09-19 15:13:47
【问题描述】:

我是 Hibernate / spring-data-jpa 的新手,我正在尝试实现单向 @OneToMany 关系。

我的父类如下所示:

@Entity
public class Parent {

    @Id
    @GeneratedValue
    private int id;

    @OneToMany(fetch = EAGER)
    @JoinColumn(name = "parent_id")
    private List<Child> children;
}

还有我的孩子班:

@Entity
public class Child {

    @Id
    @GeneratedValue
    private int id;
    private String name;
}

现在我想通过

坚持一个新的孩子
Child newChild = new Child();
newChild.setName("child_1");

this.parentService.findParentByParentId(1).getChildren().add(newChild);
this.childService.saveChild(newChild);

但是当我查看我的数据库时,子表中的外键没有设置:

-----------------------------------------
|  id |    name       |    parent_id    |
-----------------------------------------
|  1  |    child_1    |    NULL         |
-----------------------------------------

关于这里出了什么问题有什么建议吗?谢谢!

【问题讨论】:

    标签: hibernate spring-data-jpa


    【解决方案1】:

    我查看了映射,没有任何问题。我什至与一些我用来运行 JPA 研讨会的 code 进行了比较,你的应该可以工作。

    我敢打赌,问题出在您开始交易的地方。事务应该从执行代码的方法开始

    Child newChild = new Child();
    newChild.setName("child_1");
    
    this.parentService.findParentByParentId(1).getChildren().add(newChild);
    this.childService.saveChild(newChild);
    

    否则 JPA 的工作单元不会看到您在父级中添加了一个子级。

    强烈建议您阅读 spring 文档中解释 declarative transaction management 的部分,否则您将在绝望中花费数天时间试图弄清楚它为什么不起作用。

    【讨论】:

      猜你喜欢
      • 2017-02-24
      • 2021-01-08
      • 1970-01-01
      • 2018-05-07
      • 2015-10-28
      • 1970-01-01
      • 1970-01-01
      • 2018-04-14
      • 2022-10-07
      相关资源
      最近更新 更多