With hibernate cascading merge from Child to Parent leads to same child row inserted twice and Unique constraint violation

Solution Verified - Updated -

Issue

  • Using following code

    FooEty foo = new FooEty();
    BarEty bar = new BarEty();
    foo.getBars().add(bar);
    bar.setFoo(foo);
    bar.setName("mytest");
    em.merge(bar);
    

leads to bar inserted twice, and unique constraint violation.

Environment

  • Enterprise Application Platform < 5.0
  • Hibernate < 3.3.2
  • Domain Model like

    @Entity
    public class BarEty {
        @Id
        @SequenceGenerator(name = "seq", sequenceName = "Sq_Id_Bar")
        @GeneratedValue(generator = "seq")
        @Column(name = "Id_Bar")
        private Long id;
    
        @Column(nullable = false, unique = true)
        private String name;
    
        @ManyToOne(cascade = { PERSIST,  REFRESH, MERGE })
        @JoinColumn(name = "Id_Foo", nullable = false)
        private FooEty foo;
    ...
    
    @Entity
    public  class FooEty {
        @Id
        @SequenceGenerator(name = "seq",  sequenceName = "Sq_Id_Foo")
        @GeneratedValue(generator = "seq")
        @Column(name = "Id_Foo")
        private Long id;
    
        @OneToMany(cascade = CascadeType.ALL, mappedBy = "foo")
        private  List<BarEty> bars = new ArrayList<BarEty>();
    ...
    

Subscriber exclusive content

A Red Hat subscription provides unlimited access to our knowledgebase, tools, and much more.

Current Customers and Partners

Log in for full access

Log In

New to Red Hat?

Learn more about Red Hat subscriptions

Using a Red Hat product through a public cloud?

How to access this content