I am trying to create a @OneToMany relationship in JPA using the following table structure.
+----------------+
| CATALOG |
+----------------+
| catalogId : PK |
| name |
+----------------+
|
+----------------+
| PRODUCT |
+----------------+
| productId : PK |
| name |
| catalogId : FK |
+----------------+
I have defined the classes as
@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;
}
However, when I try to persist the catalog object, EclipseLink does not put in the catalogId value as expected and I get a SQL constraint violation that there is a null.
Also, I don't need nor want a @ManyToOne on the Product end.
The persistence code:
final Catalog catalog = new Catalog();
catalog.name = text;
final Product p = new Product();
p.name = text;
catalog.products.add(p);
em.persist(catalog);
The stack trace:
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)