By specifying the @JoinColumn on both models you don’t have a two way relationship. mappedby One to One
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
@Entity(name = "PostDetails") @Table(name = "post_details") public class PostDetails { @OneToOne(fetch = FetchType.LAZY) @JoinColumn(name = "post_id") private Post post; } @Entity(name = "Post") @Table(name = "post") public class Post { @OneToOne(mappedBy = "post", cascade = CascadeType.ALL, fetch = FetchType.LAZY, optional = false) private PostDetails details; } |
bidirectional One to One is EAGER @MapsId (before jpa2 – @PrimaryKeyJoinColumn)
1 2 3 4 5 6 7 |
@Entity(name = "PostDetails") @Table(name = "post_details") public class PostDetails { @OneToOne(fetch = FetchType.LAZY) @MapsId private Post post; } |
One To Many, Many To One Unidirectional without @JoinColumn requires additional table for joining
1 2 3 4 5 6 7 8 9 |
@Entity(name = "Post") @Table(name = "post") public class Post { @OneToMany( cascade = CascadeType.ALL, orphanRemoval = true ) private List<PostComment> comments = new ArrayList<>(); } |
1 2 3 |
@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true) @JoinColumn(name = "post_id") private List<PostComment> comments = new ArrayList<>(); |
Bidirectional
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
@Entity(name = "Post") @Table(name = "post") public class Post { @OneToMany( mappedBy = "post", cascade = CascadeType.ALL, orphanRemoval = true ) private List<PostComment> comments = new ArrayList<>(); } @Entity(name = "PostComment") @Table(name = "post_comment") public class PostComment { @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "post_id") private Post post; |
Is it possible to limit the […]