英文:
org.hibernate.id.IdentifierGenerationException: attempted to assign id from null one-to-one property (hibernate+postgres)
问题
我正在使用 Hibernate 5.3.11 与 Spring Data JPA 以及 PostgreSQL,当我尝试更新复杂实体 ClassC 时,出现 "org.hibernate.id.IdentifierGenerationException: attempted to assign id from null one-to-one property [packagename.ClassB.classA]" 错误。
- ClassC 使用 @OneToMany 与 ClassA 关联
- ClassA 使用 @OneToOne 与 ClassB 关联
- 在调用更新方法之前,所有实体之间都有链接
- ClassC 是一个父实体,级联到 ClassA,ClassA 级联到 ClassB
- 问题似乎仅与 A<->B 关系有关
- show-sql 告诉我 ClassA 成功持久化,但似乎由于某种原因,在 Hibernate 的某个地方丢失了与 ClassB 的链接
- 第一次持久化实体运行良好。错误仅在更新时出现。我甚至不会更新现有的 ClassB 和 ClassA 实体,而是用新实体替换它们。
关系图:
SQL 中的 ClassB:
SQL 中的 ClassA:
Java 实体:
@Data
@Entity
@EqualsAndHashCode(exclude = {"classA"})
public class ClassA {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne
@JoinColumn(name = "classC_id")
private ClassC classC;
@OneToOne(mappedBy = "classA", cascade = CascadeType.ALL)
private ClassB classB;
}
@Data
@Entity
public class ClassB {
@Id
private Long id;
@OneToOne
@JoinColumn(name = "id")
@MapsId
private ClassA classA;
}
英文:
I'm using hibernate 5.3.11 with SpringDataJpa and PostgreSQL and I get "org.hibernate.id.IdentifierGenerationException: attempted to assign id from null one-to-one property [packagename.ClassB.classA]" when trying to update a complex entity ClassC.
- ClassC is @OneToMany with ClassA
- ClassA is @OneToOne with ClassB.
- All entities have links to each other before calling update method.
- ClassC is a parent entity and cascades to ClassA, which cascades to ClassB.
- The issue seems to be related only to A<->B relationship.
- show-sql tells me that ClassA persists fine, but seems like for some reason it looses link to ClassB somewhere in hibernate.
- Persisting entity for the first time works fine. The error only comes on update. And I don't even update existing entities of ClassB and ClassA, I replace them with new ones.
Relationship:
Java entities:
@Data
@Entity
@EqualsAndHashCode(exclude = {"classA"})
public class ClassA {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne
@JoinColumn(name = "classC_id")
private ClassC classC;
@OneToOne(mappedBy = "classA", cascade = CascadeType.ALL)
private ClassB classB;
}
@Data
@Entity
public class ClassB {
@Id
private Long id;
@OneToOne
@JoinColumn(name = "id")
@MapsId
private ClassA classA;
}
答案1
得分: 0
我使用了SpringBoot版本2.1.8。升级到2.2.1有所帮助。
详细答案请参考此处:https://stackoverflow.com/questions/58561156/post-upgrade-mapsid-is-throwing-an-error-when-saving-an-existing-entity-but-o
英文:
Short Answer: I used SpringBoot ver.2.1.8. Updating to 2.2.1 helped.
Long answer here https://stackoverflow.com/questions/58561156/post-upgrade-mapsid-is-throwing-an-error-when-saving-an-existing-entity-but-o
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论