Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPA Unidirectional @OnetoMany fails

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.

like image 935
Somasundaram Sekar Avatar asked Jan 08 '23 20:01

Somasundaram Sekar


1 Answers

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

like image 56
Alex Vayda Avatar answered Jan 14 '23 21:01

Alex Vayda