我在为某些实体设置 jpa 映射时遇到问题。下面是我要实现的场景。
有3张桌子:
- 用户:存储用户信息。(自动生成的 ID 是主键)
- 帖子:存储公司发布的 Feed。(自动生成的 ID 是主键)
- 点赞:存储用户点赞的动态。( User-Id, Post-Id 作为复合主键)
下面是我尝试实现的代码,但它不起作用
@Entity(name = "likes")
@IdClass(LikesId.class)
public class Likes {
@Id
@ManyToOne(optional = false)
@JoinColumn(name = "post_id")
private Post post;
@Id
@ManyToOne(optional = false)
@JoinColumn(name = "user_id")
private User user;
@UpdateTimestamp
private Date timestamp;
public Like (Post post, User user){
this.setPost(post);
this.setUser(user);
}
}
下面是复合键的 IdClass :
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode
public class LikesId implements Serializable {
@ManyToOne(optional = false)
@JoinColumn(name = "post_id")
private Post post;
@ManyToOne(optional = false)
@JoinColumn(name = "user_id")
private User user;
}
我在 saveAndFlush 调用时遇到以下错误:
java.lang.IllegalArgumentException: Can not set com.app.models.post.Post field com.app.models.likes.LikesId.post to java.lang.Long