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
could not insert: [com.xx.ProductSpec]; SQL [insert into Products_spec Column '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);
Issue was i had product_id column (join column in child) as not-null. After making it nullable it worked.
I was unaware of queries executed by hibernate for cascade all.
First hibernate adds child entries with join column value as null, and then it updates the entry.
来源:https://stackoverflow.com/questions/24270570/one-to-many-cascade-all-is-not-setting-parent-id-while-child-entry-insertion