IllegalStateException with Hibernate 4 and ManyToOne cascading

后端 未结 9 1991
梦如初夏
梦如初夏 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:41

    According to logic in EventCache all entities in object graph should be unique. So the best solution(or is it work around?) is to remove cascade in MyItem to Component. And merge Component separately if it's really needed - I would bet that in 95% of cases Component shouldn't been merged according to business logic.

    From other hand - I really interested to know the real thoughts behind that restriction.

    0 讨论(0)
  • 2020-12-01 16:42

    Try adding the @GeneratedValue annotation under @Id in the Component class. otherwise two different instances might get the same id, and collide.

    It seams that you are giving them the same ID.

        Component c1 = new Component();
        c1.setName("comp");
        Component c2 = new Component();
        c2.setName("comp");
    

    That just might solve you'r problem.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题