[JIRA] (HHH-16394) Statement Batch + Version + Dirty Collection leads to OptimisticLockException: Batch update returned unexpected row count from update
by Jones (JIRA)
Jones ( https://hibernate.atlassian.net/secure/ViewProfile.jspa?accountId=557058%... ) *created* an issue
Hibernate ORM ( https://hibernate.atlassian.net/browse/HHH?atlOrigin=eyJpIjoiYjc3ZDI5N2Qx... ) / Bug ( https://hibernate.atlassian.net/browse/HHH-16394?atlOrigin=eyJpIjoiYjc3ZD... ) HHH-16394 ( https://hibernate.atlassian.net/browse/HHH-16394?atlOrigin=eyJpIjoiYjc3ZD... ) Statement Batch + Version + Dirty Collection leads to OptimisticLockException: Batch update returned unexpected row count from update ( https://hibernate.atlassian.net/browse/HHH-16394?atlOrigin=eyJpIjoiYjc3ZD... )
Issue Type: Bug Affects Versions: 6.2.0.CR4 Assignee: Unassigned Created: 29/Mar/2023 02:56 AM Priority: Critical Reporter: Jones ( https://hibernate.atlassian.net/secure/ViewProfile.jspa?accountId=557058%... )
Given
* statement batch is enabled
* A versioned entity
* One managed instance of the versioned entity has dirty attributes
* Another managed instance of the versioned entity has a dirty collection
When
* flushing
Then
* OptimisticLockException: Batch update returned unexpected row count from update
@Entity
@Table(name = "ENTITY_A" )
public class EntityA {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "ID" )
Integer id;
@Version
@Column(name = "VERSION" )
long version;
@Column(name = "PROPERTY_A" )
int propertyA;
@ManyToMany
@JoinTable(name = "ENTITY_A_TO_ENTITY_A" , //
inverseJoinColumns = @JoinColumn(name = "SIDE_B" ), //
joinColumns = @JoinColumn(name = "SIDE_A" ))
final List<EntityA> owners = new ArrayList<>();
@Override
protected void configure(Configuration configuration) {
super.configure(configuration);
configuration.setProperty(AvailableSettings.SHOW_SQL, Boolean.TRUE.toString());
configuration.setProperty(AvailableSettings.FORMAT_SQL, Boolean.TRUE.toString());
configuration.setProperty(AvailableSettings.STATEMENT_BATCH_SIZE, "2" );
}
// Add your tests, using standard JUnit.
@Test
public void hhhXXXTest() throws Exception {
// BaseCoreFunctionalTestCase automatically creates the SessionFactory and
// provides the Session.
try (Session s = openSession()) {
Transaction tx = s.beginTransaction();
EntityA ownerA1 = new EntityA();
EntityA entityA1 = new EntityA();
EntityA ownerA2 = new EntityA();
EntityA entityA2 = new EntityA();
s.persist(ownerA1);
s.persist(ownerA2);
s.persist(entityA1);
s.persist(entityA2);
s.flush();
entityA1.propertyA = 1;
entityA2.owners.add(ownerA2);
tx.commit();
}
}
jakarta.persistence.OptimisticLockException: Batch update returned unexpected row count from update [1]; actual row count: 0; expected: 1; statement executed: update ENTITY_A set PROPERTY_A=?,VERSION=? where ID=? and VERSION=?
at org.hibernate.internal.ExceptionConverterImpl.wrapStaleStateException(ExceptionConverterImpl.java:216)
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:93)
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:162)
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:168)
at org.hibernate.internal.SessionImpl.doFlush(SessionImpl.java:1416)
at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:485)
at org.hibernate.internal.SessionImpl.flushBeforeTransactionCompletion(SessionImpl.java:2296)
at org.hibernate.internal.SessionImpl.beforeTransactionCompletion(SessionImpl.java:1961)
at org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl.beforeTransactionCompletion(JdbcCoordinatorImpl.java:426)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.beforeCompletionCallback(JdbcResourceLocalTransactionCoordinatorImpl.java:169)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.commit(JdbcResourceLocalTransactionCoordinatorImpl.java:267)
at org.hibernate.engine.transaction.internal.TransactionImpl.commit(TransactionImpl.java:101)
at org.hibernate.bugs.ORMUnitTestCase.hhhXXXXTest(ORMUnitTestCase.java:75)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:568)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:59)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:56)
at org.hibernate.testing.junit4.ExtendedFrameworkMethod.invokeExplosively(ExtendedFrameworkMethod.java:45)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
at org.junit.internal.runners.statements.FailOnTimeout$CallableStatement.call(FailOnTimeout.java:299)
at org.junit.internal.runners.statements.FailOnTimeout$CallableStatement.call(FailOnTimeout.java:293)
at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
at java.base/java.lang.Thread.run(Thread.java:833)
Caused by: org.hibernate.StaleStateException: Batch update returned unexpected row count from update [1]; actual row count: 0; expected: 1; statement executed: update ENTITY_A set PROPERTY_A=?,VERSION=? where ID=? and VERSION=?
at org.hibernate.jdbc.Expectations$BasicExpectation.checkBatched(Expectations.java:67)
at org.hibernate.jdbc.Expectations$BasicExpectation.verifyOutcome(Expectations.java:54)
at org.hibernate.engine.jdbc.batch.internal.BatchImpl.checkRowCounts(BatchImpl.java:320)
at org.hibernate.engine.jdbc.batch.internal.BatchImpl.lambda$performExecution$2(BatchImpl.java:283)
at org.hibernate.engine.jdbc.mutation.internal.PreparedStatementGroupSingleTable.forEachStatement(PreparedStatementGroupSingleTable.java:59)
at org.hibernate.engine.jdbc.batch.internal.BatchImpl.performExecution(BatchImpl.java:265)
at org.hibernate.engine.jdbc.batch.internal.BatchImpl.addToBatch(BatchImpl.java:155)
at org.hibernate.engine.jdbc.mutation.internal.MutationExecutorSingleBatched.performBatchedOperations(MutationExecutorSingleBatched.java:60)
at org.hibernate.engine.jdbc.mutation.internal.AbstractMutationExecutor.execute(AbstractMutationExecutor.java:45)
at org.hibernate.persister.entity.mutation.UpdateCoordinatorStandard.doVersionUpdate(UpdateCoordinatorStandard.java:485)
at org.hibernate.persister.entity.mutation.UpdateCoordinatorStandard.handlePotentialImplicitForcedVersionIncrement(UpdateCoordinatorStandard.java:407)
at org.hibernate.persister.entity.mutation.UpdateCoordinatorStandard.coordinateUpdate(UpdateCoordinatorStandard.java:146)
at org.hibernate.persister.entity.AbstractEntityPersister.update(AbstractEntityPersister.java:2739)
at org.hibernate.action.internal.EntityUpdateAction.execute(EntityUpdateAction.java:166)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:616)
at org.hibernate.engine.spi.ActionQueue.lambda$executeActions$1(ActionQueue.java:487)
at java.base/java.util.LinkedHashMap.forEach(LinkedHashMap.java:721)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:484)
at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:358)
at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:39)
at org.hibernate.event.service.internal.EventListenerGroupImpl.fireEventOnEachListener(EventListenerGroupImpl.java:127)
at org.hibernate.internal.SessionImpl.doFlush(SessionImpl.java:1412)
... 23 more
the test scenario to be attached
( https://hibernate.atlassian.net/browse/HHH-16394#add-comment?atlOrigin=ey... ) Add Comment ( https://hibernate.atlassian.net/browse/HHH-16394#add-comment?atlOrigin=ey... )
Get Jira notifications on your phone! Download the Jira Cloud app for Android ( https://play.google.com/store/apps/details?id=com.atlassian.android.jira.... ) or iOS ( https://itunes.apple.com/app/apple-store/id1006972087?pt=696495&ct=EmailN... ) This message was sent by Atlassian Jira (v1001.0.0-SNAPSHOT#100219- sha1:6a6077b )
1 year, 9 months
[JIRA] (HHH-16392) @Where(clause = "deleted = false" ) generate bad query with entity name instead of alias
by srodrigues (JIRA)
srodrigues ( https://hibernate.atlassian.net/secure/ViewProfile.jspa?accountId=5e1d924... ) *created* an issue
Hibernate ORM ( https://hibernate.atlassian.net/browse/HHH?atlOrigin=eyJpIjoiZDBkZjQ2NGQ1... ) / Bug ( https://hibernate.atlassian.net/browse/HHH-16392?atlOrigin=eyJpIjoiZDBkZj... ) HHH-16392 ( https://hibernate.atlassian.net/browse/HHH-16392?atlOrigin=eyJpIjoiZDBkZj... ) @Where(clause = "deleted = false" ) generate bad query with entity name instead of alias ( https://hibernate.atlassian.net/browse/HHH-16392?atlOrigin=eyJpIjoiZDBkZj... )
Issue Type: Bug Affects Versions: 6.1.7 Assignee: Unassigned Components: hibernate-core Created: 29/Mar/2023 00:10 AM Environment: Spring Boot 3.0.2 Spring Cloud 2022.0.1 and spring-boot-starter-data-jpa hibernate-core 6.1.7 Priority: Major Reporter: srodrigues ( https://hibernate.atlassian.net/secure/ViewProfile.jspa?accountId=5e1d924... )
Hi i wrote a user role entities with @ManyToMany with soft delete like this:
@Entity
@Audited(targetAuditMode = NOT_AUDITED)
@Table(name = "users")
@Where(clause = "deleted = false")
@SQLDelete(sql = "UPDATE users SET deleted = true WHERE id = ? and version = ?")
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Builder
@ToString
public class UserEntity extends BaseEntity
{ @Column(length = 100) @NotNull @NotEmpty private String firstName; @Column(length = 100) @NotNull @NotEmpty private String lastName; @Column(length = 100,unique=true) @NotNull @NotEmpty private String email; @Column(length = 100) @NotNull @NotEmpty private String password; @Builder.Default private boolean enabled = false; @Builder.Default private boolean changePassword = true; private boolean tokenExpired; @ManyToMany(fetch = FetchType.EAGER) @JoinTable( name = "users_roles", joinColumns = @JoinColumn( name = "user_id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn( name = "role_id", referencedColumnName = "id")) private Collection<RoleEntity> roles; }
@Entity
@Table(name = "role")
@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
@ToString
public class RoleEntity extends BaseEntity
{ @NotNull @NotEmpty @Column(length=25,unique=true) private String name; @ManyToMany(mappedBy = "roles") private Collection<UserEntity> users; }
All works until i try to hard delete a user (i want to keep soft delete for some times 5years and hard delete for RGPD purpose).
@Transactional
@Modifying
@Query("delete from UserEntity where id =?1")
void deleteRgpd(Long id);
Hibernate try to generate a query to delete user_roles in cascade and the query is:
delete from users_roles where users_roles.user_id in(select u1_0.id from users u1_0 where u1_0.id=? and ( *users*.deleted = false))
JPA put "users.deleted" instead of "u1_0.deleted"
I also try with query:
EntityManager em = entityManagerFactory.createEntityManager();
em.getTransaction().begin();
em.flush();
em.clear();
Query deleteUser = em.createQuery("DELETE FROM UserEntity WHERE id = :id");
deleteUser.setParameter("id", user.getId());
deleteUser.executeUpdate();
em.getTransaction().commit();
em.close();
Same issue
For information the select for user with roles:
select r1_0.user_id,r1_1.id,r1_1.created_by,r1_1.created_date,r1_1.deleted,r1_1.last_modified_by,r1_1.last_modified_date,r1_1.name,r1_1.version from users_roles r1_0 join role r1_1 on r1_1.id=r1_0.role_id where r1_0.user_id=? and ( r1_1.deleted= false)
is ok
( https://hibernate.atlassian.net/browse/HHH-16392#add-comment?atlOrigin=ey... ) Add Comment ( https://hibernate.atlassian.net/browse/HHH-16392#add-comment?atlOrigin=ey... )
Get Jira notifications on your phone! Download the Jira Cloud app for Android ( https://play.google.com/store/apps/details?id=com.atlassian.android.jira.... ) or iOS ( https://itunes.apple.com/app/apple-store/id1006972087?pt=696495&ct=EmailN... ) This message was sent by Atlassian Jira (v1001.0.0-SNAPSHOT#100219- sha1:6a6077b )
1 year, 9 months