Hibernate级联抛出保存时出现异常

时间:2013-07-10 17:31:16

标签: hibernate jpa-2.0 one-to-many hibernate-mapping cascade

我正在尝试在数据库中插入一个对象。它包含一个也应插入的集合,但我得到以下例外:

SQLServerException: Cannot insert the value NULL into column 'ID_CUSTOMER', table 'dbo.CUSTOMER_ADDRESS'; column does not allow nulls. INSERT fails.

映射如下:

CustomerDB.java

@OneToMany(fetch = FetchType.LAZY, mappedBy = "customer", orphanRemoval = true, cascade = CascadeType.ALL)
private List<CustomerAddressDB> addresses;

CustomerAddressDB.java

@ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.REFRESH)
@JoinColumn(name = "ID_CUSTOMER", nullable = false, updatable=false, insertable=false)
private CustomerDB customer;

因此,当我为CustomerDB实体调用persist方法时,我可以看到正在执行的HQL:

Hibernate: insert into M2M_CUSTOMER (NM_COMPANY_NAME, DT_CREATED, ID_PARENT, ID_LAYER, DS_OBS, DS_SHORT_NAME, ID_CUSTOMER_STATUS, NM_TRADING_NAME) values (?, ?, ?, ?, ?, ?, ?, ?)
Hibernate: insert into M2M_CUSTOMER_ADDRESS (DS_CITY, DS_COUNTRY, NR_NUMBER, NR_POSTAL_CODE, DS_STATE, DS_STREET, ID_ADDRESS_TYPE) values (?, ?, ?, ?, ?, ?, ?)

但在此之后抛出前面提到的异常。我无法理解为什么它说CUSTOMER_ID为null,因为客户是在地址之前插入的。有映射错误吗?

谢谢!

1 个答案:

答案 0 :(得分:0)

你告诉Hibernate不应该插入或更新Address实体中的客户,因此Hibernate不会插入它。替换

@ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.REFRESH)
@JoinColumn(name = "ID_CUSTOMER", nullable = false, updatable=false, insertable=false)
private CustomerDB customer;

通过

@ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.REFRESH)
@JoinColumn(name = "ID_CUSTOMER", nullable = false)
private CustomerDB customer;