我正在尝试使用下表结构在 JPA 中创建 @OneToMany 关系。
+----------------+
| CATALOG |
+----------------+
| catalogId : PK |
| name |
+----------------+
|
+----------------+
| PRODUCT |
+----------------+
| productId : PK |
| name |
| catalogId : FK |
+----------------+
我已将类定义为
@Entity
public class Catalog {
@Id
@GeneratedValue
long catalogId;
@OneToMany(cascade = CascadeType.ALL,
orphanRemoval = true, fetch = FetchType.LAZY)
@JoinColumn(name = "catalogId",
nullable = false, insertable = true, updatable = true)
Set<Product> products = new HashSet<>();
String name;
}
@Entity
public class Product {
@Id
@GeneratedValue
long productId;
String name;
}
但是,当我尝试持久化目录对象时,EclipseLink 没有按预期输入 catalogId 值,并且我得到一个 SQL 约束冲突,即存在空值。
另外,我不需要也不需要产品端的@ManyToOne。
持久化代码:
final Catalog catalog = new Catalog();
catalog.name = text;
final Product p = new Product();
p.name = text;
catalog.products.add(p);
em.persist(catalog);
堆栈跟踪:
javax.persistence.PersistenceException: org.hibernate.exception.ConstraintViolationException: Column 'CATALOGID' cannot accept a NULL value.
at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1367)
at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1295)
at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1301)
at org.hibernate.ejb.AbstractEntityManagerImpl.persist(AbstractEntityManagerImpl.java:866)
at net.trajano.maven_jee6.ws_mdb_ejb_web.TextMessages.putText(TextMessages.java:61)