Skip to content

HHH-19522 upsert should not fail silently instead of throwing StaleObjectStateException #10289

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Jun 11, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -181,7 +181,7 @@ protected int expectedRowCount() {

/**
* Essentially identical to {@link RowCount} except that the row count
* is obtained via an output parameter of a {@link CallableStatement
* is obtained via an output parameter of a {@linkplain CallableStatement
* stored procedure}.
* <p>
* Statement batching is disabled when {@code OutParameter} is used.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
import org.hibernate.engine.jdbc.mutation.spi.Binding;
import org.hibernate.engine.jdbc.spi.JdbcServices;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.jdbc.Expectation;
import org.hibernate.persister.entity.mutation.EntityMutationTarget;
import org.hibernate.persister.entity.mutation.EntityTableMapping;
import org.hibernate.persister.entity.mutation.UpdateValuesAnalysis;
Expand All @@ -40,6 +41,8 @@ public class DeleteOrUpsertOperation implements SelfExecutingUpdateOperation {

private final OptionalTableUpdate optionalTableUpdate;

private final Expectation expectation = new Expectation.RowCount();

public DeleteOrUpsertOperation(
EntityMutationTarget mutationTarget,
EntityTableMapping tableMapping,
Expand Down Expand Up @@ -123,6 +126,16 @@ private void performDelete(JdbcValueBindings jdbcValueBindings, SharedSessionCon
final int rowCount = session.getJdbcCoordinator().getResultSetReturn()
.executeUpdate( upsertDeleteStatement, statementDetails.getSqlString() );
MODEL_MUTATION_LOGGER.tracef( "`%s` rows upsert-deleted from `%s`", rowCount, tableMapping.getTableName() );
try {
expectation.verifyOutcome( rowCount, upsertDeleteStatement, -1, statementDetails.getSqlString() );
}
catch (SQLException e) {
throw jdbcServices.getSqlExceptionHelper().convert(
e,
"Unable to verify outcome for upsert delete",
statementDetails.getSqlString()
);
}
}
finally {
statementDetails.releaseStatement( session );
Expand Down Expand Up @@ -182,12 +195,23 @@ private void performUpsert(JdbcValueBindings jdbcValueBindings, SharedSessionCon
final var statementDetails = statementGroup.resolvePreparedStatementDetails( tableMapping.getTableName() );
try {
final PreparedStatement updateStatement = statementDetails.resolveStatement();
session.getJdbcServices().getSqlStatementLogger().logStatement( statementDetails.getSqlString() );
final JdbcServices jdbcServices = session.getJdbcServices();
jdbcServices.getSqlStatementLogger().logStatement( statementDetails.getSqlString() );
jdbcValueBindings.beforeStatement( statementDetails );
final int rowCount =
session.getJdbcCoordinator().getResultSetReturn()
.executeUpdate( updateStatement, statementDetails.getSqlString() );
MODEL_MUTATION_LOGGER.tracef( "`%s` rows upserted into `%s`", rowCount, tableMapping.getTableName() );
try {
expectation.verifyOutcome( rowCount, updateStatement, -1, statementDetails.getSqlString() );
}
catch (SQLException e) {
throw jdbcServices.getSqlExceptionHelper().convert(
e,
"Unable to verify outcome for upsert",
statementDetails.getSqlString()
);
}
}
finally {
statementDetails.releaseStatement( session );
Comment on lines 195 to 217
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@sebersole Why does this stuff not go through a MutationCoordinator/MutationExecutor?

I'm not clear on how these differ from MutationOperation.

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,13 +23,12 @@ public MergeOperation(
MutationTarget<?> mutationTarget,
String sql,
List<? extends JdbcParameterBinder> parameterBinders) {
super( tableDetails, mutationTarget, sql, false, Expectation.None.INSTANCE, parameterBinders );
super( tableDetails, mutationTarget, sql, false, new Expectation.RowCount(), parameterBinders );
}

@Override
public MutationType getMutationType() {
return MutationType.UPDATE;
}


}
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
import java.util.Locale;
import java.util.Objects;

import org.hibernate.StaleStateException;
import org.hibernate.engine.jdbc.mutation.JdbcValueBindings;
import org.hibernate.engine.jdbc.mutation.ParameterUsage;
import org.hibernate.engine.jdbc.mutation.internal.JdbcValueDescriptorImpl;
Expand All @@ -23,6 +24,7 @@
import org.hibernate.engine.jdbc.spi.JdbcServices;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.exception.ConstraintViolationException;
import org.hibernate.internal.util.collections.CollectionHelper;
import org.hibernate.jdbc.Expectation;
import org.hibernate.persister.entity.mutation.EntityMutationTarget;
Expand All @@ -48,6 +50,7 @@
import org.hibernate.sql.model.internal.TableUpdateCustomSql;
import org.hibernate.sql.model.internal.TableUpdateStandard;

import static org.hibernate.exception.ConstraintViolationException.ConstraintKind.UNIQUE;
import static org.hibernate.sql.model.ModelMutationLogging.MODEL_MUTATION_LOGGER;

/**
Expand Down Expand Up @@ -149,7 +152,16 @@ public void performMutation(
"Upsert update altered no rows - inserting : %s",
tableMapping.getTableName()
);
performInsert( jdbcValueBindings, session );
try {
performInsert( jdbcValueBindings, session );
}
catch (ConstraintViolationException cve) {
throw cve.getKind() == UNIQUE
// assume it was the primary key constraint which was violated,
// due to a new version of the row existing in the database
? new StaleStateException( mutationTarget.getRolePath(), cve )
: cve;
}
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,13 +23,12 @@ public UpsertOperation(
MutationTarget<?> mutationTarget,
String sql,
List<? extends JdbcParameterBinder> parameterBinders) {
super( tableDetails, mutationTarget, sql, false, Expectation.None.INSTANCE, parameterBinders );
super( tableDetails, mutationTarget, sql, false, new Expectation.RowCount(), parameterBinders );
}

@Override
public MutationType getMutationType() {
return MutationType.UPDATE;
}


}
Original file line number Diff line number Diff line change
Expand Up @@ -7,17 +7,21 @@
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.Version;
import org.hibernate.StaleStateException;
import org.hibernate.testing.orm.junit.DomainModel;
import org.hibernate.testing.orm.junit.SessionFactory;
import org.hibernate.testing.orm.junit.SessionFactoryScope;
import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.fail;

@SessionFactory
@DomainModel(annotatedClasses = UpsertVersionedTest.Record.class)
public class UpsertVersionedTest {

@Test void test(SessionFactoryScope scope) {
scope.getSessionFactory().getSchemaManager().truncate();
scope.inStatelessTransaction(s-> {
s.upsert(new Record(123L,null,"hello earth"));
s.upsert(new Record(456L,2L,"hello mars"));
Expand All @@ -41,6 +45,29 @@ public class UpsertVersionedTest {
assertEquals( "goodbye mars", s.get( Record.class,456L).message );
});
}

@Test void testStaleUpsert(SessionFactoryScope scope) {
scope.getSessionFactory().getSchemaManager().truncate();
scope.inStatelessTransaction( s -> {
s.insert(new Record(789L, 1L, "hello world"));
} );
scope.inStatelessTransaction( s -> {
s.upsert(new Record(789L, 1L, "hello mars"));
} );
try {
scope.inStatelessTransaction( s -> {
s.upsert(new Record( 789L, 1L, "hello venus"));
} );
fail();
}
catch (StaleStateException sse) {
//expected
}
scope.inStatelessTransaction( s-> {
assertEquals( "hello mars", s.get(Record.class,789L).message );
} );
}

@Entity(name = "Record")
static class Record {
@Id Long id;
Expand Down