One to many cascade All is not setting parent id while child entry insertion

家住魔仙堡 提交于 2020-01-03 03:02:07

问题


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);

回答1:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!