unidirectional onetoone mapping code example
Example 1: hibernate onetone with mapsid
@Entity
public class VitalStats
{
@Id @Column(name="vitalstats_id") Long id;
@MapsId
@OneToOne(mappedBy = "vitalStats")
@JoinColumn(name = "vitalstats_id") //same name as id @Column
private Person person;
private String stats;
}
Example 2: one to one best practices
@Entity(name = "Post")
@Table(name = "post")
public class Post {
@Id
@GeneratedValue
private Long id;
private String title;
@OneToOne(mappedBy = "post", cascade = CascadeType.ALL,
fetch = FetchType.LAZY, optional = false)
private PostDetails details;
//Getters and setters omitted for brevity
public void setDetails(PostDetails details) {
if (details == null) {
if (this.details != null) {
this.details.setPost(null);
}
}
else {
details.setPost(this);
}
this.details = details;
}
}