我发现 hibernate(或 mariadb)JPA 似乎无法处理外键中的 0 值。
我有一个父类
class Parent {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "PARENT_ID", unique = true, nullable = false)
private Integer parentId;
}
还有一个子类
class Child {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "CHILD_ID", unique = true, nullable = false)
private Integer childId;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "PARENT_ID", nullable = false)
private Parent parent;
}
所以父级中有 2 行。 parent_id=0
和 parent_id=1
我的问题是,当尝试使用 ID 为 0 的父级时,我收到错误。即此代码
Parent p = entityManager.find(Parent.class, new Integer(0));
Child c = new Child();
c.setParent(p);
entityManager.persist(c);
将失败并出现以下错误:
java.lang.IllegalStateException: org.hibernate.TransientPropertyValueException: Not-null property references a transient value - transient instance must be saved before current operation : com.whatever.Child.parent -> com.whatever.Parent
但以下效果很好:
Parent p = entityManager.find(Parent.class, new Integer(1));
Child c = new Child();
c.setParent(p);
entityManager.persist(c);
因此,我假设 PARENT_ID=0
不知何故混淆了 JPA,认为它不是有效的父对象。
或者这实际上是 mariadb 问题?与您必须更改 session 设置才能将 0 插入 AUTO_INCRMENT
列这一事实相关。
我可以做任何配置或注释来完成这项工作吗?不幸的是,我们将 JPA 代码放在现有系统上,因此更改 PARENT_ID
值并不是一项简单的任务。 (每个人都讨厌数据转换)。
非常感谢任何提示。
最佳答案
MariaDB/MySQL 处理 AUTO_INCRMENT
因此:数字为 1 或更大; 0 是有效的序列号。如果 JPA 无法忍受这些(以及其他一些)限制,JPA 就会被破坏。 (抱歉,但我对让 MySQL 用户的生活变得困难的第 3 方软件感到恼火。)
关于java - JPA外键零0值 hibernate TransientPropertyValueException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41114202/