From 99868fb5f9aee7f09c25b68ddd9005e5aaa1f68b Mon Sep 17 00:00:00 2001 From: Gail Badner Date: Tue, 19 Nov 2019 11:49:59 -0800 Subject: [PATCH] HHH-13355 : StaleStateException for updates to optional secondary table using saveOrUpdate --- .../persister/entity/AbstractEntityPersister.java | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/hibernate-core/src/main/java/org/hibernate/persister/entity/AbstractEntityPersister.java b/hibernate-core/src/main/java/org/hibernate/persister/entity/AbstractEntityPersister.java index d60aada559..66a0f7298e 100644 --- a/hibernate-core/src/main/java/org/hibernate/persister/entity/AbstractEntityPersister.java +++ b/hibernate-core/src/main/java/org/hibernate/persister/entity/AbstractEntityPersister.java @@ -3321,7 +3321,18 @@ protected boolean update( final Expectation expectation = Expectations.appropriateExpectation( updateResultCheckStyles[j] ); final int jdbcBatchSizeToUse = session.getConfiguredJdbcBatchSize(); - final boolean useBatch = expectation.canBeBatched() && isBatchable() && jdbcBatchSizeToUse > 1; + // IMPLEMENTATION NOTE: If Session#saveOrUpdate or #update is used to update an entity, then + // Hibernate does not have a database snapshot of the existing entity. + // As a result, oldFields will be null. + // Don't use a batch if oldFields == null and the jth table is optional (isNullableTable( j ), + // because there is no way to know that there is actually a row to update. If the update + // was batched in this case, the batch update would fail and there is no way to fallback to + // an insert. + final boolean useBatch = + expectation.canBeBatched() && + isBatchable() && + jdbcBatchSizeToUse > 1 && + ( oldFields != null || !isNullableTable( j ) ); if ( useBatch && updateBatchKey == null ) { updateBatchKey = new BasicBatchKey( getEntityName() + "#UPDATE",