简体   繁体   中英

How to fill field in entity with information from its parent entity after persisting a new entity

I have the following entities:

@Entity()
public class Parent {

    @Id
    private Long id;

    private String name;

    ...

}
@Entity()
public class Child {

    @Id
    private Long id;

    private String name;

    @Column(name = "parent_id")
    private long parent_id;

    @ManyToOne(targetEntity = Parent.class)
    @JoinColumn(name = "parent_id", insertable = false, updatable = false)
    private Parent parent;

    ...

}

The Child entity must always have a Parent entity.

I want the Child class to have the parent_id as a field and a Parent object with all the fields from its parent.

This way I can save a Child entity having only the id of the Parent and, ideally, the parent object inside the Child would be filled when retrieving a Child from the database.

I have achieved that when retrieving a Child from the database the parent field is filled with the Parent entity, but if I persist a new Child entity with only the parent_id, the parent object is not filled automatically.

Is there any way to achieve this?

It looks like this should help.

If you want provide correct reference between the Child and the Parent entities and postpone the real loading of the Parent entity. You should do something like that:

  Child newChild = new Child();
  newChild.setParent(entityManager.getReference(Parent.class, parent_id));
  // ...
  entityManager.persist(newChild);

Or if you want to have the newChild with completely initialized Parent instead of entityManager.getReference you should use entityManager.find(Parent.class, parent_id) .

PS The same advice was given by @JBNizet in comments.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM