合并父级正在导致orphandelete

时间:2018-06-11 12:43:01

标签: hibernate jpa one-to-many

我有两个类/实体ProcJobData和SubstrateData

ProcjobData:

...
@OneToMany(mappedBy = "procJobData", orphanRemoval = true, cascade = { CascadeType.ALL })
private List<SubstrateData> substrateData;
...

和SubstrateData:

@ManyToOne
@JoinColumn(name = "procjobdata_fk")
privateProcJobData procJobData();

在我的代码jobmanager中,我创建一个新的procjobdata并设置一些值并将其保存为成员。

EntityManager em = emf.createEntityManager();

try {
     em.getTransaction().begin();
     pjData = new ProcJobData();
     ... set some values
     pjData = ProcJobDataDAO.create(em, pjData);
     em.getTransaction().commit();
} catch (Exception ex) {
     LOG.error("Failed to persist ProcJob[" + procJobNo + "]", ex);
     if (em.getTransaction().isActive()) {
           em.getTransaction().rollback();
     }
} finally {
     if (em != null && em.isOpen()) {
           em.close();
     }
}

然后稍后我添加了SubstrateData:

em.getTransaction().begin();
for(int i = 0; i < MAX_SUBSTRATES; i++){
    ...
    SubstrateData substrate = new SubstrateData();
    ...
    substrate.setProcJobData(this.procJobData);
    SubstrateData create = SubstrateDataDAO.create(em, substrate);
    procJobData.addSubstrateData(create);
}
this.procJobData = em.merge(this.procJobData);
em.getTransaction().commit();

SubstrateDataDAO的create方法:

public static SubstrateData create(final EntityManager entityManager, final    SubstrateData entity) {
    entityManager.persist(entity);
    entityManager.flush();
    return entity;
}

现在我的问题:如果我改变一些值,我总是使用交易。如果我在一个打开的事务中合并procJobData实体,我将得到它的一个新实例,我所有的SubstDatas都是孤儿,因为它们仍然链接到旧实例,而hibernate将删除条目。 我在交易中删除了合并,一切都很好 - 但为什么? 问题是:我是否需要在交易中进行合并?

编辑:如果我稍后将合并procjobdata实体 - 基板仍会被删除。比如稍后的代码 - 此时有基板的数据库条目:

em.getTransaction().begin();
this.procJobData.setLoadOn(new Date());
this.procJobData = em.merge(this.procJobData); //edit -> using return value
em.getTransaction().commit(); 

1 个答案:

答案 0 :(得分:0)

您的合并代码应该这样做:

this.procJobData = em.merge( this.procJobData );

原因很明显来自java文档

Returns: the managed instance that the state was merged to

您提供的实例仅用作数据容器。您希望确保持有对返回对象的引用,以便在类中保持持久性提供程序当前已合并的状态。