一对多级联全部未在插入子项时设置父ID [英] One to many cascade All is not setting parent id while child entry insertion

查看:109
本文介绍了一对多级联全部未在插入子项时设置父ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用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_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);

推荐答案

问题是我的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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆