为什么在首先合并实体时,我会将已删除的实例传递给合并 [英] Why am I getting deleted instance passed to merge, when merging the entity first

查看:478
本文介绍了为什么在首先合并实体时,我会将已删除的实例传递给合并的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我相信我想删除的实体是一个管理实体。但是,无论如何,为什么合并它然后删除它给我以下错误:

I believe the entity that I wish to delete, is a managed entity. But, regardless, why is merging it then removing it giving me the following error:

已删除的实例传递给合并

有人在stackoverflow上说如果它是一个托管实体,那么合并应该被忽略。那为什么不被忽视呢?

Someone said on stackoverflow that merge should be ignored if it is a managed entity. So why is this not being ignored?

我希望删除它的方式如下:

The way I wish to delete it is like so:

TrialUser mergedEntity = em.merge(tu);
em.remove(mergedEntity);

但这个错误,但如果我摆脱第一行似乎工作正常。但我想用另一种方式,因为这与代码的其余部分一致。

But this errors, but if I get rid of the first line it seems to work fine. But I want it the other way because that is consistent with the rest of the code.

编辑:

@PersistenceContext(unitName = "UnitName")
protected EntityManager entityManager;

     @Table(name="TRIAL_USER")

     @Id
     private BigDecimal id;

     @ManyToOne(cascade= {CascadeType.ALL }, fetch=FetchType.EAGER)
     @JoinColumn(name="TRIAL_USER_CLASS_ID3")
     private TrialUserElement trialUserElement3;

@ManyToOne(cascade= {CascadeType.ALL }, fetch=FetchType.EAGER)
@JoinColumn(name="TRIAL_USER_CLASS_ID1")
private TrialUserElement trialUserElement1;


@ManyToOne(cascade= {CascadeType.ALL }, fetch=FetchType.EAGER)
@JoinColumn(name="TRIAL_USER_CLASS_ID2")
private TrialUserElement trialUserElement2;


推荐答案

运行某些代码时可能会出现此错误一个事务,当你在最后提交时,该方法。
在用

You can have this error when you run some code into a transaction, when you commit at the end og the method. When using spring in a method or class annotated with

@Transactional

这是因为您首先删除了对象(未提交),然后尝试更新它。

This happens because you first delete the object (without committing) and then try to update it.

此代码将生成异常:

    @Transactional
    myethod(){
      dao.delete(myObject);
      myObject.setProperty("some value");
      dao.save();  
    }

为避免错误,您不应删除然后保存在同一事务中。

To avoid the error you should not delete and then save in the same transaction.

这篇关于为什么在首先合并实体时,我会将已删除的实例传递给合并的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆