我在用户和评论之间有很多关系。它的工作原理是用户只能发表一条评论。我需要添加另一个生成的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
CommentPK
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,它工作正常。
答案 0 :(得分:0)
正如我在您的代码中看到的,错误消息指出类型在idClass和实体之间不匹配。
如你所见,你的idclass有Long,Long,Long作为类型,而你的实体有Long,Game,User。 或许尝试以下
@Entity
@IdClass(CommentPK.class)
public class Comment {
@Id
private Long id;
@Id
@Column(name="gameID")
private Long gameId;
@ManyToOne
@JoinColumn(name = "gameID" ,referencedColumnName = "id", insertable=false, updatable=false)
private Game game;
@Id
@Column(name="userID")
private Long userId;
@ManyToOne
@JoinColumn(name = "userID",referencedColumnName = "id", insertable=false, updatable=false)
private User user;
private String Text;
并根据实体中的属性重命名IdClass中的字段。