gpt4 book ai didi

java - 连接表中的复合 ID

转载 作者:行者123 更新时间:2023-12-02 08:46:50 25 4
gpt4 key购买 nike

我有以下 PostLike 类:

@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;
}

该类已具有父 BaseEntity 类提供的 ID 字段。

在 User 类中,我有以下字段:

@OneToMany(mappedBy = "user", fetch = FetchType.LAZY)
Set<PostLike> userLikes = new HashSet<PostLike>();

在 Post 类中:

@OneToMany(mappedBy = "post")
private Set<PostLike> postLikes = new HashSet<PostLike>();

我希望 PostLike 有一个复合主键,由 user_id 和 post_id 组成。提前致谢。

最佳答案

作为执行此操作的一种方法,您可以使用 @EmbeddedId 注释并使用可嵌入类表达此组合键:

@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

There must be only one EmbeddedId annotation and no Id annotation when the EmbeddedId annotation is used.

来自 Java Persistence with Hibernate

The primary advantage of this strategy is the possibility for bidirectional navigation. ...
A disadvantage is the more complex code needed to manage the intermediate entity instances to create and remove links, which you have to save and delete independently.

关于java - 连接表中的复合 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61018594/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com