org.hibernate.TransientObjectException:object是未保存的瞬态实例 - 在合并之前保存瞬态实例

时间:2014-06-11 16:23:27

标签: java hibernate jpa

我知道有很多关于这个错误的问题。我已经尝试过了,没有解决任何问题。

我有一个已经在数据库中的dtoDevice。我从数据库中获取了数据。现在我想将dtoValue对象添加到该设备,但它不起作用。

我有以下DTO课程

@Entity
public class DtoValue {
   @Id 
   @GeneratedValue
   protected int id;

   private int value;

   @ManyToOne
   private DtoDevice dtoDevice;

  ... /* Getters and Setters */
}

@Entity
public class DtoDevice{

    @Id
    @GeneratedValue
    protected int id;

    String deviceName;

    @OneToMany(cascade= CascadeType.REMOVE)
    List<DtoValue> values;

          ... /* Getters and Setters */

    public void addValue(DtoValue dtoValue){
        if(dtoValue != null)
            values.add(dtoValue);
        dtoValue.setDtoDevice(this);
    }
}

当我尝试运行此代码时:

          ... /* em = EntityManager */

    try{
        em.getTransaction().begin(); 


            DtoValue dtoValue = new DtoValue();

            dtoValue.setValue(1);
            /* Even if I try saving dtoValue here (em.persist/merge(dtoValue)) It doesn't work */

            **// THIS dtoDevice is already in the DB - I want to modify it**
            dtoDevice.addValue(dtoValue);
            /* Even if I try saving dtoValue here (em.persist/merge(dtoValue)) It doesn't work */


        /* persist doesnt work, since dtoDevice is already in the DB */
        em.merge(dtoDevice); 

        em.getTransaction().commit();
    }
    catch(Exception e){
        em.getTransaction().rollback();
        showConnectionError(e);
    }

我收到错误:

org.hibernate.TransientObjectException: object is an unsaved transient instance - save the transient instance before merging: **not_important**.model.DtoValue

到目前为止,我尝试了很多方法,并且没有提供任何建议。

2 个答案:

答案 0 :(得分:0)

您首先尝试保存DtoDevice,然后将dtoValue分配给DtoDevice,然后保存DtoDevice。

答案 1 :(得分:0)

当你去保存DtoDevice时,它有一个未保存的DtoValues集合(问题的根源)。您可以通过以下几种方式解决:

1 - 将PERSIST添加到从DtoDevice到DtoValues的级联操作列表中,如下所示:

@OneToMany(cascade= {CascadeType.REMOVE, CascadeType.PERSIST}) 
List<DtoValue> values;

2 - 保存每个新的DtoValue,然后将它们添加到DtoDevice中,如下所示:

DtoValue dtoValue = new DtoValue();
dtoValue.setValue(1);
DtoValue savedDtoValue = ... save it here
dtoDevice.addValue(savedDtoValue);
相关问题