0

我在为某些实体设置 jpa 映射时遇到问题。下面是我要实现的场景。

有3张桌子:

  1. 用户:存储用户信息。(自动生成的 ID 是主键)
  2. 帖子:存储公司发布的 Feed。(自动生成的 ID 是主键)
  3. 点赞:存储用户点赞的动态。( 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
4

1 回答 1

1

您的 id 类应如下所示。

@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode
public class LikesId implements Serializable {

    private Long postId;

    private Long userId;

}
于 2021-07-09T08:27:51.963 回答