【发布时间】:2015-08-04 14:26:31
【问题描述】:
我有几个单向 JPA2 @OnetoMany 关系的失败案例 下面是代码sn-p
@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]
当我从@JoinColumn 注释中删除referencedColumnName 属性时,服务器启动一切正常
但是当我尝试持久化实体时,它在下面失败是 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.
第一种情况下失败的原因是什么,以及如何让它以任何一种方式工作,非常感谢任何帮助。
【问题讨论】:
-
你能确认你的注释@JoinColumn 带有“name”和“referencedColumnName”吗?示例:name:如果连接是针对使用外键映射策略的单向 OneToMany 映射,则外键在目标实体的表中。 referencedColumnName:与单向 OneToMany 外键映射一起使用时,引用的列位于源实体的表中。
-
如果你真的想要一个单向
OneToMany映射,你应该检查One-To-Many Relationship with Join Table。 -
@Mário Kapusta:外键在目标实体中,而我将 Joincolumn 放在源实体中。由于我只想从客户实体中检索地址,而不是作为独立数据,在这种情况下,它可能没有任何数据价值。因此,根据您的评论 JoinColumn(name="CUSTOMER_ID", referencedColumnName="CUSTOMER_ID") private List customerAddresses;在这种情况下应该会导致错误?
-
你好(对不起,我来晚了)...答案:是的...你应该有“referencedColumnName” - 源实体的列,,,,,“名称” - 目标实体中的 fk .在您的情况下,似乎存在错误。
标签: hibernate jpa-2.0 one-to-many