HHH-15797 better error messages

1. include the SQL in some SQLGrammarExceptions where it was missing
2. append the SQL to the error message in JDBCException
3. don't wrap HibernateException in PersistenceException b/c it is one already
This commit is contained in:
Gavin 2022-12-02 21:50:59 +01:00 committed by Gavin King
parent 239dfa30fa
commit cb35e0e734
42 changed files with 243 additions and 131 deletions

View File

@ -64,7 +64,7 @@ public class CheckTest extends BaseEntityManagerFunctionalTestCase {
fail("Should fail because the ISBN is not of the right length!");
}
catch (PersistenceException e) {
assertEquals(ConstraintViolationException.class, e.getCause().getCause().getClass());
assertEquals(ConstraintViolationException.class, e.getCause().getClass());
}
try {
doInJPA(this::entityManagerFactory, entityManager -> {
@ -78,7 +78,7 @@ public class CheckTest extends BaseEntityManagerFunctionalTestCase {
fail("Should fail because the code is 0!");
}
catch (PersistenceException e) {
assertEquals(ConstraintViolationException.class, e.getCause().getCause().getClass());
assertEquals(ConstraintViolationException.class, e.getCause().getClass());
}
}

View File

@ -473,7 +473,7 @@ public class SQLTest extends BaseEntityManagerFunctionalTestCase {
fail("Should throw NonUniqueDiscoveredSqlAliasException!");
}
catch (PersistenceException expected) {
assertEquals(NonUniqueDiscoveredSqlAliasException.class, expected.getCause().getClass());
assertEquals(NonUniqueDiscoveredSqlAliasException.class, expected.getClass());
}
}

View File

@ -17,27 +17,32 @@ import java.sql.SQLException;
*/
public class JDBCException extends HibernateException {
private final SQLException sqlException;
private final String message;
private final String sql;
/**
* Constructs a JDBCException using the given information.
* Constructs a {@code JDBCException} using the given information.
*
* @param message The message explaining the exception condition
* @param cause The underlying cause
*/
public JDBCException(String message, SQLException cause) {
this( message, cause, null );
super( message, cause );
this.message = message;
this.sqlException = cause;
this.sql = null;
}
/**
* Constructs a JDBCException using the given information.
* Constructs a {@code JDBCException} using the given information.
*
* @param message The message explaining the exception condition
* @param cause The underlying cause
* @param sql The sql being executed when the exception occurred
*/
public JDBCException(String message, SQLException cause, String sql) {
super( message, cause );
super( message + " [" + sql + "]", cause );
this.message = message;
this.sqlException = cause;
this.sql = sql;
}
@ -82,4 +87,10 @@ public class JDBCException extends HibernateException {
return sql;
}
/**
* @return The error message without the SQL statement appended
*/
public String getErrorMessage() {
return message;
}
}

View File

@ -47,7 +47,8 @@ public class SqlFunction
final SqlAstNode argument = arguments.get( i );
final int paramIndex = sqlFragment.indexOf( '?', index );
if ( paramIndex == -1 ) {
throw new IllegalArgumentException( "The SQL function passes an argument at index " + i + " but the fragment contains no placeholder for the argument: " + sqlFragment );
throw new IllegalArgumentException( "The SQL function passes an argument at index " + i
+ " but the fragment contains no placeholder for the argument: " + sqlFragment );
}
sqlAppender.append( sqlFragment, index, paramIndex );
argument.accept( walker );

View File

@ -90,7 +90,7 @@ public class PessimisticReadUpdateLockingStrategy implements LockingStrategy {
lockable.getVersionType().nullSafeSet( st, version, offset, session );
}
final int affected = jdbcCoordinator.getResultSetReturn().executeUpdate( st );
final int affected = jdbcCoordinator.getResultSetReturn().executeUpdate( st, sql );
// todo: should this instead check for exactly one row modified?
if ( affected < 0 ) {
final StatisticsImplementor statistics = factory.getStatistics();

View File

@ -89,7 +89,7 @@ public class PessimisticWriteUpdateLockingStrategy implements LockingStrategy {
lockable.getVersionType().nullSafeSet( st, version, offset, session );
}
final int affected = jdbcCoordinator.getResultSetReturn().executeUpdate( st );
final int affected = jdbcCoordinator.getResultSetReturn().executeUpdate( st, sql );
// todo: should this instead check for exactly one row modified?
if ( affected < 0 ) {
final StatisticsImplementor statistics = factory.getStatistics();

View File

@ -96,7 +96,7 @@ public class UpdateLockingStrategy implements LockingStrategy {
lockableVersionType.nullSafeSet( st, version, offset, session );
}
final int affected = jdbcCoordinator.getResultSetReturn().executeUpdate( st );
final int affected = jdbcCoordinator.getResultSetReturn().executeUpdate( st, sql );
if ( affected < 0 ) {
final StatisticsImplementor statistics = factory.getStatistics();
if ( statistics.isStatisticsEnabled() ) {

View File

@ -160,7 +160,7 @@ public class TemporaryTableHelper {
ps.setString( 1, sessionUid );
}
session.getJdbcCoordinator().getResultSetReturn().executeUpdate( ps );
session.getJdbcCoordinator().getResultSetReturn().executeUpdate( ps, sql );
}
catch( Throwable t ) {
log.unableToCleanupTemporaryIdTable(t);

View File

@ -68,6 +68,31 @@ public class ResultSetReturnImpl implements ResultSetReturn {
}
}
@Override
public ResultSet extract(PreparedStatement statement, String sql) {
// IMPL NOTE : SQL logged by caller
long executeStartNanos = 0;
if ( this.sqlStatementLogger.getLogSlowQuery() > 0 ) {
executeStartNanos = System.nanoTime();
}
try {
final ResultSet rs;
try {
jdbcExecuteStatementStart();
rs = statement.executeQuery();
}
finally {
jdbcExecuteStatementEnd();
sqlStatementLogger.logSlowQuery( sql, executeStartNanos );
}
postExtract( rs, statement );
return rs;
}
catch (SQLException e) {
throw sqlExceptionHelper.convert( e, "could not extract ResultSet", sql );
}
}
private void jdbcExecuteStatementEnd() {
jdbcCoordinator.getJdbcSessionOwner().getJdbcSessionContext().getObserver().jdbcExecuteStatementEnd();
}
@ -122,7 +147,7 @@ public class ResultSetReturnImpl implements ResultSetReturn {
return rs;
}
catch (SQLException e) {
throw sqlExceptionHelper.convert( e, "could not extract ResultSet" );
throw sqlExceptionHelper.convert( e, "could not extract ResultSet", sql );
}
}
@ -156,6 +181,36 @@ public class ResultSetReturnImpl implements ResultSetReturn {
}
}
@Override
public ResultSet execute(PreparedStatement statement, String sql) {
// sql logged by StatementPreparerImpl
long executeStartNanos = 0;
if ( this.sqlStatementLogger.getLogSlowQuery() > 0 ) {
executeStartNanos = System.nanoTime();
}
try {
final ResultSet rs;
try {
jdbcExecuteStatementStart();
if ( !statement.execute() ) {
while ( !statement.getMoreResults() && statement.getUpdateCount() != -1 ) {
// do nothing until we hit the resultset
}
}
rs = statement.getResultSet();
}
finally {
jdbcExecuteStatementEnd();
sqlStatementLogger.logSlowQuery( sql, executeStartNanos );
}
postExtract( rs, statement );
return rs;
}
catch (SQLException e) {
throw sqlExceptionHelper.convert( e, "could not execute statement", sql );
}
}
@Override
public ResultSet execute(Statement statement, String sql) {
sqlStatementLogger.logStatement( sql );
@ -176,13 +231,13 @@ public class ResultSetReturnImpl implements ResultSetReturn {
}
finally {
jdbcExecuteStatementEnd();
sqlStatementLogger.logSlowQuery( statement, executeStartNanos );
sqlStatementLogger.logSlowQuery( sql, executeStartNanos );
}
postExtract( rs, statement );
return rs;
}
catch (SQLException e) {
throw sqlExceptionHelper.convert( e, "could not execute statement" );
throw sqlExceptionHelper.convert( e, "could not execute statement", sql );
}
}
@ -207,6 +262,27 @@ public class ResultSetReturnImpl implements ResultSetReturn {
}
}
@Override
public int executeUpdate(PreparedStatement statement, String sql) {
assert statement != null;
long executeStartNanos = 0;
if ( this.sqlStatementLogger.getLogSlowQuery() > 0 ) {
executeStartNanos = System.nanoTime();
}
try {
jdbcExecuteStatementStart();
return statement.executeUpdate();
}
catch (SQLException e) {
throw sqlExceptionHelper.convert( e, "could not execute statement", sql );
}
finally {
jdbcExecuteStatementEnd();
sqlStatementLogger.logSlowQuery( sql, executeStartNanos );
}
}
@Override
public int executeUpdate(Statement statement, String sql) {
sqlStatementLogger.logStatement( sql );
@ -219,11 +295,11 @@ public class ResultSetReturnImpl implements ResultSetReturn {
return statement.executeUpdate( sql );
}
catch (SQLException e) {
throw sqlExceptionHelper.convert( e, "could not execute statement" );
throw sqlExceptionHelper.convert( e, "could not execute statement", sql );
}
finally {
jdbcExecuteStatementEnd();
sqlStatementLogger.logSlowQuery( statement, executeStartNanos );
sqlStatementLogger.logSlowQuery( sql, executeStartNanos );
}
}

View File

@ -95,7 +95,7 @@ public abstract class AbstractMutationExecutor implements MutationExecutor {
try {
final int affectedRowCount = session.getJdbcCoordinator()
.getResultSetReturn()
.executeUpdate( statementDetails.getStatement() );
.executeUpdate( statementDetails.getStatement(), statementDetails.getSqlString() );
if ( affectedRowCount == 0 && tableDetails.isOptional() ) {
// the optional table did not have a row

View File

@ -207,7 +207,7 @@ public class MutationExecutorPostInsert implements MutationExecutor {
try {
final int affectedRowCount = session.getJdbcCoordinator()
.getResultSetReturn()
.executeUpdate( statementDetails.getStatement() );
.executeUpdate( statementDetails.getStatement(), statementDetails.getSqlString() );
ModelMutationHelper.checkResults( resultChecker, statementDetails, affectedRowCount, -1 );
}

View File

@ -12,86 +12,116 @@ import java.sql.ResultSet;
import java.sql.Statement;
/**
* Contract for extracting ResultSets from Statements, executing Statements,
* managing Statement/ResultSet resources, and logging statement calls.
*
* TODO: This could eventually utilize the new Return interface. It would be
* great to have a common API shared.
* Contract for extracting {@link ResultSet}s from {@link Statement}s, executing the statements,
* managing resources, and logging statement calls.
* Generally the methods here for dealing with {@link CallableStatement} are extremely limited
*
* Generally the methods here dealing with CallableStatement are extremely limited, relying on the legacy
*
*
* @author Brett Meyer
* @author Steve Ebersole
*/
//TODO: This could eventually utilize the new Return interface. It would be great to have a common API.
public interface ResultSetReturn {
/**
* Extract the ResultSet from the PreparedStatement.
* Extract the {@link ResultSet} from the {@link PreparedStatement}.
* <p>
* If user passes {@link CallableStatement} reference, this method calls {@link #extract(CallableStatement)}
* internally. Otherwise, generally speaking, {@link PreparedStatement#executeQuery()} is called
* If client passes {@link CallableStatement} reference, this method calls {@link #extract(CallableStatement)}
* internally. Otherwise, {@link PreparedStatement#executeQuery()} is called.
*
* @param statement The PreparedStatement from which to extract the ResultSet
* @param statement The {@link PreparedStatement} from which to extract the {@link ResultSet}
*
* @return The extracted ResultSet
*/
ResultSet extract(PreparedStatement statement);
/**
* Extract the ResultSet from the CallableStatement. Note that this is the limited legacy form which delegates to
* {@link org.hibernate.dialect.Dialect#getResultSet}. Better option is to integrate
* Extract the {@link ResultSet} from the {@link PreparedStatement}.
* <p>
* If client passes {@link CallableStatement} reference, this method calls {@link #extract(CallableStatement)}
* internally. Otherwise, {@link PreparedStatement#executeQuery()} is called.
*
* @param statement The {@link PreparedStatement} from which to extract the {@link ResultSet}
*
* @return The extracted {@link ResultSet}
*/
ResultSet extract(PreparedStatement statement, String sql);
/**
* Extract the {@link ResultSet} from the {@link CallableStatement}. Note that this is the limited legacy
* form which delegates to {@link org.hibernate.dialect.Dialect#getResultSet}. Better option is to integrate
* {@link org.hibernate.procedure.ProcedureCall}-like hooks
*
* @param callableStatement The CallableStatement from which to extract the ResultSet
* @param callableStatement The {@link CallableStatement} from which to extract the {@link ResultSet}
*
* @return The extracted ResultSet
* @return The extracted {@link ResultSet}
*/
ResultSet extract(CallableStatement callableStatement);
/**
* Performs the given SQL statement, expecting a ResultSet in return
* Performs the given SQL statement, expecting a {@link ResultSet} in return
*
* @param statement The JDBC Statement object to use
* @param statement The JDBC {@link Statement} object to use
* @param sql The SQL to execute
*
* @return The resulting ResultSet
* @return The resulting {@link ResultSet}
*/
ResultSet extract(Statement statement, String sql);
/**
* Execute the PreparedStatement return its first ResultSet, if any. If there is no ResultSet, returns {@code null}
* Execute the {@link PreparedStatement} return its first {@link ResultSet}, if any.
* If there is no {@link ResultSet}, returns {@code null}
*
* @param statement The PreparedStatement to execute
* @param statement The {@link PreparedStatement} to execute
*
* @return The extracted ResultSet, or {@code null}
* @return The extracted {@link ResultSet}, or {@code null}
*/
ResultSet execute(PreparedStatement statement);
/**
* Performs the given SQL statement, returning its first ResultSet, if any. If there is no ResultSet,
* returns {@code null}
* Execute the {@link PreparedStatement} return its first {@link ResultSet}, if any.
* If there is no {@link ResultSet}, returns {@code null}
*
* @param statement The JDBC Statement object to use
* @param statement The {@link PreparedStatement} to execute
* @param sql For error reporting
*
* @return The extracted {@link ResultSet}, or {@code null}
*/
ResultSet execute(PreparedStatement statement, String sql);
/**
* Performs the given SQL statement, returning its first {@link ResultSet}, if any.
* If there is no {@link ResultSet}, returns {@code null}
*
* @param statement The JDBC {@link Statement} object to use
* @param sql The SQL to execute
*
* @return The extracted ResultSet, or {@code null}
* @return The extracted {@link ResultSet}, or {@code null}
*/
ResultSet execute(Statement statement, String sql);
/**
* Execute the PreparedStatement, returning its "affected row count".
* Execute the {@link PreparedStatement}, returning its "affected row count".
*
* @param statement The PreparedStatement to execute
* @param statement The {@link PreparedStatement} to execute
*
* @return The {@link PreparedStatement#executeUpdate()} result
*/
int executeUpdate(PreparedStatement statement);
/**
* Execute the {@link PreparedStatement}, returning its "affected row count".
*
* @param statement The {@link PreparedStatement} to execute
* @param sql For error reporting
*
* @return The {@link PreparedStatement#executeUpdate()} result
*/
int executeUpdate(PreparedStatement statement, String sql);
/**
* Execute the given SQL statement returning its "affected row count".
*
* @param statement The JDBC Statement object to use
* @param statement The JDBC {@link Statement} object to use
* @param sql The SQL to execute
*
* @return The {@link PreparedStatement#executeUpdate(String)} result

View File

@ -10,8 +10,8 @@ import java.sql.SQLException;
import org.hibernate.JDBCException;
/**
* Implementation of JDBCException indicating that the SQL sent to the database
* server was invalid (syntax error, invalid object references, etc).
* Specialization of {@link JDBCException} indicating that the SQL sent to the
* database server was invalid (syntax error, invalid object references, etc).
*
* @author Steve Ebersole
*/

View File

@ -108,8 +108,8 @@ public class SourceGeneration implements InMemoryGenerator {
try {
statement = prepareStatement( coordinator, timestampSelectString, callable );
Timestamp ts = callable
? extractCalledResult( statement, coordinator )
: extractResult( statement, coordinator );
? extractCalledResult( statement, coordinator, timestampSelectString )
: extractResult( statement, coordinator, timestampSelectString );
logResult( ts );
return ts;
}
@ -135,16 +135,18 @@ public class SourceGeneration implements InMemoryGenerator {
return coordinator.getStatementPreparer().prepareStatement( timestampSelectString, callable );
}
private static Timestamp extractResult(PreparedStatement statement, JdbcCoordinator coordinator) throws SQLException {
ResultSet resultSet = coordinator.getResultSetReturn().extract( statement );
private static Timestamp extractResult(PreparedStatement statement, JdbcCoordinator coordinator, String sql)
throws SQLException {
ResultSet resultSet = coordinator.getResultSetReturn().extract( statement, sql );
resultSet.next();
return resultSet.getTimestamp( 1 );
}
private static Timestamp extractCalledResult(PreparedStatement statement, JdbcCoordinator coordinator) throws SQLException {
private static Timestamp extractCalledResult(PreparedStatement statement, JdbcCoordinator coordinator, String sql)
throws SQLException {
CallableStatement callable = (CallableStatement) statement;
callable.registerOutParameter( 1, TIMESTAMP );
coordinator.getResultSetReturn().execute( callable );
coordinator.getResultSetReturn().execute( callable, sql );
return callable.getTimestamp( 1 );
}

View File

@ -25,7 +25,6 @@ import org.hibernate.id.factory.spi.StandardGenerator;
import org.hibernate.internal.CoreLogging;
import org.hibernate.internal.CoreMessageLogger;
import org.hibernate.internal.util.StringHelper;
import org.hibernate.mapping.Table;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.type.Type;

View File

@ -72,7 +72,8 @@ public abstract class AbstractSelectingDelegate implements InsertGeneratedIdenti
jdbcServices.getSqlStatementLogger().logStatement( insertStatementDetails.getSqlString() );
jdbcValueBindings.beforeStatement( insertStatementDetails, session );
jdbcCoordinator.getResultSetReturn().executeUpdate( insertStatementDetails.resolveStatement() );
jdbcCoordinator.getResultSetReturn()
.executeUpdate( insertStatementDetails.resolveStatement(), insertStatementDetails.getSqlString() );
// the insert is complete, select the generated id...
@ -115,7 +116,7 @@ public abstract class AbstractSelectingDelegate implements InsertGeneratedIdenti
PreparedStatement insert = statementPreparer.prepareStatement( insertSQL, NO_GENERATED_KEYS );
try {
binder.bindValues( insert );
jdbcCoordinator.getResultSetReturn().executeUpdate( insert );
jdbcCoordinator.getResultSetReturn().executeUpdate( insert, insertSQL );
}
finally {
jdbcCoordinator.getLogicalConnection().getResourceRegistry().release( insert );

View File

@ -99,7 +99,7 @@ public class GetGeneratedKeysDelegate extends AbstractReturningDelegate {
jdbcValueBindings.beforeStatement( insertStatementDetails, session );
try {
jdbcCoordinator.getResultSetReturn().executeUpdate( insertStatement );
jdbcCoordinator.getResultSetReturn().executeUpdate( insertStatement, insertSql );
try {
final ResultSet resultSet = insertStatement.getGeneratedKeys();
@ -147,7 +147,7 @@ public class GetGeneratedKeysDelegate extends AbstractReturningDelegate {
final JdbcCoordinator jdbcCoordinator = session.getJdbcCoordinator();
final JdbcServices jdbcServices = session.getJdbcServices();
jdbcCoordinator.getResultSetReturn().executeUpdate( insertStatement );
jdbcCoordinator.getResultSetReturn().executeUpdate( insertStatement, insertSql );
try {
final ResultSet resultSet = insertStatement.getGeneratedKeys();

View File

@ -66,7 +66,7 @@ public class InsertReturningDelegate extends AbstractReturningDelegate {
final JdbcCoordinator jdbcCoordinator = session.getJdbcCoordinator();
final JdbcServices jdbcServices = session.getJdbcServices();
final ResultSet resultSet = jdbcCoordinator.getResultSetReturn().execute( insertStatement );
final ResultSet resultSet = jdbcCoordinator.getResultSetReturn().execute( insertStatement, insertSql );
try {
return getGeneratedIdentity( persister.getNavigableRole().getFullPath(), resultSet, persister, session );
}

View File

@ -152,9 +152,8 @@ public class ExceptionConverterImpl implements ExceptionConverter {
return new IllegalStateException( exception );
}
else {
final PersistenceException converted = new PersistenceException( exception.getMessage(), exception );
rollbackIfNecessary( converted );
return converted;
rollbackIfNecessary( exception );
return exception;
}
}

View File

@ -177,9 +177,8 @@ public class OptionalTableUpdateOperation implements SelfExecutingUpdateOperatio
bindKeyValues( jdbcValueBindings, deleteStatement, jdbcDelete, session );
session.getJdbcCoordinator()
.getResultSetReturn()
.executeUpdate( deleteStatement );
session.getJdbcCoordinator().getResultSetReturn()
.executeUpdate( deleteStatement, jdbcDelete.getSqlString() );
}
private void bindKeyValues(
@ -346,14 +345,12 @@ public class OptionalTableUpdateOperation implements SelfExecutingUpdateOperatio
try {
final PreparedStatement updateStatement = statementDetails.resolveStatement();
final SqlStatementLogger sqlStatementLogger = session.getJdbcServices().getSqlStatementLogger();
sqlStatementLogger.logStatement( statementDetails.getSqlString() );
session.getJdbcServices().getSqlStatementLogger().logStatement( statementDetails.getSqlString() );
jdbcValueBindings.beforeStatement( statementDetails, session );
final int rowCount = session.getJdbcCoordinator()
.getResultSetReturn()
.executeUpdate( updateStatement );
final int rowCount = session.getJdbcCoordinator().getResultSetReturn()
.executeUpdate( updateStatement, statementDetails.getSqlString() );
if ( rowCount == 0 ) {
return false;
@ -406,9 +403,8 @@ public class OptionalTableUpdateOperation implements SelfExecutingUpdateOperatio
} );
}
session.getJdbcCoordinator()
.getResultSetReturn()
.executeUpdate( insertStatement );
session.getJdbcCoordinator().getResultSetReturn()
.executeUpdate( insertStatement, jdbcInsert.getSqlString() );
}
finally {
session.getJdbcCoordinator().getLogicalConnection().getResourceRegistry().release( insertStatement );

View File

@ -58,7 +58,7 @@ public class EmbeddableIntegratorTest {
assertEquals( new BigDecimal( "100" ), inv.getInvestments().get( 0 ).getAmount().getAmount() );
}
catch (PersistenceException e) {
assertTyping( JDBCException.class, e.getCause() );
assertTyping( JDBCException.class, e );
sess.getTransaction().rollback();
}
finally {

View File

@ -66,10 +66,10 @@ public class ImmutableEntityUpdateQueryHandlingModeExceptionTest extends BaseNon
fail("Should throw PersistenceException");
}
catch (PersistenceException e) {
assertTrue( e.getCause() instanceof HibernateException );
assertTrue( e instanceof HibernateException );
assertEquals(
"The query: [update Country set name = :name] attempts to update an immutable entity: [Country]",
e.getCause().getMessage()
e.getMessage()
);
}

View File

@ -176,7 +176,7 @@ public class JoinTest extends BaseNonConfigCoreFunctionalTestCase {
}
catch (PersistenceException e) {
try {
assertTyping( ConstraintViolationException.class, e.getCause() );
assertTyping( ConstraintViolationException.class, e );
//success
}
finally {

View File

@ -184,7 +184,7 @@ public class OneToManyTest extends BaseNonConfigCoreFunctionalTestCase {
}
catch (PersistenceException ce) {
try {
assertTyping( ConstraintViolationException.class, ce.getCause() );
assertTyping( ConstraintViolationException.class, ce );
//success
}

View File

@ -45,7 +45,7 @@ public class OptionalOneToOneMappedByTest extends BaseCoreFunctionalTestCase {
} );
}
catch (PersistenceException ex) {
assertTyping( IdentifierGenerationException.class, ex.getCause() );
assertTyping( IdentifierGenerationException.class, ex );
// expected
}
}

View File

@ -44,7 +44,7 @@ public class OptionalOneToOnePKJCTest extends BaseCoreFunctionalTestCase {
fail( "should have thrown IdentifierGenerationException.");
}
catch (PersistenceException ex) {
assertTyping(IdentifierGenerationException.class, ex.getCause());
assertTyping(IdentifierGenerationException.class, ex);
// expected
}
finally {
@ -68,7 +68,7 @@ public class OptionalOneToOnePKJCTest extends BaseCoreFunctionalTestCase {
fail( "should have thrown IdentifierGenerationException.");
}
catch (PersistenceException ex) {
assertTyping(IdentifierGenerationException.class, ex.getCause());
assertTyping(IdentifierGenerationException.class, ex);
// expected
}
finally {

View File

@ -84,7 +84,7 @@ public class TablePerClassTest {
fail( "Database Exception not handled" );
}
catch (PersistenceException e) {
assertTyping( JDBCException.class, e.getCause() );
assertTyping( JDBCException.class, e );
//success
}
}

View File

@ -62,7 +62,7 @@ public class UniqueConstraintTest extends BaseCoreFunctionalTestCase {
fail( "Database constraint non-existent" );
}
catch (PersistenceException e) {
assertTyping( JDBCException.class, e.getCause() );
assertTyping( JDBCException.class, e );
//success
}
finally {

View File

@ -54,7 +54,7 @@ public class UniqueConstraintThrowsConstraintViolationExceptionTest extends Base
catch ( PersistenceException e ) {
assertEquals(
ConstraintViolationException.class,
e.getCause().getClass()
e.getClass()
);
}
}

View File

@ -34,8 +34,8 @@ interface ExceptionExpectations {
@Override
public void onConstraintViolationOnPersistAndMergeAndFlush(RuntimeException e) {
assertThat( e, instanceOf( PersistenceException.class ) );
assertThat( e.getCause(), instanceOf( ConstraintViolationException.class ) );
assertThat( e.getCause().getCause(), instanceOf( SQLException.class ) );
assertThat( e, instanceOf( ConstraintViolationException.class ) );
assertThat( e.getCause(), instanceOf( SQLException.class ) );
}
@Override
@ -79,7 +79,7 @@ interface ExceptionExpectations {
@Override
public void onIdentifierGeneratorFailure(RuntimeException e) {
assertThat( e, instanceOf( PersistenceException.class ) );
assertThat( e.getCause(), instanceOf( IdentifierGenerationException.class ) );
assertThat( e, instanceOf( IdentifierGenerationException.class ) );
}
@Override
@ -90,21 +90,21 @@ interface ExceptionExpectations {
@Override
public void onTransactionExceptionOnPersistAndMergeAndFlush(RuntimeException e) {
assertThat( e, instanceOf( PersistenceException.class ) );
assertThat( e.getCause(), instanceOf( TransactionException.class ) );
assertThat( e, instanceOf( TransactionException.class ) );
}
@Override
public void onTransactionExceptionOnCommit(RuntimeException e) {
assertThat( e, instanceOf( RollbackException.class ) );
assertThat( e.getCause(), instanceOf( PersistenceException.class ) );
assertThat( e.getCause().getCause(), instanceOf( TransactionException.class ) );
assertThat( e, instanceOf( PersistenceException.class ) );
assertThat( e.getCause(), instanceOf( TransactionException.class ) );
}
@Override
public void onExecuteUpdateWithConstraintViolation(RuntimeException e) {
assertThat( e, instanceOf( PersistenceException.class ) );
assertThat( e.getCause(), instanceOf( ConstraintViolationException.class ) );
assertThat( e.getCause().getCause(), instanceOf( SQLException.class ) );
assertThat( e, instanceOf( ConstraintViolationException.class ) );
assertThat( e.getCause(), instanceOf( SQLException.class ) );
}
};
}
@ -114,13 +114,13 @@ interface ExceptionExpectations {
@Override
public void onConstraintViolationOnSaveAndSaveOrUpdate(RuntimeException e) {
assertThat( e, instanceOf( ConstraintViolationException.class ) );
assertThat( e.getCause(), instanceOf( SQLException.class ) );
assertThat( e, instanceOf( SQLException.class ) );
}
@Override
public void onConstraintViolationOnPersistAndMergeAndFlush(RuntimeException e) {
assertThat( e, instanceOf( ConstraintViolationException.class ) );
assertThat( e.getCause(), instanceOf( SQLException.class ) );
assertThat( e, instanceOf( SQLException.class ) );
}
@Override
@ -197,8 +197,8 @@ interface ExceptionExpectations {
@Override
public void onConstraintViolationOnPersistAndMergeAndFlush(RuntimeException e) {
assertThat( e, instanceOf( PersistenceException.class ) );
assertThat( e.getCause(), instanceOf( ConstraintViolationException.class ) );
assertThat( e.getCause().getCause(), instanceOf( SQLException.class ) );
assertThat( e, instanceOf( ConstraintViolationException.class ) );
assertThat( e.getCause(), instanceOf( SQLException.class ) );
}
@Override
@ -242,7 +242,7 @@ interface ExceptionExpectations {
@Override
public void onIdentifierGeneratorFailure(RuntimeException e) {
assertThat( e, instanceOf( PersistenceException.class ) );
assertThat( e.getCause(), instanceOf( IdentifierGenerationException.class ) );
assertThat( e, instanceOf( IdentifierGenerationException.class ) );
}
@Override
@ -253,20 +253,20 @@ interface ExceptionExpectations {
@Override
public void onTransactionExceptionOnPersistAndMergeAndFlush(RuntimeException e) {
assertThat( e, instanceOf( PersistenceException.class ) );
assertThat( e.getCause(), instanceOf( TransactionException.class ) );
assertThat( e, instanceOf( TransactionException.class ) );
}
@Override
public void onTransactionExceptionOnCommit(RuntimeException e) {
assertThat( e, instanceOf( PersistenceException.class ) );
assertThat( e.getCause(), instanceOf( TransactionException.class ) );
assertThat( e, instanceOf( TransactionException.class ) );
}
@Override
public void onExecuteUpdateWithConstraintViolation(RuntimeException e) {
assertThat( e, instanceOf( PersistenceException.class ) );
assertThat( e.getCause(), instanceOf( ConstraintViolationException.class ) );
assertThat( e.getCause().getCause(), instanceOf( SQLException.class ) );
assertThat( e, instanceOf( ConstraintViolationException.class ) );
assertThat( e.getCause(), instanceOf( SQLException.class ) );
}
};
}

View File

@ -48,8 +48,8 @@ public class NonActiveTransactionSessionFindJdbcExceptionHandlingTest extends Ba
fail( "A PersistenceException should have been thrown." );
}
catch ( PersistenceException ex ) {
assertTrue( JDBCException.class.isInstance( ex.getCause() ) );
assertTrue( SQLException.class.isInstance( ex.getCause().getCause() ) );
assertTrue( JDBCException.class.isInstance( ex ) );
assertTrue( SQLException.class.isInstance( ex.getCause() ) );
}
finally {
entityManager.close();

View File

@ -165,11 +165,11 @@ public class InterceptorTest extends BaseCoreFunctionalTestCase {
fail( "Transaction should have timed out" );
}
catch (PersistenceException e) {
assertTyping( TransactionException.class, e.getCause() );
assertTyping( TransactionException.class, e );
assertTrue(
"Transaction failed for the wrong reason. Expecting transaction timeout, but found [" +
e.getCause().getMessage() + "]",
e.getCause().getMessage().contains( "transaction timeout expired" )
e.getMessage() + "]",
e.getMessage().contains( "transaction timeout expired" )
);
}
}

View File

@ -20,7 +20,6 @@ import org.hibernate.resource.transaction.spi.TransactionCoordinatorBuilder;
import org.hibernate.testing.TestForIssue;
import org.junit.Test;
import jakarta.persistence.PersistenceException;
import org.mockito.Mockito;
import static org.hibernate.testing.transaction.TransactionUtil.doInJPA;
@ -89,9 +88,8 @@ public class NamedQueryTransactionFailureTest extends BaseEntityManagerFunctiona
entityManager.createNamedQuery( "NamedQuery" );
}
catch (Exception e) {
assertEquals( PersistenceException.class, e.getClass() );
assertEquals( HibernateException.class, e.getCause().getClass() );
assertEquals( MarkedForRollbackException.class, e.getCause().getCause().getClass() );
assertEquals( HibernateException.class, e.getClass() );
assertEquals( MarkedForRollbackException.class, e.getCause().getClass() );
}
});
}

View File

@ -84,7 +84,7 @@ public class CriteriaLiteralsTest extends BaseEntityManagerFunctionalTestCase {
catch ( Exception expected ) {
assertEquals(
SQLGrammarException.class,
expected.getCause().getClass()
expected.getClass()
);
}
}

View File

@ -139,8 +139,7 @@ public class ExceptionTest {
fail();
}
catch ( PersistenceException e ) {
Throwable t = e.getCause();
assertTrue( t instanceof ConstraintViolationException, "Should be a constraint violation" );
assertTrue( e instanceof ConstraintViolationException, "Should be a constraint violation" );
entityManager.getTransaction().rollback();
}
}

View File

@ -300,7 +300,7 @@ public class TransactionJoiningTest {
em.persist( new Book( "The Book of Foo", 1 ) );
}
catch (PersistenceException e) {
caught = e.getCause().getClass().equals( HibernateException.class );
caught = e.getClass().equals( HibernateException.class );
}
assertTrue( caught );

View File

@ -55,7 +55,7 @@ public class ManyToManyAssociationClassGeneratedIdTest extends AbstractManyToMan
catch (Exception e) {
session.getTransaction().rollback();
// expected
assertTyping( ConstraintViolationException.class, e.getCause() );
assertTyping( ConstraintViolationException.class, e );
}
}
);
@ -84,7 +84,7 @@ public class ManyToManyAssociationClassGeneratedIdTest extends AbstractManyToMan
catch (PersistenceException e) {
session.getTransaction().rollback();
// expected
assertTyping( ConstraintViolationException.class, e.getCause() );
assertTyping( ConstraintViolationException.class, e );
}
}
);
@ -113,7 +113,7 @@ public class ManyToManyAssociationClassGeneratedIdTest extends AbstractManyToMan
catch (PersistenceException e) {
session.getTransaction().rollback();
// expected
assertTyping( ConstraintViolationException.class, e.getCause() );
assertTyping( ConstraintViolationException.class, e );
}
}
);

View File

@ -47,7 +47,7 @@ public class OneToOneJoinTableTest {
fail();
}
catch (PersistenceException e) {
assertTyping( ConstraintViolationException.class, e.getCause() );
assertTyping( ConstraintViolationException.class, e );
// expected
}
finally {

View File

@ -137,7 +137,7 @@ public class CreateTest extends AbstractOperationTestCase {
catch (PersistenceException e) {
//verify that an exception is thrown!
assertTyping( ConstraintViolationException.class, e.getCause() );
assertTyping( ConstraintViolationException.class, e );
}
finally {
if(session.getTransaction().isActive()){
@ -160,7 +160,7 @@ public class CreateTest extends AbstractOperationTestCase {
}
catch (PersistenceException e) {
//verify that an exception is thrown!
assertTyping( ConstraintViolationException.class, e.getCause() );
assertTyping( ConstraintViolationException.class, e );
}
finally {
if(session.getTransaction().isActive()){
@ -189,7 +189,7 @@ public class CreateTest extends AbstractOperationTestCase {
}
catch (PersistenceException e) {
//verify that an exception is thrown!
assertTyping( PersistentObjectException.class, e.getCause() );
assertTyping( PersistentObjectException.class, e );
}
}
);
@ -205,7 +205,7 @@ public class CreateTest extends AbstractOperationTestCase {
}
catch (PersistenceException e) {
//verify that an exception is thrown!
assertTyping( PersistentObjectException.class, e.getCause() );
assertTyping( PersistentObjectException.class, e );
}
}
);

View File

@ -99,7 +99,7 @@ public class TenantIdTest implements SessionFactoryProducer {
fail("should have thrown");
}
catch (Throwable e) {
assertTrue( e.getCause() instanceof PropertyValueException );
assertTrue( e instanceof PropertyValueException );
}
}

View File

@ -101,7 +101,7 @@ public class TenantLongIdTest implements SessionFactoryProducer {
fail("should have thrown");
}
catch (Throwable e) {
assertTrue( e.getCause() instanceof PropertyValueException );
assertTrue( e instanceof PropertyValueException );
}
}

View File

@ -103,7 +103,7 @@ public class TenantUuidTest implements SessionFactoryProducer {
fail("should have thrown");
}
catch (Throwable e) {
assertTrue( e.getCause() instanceof PropertyValueException );
assertTrue( e instanceof PropertyValueException );
}
}