Hibernate中的单向一对多关联/spring-data-jpa [英] Unidirectional one to many association in Hibernate / spring-data-jpa
问题描述
我是Hibernate
/spring-data-jpa
的新手,我正在尝试实现单向@OneToMany
关系.
I'm new to Hibernate
/ spring-data-jpa
and I'm trying to implement an unidirectional @OneToMany
relationship.
我的父类如下:
@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;
}
现在我想通过保留一个新孩子
Now I want to persist a new child via
Child newChild = new Child();
newChild.setName("child_1");
this.parentService.findParentByParentId(1).getChildren().add(newChild);
this.childService.saveChild(newChild);
但是当我查看数据库时,未设置子表中的外键:
but when I have a look into my database, the foreign key in child table is not set:
-----------------------------------------
| id | name | parent_id |
-----------------------------------------
| 1 | child_1 | NULL |
-----------------------------------------
关于这里出了什么问题的任何建议吗?谢谢!
Any suggestions about what's going wrong here? Thanks!
推荐答案
我已经查看了映射,但没有任何问题.我什至与一些代码我用来举办JPA研讨会,您的应该可以.
I've looked at the mapping and there's nothing wrong with it. I've even compared with some code I use to run JPA workshops and yours should work.
我敢打赌,问题出在您开始交易的地方.交易应从执行代码的方法开始
I would bet that the problem is the place where you start the transaction. The transaction should start in the method that executes the code
Child newChild = new Child();
newChild.setName("child_1");
this.parentService.findParentByParentId(1).getChildren().add(newChild);
this.childService.saveChild(newChild);
否则,JPA的工作单位不会看到您在父级中添加了一个子级.
Otherwise JPA's unit of work won't see that you've added a child in the parent.
I strongly suggest you to read the section in the spring docs that explains the declarative transaction management, otherwise know that you'll spend days in despair trying to figure out why it doesn't work.
这篇关于Hibernate中的单向一对多关联/spring-data-jpa的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!