a new object was found through a relationship that was not marked cascade PERSIST

怎甘沉沦 提交于 2019-11-28 21:07:19
Mikko Maunu

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:

  1. persist also other instances referenced from Article via em.persist
  2. 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.

just add CascadeType.ALL on your relation

OneToMany(mappedBy = "article", cascade = CascadeType.ALL)  
private List<HeaderField> someOrAllHeaderFields = new ArrayList<>();
kuma

I removed the cascade attribute and it worked for me:

OneToMany(mappedBy = "article")  
private List<HeaderField> someOrAllHeaderFields = new ArrayList<>();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!