[英]Composite ID in join-table
我有以下 PostLike class:
@Entity
@Data
@NoArgsConstructor
@AllArgsConstructor
public class PostLike extends BaseEntity {
@ManyToOne
@JoinColumn(name = "user_id")
private User user;
@ManyToOne
@JoinColumn(name = "post_id")
private Post post;
}
class 已經有一個由父 BaseEntity class 提供的 ID 字段。
在用戶 class 中,我有以下字段:
@OneToMany(mappedBy = "user", fetch = FetchType.LAZY)
Set<PostLike> userLikes = new HashSet<PostLike>();
在 class 后:
@OneToMany(mappedBy = "post")
private Set<PostLike> postLikes = new HashSet<PostLike>();
我希望 PostLike 有一個復合主鍵,它由 user_id 和 post_id 組成。 提前致謝。
作為一種方法,您可以使用@EmbeddedId
注釋並使用可嵌入的 class 表達此復合鍵:
@Entity
public class PostLike {
@Embeddable
private static class Id implements Serializable {
@Column(name = "user_id")
private Long userId;
@Column(name = "post_id")
private Long postId;
public Id() {
}
public Id(Long userId, Long postId) {
this.userId = userId;
this.postId = postId;
}
// equals and hashCode
}
@EmbeddedId
Id id = new Id();
@ManyToOne
@JoinColumn(name = "user_id")
private User user;
@ManyToOne
@JoinColumn(name = "post_id")
private Post post;
public PostLike() {
}
public PostLike(User user , Post post) {
this.user = user;
this.post = post;
this.id.postId = post.getId();
this.id.userId = user.getId();
post.getUserLikes().add(this);
user.getUserLikes().add(this);
}
... // getters and setters
}
一些注意事項:
來自@EmbeddedId
的javadoc
使用
EmbeddedId
注解時,EmbeddedId
注解必須只有一個且沒有Id
注解。
這種策略的主要優點是雙向導航的可能性。 ...
缺點是管理中間實體實例以創建和刪除鏈接所需的代碼更復雜,您必須獨立保存和刪除這些鏈接。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.