ConstrainVoilationException:无法删除或更新hibernate jpa中的父行

时间:2016-03-30 04:10:04

标签: java hibernate jpa

我在OneToOne关系中有三个实体Product - > SkuImpl - > SkuAvailabilityImpl

产品

@Entity 
public class ProductImpl implements  Product {
@OneToOne(targetEntity=SkuImpl.class, cascade=   {cascadeType.ALL},orphanRemoval=true) 
@Cache(usage=CacheConcurrencyStrategy.READ_WRITE)
@JoinColumn(name="DEFAULT_SKU_ID")
   protected Sku defaultSku;
//setter and getters
}

SkuImpl

@Entity 
public class SkuImpl implements  Sku {
@OneToOne(targetEntity=SkuAvailabilityImpl.class, cascade=   {cascadeType.ALL},fetch=FetchType.LAZY) 
@Cache(usage=CacheConcurrencyStrategy.READ_WRITE)
@JoinColumn(name="SKU_AVAILABILITY_ID",referencedColumnName="SKU_AVAILABILITY_ID")
@LazyCollection(LazyCollectionOption.FALSE)
protected SkuAvailability totalSku;
//product
@OneToOne(targetEntity=ProductImpl.class, cascade=   {cascadeType.ALL}) 
@JoinColumn(name="DEFAULT_PRODUCT_ID")
protected Product defaultProduct;

//setter and getters
}

SkuavailabilityImpl.java

@Entity 
public class SkuAvailabilityImpl implements SkuAvailability{
@OneToOne(optional=true,targetEntity=SkuImpl.class) 
@Cascade(value={org.hibernate.annotations.CascadeType.ALL})
@JoinColumn(name="SKU_ID", referencedColumnName='SKU_ID',insertable=false,updatable=false)
@Cache(usage=CacheConcurrencyStrategy.READ_WRITE)
protected Sku sku;
//setter and getters
}

在DAO中

protected EntityManager manager;
public void remove(Serializable entity){
manager.remove(entity);
manager.flush();//here getting an exception
}

当我插入Product记录时,会在相应的表中插入。但问题是当我试图删除product获得一个删除

javax.persistence.PersistenceException:  org.hibernate.exception.ConstraintVoilationException:  Cannot delete or  update a parent row: a foreign key constraint fails (`ssz01b`.`blc_product`, CONSTRAINT  `FKBC3A8A84B` FOREIGN KEY (`DEFAULT_SKU_ID`) REFERENCES `blc_sku` (`SKU_ID`))

我用谷歌搜索解决方案,我发现orphanRemoval=true可以解决问题,但遗憾的是它不适用于我,任何人都可以帮助解决这个问题。

2 个答案:

答案 0 :(得分:0)

尝试调用merge,然后在entity

上删除
entityManager.remove(entityManager.merge(entity));

答案 1 :(得分:0)

为SkuImpl Entitiy中的SkuAvailability子项添加orphanRemoval=true