JPA Unidirectional @OnetoMany fails

六月ゝ 毕业季﹏ 提交于 2020-07-18 21:10:23

问题


I have couple of failure cases for Unidirectional JPA2 @OnetoMany relationship below is the code snippet

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

....
}

In this case it fails to create Entity manager factory during server startup with the following error

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]

The server startup is all good when I remove the referencedColumnName attribute from the @JoinColumn annotation

But when I try to persist the entity it fails below are the Hibernate generated traces for the failure(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.

What is the reason for failure in the first case, and how to get it to work either way, any help is much appreciated.


回答1:


I had the same issue. Adding @JoinColumn(nullable = false, ...) fixed it.




回答2:


Probably the links below could give you more information on oneToMany relationship.

It indicates to use mappedBy at parent side and use JoinColumn at childs.

JPA JoinColumn vs mappedBy



来源:https://stackoverflow.com/questions/31811989/jpa-unidirectional-onetomany-fails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!