更新时Hibernate CascadeType.SAVE_UPDATE transcient异常

时间:2017-05-29 23:46:11

标签: java spring hibernate jpa

我在内存数据库中使用带有H2的Spring启动

spring.jpa.database-platform=org.hibernate.dialect.H2Dialect

Hibernate Core {5.0.12.Final}

我有一个对象实体

@Entity
@Table(name = "T_OBJECT")
public class ObjectEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "IDT_OBJECT")
    private Long id; 

    @Column(name = "NAME",length = 50, nullable = false)
    private String name;

    // from org.hibernate.annotations.CascadeType;
    @Cascade(CascadeType.SAVE_UPDATE)
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "CATEGORY_OBJECT", referencedColumnName = "IDT_CATEGORY")
    private CategoryEntity category;
}

和CategoryEntity

@Entity
@Table(name = "T_CATEGORY")
public class CategoryEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "IDT_CATEGORY")
    private Long id; 

    @Column(name = "NAME")
    private String name;
}

我有这个objectService

@Transactional(rollbackOn = Exception.class)
public void saveOrUpdateObject(ObjectForm object) {

   ObjectEntity objEntity = null;

   if(object.getId() != null) {
     objEntity = daoObject.findById(object.getId())
   }

   if(objEntity == null) {
     objEntity = new ObjectEntity();

     // we can't change the name
     objEntity.setName(object.getName);
   }

   CategoryEntity catEntity = objEntity.getCategory();

   if(catEntity == null) {
         catEntity = new CategoryEntity();
   }
   catEntity.setName(object.getCategoryName())

   objEntity.setCategory(catEntity);

   // execute sessionFactory.getCurrentSession().saveOrUpdate()
   daoObject.saveOrUpdate(objEntity);

}

当我创建对象时,此代码完美无缺,但在使用其他类别进行更新时,我会收到一个错误的错误

Caused by: org.hibernate.TransientPropertyValueException: object references an unsaved transient instance - save the transient instance before flushing : com.appli.entity.ObjectEntity.category -> com.appli.entity.CategoryEntity

当然,如果我使用daoCategory.saveOrUpdate(catEntity)将CategoryEntity保存到我的服务中,然后保存有效的ObjectEntity,但使用Cascade SAVE_UPDATE

时不需要

但是,如果我通过persistance.Cascade更改CascadeType.SAVE_UPDATE

@ManyToOne(fetch = FetchType.LAZY,cascade = {javax.persistence.CascadeType.PERSIST, javax.persistence.CascadeType.REFRESH, javax.persistence.CascadeType.MERGE})
@JoinColumn(name = "CATEGORY_OBJECT", referencedColumnName = "IDT_CATEGORY")
private CategoryEntity category;

它适用于创建和更新而无需更改服务线。 @Cascade(CascadeType.ALL)也有效

我虽然@Cascade(hibernate.annotations.CascadeType.SAVE_UPDATE)cascade = {javax.persistence.CascadeType.PERSIST, javax.persistence.CascadeType.REFRESH, javax.persistence.CascadeType.MERGE}

相同

0 个答案:

没有答案