Rohan Lopes
Rohan Lopes

Reputation: 165

Spring JPA : OneToMany List update results in duplicate entries

I have below JPA Tables. I have used uni-directional OneToMany relationship.

@Entity
@Table(name = "xxx")
public class Parent {
   @OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL, orphanRemoval = true)
   @JoinColumn(name = "Child_ID")
   private Set<Child1> child;

   //getter setters

}

@Entity
@Table(name = "xxx")
public class Child {
   //other colmns

   //getter setters

}

When I first add entries to above parent Set(say 20) and save(), it saves to database successfully. Then In same set I have added 10 more and called save method. It save 10 new to db. If I again call save it add same 10 more to database again creating duplicate entries.

Parentrepository.save(parentObject);

Upvotes: 0

Views: 4482

Answers (3)

TheSprinter
TheSprinter

Reputation: 1528

As per the code Parent class has one to many mappping with class Child.
Every time you are calling
Parentrepository.save(parentObject);
make sure that you have set the below line properly

parentObject.setChild(SetOfChildObjects);

Also override Equals and hashCode in Child class

if you set that improperly then then the tables in DB will get updated accordingly.

NOTE: for better analysis can you share the actual code?

Upvotes: 1

Rohan Lopes
Rohan Lopes

Reputation: 165

I found the issue. Jpa repository saves the object and returns updated object.

    <S extends T> S save(S var1);

Entity object should be Immutable(Which I thought so). That means it updates values(in this case sequence number) after save operation. But after save operation it has not updated sequence number in same object. When I used returned object it worked. Below is changed code.

    parentObject = Parentrepository.save(parentObject);

Upvotes: 0

Nick
Nick

Reputation: 852

Just generate valid Primary key in the Child entity, i.e

@Id
@Column(name = "child_name")
private String name;

and override @Equals and @HashCode methods:

@Override
public boolean equals(Object o) {
    if (this == o) return true;
    if (!(o instanceof Child )) return false;
    return name != null && name.equals(((Child) o).name);
}
@Override
public int hashCode() {
    return Objects.hashCode(this);
}

Upvotes: 1

Related Questions