0

Is there any clean way to get the id of a child object, when the parent has been merged?

I.e.

Parent parent = parentDao.get(parentid);
Child child = new Child();
parent.addChild(child);
parentDao.merge(parent);
child.getId() // is null

I have a many to one relationship between the parent and the child.

Another question asked this, and the only solution that worked was to traverse the list of children, but that sounds horrible and hacky.

JPA How can I get the generated id/object when using merge from parent but child is created?

Surely there must be a nicer solution to this.

Community
  • 1
  • 1
wybourn
  • 638
  • 9
  • 29

1 Answers1

0

Considering the following bi-directional entity structure, i.e.

class Parent{
    @OneToMany
    List<Child> children;
}

class Child{
    @ManyToOne
    Parent parent;
}

You'll need to persist the child first in order to get the id for the child.

like entityManager.persist(child) and then associate it with the parent unless you have set cascadeType to Cascade.ALL in Parent class.

Pallav Jha
  • 3,409
  • 3
  • 29
  • 52