JPA @OneToMany -> Parent - Child Reference (Foreign Key)

☆樱花仙子☆ 提交于 2019-12-28 08:08:07

问题


i have a Question about referencing ParentEntities from Child Entites ir If i have something like this:

Parent.java:

@Entity(name ="Parent")
public class Parent {
    @Id
    @Generate.....
    @Column
    private int id;

    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "parent")
    private Set<Child> children;

    simple ... getter and setter ...
}

And the Child.java:

@Entity(name ="Child")
public class Child{
    @Id
    @Generate....
    @Column
    private int id;

    @ManyToOne
    private Parent parent;

    ... simple getter an setter
}

Following Tables are going to be created:

Parent:
     int id

Child:
     int id
     int parent_id (foreign key: parent.id)

Ok, so far, everthings fine. But when it comes to using this Reference from Java, i would think, you can do something like this.

 @Transactional
 public void test() {
    Parent parent = new Parent();

    Child child = new Child();
    Set<Child> children = new HashSet<Child>();
    children.add(child);

    parent.setChildren(children);
    entityManager.persist(parent);
  }

which leads to this in Database:

Parent:
     id
     100

Child
     id     paren_id
     101    100

But thats not the case, you have to explicity set the Parent to the Child (which, i would think, the framework could probably do by itself).

So whats really in the database is this:

Parent:
     id
     100

Child
     id     paren_id
     101    (null)

cause i haven't set the Parent to the Child. So my Question:

Do I really have to do sth. like this?

Parent.java:

...
setChildren(Set<Child> children) {
   for (Child child : children) {
     child.setParent.(this);
   }

   this.children = children;
}
...

Edit:

According to the fast Replies i was able to solve this Problem by using the @JoinColumn on the Reference-Owning Entity. If we take the Example from above, i did sth. like this:

Parent.java:

  @Entity(name ="Parent")
    public class Parent {
        @Id
        @Generate.....
        @Column
        private int id;

        @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
        @JoinColumn(name= "paren_id")
        private Set<Child> children;

        simple ... getter and setter ...
    }

And the Child.java:

@Entity(name ="Child")
public class Child{
    @Id
    @Generate....
    @Column
    private int id;

    ... simple getter an setter
}

Now if we do this:

 @Transactional
 public void test() {
    Parent parent = new Parent();

    Child child = new Child();
    Set<Child> children = new HashSet<Child>();
    children.add(child);

    parent.setChildren(children);
    entityManager.persist(parent);
  }

The Reference is correctly set by the Parent:

Parent:
     id
     100

Child
     id     paren_id
     101    100

Thanks for the Answers.


回答1:


Do I really have to do sth. like this?

That is one strategy, yes.

On bi-directional relationships there is an "owning" and a "non-owning" side of the relationship. Because the owning side in your case is on Child, you need to set the relationship there for it to be persisted. The owning side is usually determined by where you specify @JoinColumn, but it doesn't look like you're using that annotation, so it's likely being inferred from the fact that you used mappedBy in the Parent annotation.

You can read a lot more about this here.




回答2:


It still seems to be the case. In parent Entity you can have something like

@PrePersist
private void prePersist() {
   children.forEach( c -> c.setParent(this));
}

in order to avoid repeating code for setting child/parent relationship elsewhere in code.




回答3:


Yes, that is the case. JPA does not keep care about consistency of your entity graph. Especially you have to set it to the owner side of bidirectional relationship (in your case to the parent attribute of Child).

In JPA 2.0 specification this is said with following words:

Note that it is the application that bears responsibility for maintaining the consistency of run- time relationships—for example, for insuring that the “one” and the “many” sides of a bidi- rectional relationship are consistent with one another when the application updates the relationship at runtime.




回答4:


We ran into a problem while persisting a simple object graph like the one shown above. Running in H2 everything would work, but when we ran against MySQL the "paren_id" in the child table (defined in the @JoinColumn annotation) wasn't getting populated with the generated id of the parent - even though it was set as a non-null column with a foreign key constraint in the DB.

We'd get an exception like this:

org.hibernate.exception.GenericJDBCException: Field 'paren_id' doesn't have a default value

For anyone else who might run into this, what we eventually found was that we had to another attribute to the @JoinColumn to get it to work:

@JoinColumn(name="paren_id", nullable=false)



回答5:


If I am getting you correctly, according to EntityManager, if you want it to manage the transaction's insert order your have to "tell him" that it should persist the children too. And you are not doing that, so "he" doesn't know what to persist, but your parent's child list is not empty so "he" takes it has correct but the stored value is null.

So you should consider do something like:

... begin, etc
em.persist(child)
em.persist(parent)

do what you want with the parent object here then commit and this should work for similar cases too.



来源:https://stackoverflow.com/questions/9533676/jpa-onetomany-parent-child-reference-foreign-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!