Unidirectional one to many association in Hibernat

2019-07-03 08:09发布

I'm new to Hibernate / spring-data-jpa and I'm trying to implement an unidirectional @OneToMany relationship.

My parent class looks like this:

@Entity
public class Parent {

    @Id
    @GeneratedValue
    private int id;

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

And my child class:

@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!

1条回答
Summer. ? 凉城
2楼-- · 2019-07-03 08:41

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);

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.

查看更多
登录 后发表回答