首页 > 解决方案 > JPA 和 Hibernate 问题,x 实例的标识符

问题描述

我有一个使用复合键作为主键的 JPA/Hibernate 实体。当我从数据库中读取对象并进行更新时,我得到了错误

javax.persistence.PersistenceException: org.hibernate.HibernateException: identifier of an instance of navigation.external.CustomerNavigationType was altered from navigation.external.CustomerNavigationTypeId@7ccdbbc5 to navigation.external.CustomerNavigationTypeId@bba8c505

当我冲洗时发生错误。

我已经阅读了其他几篇 stackoverflow 帖子并尝试实施这些建议,但我仍然收到错误消息。你能看到我错过了什么吗?

实体:

@NoArgsConstructor
@Getter
@Setter
@Entity(name = "CustomerNavigationType")
@IdClass(CustomerNavigationTypeId.class)
@Table(name = "MY_TABLE")
public class CustomerNavigationType {

    @Id
    @Column(name = "BANKNR")
    private BigDecimal bankNr;

    @Id
    @Column(name = "NAVTYPE")
    private String navType;

    @Id
    @Column(name = "JUREN")
    private String juren;

    @Column(name = "STATU")
    private String state;
}

复合键:

@AllArgsConstructor
@NoArgsConstructor
@Getter
public class CustomerNavigationTypeId implements Serializable {

    private BigDecimal bankNr;

    private String navType;

    private String juren;

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }

        if (obj == null) {
            return false;
        }

        if (getClass() != obj.getClass()) {
            return false;
        }

        CustomerNavigationTypeId other = (CustomerNavigationTypeId) obj;
        return Objects.equals(bankNr, other.getBankNr())
            && Objects.equals(navType, other.getNavType())
            && Objects.equals(juren, other.juren());
    }

    @Override
    public int hashCode() {
        return Objects.hash(bankNr, navType, juren);
    }
}

数据库客户端代码:

EntityManager em = entityManagerProducer.getEntityManager();
CustomerNavigationTypeId compositeId = new CustomerNavigationTypeId(
   BigDecimal.valueOf(1),
   "NAVRULE1",
   "2021-08-05 22:15:00.384395");

em.getTransaction().begin();
CustomerNavigationType customerNavigationType = em.find(CustomerNavigationType.class, compositeId);
customerNavigationType.setState("ACTIVE");
em.flush();
em.getTransaction().commit();

标签: javahibernatejpa

解决方案


我通过使用@EmbeddedId 和@Embeddable 代替@Idclass 等解决了这个问题。


推荐阅读