我遇到这个问题的原因是:把主键作为外键关联到了其他表的主键。
在实体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列(我的表结构是用实体生成的)。