问题描述
我正在使用Hibernate 3批注.我有一个表"product"和一个子表"product_spec",具有一对多关系.当我做hibernateTemplate.save(product)时报错
I am using Hibernate 3 annotations.I have a table 'product' and child table 'product_spec' with one-to-many relation.When i do hibernateTemplate.save(product) it is giving error
无法插入:[com.xx.ProductSpec]; SQL [插入Products_spec列"PRODUCT_ID"不能为空
could not insert: [com.xx.ProductSpec]; SQL [insert into Products_specColumn 'PRODUCT_ID' cannot be null
@Entity
@Table(name = "product")
public class Product implements Serializable {
private static final long serialVersionUID = 1L;
@Id @GeneratedValue
@Column(name = "PRODUCT_ID")
private Integer productId;
@Column(name = "PRODUCT_NAME")
private String productName;
@OneToMany(mappedBy = "product",fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private List<ProductSpec> specs = new ArrayList<ProductSpec>();
//getter and setter
}
@Entity
@Table(name = "Products_spec")
public class ProductSpec implements Serializable {
private static final long serialVersionUID = 1L;
@Id @GeneratedValue
@Column(name = "spec_id")
private Integer specId;
@ManyToOne
@JoinColumn(name = "PRODUCT_ID")
private Product product;
//getter and setter
}
hibernateUtil.getTemplate().save(product);
推荐答案
问题是我的product_id列(子级中的join列)为非空.将其设置为空后,它可以工作.
Issue was i had product_id column (join column in child) as not-null.After making it nullable it worked.
我没有意识到由hibernate执行的所有级联查询.
I was unaware of queries executed by hibernate for cascade all.
首先,hibernate添加连接列值为空的子条目,然后更新该条目.
First hibernate adds child entries with join column value as null, and then it updates the entry.
这篇关于一对多级联全部未在插入子项时设置父ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!