Reputation: 972
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?
Upvotes: 1
Views: 639
Reputation: 13041
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)
.
P.S. The same advice was given by @JBNizet in comments.
Upvotes: 1