IllegalStateException with Hibernate 4 and ManyToOne cascading

后端 未结 9 2152
梦如初夏
梦如初夏 2020-12-01 16:06

I\'ve got those two classes

MyItem Object:

@Entity
public class MyItem implements Serializable {

    @Id
    private Integer id;
    @ManyToOne(casc         


        
9条回答
  •  自闭症患者
    2020-12-01 16:50

    I had the same problem, just solved it. While the above answers may solve the problem I disagree with a few of them, especially altering the implemented equlas() and hashcode() methods. However I feel like my answer reinforces @Tobb and @Supun s' answer(s).

    On my Many side (child side) I had

     @OneToMany(mappedBy = "authorID", cascade =CascadeType.ALL, fetch=FetchType.EAGER)
     private Colllection books;
    

    And on my one side (parent side)

     @ManyToOne(cascade =CascadeType.ALL)
     private AuthorID authorID;
    

    After reading the excellent top answer provided by @Tobb and a little bit of thinking I realized the annotations didn't make sense. The way I understand it (in my case) I was merging() the Author object and merging() the book Object. But because the book collection is a component of the Author object it was trying to save it twice. My solution was to change the cascade types to:

      @OneToMany(mappedBy = "authorID", cascade =CascadeType.PERSIST, fetch=FetchType.EAGER)
      private Collection bookCollection;
    

    and

     @ManyToOne(cascade =CascadeType.MERGE)
     private AuthorID authorID;
    

    To make a long story short, Persist the parent object and merge the child object.

    Hope this helps/makes sense.

提交回复
热议问题