JPA 外键零 0 值休眠 TransientPropertyValueException
JPA foreign key zero 0 value hibernate TransientPropertyValueException
我发现 hibernate(或 mariadb)JPA 似乎无法在外键中使用 0 值。
我有一个parentclass
class Parent {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "PARENT_ID", unique = true, nullable = false)
private Integer parentId;
}
还有一个childclass
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;
}
所以我们在 parent 中有 2 行。 parent_id=0
和 parent_id=1
我的问题是在尝试使用 ID 0 的 parent 时出现错误。即此代码
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 认为它不是有效的 parent object.
或者这实际上是 mariadb 问题?与您必须更改会话设置以便将 0 插入 AUTO_INCREMENT
列这一事实有关。
我可以做任何配置或注释来完成这项工作吗?不幸的是,我们将 JPA 代码放在现有系统上,因此更改 PARENT_ID
值并非易事。 (每个人都讨厌数据转换)。
非常感谢任何提示。
MariaDB/MySQL 处理 AUTO_INCREMENT
因此:数字为 1 或更大; 0 是一个有效的序列号。如果 JPA 不能忍受这些(和其他一些)限制,那么 JPA 就坏了。 (抱歉,但我对第 3 方软件感到恼火,这让 MySQL 用户的生活变得困难。)
我发现 hibernate(或 mariadb)JPA 似乎无法在外键中使用 0 值。
我有一个parentclass
class Parent {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "PARENT_ID", unique = true, nullable = false)
private Integer parentId;
}
还有一个childclass
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;
}
所以我们在 parent 中有 2 行。 parent_id=0
和 parent_id=1
我的问题是在尝试使用 ID 0 的 parent 时出现错误。即此代码
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 认为它不是有效的 parent object.
或者这实际上是 mariadb 问题?与您必须更改会话设置以便将 0 插入 AUTO_INCREMENT
列这一事实有关。
我可以做任何配置或注释来完成这项工作吗?不幸的是,我们将 JPA 代码放在现有系统上,因此更改 PARENT_ID
值并非易事。 (每个人都讨厌数据转换)。
非常感谢任何提示。
MariaDB/MySQL 处理 AUTO_INCREMENT
因此:数字为 1 或更大; 0 是一个有效的序列号。如果 JPA 不能忍受这些(和其他一些)限制,那么 JPA 就坏了。 (抱歉,但我对第 3 方软件感到恼火,这让 MySQL 用户的生活变得困难。)