【问题标题】:JPA: There should be one non-read-only mapping defined for the primary key fieldJPA:应该为主键字段定义一个非只读映射
【发布时间】:2019-10-04 23:57:44
【问题描述】:

我在尝试运行我的应用程序时收到An internal error occurred accessing the primary key object [class domein.PersoonSessieKey]. Internal Exception: java.lang.NoSuchMethodException: domein.PersoonSessieKey.getPersoon()error。我看过类似的问题,但我不知道我做错了什么。

我尝试过使用 Embeddable,但由于我不知道自己在做什么,这也引发了错误,这让我尝试使用 ClassId。但是现在我也遇到了一个错误,我不知道是什么原因造成的。

实体类

@Entity
@Access(AccessType.PROPERTY)
@IdClass(PersoonSessieKey.class)
@Table(name = "PersoonSessie")
public class ClubPersoonSessie implements Serializable {

    private ClubSessie sessie;
    private ClubPersoon persoon;

    @Id
    @ManyToOne(cascade = CascadeType.PERSIST)
    @JoinColumn(name = "SessieId")
    public ClubSessie getSessie() {
        return sessie;
    }

    public void setSessie(ClubSessie sessie) {
        this.sessie = sessie;
    }

    @Id
    @ManyToOne(cascade = CascadeType.PERSIST)
    @JoinColumn(name = "PersoonId")
    public ClubPersoon getPersoon() {
        return persoon;
    }

    public void setPersoon(ClubPersoon persoon) {
        this.persoon = persoon;
    }

    public ClubPersoonSessie() {
    }
}

主键类

public class PersoonSessieKey implements Serializable {

    private int persoonId;
    private int sessieId;

    public int getPersoonId() {
        return persoonId;
    }

    public int getSessieId() {
        return sessieId;
    }

    public PersoonSessieKey(int persoonId, int sessieId) {
        this.persoonId = persoonId;
        this.sessieId = sessieId;
    }

    public PersoonSessieKey() {
    }

    @Override
    public int hashCode() {
        int hash = 5;
        hash = 89 * hash + this.persoonId;
        hash = 89 * hash + this.sessieId;
        return hash;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final PersoonSessieKey other = (PersoonSessieKey) obj;
        if (this.persoonId != other.persoonId) {
            return false;
        }
        if (this.sessieId != other.sessieId) {
            return false;
        }
        return true;
    }

}

【问题讨论】:

    标签: jpa mapping eclipselink


    【解决方案1】:

    IdClass 的属性应与您的实体中用@Id 注释的字段匹配。您发布的代码显然不是这种情况。

    domein.PersoonSessieKey.getPersoon() 是预期的(但未找到),因为您有一个带有Id 注释的 persoon 属性

    使其与 idclass 方法一起工作

    • 将与 idclass 中相同的字段添加到实体并使用 @Id 注释它们
    • 从关系中删除 @Id
    • 将关系标记为不可更新和不可插入(解决帖子标题的问题,即多个可写字段映射到同一列)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-02-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-21
      • 2017-01-03
      • 2021-07-03
      相关资源
      最近更新 更多