JPA Unidirectional @OnetoMany失败

时间:2015-08-04 14:26:31

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

我有几个单向JPA2 @OnetoMany关系的失败案例 下面是代码段

@Entity
@Table(name="CUSTOMER")
@Access(AccessType.FIELD)
public class Customer {

       @OneToMany(cascade=CascadeType.ALL, fetch=FetchType.LAZY)
       @JoinColumn(name="CUSTOMER_ID", referencedColumnName="CUSTOMER_ID")
       private List<Address> customerAddresses;

....
}

在这种情况下,它无法在服务器启动期间创建实体管理器工厂,并出现以下错误

DEBUG - Second pass for collection: xx.xxx.xxxxxxx.core.domainmodel.customerinfo.Customer.customerAddresses
 DEBUG - Binding a OneToMany: xx.xxx.xxxxxxx.core.domainmodel.customerinfo.Customer.customerAddresses through a foreign key
 DEBUG - Mapping collection: xx.xxx.xxxxxxx.core.domainmodel.customerinfo.Customer.customerAddresses -> CUSTOMER_ADDRESS
 DEBUG - Unable to build entity manager factory
java.lang.NullPointerException: null
 at org.hibernate.cfg.annotations.CollectionBinder.bindCollectionSecondPass(CollectionBinder.java:1456) ~[hibernate-core-4.3.6.Final.jar:4.3.6.Final]

当我从referencedColumnName注释

中删除@JoinColumn属性时,服务器启动就很好了

但是当我试图坚持下面失败的实体时,Hibernate为失败生成了跟踪(CUSTOMER_ID is the name of the identity generated PK column in CUSTOMER table and FK in the CUSTOMER_ADDRESS table

DEBUG - Executing identity-insert immediately
DEBUG - insert into CUSTOMER (ESTABLISHMENT_DATE, ESTABLISHMENT_PLACE, MAJOR_PRODUCT, PAID_UP_CAPITAL, TYPE_OF_BUSINESS, COMPANY_REGISTRATION_NUMBER, CUSTOMER_TYPE, FAX_NUMBER, ID_EXPIRY_DATE, ID_ISSUE_DATE, ID_ISSUE_PLACE, ID_NUMBER, ID_TYPE, TELEPHONE_NO, ENGLISH_NAME, RACE, NATIONALITY, MALAY_NAME) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
DEBUG - Natively generated identity: 6
DEBUG - Executing identity-insert immediately
DEBUG - insert into CUSTOMER_ADDRESS (COUNTRY, ADDRESS_LINE1, ADDRESS_LINE2, ADDRESS_LINE3, ADDRESS_LINE4, PINCODE, STATE, ADDRESS_TYPE) values (?, ?, ?, ?, ?, ?, ?, ?)
DEBUG - could not execute statement [n/a]
com.microsoft.sqlserver.jdbc.SQLServerException: Cannot insert the value NULL into column 'CUSTOMER_ID', table 'xxxxxxx.xxx.CUSTOMER_ADDRESS'; column does not allow nulls. INSERT fails.

第一种情况失败的原因是什么,以及如何让它以任何方式发挥作用,我们非常感谢任何帮助。

2 个答案:

答案 0 :(得分:5)

我有同样的问题。添加@JoinColumn(nullable = false, ...)修复了它。

答案 1 :(得分:-1)

以下链接可能会为您提供有关oneToMany关系的更多信息。

它表示在父端使用mappedBy并在子级使用JoinColumn。

JPA JoinColumn vs mappedBy