Hi there!
Background:
Here is an example of 2 tables:
CREATE TABLE parent
(
id serial PRIMARY KEY
);
CREATE TABLE child
(
id serial PRIMARY KEY
parent_id int REFERENCES parent (id)
);
And the corresponding Entities:
@Entity
public class Parent {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@OneToOne(mappedBy = "parent", cascade = CascadeType.ALL, fetch = FetchType.LAZY, optional = false)
private Child child;
public void createChild(Child child) {
child.setParent(this);
this.child = child;
}
}
@Entity
public class Child {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String name;
@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "parent_id")
private Parent parent;
}
Question:
Is it possible to get rid of the bidirectional mapping and keep the @OneToOne only on the parent side while still using parent_id in Child? (Having only parentId instead of Parent on the Child side is also appropriate)
PS:
I know that it’s possible to have unidirectional mapping if I add child_id in the parent like this, but that’s not the case:
@Entity
public class Parent {
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "child_id", referencedColumnName = "id")
private Child child;
}
@Entity
public class Child {
// nothing here
}