In trying to get a @OneToMany
relationship between Article
and HeaderField
I probably have the mapping not quite right, resulting in:<
just add CascadeType.ALL on your relation
OneToMany(mappedBy = "article", cascade = CascadeType.ALL)
private List<HeaderField> someOrAllHeaderFields = new ArrayList<>();
What you had likely done is that you created new instance of Article and and some new instance(s) of HeaderField. These instance(s) of HeaderField were then associated with Article.
After that trying to persist Article fails, because as error message says, it refers to new objects and relationship is not marked as PERSIST. Additionally according your logs these instances of HeaderField does not have headerName and headerValue set.
You have two options:
cascade persist operation from Article to HeaderFields with following
OneToMany(mappedBy = "article", cascade = CascadeType.PERSIST)
private List<HeaderField> someOrAllHeaderFields = new ArrayList<>();
Additionally you should not remove no-arg constructor. JPA
implementation always calls this constructor when it creates instance.
But you can make no-arg constructor protected. In JPA 2.0 specification this is told wit following words:
The entity class must have a no-arg constructor. The entity class may have other constructors as well. The no-arg constructor must be public or protected.
I removed the cascade attribute and it worked for me:
OneToMany(mappedBy = "article")
private List<HeaderField> someOrAllHeaderFields = new ArrayList<>();
JPA by default provide no cascade feature. So in my case cascade annotation was missing, so I defined it with the @ManyToOne
annotation. Please defined cascade type along with @ManyToOne
Ex:
@ManyToOne(cascade = CascadeType.PERSIST)
private Article article = new Article();