I don't know if this is possible at all, I've been searching a lot for it but i couldn't find an answer.
Say I have two tables, Parent
and Child
.
I would like to map the Parent
entity in such a way that it contains a reference to the Child
entity, but the Child
entity doesn't need to know about the Parent
entity. Ideal mapping should be like this:
@Entity
public class Parent {
@Id
@SequenceGenerator(name = "parentSeq", sequenceName = "parentSeq", allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "parentSeq")
@Column(name = "id_")
private Long id;
@OneToOne // ??
private Child child;
// getters & setters
}
@Entity
public class Child {
@Id
private Long id;
private String name;
// has no back reference to the Parent entity
// getters & setters
}
I could share the PK of the Parent
table to the Child
entity and make it PK and FK in the Child
table if that could help, or in general i could modify the DB tables as needed in order to achieve this. Worst case scenario I can have a PK for the Child
table and a FK to the Parent
table. However I would not like to have a FK on the Parent
table to the Child
table.
The desired behavour would be:
Parent parent = new Parent();
Child child = new Child();
child.setName("childName");
parent.setChild(child);
parent.save();
So, in the case of a shared PK, the correct way to do this (AFAIK) is to first insert the Parent
row, then get its Id and use it to insert a new Child
row with that Id.
Is there a way to achieve this?
Hibernate version is 5.4.28 Final, JPA version 2.1
Thank you
Update:
Just to clarify, best scenario for the db structure would be like this:
Parent
table:
- Id (Pk)
- Name
Child
table:
- Id (Pk, Fk reference Parent Id)
- Name
Another acceptable solution however would be:
Parent
table:
- Id (Pk)
- Name
Child
table:
- Id (Pk)
- Name
- ParentId (Fk reference Parent Id)
Again, I would like to have a unidirectional mapping from Parent
to Child
but according to the link provided by Davide this seems impossible.