What does "Batch update returned unexpected row count from update [0]; actual row count: 2; expected: 1" mean

4.2k views Asked by At

I would like to save two entities with the following relationship:

@Entity
public class Synonyme {
    @OneToMany(fetch=FetchType.LAZY, cascade=CascadeType.ALL, orphanRemoval = true)
    @JoinColumn(name="ID", nullable = false)
    private List<Term> terms = new ArrayList<>();
}

@Entity
public class Term {
   private String word;
   public static createTerm(String word, Synonyme newSyn, Long someothercriteria) {
    Term term = new Term();
    ...
    newSyn.addTerm(term);
   }
}

And I want to save them like this:

Synonyme newSyn= Synonyme.createSynonyme ();

entityManager.persist(newSyn);

for(String word : words) {
    Term term = Term.createTerm(word, newSyn, 0L );
}

 entityManager.flush();

These codes work fine in Junit-Test (The Junit-Test uses an in-memory database of spring) but if I use them in the real database I got the following exception:

Caused by: javax.persistence.PersistenceException: org.hibernate.jdbc.BatchedTooManyRowsAffectedException: Batch update returned unexpected row count from update [0]; actual row count: 2; expected: 1

I don't understand this exception. What does it mean and what I could do?

2

There are 2 answers

4
Predrag Maric On BEST ANSWER

(too long for comment, so adding an answer)

You should update the question with the code of Synonyme.createSynonyme() and Term.createTerm().

Your @OneToMany mapping is strange, that could be the cause of the problem (check out the documentation for collection mappings). In this @OneToMany the target table (Term) contains foreign key to source table (Synonyme). That said, ID is probably not the column you want, but something like SYNONYME_ID. You can also post your table structure so anyone interested can have the full picture. Once the mapping looks OK, it will be easier to look for the solution to the problem, if it doesn't get resolved when mappings are fixed.

0
Marco Mascellani On

That usually means you defined a primary key in hibernate but not on the actual DBMS.

And now there are 2 rows with the same primary key ("actual row count 2, expected 1") so hibernate cannot even perform a simple non-update query (!).

To fix, delete in DBMS the duplicated row or change hibernate key definition on that table.