【发布时间】:2017-05-13 14:40:56
【问题描述】:
我在用户和评论之间有多对多的关系。它可以工作,但用户只能发表一条评论。我需要添加另一个生成的 id,使密钥唯一。
评论类
@Entity
@IdClass(CommentPK.class)
public class Comment {
@Id
private Long id;
@Id
@ManyToOne
@JoinColumn(name = "gameID" ,referencedColumnName = "id")
private Game game;
@Id
@ManyToOne
@JoinColumn(name = "userID",referencedColumnName = "id")
private User user;
private String Text;
public Comment() {
super();
this.id = null;
this.game = null;
this.user = null;
Text = null;
}
public Comment(Game game, User user, String text) {
this();
this.id = null;
this.game = game;
this.user = user;
Text = text;
}
public Comment(Game game, String text) {
this();
this.id = null;
this.game = game;
this.Text = text;
} }//setters and getters
评论PK
public class CommentPK implements Serializable {
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private Long game;
private Long user; }//setters and getters
错误并不是很大
Can not set java.lang.Long field guru.springframework.domain.CommentPK.game to guru.springframework.domain.TF_Game
没有生成的 id 也可以正常工作。
【问题讨论】:
-
为什么?你为什么要让你的生活如此复杂?为什么不为您的实体使用单列、纯技术、自动生成的主键?
-
我需要获得游戏评论,也可以获得用户评论?当游戏被删除时,它的 cmets 也被删除了
-
这不是将用户和游戏放在实体的ID中的理由。使它们成为实体的一部分,而不是其 ID。
-
它可以工作,我删除了commentPK,还从用户和游戏中删除了@Id注释,谢谢
标签: java spring hibernate jpa relationship