2013-07-10 112 views
0

我試圖在數據庫中插入一個對象。它包含其中也應插入的一個集合,但我得到下面的異常:Hibernate級聯拋出異常保存

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實體,我可以看到正在執行的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爲空,因爲客戶正在插入地址之前。有映射錯誤嗎?

謝謝!

+0

你在你的客戶的 'ID' 字段有哪些註釋更換

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

? –

回答

0

你告訴Hibernate,Address實體中的客戶不應該被插入也不能更新,所以Hibernate不會插入它。通過

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