我知道有关此错误的问题很多。我已经尝试过了,但没有解决。

我有一个已经在数据库中的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


我尝试了许多方法,并遵循了一些技巧,但到目前为止没有任何进展。

最佳答案

嗨,请尝试先保存DtoDevice,然后将dtoValue设置到DtoDevice,然后再保存DtoDevice。

10-01 02:58