Save child objects automatically using JPA Hibernate

前端 未结 7 658
南方客
南方客 2020-11-27 13:13

I have a one-to-many relation between Parent and Child table. In the parent object I have a

List setChildren(List childs)
         


        
相关标签:
7条回答
  • 2020-11-27 14:04

    I tried the above but I'm getting a database error complaining that the foreign key field in the Child table can not be NULL. Is there a way to tell JPA to automatically set this foreign key into the Child object so it can automatically save children objects?

    Well, there are two things here.

    First, you need to cascade the save operation (but my understanding is that you are doing this or you wouldn't get a FK constraint violation during inserts in the "child" table)

    Second, you probably have a bidirectional association and I think that you're not setting "both sides of the link" correctly. You are supposed to do something like this:

    Parent parent = new Parent();
    ...
    Child c1 = new Child();
    ...
    c1.setParent(parent);
    
    List<Child> children = new ArrayList<Child>();
    children.add(c1);
    parent.setChildren(children);
    
    session.save(parent);
    

    A common pattern is to use link management methods:

    @Entity
    public class Parent {
        @Id private Long id;
    
        @OneToMany(mappedBy="parent")
        private List<Child> children = new ArrayList<Child>();
    
        ...
    
        protected void setChildren(List<Child> children) {
            this.children = children;
        }
    
        public void addToChildren(Child child) {
            child.setParent(this);
            this.children.add(child);
        }
    }
    

    And the code becomes:

    Parent parent = new Parent();
    ...
    Child c1 = new Child();
    ...
    
    parent.addToChildren(c1);
    
    session.save(parent);
    
    References
    • Hibernate Core Reference Guide
      • 1.2.6. Working bi-directional links
    0 讨论(0)
提交回复
热议问题