Amjith
Amjith

Reputation: 17

Error: Delete then insert using JPA in single transaction

Using JPA and mysql,I want to write program for delete and insert into a table in single transaction using @Transaction annotation

My code is like this

 //Delete 
entityManager.createNamedQuery( "DELETE_QUERY" ).setParameter( "userId", userId ).executeUpdate();

entityManager.flush();


//Insert

User user = new User();
user.setUserId(122);
user.setPassword("test");

entityManager.merge( user );
entityManager.flush();

Delete query is displayed. Then the update query is running here...Then it throw the below mentioned error

..............

javax.persistence.OptimisticLockException: org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1

...............

Caused by: org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1 ............... ............... org.springframework.transaction.TransactionSystemException: Could not commit JPA transaction; nested exception is javax.persistence.RollbackException: Transaction marked as rollbackOnly

Upvotes: 0

Views: 1958

Answers (1)

JB Nizet
JB Nizet

Reputation: 691825

You have a field annotated with @Version in your User entity, which is precisely used for optimistic locking, making sure that when you update a user, you're passing the same version in the user object as the one stored in the database.

But you're not, because you're creating a user that already exists in database from scratch, with its version field having its default value. So you get this exception.

Upvotes: 1

Related Questions