Rajeev Naik
Rajeev Naik

Reputation: 61

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

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

Upvotes: 2

Views: 3363

Answers (1)

Rajeev Naik
Rajeev Naik

Reputation: 61

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.

Upvotes: 3

Related Questions