2017-05-13 75 views
0

我在用户和评论之间有很多关系。它的工作方式,但用户只能发表一条评论。我需要添加另一个生成的ID,使密钥具有唯一性。使用IdClass弹簧jpa数据jpa与3个主键合成

Comment类

@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

我需要得到游戏的评论,也可以得到用户评论?当游戏被删除时,它的评论也被删除 –

+0

这不是将用户和游戏置于实体的** ID **中的原因。使它们成为实体的一部分,而不是它的ID。 –

回答

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重命名字段。