gpt4 book ai didi

java - 在监听器中创建子实体时出现 HibernateException

转载 作者:行者123 更新时间:2023-11-30 02:37:02 26 4
gpt4 key购买 nike

假设我们有一些看起来像这样的实体(我会尽量保持简单):

@Entity
class MainEntity {
//nothing too special here
}

@Entity
class DependentEntity implements Serializable {

@Id
@OneToOne( fetch = FetchType.LAZY, optional = false )
@JoinColumn( name = "mainEntityId", insertable = false, updatable = false, nullable = false )
private MainEntity mainEntity;
}

@Entity
@IdClass(AnotherDependentEntityId.class)
class AnotherDependentEntity {

@Id
@ManyToOne( fetch = FetchType.LAZY, optional = false )
@JoinColumn( name = "mainEntityId", insertable = false, updatable = false, nullable = false )
private MainEntity mainEntity;

@Id
@Column ( name = "type", insertable = false, updatable = false, nullable = false )
private SomeEnum type;
}

如您所见,每个 MainEntity 最多可以有一个 DependentEntity,但可以有多个 AnotherDependentEntity - 每个 值一个。 SomeEnum.

现在,每当有人创建 MainEntity 时,我们也希望创建必要的 DependentEntityAnotherDependentEntity 实例。我们尝试通过 PostInsertEventListener 和依赖的子 session 来完成此操作,如下所示:

Session subSession = pEvent.getSession().sessionWithOptions()         
.autoClose( true)
.autoJoinTransactions( true )
.noInterceptor()
.openSession();

subSession.saveOrUpdate( new DependentEntity( mainEntity ) );
subSession.saveOrUpdate( new AnotherDependentEntity ( mainEntity, SomeEnum.VALUE1 ) );

它适用于 DependentEntity,但不适用于 AnotherDependentEntity,我们无法弄清楚原因。

我们在第二个 saveOrUpdate() 中收到以下消息:

HHH000346: Error during managed flush [org.hibernate.HibernateException: No part of a composite identifier may be null]
(in org.hibernate.tuple.entity.AbstractEntityTuplizer$IncrediblySillyJpaMapsIdMappedIdentifierValueMarshaller.getIdentifier(AbstractEntityTuplizer.java:367) )

在调试代码时,似乎当执行 AnotherDependentEntity 上的持久化时,mainEntity 属性为 null,即使它之前已设置(并且在原始 session 也已正确设置)。

这会导致这样的印象:mainEntity 必须以某种方式设置为 null,但即使是值监视断点也不会被触发,因此它必须通过反射发生(并且我们验证了它是相同的AnotherDependentEntity 实例在两种情况下)。

所以问题是:

有谁知道为什么/哪里 id 的该部分设置为 null?也许我们做的都是错误的,并且有更好的方法来做到这一点(注意:我们不能将引用添加到 MainEntity 中,并且出于多种原因让它级联)。

环境:Wildfly 10.1.0 和 Hibernate 5.2.7

编辑:

我们观察到的另一件事是:在调试时可以看到实体持久化器具有对实体和 id 类实例的引用(即 AnotherDependentEntityId)。 id-class 包含这两个值,即两个字段均为 null,而实际实体的 id 已部分为 null。

最佳答案

我在hibernate.atlassian中发现了一个问题。尝试这个解决方案来工作...

关于java - 在监听器中创建子实体时出现 HibernateException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42770718/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com