TheQuestionIs
TheQuestionIs

Reputation: 47

Repository.saveAll throws InvalidDataAccessApiUsageException

I query a Bugzilla REST API with Spring, which returns a JSON object with the following structure: https://bugzilla.mozilla.org/rest/bug/35

I have the following JPA class (excerpt):

@Entity
@Table
public class bug {
....
@ManyToOne (fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@JoinColumn (name = "assigned_to_user_id")
@SerializedName ("assigned_to_detail")
protected BugUser assignedTo;

@ManyToMany (cascade = CascadeType.ALL)
@JoinColumn (/ * ... shortened ... * /)
@SerializedName ("c_detail")
protected List <BugUser> cc;
...
}

The web service call takes place with the help of the Spring remainder template. Then the object is mapped from the rest template into my JPA class. However, when the data set is persisted by the Spring repository, I get the following exception:

Caused by: org.springframework.dao.InvalidDataAccessApiUsageException: Multiple representations of the same entity [BugUser # 2] are being merged. Detached: [BugUser @ 21]; Detached: [BugUser @ 12];

As soon as I only comment one member variable of type BugUser in the Bug class, everything works.

How can I work around this problem?

Upvotes: 0

Views: 243

Answers (1)

Christian Beikov
Christian Beikov

Reputation: 16400

You will have to make sure there is only one object with the same primary key. You can go through the list before merging and do something like the following:

Bug b = ...
BugUser assignee = b.assignedTo;
ListIterator<BugUser> iter = b.cc.listIterator();
while (iter.hasNext()) {
    if (assignee.id.equals(iter.next().id) {
        iter.set(assignee);
    }
}

This way you ensure that the objects in the list of the same primary key are the same as the assignee. That is exactly why Hibernate complains.

Upvotes: 1

Related Questions