Spring 启动 JPA 复合外键映射
Spring boot JPA composite foreign key mapping
我在为某些实体设置 jpa 映射时遇到问题。下面是我要实现的场景。
有 3 个表:
- Users:存储用户信息。 (自动生成的 ID 是主键)
- Posts:存放公司发布的Feed。 (自动生成的 ID 是主键)
- Likes:存储用户喜欢的Feed。 ( User-Id, Post-Id as composite Primary key )
下面是我尝试实现的代码,但它不起作用
@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
您的 ID class 应如下所示。
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode
public class LikesId implements Serializable {
private Long postId;
private Long userId;
}
我在为某些实体设置 jpa 映射时遇到问题。下面是我要实现的场景。
有 3 个表:
- Users:存储用户信息。 (自动生成的 ID 是主键)
- Posts:存放公司发布的Feed。 (自动生成的 ID 是主键)
- Likes:存储用户喜欢的Feed。 ( User-Id, Post-Id as composite Primary key )
下面是我尝试实现的代码,但它不起作用
@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
您的 ID class 应如下所示。
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode
public class LikesId implements Serializable {
private Long postId;
private Long userId;
}