hibernate报错:Cannot add or update a child row: a foreign key constraint fails

6 篇文章 0 订阅
3 篇文章 0 订阅

我遇到这个问题的原因是:把主键作为外键关联到了其他表的主键。

在实体Product:

 

package pp.entity;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.DiscriminatorColumn;
import javax.persistence.DiscriminatorType;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.OneToMany;
import javax.persistence.Table;


@Entity
@Table
@Inheritance(strategy=InheritanceType.SINGLE_TABLE) 
@DiscriminatorColumn(name="type",discriminatorType=DiscriminatorType.STRING)  
@DiscriminatorValue("product")
public class Product extends Goods{

	@OneToMany(targetEntity=ProductAssembleRecord.class,fetch=FetchType.LAZY,cascade={CascadeType.PERSIST,CascadeType.MERGE})
	@JoinColumn(name="productAssembleId",insertable=true,updatable=true)//成功的
	private List<ProductAssembleRecord> productAssembleRecords=new ArrayList<ProductAssembleRecord>();
	//.....
	
}

 配置一对多时:@JoinColumn(name="productAssembleRecordId",insertable=true,updatable=true)(错误的。)

 

 

实体ProductAssembleRecord:

 

@Entity
@Table
public class ProductAssembleRecord implements IEntity {
	@Id
	@GeneratedValue(strategy=GenerationType.AUTO)
	private int  productAssembleRecordId;
//......
}
 

看起来这样的配置会导致ProductAssembleRecord的主键productAssembleRecordId会作为外键映射到实体Product的主键goodsId(这个是其父类的主键,同一个表所以共享,不用管它)。我如果插入第一个ProductAssembleRecord没有问题,因为productAssembleRecordId能找到一个goodsId(只有一条数据)来外键关联。第二次就会失败,因为主键会自动增长。

解决:把@JoinColumn(name="productAssembleRecordId",insertable=true,updatable=true)

换做:@JoinColumn(name="productAssembleId",insertable=true,updatable=true)

从新建立表结构。ok。实体ProductAssembleRecord对应的表多了一个叫productAssembleId列(我的表结构是用实体生成的)。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值