java - 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();
解决方案
我通过使用@EmbeddedId 和@Embeddable 代替@Idclass 等解决了这个问题。
推荐阅读
- java - Jenkins 对 jenkins.xml 的变化没有反应
- c# - 如何在另一个 ObservableCollection 中使用 ObservableCollection?
- c# - 错误 CS0103:当前上下文中不存在名称“_context”
- javascript - React Router 以编程方式导航到路由
- python - 将 TensorFlow 安装到现有的 Anaconda 环境?
- gitlab-ci - Gitlab/CI 作业规则评估
- c# - 如何在 Unity 中只跳转一次?
- lua - 如何在lua中获取数组的大小
- c - 超时处理 libcurl 中止
- powershell - Powershell - 获取任务计划程序运行结果的历史记录