【问题标题】:Spring jpa data jpa composite with 3 primary key using IdClass使用 IdClass 的具有 3 个主键的 Spring jpa 数据 jpa 复合
【发布时间】: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


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2014-11-10
    • 1970-01-01
    • 2020-06-10
    • 1970-01-01
    • 2021-10-07
    • 1970-01-01
    • 2018-02-02
    • 2013-03-19
    • 2020-02-19
    相关资源
    最近更新 更多