繁体   English   中英

使用IdClass使用3个主键的Spring JPA数据JPA复合

[英]Spring jpa data jpa composite with 3 primary key using IdClass

我与用户和评论之间有很多关系。 它有效,但是用户只能发表评论。 我需要添加另一个使密钥唯一的生成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,它工作正常。

正如我在您的代码中看到的那样,错误消息指出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中的字段。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM