Make use of connection pooling in most tests

This commit is contained in:
Christian Beikov 2023-08-21 12:42:00 +02:00
parent f43eb74e8d
commit 82e66d0037
351 changed files with 2076 additions and 1555 deletions

View File

@ -20,7 +20,7 @@ elif [ "$RDBMS" == "edb" ] || [ "$RDBMS" == "edb_10" ]; then
goal="-Pdb=edb_ci -DdbHost=localhost:5444"
elif [ "$RDBMS" == "oracle" ]; then
# I have no idea why, but these tests don't seem to work on CI...
goal="-Pdb=oracle_ci -PexcludeTests=**.LockTest.testQueryTimeout*"
goal="-Pdb=oracle_ci"
elif [ "$RDBMS" == "oracle_11_2" ]; then
# I have no idea why, but these tests don't seem to work on CI...
goal="-Pdb=oracle_legacy_ci -PexcludeTests=**.LockTest.testQueryTimeout*"

View File

@ -494,18 +494,23 @@ oracle_setup() {
sleep 5;
# On WSL, health-checks intervals don't work for Podman, so run them manually
if command -v podman > /dev/null; then
$CONTAINER_CLI healthcheck run oracle > /dev/null
$PRIVILEGED_CLI $CONTAINER_CLI healthcheck run oracle > /dev/null
fi
HEALTHSTATUS="`$CONTAINER_CLI inspect -f $HEALTCHECK_PATH oracle`"
HEALTHSTATUS="`$PRIVILEGED_CLI $CONTAINER_CLI inspect -f $HEALTCHECK_PATH oracle`"
HEALTHSTATUS=${HEALTHSTATUS##+( )} #Remove longest matching series of spaces from the front
HEALTHSTATUS=${HEALTHSTATUS%%+( )} #Remove longest matching series of spaces from the back
done
sleep 2;
echo "Oracle successfully started"
# We increase file sizes to avoid online resizes as that requires lots of CPU which is restricted in XE
$CONTAINER_CLI exec oracle bash -c "source /home/oracle/.bashrc; bash -c \"
$PRIVILEGED_CLI $CONTAINER_CLI exec oracle bash -c "source /home/oracle/.bashrc; bash -c \"
cat <<EOF | \$ORACLE_HOME/bin/sqlplus / as sysdba
set timing on
-- Remove DISABLE_OOB parameter from Listener configuration and restart it
!echo Enabling OOB for Listener...
!echo NAMES.DIRECTORY_PATH=\(EZCONNECT,TNSNAMES\) > /opt/oracle/oradata/dbconfig/XE/sqlnet.ora
!lsnrctl reload
-- Increasing redo logs
alter database add logfile group 4 '\$ORACLE_BASE/oradata/XE/redo04.log' size 500M reuse;
alter database add logfile group 5 '\$ORACLE_BASE/oradata/XE/redo05.log' size 500M reuse;
@ -569,14 +574,14 @@ oracle_setup_old() {
sleep 5;
# On WSL, health-checks intervals don't work for Podman, so run them manually
if command -v podman > /dev/null; then
$CONTAINER_CLI healthcheck run oracle > /dev/null
$PRIVILEGED_CLI $CONTAINER_CLI healthcheck run oracle > /dev/null
fi
HEALTHSTATUS="`$CONTAINER_CLI inspect -f $HEALTCHECK_PATH oracle`"
HEALTHSTATUS="`$PRIVILEGED_CLI $CONTAINER_CLI inspect -f $HEALTCHECK_PATH oracle`"
HEALTHSTATUS=${HEALTHSTATUS##+( )} #Remove longest matching series of spaces from the front
HEALTHSTATUS=${HEALTHSTATUS%%+( )} #Remove longest matching series of spaces from the back
done
# We increase file sizes to avoid online resizes as that requires lots of CPU which is restricted in XE
$CONTAINER_CLI exec oracle bash -c "source /home/oracle/.bashrc; bash -c \"
$PRIVILEGED_CLI $CONTAINER_CLI exec oracle bash -c "source /home/oracle/.bashrc; bash -c \"
cat <<EOF | \$ORACLE_HOME/bin/sqlplus / as sysdba
alter database tempfile '\$ORACLE_BASE/oradata/XE/temp.dbf' resize 400M;
alter database datafile '\$ORACLE_BASE/oradata/XE/system.dbf' resize 1000M;
@ -626,15 +631,30 @@ EOF\""
echo "Oracle successfully started"
}
disable_userland_proxy() {
if [[ "$HEALTCHECK_PATH" == "{{.State.Health.Status}}" ]]; then
if [[ ! -f /etc/docker/daemon.json ]]; then
sudo service docker stop
echo '{"userland-proxy": false}' > /etc/docker/daemon.json
sudo service docker start
elif ! grep -q userland-proxy /etc/docker/daemon.json; then
docker_daemon_json=$(</etc/docker/daemon.json)
sudo service docker stop
echo "${docker_daemon_json/\}/,}\"userland-proxy\": false}" > /etc/docker/daemon.json
sudo service docker start
fi
fi
}
oracle() {
oracle_21
}
oracle_11() {
$CONTAINER_CLI rm -f oracle || true
$PRIVILEGED_CLI $CONTAINER_CLI rm -f oracle || true
# We need to use the defaults
# SYSTEM/Oracle18
$CONTAINER_CLI run --name oracle -d -p 1521:1521 -e ORACLE_PASSWORD=Oracle18 \
$PRIVILEGED_CLI $CONTAINER_CLI run --name oracle -d -p 1521:1521 -e ORACLE_PASSWORD=Oracle18 \
--health-cmd healthcheck.sh \
--health-interval 5s \
--health-timeout 5s \
@ -643,24 +663,13 @@ oracle_11() {
oracle_setup_old
}
oracle_18() {
$CONTAINER_CLI rm -f oracle || true
# We need to use the defaults
# SYSTEM/Oracle18
$CONTAINER_CLI run --name oracle -d -p 1521:1521 -e ORACLE_PASSWORD=Oracle18 \
--health-cmd healthcheck.sh \
--health-interval 5s \
--health-timeout 5s \
--health-retries 10 \
docker.io/gvenzl/oracle-xe:18.4.0-full
oracle_setup
}
oracle_21() {
$CONTAINER_CLI rm -f oracle || true
$PRIVILEGED_CLI $CONTAINER_CLI rm -f oracle || true
disable_userland_proxy
# We need to use the defaults
# SYSTEM/Oracle18
$CONTAINER_CLI run --name oracle -d -p 1521:1521 -e ORACLE_PASSWORD=Oracle18 \
$PRIVILEGED_CLI $CONTAINER_CLI run --name oracle -d -p 1521:1521 -e ORACLE_PASSWORD=Oracle18 \
--cap-add cap_net_raw \
--health-cmd healthcheck.sh \
--health-interval 5s \
--health-timeout 5s \
@ -924,7 +933,6 @@ if [ -z ${1} ]; then
echo -e "\tmysql_5_7"
echo -e "\toracle"
echo -e "\toracle_21"
echo -e "\toracle_18"
echo -e "\toracle_11"
echo -e "\tpostgresql"
echo -e "\tpostgresql_15"

View File

@ -35,16 +35,16 @@ ext {
'jdbc.driver': 'org.apache.derby.iapi.jdbc.AutoloadedDriver',
'jdbc.user' : 'hibernate_orm_test',
'jdbc.pass' : 'hibernate_orm_test',
'jdbc.url' : 'jdbc:derby:target/tmp/derby/hibernate_orm_test;databaseName=hibernate_orm_test;create=true',
'connection.init_sql' : 'CALL SYSCS_UTIL.SYSCS_SET_DATABASE_PROPERTY(\'derby.locks.waitTimeout\', \'10\')'
'jdbc.url' : 'jdbc:derby:memory:;databaseName=hibernate_orm_test;create=true',
'connection.init_sql' : ''
],
derby_old : [
'db.dialect' : 'org.hibernate.dialect.DerbyDialect',
'jdbc.driver': 'org.apache.derby.jdbc.EmbeddedDriver',
'jdbc.user' : 'hibernate_orm_test',
'jdbc.pass' : 'hibernate_orm_test',
'jdbc.url' : 'jdbc:derby:target/tmp/derby/hibernate_orm_test;databaseName=hibernate_orm_test;create=true',
'connection.init_sql' : 'CALL SYSCS_UTIL.SYSCS_SET_DATABASE_PROPERTY(\'derby.locks.waitTimeout\', \'10\')'
'jdbc.url' : 'jdbc:derby:memory:;databaseName=hibernate_orm_test;create=true',
'connection.init_sql' : ''
],
pgsql : [
'db.dialect' : 'org.hibernate.dialect.PostgreSQLDialect',
@ -136,7 +136,7 @@ ext {
'jdbc.driver': 'oracle.jdbc.OracleDriver',
'jdbc.user' : 'hibernate_orm_test',
'jdbc.pass' : 'hibernate_orm_test',
'jdbc.url' : 'jdbc:oracle:thin:@' + dbHost + ':1521/xepdb1?oracle.jdbc.ReadTimeout=10000',
'jdbc.url' : 'jdbc:oracle:thin:@' + dbHost + ':1521/xepdb1',
'connection.init_sql' : ''
],
oracle_ci : [
@ -144,7 +144,7 @@ ext {
'jdbc.driver': 'oracle.jdbc.OracleDriver',
'jdbc.user' : 'hibernate_orm_test',
'jdbc.pass' : 'hibernate_orm_test',
'jdbc.url' : 'jdbc:oracle:thin:@' + dbHost + ':1521/xepdb1?oracle.jdbc.ReadTimeout=10000',
'jdbc.url' : 'jdbc:oracle:thin:@' + dbHost + ':1521/xepdb1',
'connection.init_sql' : ''
],
oracle_legacy_ci : [
@ -153,7 +153,7 @@ ext {
'jdbc.user' : 'hibernate_orm_test',
'jdbc.pass' : 'hibernate_orm_test',
// For 11 version that doesn't have any XEPDB1 database service
'jdbc.url' : 'jdbc:oracle:thin:@' + dbHost + ':1521:XE?oracle.jdbc.ReadTimeout=10000',
'jdbc.url' : 'jdbc:oracle:thin:@' + dbHost + ':1521:XE',
'connection.init_sql' : ''
],
oracle_cloud_autonomous_tls : [

View File

@ -1251,7 +1251,7 @@ public class MySQLLegacyDialect extends Dialect {
case LockOptions.WAIT_FOREVER:
return lockString;
default:
return supportsWait() ? lockString + " wait " + timeout : lockString;
return supportsWait() ? lockString + " wait " + getTimeoutInSeconds( timeout ) : lockString;
}
}

View File

@ -1248,7 +1248,7 @@ public class OracleLegacyDialect extends Dialect {
case LockOptions.WAIT_FOREVER:
return lockString;
default:
return supportsWait() ? lockString + " wait " + Math.round(timeout / 1e3f) : lockString;
return supportsWait() ? lockString + " wait " + getTimeoutInSeconds( timeout ) : lockString;
}
}

View File

@ -290,7 +290,7 @@ public class TimesTenDialect extends Dialect {
case LockOptions.WAIT_FOREVER:
return lockString;
default:
return supportsWait() ? lockString + " wait " + Math.round( timeout / 1e3f ) : lockString;
return supportsWait() ? lockString + " wait " + getTimeoutInSeconds( timeout ) : lockString;
}
}

View File

@ -19,6 +19,7 @@ import org.hibernate.orm.test.dialect.resolver.TestingDialectResolutionInfo;
import org.hibernate.service.spi.ServiceRegistryImplementor;
import org.hibernate.testing.junit4.BaseUnitTestCase;
import org.hibernate.testing.util.ServiceRegistryUtil;
import org.junit.Before;
import org.junit.Test;
@ -36,7 +37,7 @@ public class CommunityDialectFactoryTest extends BaseUnitTestCase {
final BootstrapServiceRegistry bootReg = new BootstrapServiceRegistryBuilder().applyClassLoader(
CommunityDialectFactoryTest.class.getClassLoader()
).build();
registry = new StandardServiceRegistryBuilder( bootReg ).build();
registry = ServiceRegistryUtil.serviceRegistryBuilder( bootReg ).build();
dialectFactory = new DialectFactoryImpl();
dialectFactory.injectServices( (ServiceRegistryImplementor) registry );

View File

@ -29,7 +29,6 @@ import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.sql.Statement;
import java.sql.Types;
import java.time.Duration;
import java.time.temporal.TemporalAccessor;
import java.util.Arrays;
import java.util.Date;
@ -878,11 +877,10 @@ public abstract class AbstractHANADialect extends Dialect {
@Override
public String getWriteLockString(int timeout) {
long timeoutInSeconds = getLockWaitTimeoutInSeconds( timeout );
if ( timeoutInSeconds > 0 ) {
return getForUpdateString() + " wait " + timeoutInSeconds;
if ( timeout > 0 ) {
return getForUpdateString() + " wait " + getTimeoutInSeconds( timeout );
}
else if ( timeoutInSeconds == 0 ) {
else if ( timeout == 0 ) {
return getForUpdateNowaitString();
}
else {
@ -893,7 +891,7 @@ public abstract class AbstractHANADialect extends Dialect {
@Override
public String getWriteLockString(String aliases, int timeout) {
if ( timeout > 0 ) {
return getForUpdateString( aliases ) + " wait " + getLockWaitTimeoutInSeconds( timeout );
return getForUpdateString( aliases ) + " wait " + getTimeoutInSeconds( timeout );
}
else if ( timeout == 0 ) {
return getForUpdateNowaitString( aliases );
@ -903,16 +901,6 @@ public abstract class AbstractHANADialect extends Dialect {
}
}
private long getLockWaitTimeoutInSeconds(int timeoutInMilliseconds) {
Duration duration = Duration.ofMillis( timeoutInMilliseconds );
long timeoutInSeconds = duration.getSeconds();
if ( duration.getNano() != 0 && LOG.isInfoEnabled() ) {
LOG.info( "Changing the query timeout from " + timeoutInMilliseconds + " ms to " + timeoutInSeconds
+ " s, because HANA requires the timeout in seconds" );
}
return timeoutInSeconds;
}
@Override
public String getQueryHintString(String query, List<String> hints) {
return query + " with hint (" + String.join( ",", hints ) + ")";

View File

@ -2180,6 +2180,10 @@ public abstract class Dialect implements ConversionContext, TypeContributor, Fun
return sql + new ForUpdateFragment( this, aliasedLockOptions, keyColumnNames ).toFragmentString();
}
protected int getTimeoutInSeconds(int millis) {
return millis == 0 ? 0 : Math.max( 1, Math.round( millis / 1e3f ) );
}
// table support ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

View File

@ -6,8 +6,6 @@
*/
package org.hibernate.dialect;
import java.time.Duration;
import org.hibernate.LockOptions;
/**
@ -31,15 +29,10 @@ public class MariaDB103Dialect extends MariaDBDialect {
}
if ( timeout > 0 ) {
return getForUpdateString() + " wait " + getLockWaitTimeoutInSeconds( timeout );
return getForUpdateString() + " wait " + getTimeoutInSeconds( timeout );
}
return getForUpdateString();
}
private static long getLockWaitTimeoutInSeconds(int timeoutInMilliseconds) {
Duration duration = Duration.ofMillis( timeoutInMilliseconds );
return duration.getSeconds();
}
}

View File

@ -1338,7 +1338,7 @@ public class MySQLDialect extends Dialect {
case LockOptions.WAIT_FOREVER:
return lockString;
default:
return supportsWait() ? lockString + " wait " + timeout : lockString;
return supportsWait() ? lockString + " wait " + getTimeoutInSeconds( timeout ) : lockString;
}
}

View File

@ -1257,7 +1257,7 @@ public class OracleDialect extends Dialect {
case WAIT_FOREVER:
return lockString;
default:
return supportsWait() ? lockString + " wait " + Math.round(timeout / 1e3f) : lockString;
return supportsWait() ? lockString + " wait " + getTimeoutInSeconds( timeout ) : lockString;
}
}

View File

@ -6,8 +6,6 @@
*/
package org.hibernate.dialect;
import java.time.Duration;
import org.hibernate.LockOptions;
import org.hibernate.dialect.sequence.SequenceSupport;
import org.hibernate.dialect.sequence.TiDBSequenceSupport;
@ -137,7 +135,7 @@ public class TiDBDialect extends MySQLDialect {
}
if ( timeout > 0 ) {
return getForUpdateString() + " wait " + getLockWaitTimeoutInSeconds( timeout );
return getForUpdateString() + " wait " + getTimeoutInSeconds( timeout );
}
return getForUpdateString();
@ -152,9 +150,4 @@ public class TiDBDialect extends MySQLDialect {
public String getForUpdateNowaitString(String aliases) {
return getForUpdateString( aliases ) + " nowait";
}
private static long getLockWaitTimeoutInSeconds(int timeoutInMilliseconds) {
Duration duration = Duration.ofMillis( timeoutInMilliseconds );
return duration.getSeconds();
}
}

View File

@ -64,30 +64,41 @@ public abstract class BasicConnectionCreator implements ConnectionCreator {
}
try {
if ( isolation != null ) {
conn.setTransactionIsolation( isolation );
}
}
catch (SQLException e) {
throw convertSqlException( "Unable to set transaction isolation (" + isolation + ")", e );
}
try {
if ( conn.getAutoCommit() != autoCommit ) {
conn.setAutoCommit( autoCommit );
}
}
catch (SQLException e) {
throw convertSqlException( "Unable to set auto-commit (" + autoCommit + ")", e );
}
if ( initSql != null && !initSql.trim().isEmpty() ) {
try (Statement s = conn.createStatement()) {
s.execute( initSql );
try {
if ( isolation != null ) {
conn.setTransactionIsolation( isolation );
}
}
catch (SQLException e) {
throw convertSqlException( "Unable to execute initSql (" + initSql + ")", e );
throw convertSqlException( "Unable to set transaction isolation (" + isolation + ")", e );
}
try {
if ( conn.getAutoCommit() != autoCommit ) {
conn.setAutoCommit( autoCommit );
}
}
catch (SQLException e) {
throw convertSqlException( "Unable to set auto-commit (" + autoCommit + ")", e );
}
if ( initSql != null && !initSql.trim().isEmpty() ) {
try (Statement s = conn.createStatement()) {
s.execute( initSql );
}
catch (SQLException e) {
throw convertSqlException( "Unable to execute initSql (" + initSql + ")", e );
}
}
}
catch (RuntimeException | Error e) {
try {
conn.close();
}
catch (SQLException ex) {
e.addSuppressed( ex );
}
throw e;
}
return conn;

View File

@ -100,6 +100,10 @@ public class ConnectionProviderInitiator implements StandardServiceInitiator<Con
return null;
}
if ( configurationValues.get( AvailableSettings.DATASOURCE ) != null ) {
return new DatasourceConnectionProviderImpl();
}
final StrategySelector strategySelector = registry.getService( StrategySelector.class );
final Object explicitSetting = configurationValues.get( AvailableSettings.CONNECTION_PROVIDER );
if ( explicitSetting != null ) {
@ -142,10 +146,6 @@ public class ConnectionProviderInitiator implements StandardServiceInitiator<Con
}
}
if ( configurationValues.get( AvailableSettings.DATASOURCE ) != null ) {
return new DatasourceConnectionProviderImpl();
}
ConnectionProvider connectionProvider = null;
final Class<? extends ConnectionProvider> singleRegisteredProvider = getSingleRegisteredProvider( strategySelector );

View File

@ -291,8 +291,12 @@ public class DriverManagerConnectionProviderImpl
}
}
protected int getOpenConnections() {
return state.pool.allConnections.size() - state.pool.availableConnections.size();
}
protected void validateConnectionsReturned() {
int allocationCount = state.pool.allConnections.size() - state.pool.availableConnections.size();
int allocationCount = getOpenConnections();
if ( allocationCount != 0 ) {
CONNECTIONS_MESSAGE_LOGGER.error( "Connection leak detected: there are " + allocationCount + " unclosed connections");
}
@ -462,33 +466,26 @@ public class DriverManagerConnectionProviderImpl
public void close() throws SQLException {
try {
int allocationCount = allConnections.size() - availableConnections.size();
if(allocationCount > 0) {
if (allocationCount > 0) {
CONNECTIONS_LOGGER.error( "Connection leak detected: there are " + allocationCount + " unclosed connections upon shutting down pool " + getUrl());
}
}
finally {
for ( Connection connection : allConnections ) {
connection.close();
}
removeConnections( Integer.MAX_VALUE );
}
}
public int size() {
return availableConnections.size();
return allConnections.size();
}
protected void removeConnections(int numberToBeRemoved) {
for ( int i = 0; i < numberToBeRemoved; i++ ) {
Connection connection = availableConnections.poll();
try {
if ( connection != null ) {
connection.close();
}
allConnections.remove( connection );
}
catch (SQLException e) {
CONNECTIONS_MESSAGE_LOGGER.unableToCloseConnection( e );
final Connection connection = availableConnections.poll();
if ( connection == null ) {
break;
}
closeConnection( connection, null );
}
}

View File

@ -9,25 +9,60 @@ package org.hibernate.engine.jdbc.env.internal;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.SQLException;
import java.util.Collections;
import java.util.Map;
import org.hibernate.boot.registry.StandardServiceInitiator;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.engine.config.spi.ConfigurationService;
import org.hibernate.engine.jdbc.batch.spi.BatchBuilder;
import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider;
import org.hibernate.engine.jdbc.connections.spi.JdbcConnectionAccess;
import org.hibernate.engine.jdbc.connections.spi.MultiTenantConnectionProvider;
import org.hibernate.engine.jdbc.dialect.spi.DialectFactory;
import org.hibernate.engine.jdbc.dialect.spi.DialectResolutionInfo;
import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment;
import org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl;
import org.hibernate.engine.jdbc.internal.JdbcServicesImpl;
import org.hibernate.engine.jdbc.spi.JdbcServices;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.internal.CoreMessageLogger;
import org.hibernate.internal.log.DeprecationLogger;
import org.hibernate.internal.util.NullnessHelper;
import org.hibernate.internal.util.StringHelper;
import org.hibernate.internal.util.config.ConfigurationHelper;
import org.hibernate.jdbc.AbstractReturningWork;
import org.hibernate.jpa.internal.MutableJpaComplianceImpl;
import org.hibernate.jpa.spi.JpaCompliance;
import org.hibernate.resource.jdbc.spi.JdbcObserver;
import org.hibernate.resource.jdbc.spi.JdbcSessionContext;
import org.hibernate.resource.jdbc.spi.JdbcSessionOwner;
import org.hibernate.resource.jdbc.spi.PhysicalConnectionHandlingMode;
import org.hibernate.resource.jdbc.spi.StatementInspector;
import org.hibernate.resource.transaction.spi.TransactionCoordinator;
import org.hibernate.resource.transaction.spi.TransactionCoordinatorBuilder;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.spi.ServiceRegistryImplementor;
import org.hibernate.stat.spi.StatisticsImplementor;
import org.jboss.logging.Logger;
import static org.hibernate.cfg.AvailableSettings.CONNECTION_HANDLING;
import static org.hibernate.cfg.AvailableSettings.DIALECT_DB_MAJOR_VERSION;
import static org.hibernate.cfg.AvailableSettings.DIALECT_DB_MINOR_VERSION;
import static org.hibernate.cfg.AvailableSettings.DIALECT_DB_NAME;
import static org.hibernate.cfg.AvailableSettings.JAKARTA_HBM2DDL_DB_MAJOR_VERSION;
import static org.hibernate.cfg.AvailableSettings.JAKARTA_HBM2DDL_DB_MINOR_VERSION;
import static org.hibernate.cfg.AvailableSettings.JAKARTA_HBM2DDL_DB_NAME;
import static org.hibernate.cfg.AvailableSettings.JTA_TRACK_BY_THREAD;
import static org.hibernate.cfg.AvailableSettings.PREFER_USER_TRANSACTION;
import static org.hibernate.engine.config.spi.StandardConverters.BOOLEAN;
import static org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentImpl.isMultiTenancyEnabled;
import static org.hibernate.internal.log.DeprecationLogger.DEPRECATION_LOGGER;
import static org.hibernate.internal.util.NullnessHelper.coalesceSuppliedValues;
import static org.hibernate.internal.util.StringHelper.isNotEmpty;
import static org.hibernate.internal.util.config.ConfigurationHelper.getBoolean;
import static org.hibernate.internal.util.config.ConfigurationHelper.getInteger;
/**
* @author Steve Ebersole
*/
@ -76,7 +111,10 @@ public class JdbcEnvironmentInitiator implements StandardServiceInitiator<JdbcEn
);
Integer explicitDatabaseMajorVersion = NullnessHelper.coalesceSuppliedValues(
() -> ConfigurationHelper.getInteger( AvailableSettings.JAKARTA_HBM2DDL_DB_MAJOR_VERSION, configurationValues ),
() -> ConfigurationHelper.getInteger(
AvailableSettings.JAKARTA_HBM2DDL_DB_MAJOR_VERSION,
configurationValues
),
() -> {
final Integer value = ConfigurationHelper.getInteger(
AvailableSettings.DIALECT_DB_MAJOR_VERSION,
@ -93,7 +131,10 @@ public class JdbcEnvironmentInitiator implements StandardServiceInitiator<JdbcEn
);
Integer explicitDatabaseMinorVersion = NullnessHelper.coalesceSuppliedValues(
() -> ConfigurationHelper.getInteger( AvailableSettings.JAKARTA_HBM2DDL_DB_MINOR_VERSION, configurationValues ),
() -> ConfigurationHelper.getInteger(
AvailableSettings.JAKARTA_HBM2DDL_DB_MINOR_VERSION,
configurationValues
),
() -> {
final Integer value = ConfigurationHelper.getInteger(
AvailableSettings.DIALECT_DB_MINOR_VERSION,
@ -126,7 +167,9 @@ public class JdbcEnvironmentInitiator implements StandardServiceInitiator<JdbcEn
,
() -> {
if ( configuredDatabaseMajorVersion != null ) {
return configuredDatabaseMinorVersion == null ? configuredDatabaseMajorVersion.toString() : (configuredDatabaseMajorVersion + "." + configuredDatabaseMinorVersion);
return configuredDatabaseMinorVersion == null ?
configuredDatabaseMajorVersion.toString() :
( configuredDatabaseMajorVersion + "." + configuredDatabaseMinorVersion );
}
return null;
}
@ -147,131 +190,209 @@ public class JdbcEnvironmentInitiator implements StandardServiceInitiator<JdbcEn
}
if ( useJdbcMetadata ) {
final JdbcConnectionAccess jdbcConnectionAccess = buildJdbcConnectionAccess( registry );
try {
final Connection connection = jdbcConnectionAccess.obtainConnection();
try {
final DatabaseMetaData dbmd = connection.getMetaData();
if ( log.isDebugEnabled() ) {
log.debugf(
"Database ->\n"
+ " name : %s\n"
+ " version : %s\n"
+ " major : %s\n"
+ " minor : %s",
dbmd.getDatabaseProductName(),
dbmd.getDatabaseProductVersion(),
dbmd.getDatabaseMajorVersion(),
dbmd.getDatabaseMinorVersion()
);
log.debugf(
"Driver ->\n"
+ " name : %s\n"
+ " version : %s\n"
+ " major : %s\n"
+ " minor : %s",
dbmd.getDriverName(),
dbmd.getDriverVersion(),
dbmd.getDriverMajorVersion(),
dbmd.getDriverMinorVersion()
);
log.debugf( "JDBC version : %s.%s", dbmd.getJDBCMajorVersion(), dbmd.getJDBCMinorVersion() );
}
final String databaseName;
final String databaseVersion;
final int databaseMajorVersion;
final int databaseMinorVersion;
if ( explicitDatabaseName == null ) {
databaseName = dbmd.getDatabaseProductName();
}
else {
databaseName = explicitDatabaseName;
}
if ( explicitDatabaseVersion == null ) {
databaseVersion = dbmd.getDatabaseProductVersion();
}
else {
databaseVersion = explicitDatabaseVersion;
}
if ( explicitDatabaseMajorVersion == null ) {
databaseMajorVersion = dbmd.getDatabaseMajorVersion();
}
else {
databaseMajorVersion = explicitDatabaseMajorVersion;
}
if ( explicitDatabaseMinorVersion == null ) {
databaseMinorVersion = dbmd.getDatabaseMinorVersion();
}
else {
databaseMinorVersion = explicitDatabaseMinorVersion;
}
final DialectResolutionInfo dialectResolutionInfo = new DialectResolutionInfoImpl(
dbmd,
databaseName,
databaseVersion,
databaseMajorVersion,
databaseMinorVersion,
dbmd.getDriverName(),
dbmd.getDriverMajorVersion(),
dbmd.getDriverMinorVersion(),
dbmd.getSQLKeywords()
);
return new JdbcEnvironmentImpl(
registry,
dialectFactory.buildDialect(
configurationValues,
() -> dialectResolutionInfo
),
dbmd,
jdbcConnectionAccess
);
}
catch (SQLException e) {
log.unableToObtainConnectionMetadata( e );
}
finally {
try {
jdbcConnectionAccess.releaseConnection( connection );
}
catch (SQLException ignore) {
}
}
}
catch (Exception e) {
log.unableToObtainConnectionToQueryMetadata( e );
}
return getJdbcEnvironmentUsingJdbcMetadata(
configurationValues,
registry,
dialectFactory,
explicitDatabaseName,
explicitDatabaseMajorVersion,
explicitDatabaseMinorVersion,
explicitDatabaseVersion);
}
else if ( explicitDialectConfiguration(
configurationValues,
explicitDatabaseName,
explicitDatabaseMajorVersion,
explicitDatabaseMinorVersion,
explicitDatabaseVersion) ) {
return getJdbcEnvironmentWithExplicitConfiguration(
configurationValues,
registry,
dialectFactory,
explicitDatabaseName,
explicitDatabaseMajorVersion,
explicitDatabaseMinorVersion,
explicitDatabaseVersion
);
}
else {
if (
(StringHelper.isNotEmpty( explicitDatabaseVersion ) || explicitDatabaseMajorVersion != null || explicitDatabaseMinorVersion != null)
&& ( StringHelper.isNotEmpty( explicitDatabaseName ) || isNotEmpty( configurationValues.get( AvailableSettings.DIALECT ) ) )
) {
final DialectResolutionInfo dialectResolutionInfo = new DialectResolutionInfoImpl(
null,
explicitDatabaseName,
explicitDatabaseVersion != null ? explicitDatabaseVersion : "0",
explicitDatabaseMajorVersion != null ? explicitDatabaseMajorVersion : 0,
explicitDatabaseMinorVersion != null ? explicitDatabaseMinorVersion : 0,
null,
0,
0,
null
);
return new JdbcEnvironmentImpl(
registry,
dialectFactory.buildDialect(
configurationValues,
() -> dialectResolutionInfo
)
);
}
return getJdbcEnvironmentWithDefaults( configurationValues, registry, dialectFactory );
}
}
// if we get here, either we were asked to not use JDBC metadata or accessing the JDBC metadata failed.
return new JdbcEnvironmentImpl( registry, dialectFactory.buildDialect( configurationValues, null ) );
private static JdbcEnvironmentImpl getJdbcEnvironmentWithDefaults(
Map<String, Object> configurationValues,
ServiceRegistryImplementor registry,
DialectFactory dialectFactory) {
return new JdbcEnvironmentImpl(
registry,
dialectFactory.buildDialect( configurationValues, null )
);
}
private static JdbcEnvironmentImpl getJdbcEnvironmentWithExplicitConfiguration(
Map<String, Object> configurationValues,
ServiceRegistryImplementor registry,
DialectFactory dialectFactory,
String explicitDatabaseName,
Integer explicitDatabaseMajorVersion,
Integer explicitDatabaseMinorVersion,
String explicitDatabaseVersion) {
final DialectResolutionInfo dialectResolutionInfo = new DialectResolutionInfoImpl(
null,
explicitDatabaseName,
explicitDatabaseVersion != null ? explicitDatabaseVersion : "0",
explicitDatabaseMajorVersion != null ? explicitDatabaseMajorVersion : 0,
explicitDatabaseMinorVersion != null ? explicitDatabaseMinorVersion : 0,
null,
0,
0,
null
);
return new JdbcEnvironmentImpl(
registry,
dialectFactory.buildDialect( configurationValues, () -> dialectResolutionInfo )
);
}
private JdbcEnvironmentImpl getJdbcEnvironmentUsingJdbcMetadata(
Map<String, Object> configurationValues,
ServiceRegistryImplementor registry,
DialectFactory dialectFactory, String explicitDatabaseName,
Integer explicitDatabaseMajorVersion,
Integer explicitDatabaseMinorVersion,
String explicitDatabaseVersion) {
final JdbcConnectionAccess jdbcConnectionAccess = buildJdbcConnectionAccess( registry );
final JdbcServicesImpl jdbcServices = new JdbcServicesImpl( registry );
final TemporaryJdbcSessionOwner temporaryJdbcSessionOwner = new TemporaryJdbcSessionOwner(
jdbcConnectionAccess,
jdbcServices,
registry
);
temporaryJdbcSessionOwner.transactionCoordinator = registry.getService( TransactionCoordinatorBuilder.class )
.buildTransactionCoordinator(
new JdbcCoordinatorImpl( null, temporaryJdbcSessionOwner, jdbcServices ),
() -> false
);
try {
return temporaryJdbcSessionOwner.transactionCoordinator.createIsolationDelegate().delegateWork(
new AbstractReturningWork<>() {
@Override
public JdbcEnvironmentImpl execute(Connection connection) throws SQLException {
try {
final DatabaseMetaData dbmd = connection.getMetaData();
if ( log.isDebugEnabled() ) {
log.debugf(
"Database ->\n"
+ " name : %s\n"
+ " version : %s\n"
+ " major : %s\n"
+ " minor : %s",
dbmd.getDatabaseProductName(),
dbmd.getDatabaseProductVersion(),
dbmd.getDatabaseMajorVersion(),
dbmd.getDatabaseMinorVersion()
);
log.debugf(
"Driver ->\n"
+ " name : %s\n"
+ " version : %s\n"
+ " major : %s\n"
+ " minor : %s",
dbmd.getDriverName(),
dbmd.getDriverVersion(),
dbmd.getDriverMajorVersion(),
dbmd.getDriverMinorVersion()
);
log.debugf(
"JDBC version : %s.%s",
dbmd.getJDBCMajorVersion(),
dbmd.getJDBCMinorVersion()
);
}
final String databaseName;
final String databaseVersion;
final int databaseMajorVersion;
final int databaseMinorVersion;
if ( explicitDatabaseName == null ) {
databaseName = dbmd.getDatabaseProductName();
}
else {
databaseName = explicitDatabaseName;
}
if ( explicitDatabaseVersion == null ) {
databaseVersion = dbmd.getDatabaseProductVersion();
}
else {
databaseVersion = explicitDatabaseVersion;
}
if ( explicitDatabaseMajorVersion == null ) {
databaseMajorVersion = dbmd.getDatabaseMajorVersion();
}
else {
databaseMajorVersion = explicitDatabaseMajorVersion;
}
if ( explicitDatabaseMinorVersion == null ) {
databaseMinorVersion = dbmd.getDatabaseMinorVersion();
}
else {
databaseMinorVersion = explicitDatabaseMinorVersion;
}
final DialectResolutionInfo dialectResolutionInfo = new DialectResolutionInfoImpl(
dbmd,
databaseName,
databaseVersion,
databaseMajorVersion,
databaseMinorVersion,
dbmd.getDriverName(),
dbmd.getDriverMajorVersion(),
dbmd.getDriverMinorVersion(),
dbmd.getSQLKeywords()
);
return new JdbcEnvironmentImpl(
registry,
dialectFactory.buildDialect(
configurationValues,
() -> dialectResolutionInfo
),
dbmd,
jdbcConnectionAccess
);
}
catch (SQLException e) {
log.unableToObtainConnectionMetadata( e );
}
// accessing the JDBC metadata failed
return getJdbcEnvironmentWithDefaults( configurationValues, registry, dialectFactory );
}
},
false
);
}
catch (Exception e) {
log.unableToObtainConnectionToQueryMetadata( e );
}
// accessing the JDBC metadata failed
return getJdbcEnvironmentWithDefaults( configurationValues, registry, dialectFactory );
}
private static boolean explicitDialectConfiguration(
Map<String, Object> configurationValues,
String explicitDatabaseName,
Integer explicitDatabaseMajorVersion,
Integer explicitDatabaseMinorVersion,
String explicitDatabaseVersion) {
return ( isNotEmpty(explicitDatabaseVersion) || explicitDatabaseMajorVersion != null || explicitDatabaseMinorVersion != null )
&& ( isNotEmpty(explicitDatabaseName) || isNotNullAndNotEmpty( configurationValues.get(AvailableSettings.DIALECT) ) );
}
private static boolean isNotNullAndNotEmpty(Object o) {
return o != null && ( !(o instanceof String) || !((String) o).isEmpty() );
}
private static boolean isNotEmpty(Object o) {
@ -430,4 +551,175 @@ public class JdbcEnvironmentInitiator implements StandardServiceInitiator<JdbcEn
return databaseMetadata;
}
}
/**
* This is a temporary JdbcSessionOwner for the purpose of passing a connection to the Dialect for initialization.
*/
private static class TemporaryJdbcSessionOwner implements JdbcSessionOwner, JdbcSessionContext {
private final JdbcConnectionAccess jdbcConnectionAccess;
private final JdbcServices jdbcServices;
private final ServiceRegistryImplementor serviceRegistry;
private final boolean jtaTrackByThread;
private final boolean preferUserTransaction;
private final boolean connectionProviderDisablesAutoCommit;
private final PhysicalConnectionHandlingMode connectionHandlingMode;
private final JpaCompliance jpaCompliance;
TransactionCoordinator transactionCoordinator;
public TemporaryJdbcSessionOwner(
JdbcConnectionAccess jdbcConnectionAccess,
JdbcServices jdbcServices,
ServiceRegistryImplementor serviceRegistry) {
this.jdbcConnectionAccess = jdbcConnectionAccess;
this.jdbcServices = jdbcServices;
this.serviceRegistry = serviceRegistry;
final ConfigurationService configurationService = serviceRegistry.getService( ConfigurationService.class );
this.jtaTrackByThread = configurationService.getSetting( JTA_TRACK_BY_THREAD, BOOLEAN, true );
this.preferUserTransaction = getBoolean( PREFER_USER_TRANSACTION, configurationService.getSettings() );
this.connectionProviderDisablesAutoCommit = getBoolean(
AvailableSettings.CONNECTION_PROVIDER_DISABLES_AUTOCOMMIT,
configurationService.getSettings(),
false
);
final PhysicalConnectionHandlingMode specifiedHandlingMode = PhysicalConnectionHandlingMode.interpret(
configurationService.getSettings().get( CONNECTION_HANDLING )
);
if ( specifiedHandlingMode != null ) {
this.connectionHandlingMode = specifiedHandlingMode;
}
else {
this.connectionHandlingMode = serviceRegistry.getService( TransactionCoordinatorBuilder.class )
.getDefaultConnectionHandlingMode();
}
this.jpaCompliance = new MutableJpaComplianceImpl( Collections.emptyMap(), false );
}
@Override
public JdbcSessionContext getJdbcSessionContext() {
return this;
}
@Override
public JdbcConnectionAccess getJdbcConnectionAccess() {
return jdbcConnectionAccess;
}
@Override
public TransactionCoordinator getTransactionCoordinator() {
return transactionCoordinator;
}
@Override
public void startTransactionBoundary() {
}
@Override
public void afterTransactionBegin() {
}
@Override
public void beforeTransactionCompletion() {
}
@Override
public void afterTransactionCompletion(boolean successful, boolean delayed) {
}
@Override
public void flushBeforeTransactionCompletion() {
}
@Override
public Integer getJdbcBatchSize() {
return null;
}
@Override
public boolean isScrollableResultSetsEnabled() {
return false;
}
@Override
public boolean isGetGeneratedKeysEnabled() {
return false;
}
@Override
public Integer getFetchSizeOrNull() {
return null;
}
@Override
public int getFetchSize() {
return 0;
}
@Override
public boolean doesConnectionProviderDisableAutoCommit() {
return connectionProviderDisablesAutoCommit;
}
@Override
public boolean isPreferUserTransaction() {
return preferUserTransaction;
}
@Override
public boolean isJtaTrackByThread() {
return jtaTrackByThread;
}
@Override
public PhysicalConnectionHandlingMode getPhysicalConnectionHandlingMode() {
return connectionHandlingMode;
}
@Override
public StatementInspector getStatementInspector() {
return null;
}
@Override
public JpaCompliance getJpaCompliance() {
return jpaCompliance;
}
@Override
public JdbcObserver getObserver() {
return null;
}
@Override
public SessionFactoryImplementor getSessionFactory() {
return null;
}
@Override
public ServiceRegistry getServiceRegistry() {
return serviceRegistry;
}
@Override
public JdbcServices getJdbcServices() {
return jdbcServices;
}
@Override
public BatchBuilder getBatchBuilder() {
return null;
}
@Override
public boolean isActive() {
return true;
}
}
}

View File

@ -35,6 +35,13 @@ public class JdbcServicesImpl implements JdbcServices, ServiceRegistryAwareServi
private SqlStatementLogger sqlStatementLogger;
private ParameterMarkerStrategy parameterMarkerStrategy;
public JdbcServicesImpl() {
}
public JdbcServicesImpl(ServiceRegistryImplementor serviceRegistry) {
this.serviceRegistry = serviceRegistry;
}
@Override
public void injectServices(ServiceRegistryImplementor serviceRegistry) {
this.serviceRegistry = serviceRegistry;

View File

@ -10,12 +10,12 @@
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.H2Dialect</property>
<property name="hibernate.connection.driver_class">org.h2.Driver</property>
<property name="hibernate.connection.username">sa</property>
<property name="hibernate.connection.password"></property>
<property name="hibernate.connection.init_sql"></property>
<property name="hibernate.connection.url">jdbc:h2:mem:db1;DB_CLOSE_DELAY=-1;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE</property>
<property name="hibernate.dialect">@db.dialect@</property>
<property name="hibernate.connection.driver_class">@jdbc.driver@</property>
<property name="hibernate.connection.username">@jdbc.user@</property>
<property name="hibernate.connection.password">@jdbc.pass@</property>
<property name="hibernate.connection.init_sql">@connection.init_sql@</property>
<property name="hibernate.connection.url">@jdbc.url@</property>
<property name="hibernate.cache.use_query_cache">true</property>
<property name="hibernate.cache.region_prefix">hibernate.test</property>
<property name="hibernate.jdbc.batch_size">0</property>

View File

@ -17,6 +17,8 @@ import org.hibernate.cfg.Environment;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.query.sqm.UnknownEntityException;
import org.hibernate.testing.util.ServiceRegistryUtil;
import org.junit.jupiter.api.Test;
import static org.hibernate.testing.transaction.TransactionUtil2.inTransaction;
@ -32,6 +34,7 @@ public class ConfigurationTest {
@Test
public void testDeclarativeMix() {
Configuration cfg = new Configuration();
ServiceRegistryUtil.applySettings( cfg.getStandardServiceRegistryBuilder() );
cfg.configure( "org/hibernate/orm/test/annotations/hibernate.cfg.xml" );
cfg.setProperty( Environment.HBM2DDL_AUTO, "create-drop" );
try (SessionFactory sf = cfg.buildSessionFactory()) {
@ -50,6 +53,7 @@ public class ConfigurationTest {
@Test
public void testIgnoringHbm() {
Configuration cfg = new Configuration();
ServiceRegistryUtil.applySettings( cfg.getStandardServiceRegistryBuilder() );
cfg.configure( "org/hibernate/orm/test/annotations/hibernate.cfg.xml" );
cfg.setProperty( Environment.HBM2DDL_AUTO, "create-drop" );
cfg.setProperty( Configuration.ARTEFACT_PROCESSING_ORDER, "class" );
@ -87,6 +91,7 @@ public class ConfigurationTest {
@Test
public void testPrecedenceHbm() {
Configuration cfg = new Configuration();
ServiceRegistryUtil.applySettings( cfg.getStandardServiceRegistryBuilder() );
cfg.configure( "org/hibernate/orm/test/annotations/hibernate.cfg.xml" );
cfg.setProperty( Environment.HBM2DDL_AUTO, "create-drop" );
cfg.addAnnotatedClass( Boat.class );
@ -113,6 +118,7 @@ public class ConfigurationTest {
@Test
public void testPrecedenceAnnotation() {
Configuration cfg = new Configuration();
ServiceRegistryUtil.applySettings( cfg.getStandardServiceRegistryBuilder() );
cfg.configure( "org/hibernate/orm/test/annotations/hibernate.cfg.xml" );
cfg.setProperty( Environment.HBM2DDL_AUTO, "create-drop" );
cfg.setProperty( Configuration.ARTEFACT_PROCESSING_ORDER, "class, hbm" );
@ -139,6 +145,7 @@ public class ConfigurationTest {
@Test
public void testHbmWithSubclassExtends() {
Configuration cfg = new Configuration();
ServiceRegistryUtil.applySettings( cfg.getStandardServiceRegistryBuilder() );
cfg.configure( "org/hibernate/orm/test/annotations/hibernate.cfg.xml" );
cfg.addClass( Ferry.class );
cfg.setProperty( Environment.HBM2DDL_AUTO, "create-drop" );
@ -158,6 +165,7 @@ public class ConfigurationTest {
@Test
public void testAnnReferencesHbm() {
Configuration cfg = new Configuration();
ServiceRegistryUtil.applySettings( cfg.getStandardServiceRegistryBuilder() );
cfg.configure( "org/hibernate/orm/test/annotations/hibernate.cfg.xml" );
cfg.addAnnotatedClass( Port.class );
cfg.setProperty( Environment.HBM2DDL_AUTO, "create-drop" );

View File

@ -1,67 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
//$Id$
package org.hibernate.orm.test.annotations;
import java.util.Properties;
import org.hibernate.HibernateException;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.Environment;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.testing.ServiceRegistryBuilder;
import org.junit.Assert;
import org.junit.Test;
/**
* @author Emmanuel Bernard
*/
public class SecuredBindingTest {
@Test
public void testConfigurationMethods() {
Configuration ac = new Configuration();
Properties p = new Properties();
p.put( Environment.DIALECT, "org.hibernate.dialect.HSQLDialect" );
p.put( "hibernate.connection.driver_class", "org.hsqldb.jdbcDrive" );
p.put( "hibernate.connection.url", "jdbc:hsqldb:." );
p.put( "hibernate.connection.username", "sa" );
p.put( "hibernate.connection.password", "" );
p.put( "hibernate.show_sql", "true" );
ac.setProperties( p );
ac.addAnnotatedClass( Plane.class );
SessionFactory sf=null;
ServiceRegistry serviceRegistry = null;
try {
serviceRegistry = ServiceRegistryBuilder.buildServiceRegistry( p );
sf = ac.buildSessionFactory( serviceRegistry );
try {
sf.close();
}
catch (Exception ignore) {
}
Assert.fail( "Driver property overriding should work" );
}
catch (HibernateException he) {
//success
}
finally {
if(sf!=null){
sf.close();
}
if ( serviceRegistry != null ) {
ServiceRegistryBuilder.destroy( serviceRegistry );
}
ac.getStandardServiceRegistryBuilder().getBootstrapServiceRegistry().close();
}
}
}

View File

@ -18,6 +18,7 @@ import org.hibernate.mapping.PersistentClass;
import org.hibernate.mapping.Property;
import org.hibernate.usertype.UserTypeSupport;
import org.hibernate.testing.util.ServiceRegistryUtil;
import org.junit.jupiter.api.Test;
import jakarta.persistence.Basic;
@ -31,7 +32,7 @@ import jakarta.persistence.Table;
public class CollectionAsBasicTest {
@Test
public void testCollectionAsBasic() {
StandardServiceRegistry ssr = new StandardServiceRegistryBuilder().build();
StandardServiceRegistry ssr = ServiceRegistryUtil.serviceRegistry();
try {
Metadata metadata = new MetadataSources(ssr).addAnnotatedClass( Post.class ).getMetadataBuilder().build();
PersistentClass postBinding = metadata.getEntityBinding( Post.class.getName() );

View File

@ -26,6 +26,7 @@ import org.hibernate.mapping.Column;
import org.hibernate.mapping.Table;
import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.orm.junit.BaseUnitTest;
import org.hibernate.testing.util.ServiceRegistryUtil;
import org.junit.jupiter.api.Test;
/**
@ -40,7 +41,7 @@ public class CommentTest {
@Test
@TestForIssue(jiraKey = "HHH-4369")
public void testComments() {
StandardServiceRegistry ssr = new StandardServiceRegistryBuilder().build();
StandardServiceRegistry ssr = ServiceRegistryUtil.serviceRegistry();
Metadata metadata = new MetadataSources(ssr).addAnnotatedClass(TestEntity.class).buildMetadata();
Table table = StreamSupport.stream(metadata.getDatabase().getNamespaces().spliterator(), false)
.flatMap(namespace -> namespace.getTables().stream()).filter(t -> t.getName().equals(TABLE_NAME))

View File

@ -22,6 +22,7 @@ import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.orm.junit.BaseUnitTest;
import org.hibernate.testing.util.ServiceRegistryUtil;
import org.junit.jupiter.api.Test;
import java.math.BigDecimal;
@ -46,7 +47,7 @@ public class CommentsTest {
@Test
@TestForIssue(jiraKey = "HHH-4369")
public void testComments() {
StandardServiceRegistry ssr = new StandardServiceRegistryBuilder().build();
StandardServiceRegistry ssr = ServiceRegistryUtil.serviceRegistry();
Metadata metadata = new MetadataSources(ssr).addAnnotatedClass(TestEntity.class).buildMetadata();
org.hibernate.mapping.Table table = StreamSupport.stream(metadata.getDatabase().getNamespaces().spliterator(), false)
.flatMap(namespace -> namespace.getTables().stream()).filter(t -> t.getName().equals(TABLE_NAME))

View File

@ -19,6 +19,7 @@ import org.hibernate.dialect.H2Dialect;
import org.hibernate.testing.orm.junit.BaseUnitTest;
import org.hibernate.testing.orm.junit.RequiresDialect;
import org.hibernate.testing.util.ServiceRegistryUtil;
import org.junit.jupiter.api.Test;
import jakarta.persistence.PersistenceException;
@ -39,9 +40,10 @@ public class EmbeddableIntegratorTest {
*/
@Test
public void testWithoutIntegrator() {
try (SessionFactory sf = new Configuration().addAnnotatedClass( Investor.class )
.setProperty( "hibernate.hbm2ddl.auto", "create-drop" )
.buildSessionFactory()) {
final Configuration cfg = new Configuration().addAnnotatedClass( Investor.class )
.setProperty( "hibernate.hbm2ddl.auto", "create-drop" );
ServiceRegistryUtil.applySettings( cfg.getStandardServiceRegistryBuilder() );
try (SessionFactory sf = cfg.buildSessionFactory()) {
Session sess = sf.openSession();
try {
sess.getTransaction().begin();
@ -72,10 +74,11 @@ public class EmbeddableIntegratorTest {
@Test
public void testWithTypeContributor() {
try (SessionFactory sf = new Configuration().addAnnotatedClass( Investor.class )
final Configuration cfg = new Configuration().addAnnotatedClass( Investor.class )
.registerTypeContributor( new InvestorTypeContributor() )
.setProperty( "hibernate.hbm2ddl.auto", "create-drop" )
.buildSessionFactory(); Session sess = sf.openSession()) {
.setProperty( "hibernate.hbm2ddl.auto", "create-drop" );
ServiceRegistryUtil.applySettings( cfg.getStandardServiceRegistryBuilder() );
try (SessionFactory sf = cfg.buildSessionFactory(); Session sess = sf.openSession()) {
try {
sess.getTransaction().begin();
Investor myInv = getInvestor();

View File

@ -7,6 +7,7 @@ import org.hibernate.boot.registry.BootstrapServiceRegistryBuilder;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.testing.util.ServiceRegistryUtil;
import org.junit.jupiter.api.Test;
import static org.junit.Assert.assertTrue;
@ -18,8 +19,8 @@ import static org.junit.Assert.fail;
public abstract class AbstractEmbeddableWithManyToManyTest {
@Test
public void test() {
try (BootstrapServiceRegistry serviceRegistry = new BootstrapServiceRegistryBuilder().build();
StandardServiceRegistry ssr = new StandardServiceRegistryBuilder( serviceRegistry ).build()) {
try (BootstrapServiceRegistry bsr = new BootstrapServiceRegistryBuilder().build();
StandardServiceRegistry ssr = ServiceRegistryUtil.serviceRegistryBuilder( bsr ).build()) {
MetadataSources metadataSources = new MetadataSources( ssr );
addResources( metadataSources );
addAnnotatedClasses(metadataSources);

View File

@ -22,6 +22,7 @@ import org.hibernate.mapping.SimpleValue;
import org.hibernate.mapping.Value;
import org.hibernate.type.spi.TypeConfiguration;
import org.hibernate.testing.util.ServiceRegistryUtil;
import org.junit.jupiter.api.Test;
import static org.hibernate.testing.junit4.ExtraAssertions.assertJdbcTypeCode;
@ -34,7 +35,7 @@ public class NestedEmbeddableMetadataTest {
@Test
public void testEnumTypeInterpretation() {
final StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
final StandardServiceRegistry serviceRegistry = ServiceRegistryUtil.serviceRegistryBuilder()
.enableAutoClose()
.applySetting( AvailableSettings.HBM2DDL_AUTO, "create-drop" )
.build();

View File

@ -21,6 +21,7 @@ import org.hibernate.mapping.SimpleValue;
import org.hibernate.mapping.Value;
import org.hibernate.type.spi.TypeConfiguration;
import org.hibernate.testing.util.ServiceRegistryUtil;
import org.junit.jupiter.api.Test;
import static org.hibernate.testing.junit4.ExtraAssertions.assertJdbcTypeCode;
@ -33,7 +34,7 @@ public class FieldAccessedNestedEmbeddableMetadataTest {
@Test
public void testEnumTypeInterpretation() {
StandardServiceRegistry ssr = new StandardServiceRegistryBuilder().build();
StandardServiceRegistry ssr = ServiceRegistryUtil.serviceRegistry();
try {
final Metadata metadata = new MetadataSources( ssr )

View File

@ -15,6 +15,7 @@ import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.Environment;
import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.junit4.BaseUnitTestCase;
import org.hibernate.testing.util.ServiceRegistryUtil;
import org.junit.Test;
/**
@ -26,6 +27,7 @@ public class HibernateAnnotationMappingTest extends BaseUnitTestCase {
@TestForIssue( jiraKey = "HHH-7446" )
public void testUniqueConstraintAnnotationOnNaturalIds() throws Exception {
Configuration configuration = new Configuration();
ServiceRegistryUtil.applySettings( configuration.getStandardServiceRegistryBuilder() );
configuration.setProperty( Environment.HBM2DDL_AUTO, "create-drop" );
configuration.addAnnotatedClass( Month.class);
SessionFactory sf = null;

View File

@ -15,6 +15,7 @@ import org.hibernate.mapping.RootClass;
import org.hibernate.testing.AfterClassOnce;
import org.hibernate.testing.BeforeClassOnce;
import org.hibernate.testing.junit4.BaseUnitTestCase;
import org.hibernate.testing.util.ServiceRegistryUtil;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
@ -28,7 +29,7 @@ public class NewCustomEntityMappingAnnotationsTest extends BaseUnitTestCase {
@BeforeClassOnce
public void setUp() {
ssr = new StandardServiceRegistryBuilder().build();
ssr = ServiceRegistryUtil.serviceRegistry();
metadata = new MetadataSources( ssr )
.addAnnotatedClass( Forest.class )

View File

@ -27,10 +27,10 @@ import org.hibernate.mapping.PersistentClass;
import org.hibernate.mapping.Property;
import org.hibernate.persister.entity.EntityPersister;
import org.hibernate.type.ConvertedBasicType;
import org.hibernate.type.CustomType;
import org.hibernate.type.EnumType;
import org.hibernate.testing.junit4.BaseUnitTestCase;
import org.hibernate.testing.util.ServiceRegistryUtil;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
@ -49,7 +49,7 @@ public class EnumeratedWithMappedSuperclassTest extends BaseUnitTestCase {
@Before
public void before() {
ssr = new StandardServiceRegistryBuilder()
ssr = ServiceRegistryUtil.serviceRegistryBuilder()
.applySetting( AvailableSettings.DIALECT, PostgreSQLDialect.class.getName() )
.applySetting( AvailableSettings.JAKARTA_HBM2DDL_DB_MAJOR_VERSION, "8" )
.applySetting( AvailableSettings.JAKARTA_HBM2DDL_DB_MINOR_VERSION, "1" )

View File

@ -20,6 +20,7 @@ import org.hibernate.service.ServiceRegistry;
import org.hibernate.testing.ServiceRegistryBuilder;
import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.junit4.BaseUnitTestCase;
import org.hibernate.testing.util.ServiceRegistryUtil;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
@ -72,7 +73,7 @@ public class FetchProfileTest extends BaseUnitTestCase {
@Test
public void testWrongAssociationName() {
final MetadataSources metadataSources = new MetadataSources()
final MetadataSources metadataSources = new MetadataSources( ServiceRegistryUtil.serviceRegistry() )
.addAnnotatedClass( Customer2.class )
.addAnnotatedClass( Order.class )
.addAnnotatedClass( Country.class );
@ -94,7 +95,7 @@ public class FetchProfileTest extends BaseUnitTestCase {
@Test
public void testWrongClass() {
final MetadataSources metadataSources = new MetadataSources()
final MetadataSources metadataSources = new MetadataSources( ServiceRegistryUtil.serviceRegistry() )
.addAnnotatedClass( Customer3.class )
.addAnnotatedClass( Order.class )
.addAnnotatedClass( Country.class );
@ -116,7 +117,7 @@ public class FetchProfileTest extends BaseUnitTestCase {
@Test
public void testUnsupportedFetchMode() {
final MetadataSources metadataSources = new MetadataSources()
final MetadataSources metadataSources = new MetadataSources( ServiceRegistryUtil.serviceRegistry() )
.addAnnotatedClass( Customer4.class )
.addAnnotatedClass( Order.class )
.addAnnotatedClass( Country.class );
@ -157,7 +158,7 @@ public class FetchProfileTest extends BaseUnitTestCase {
}
// now the same with no xml
final MetadataSources metadataSources = new MetadataSources()
final MetadataSources metadataSources = new MetadataSources( ServiceRegistryUtil.serviceRegistry() )
.addAnnotatedClass( Customer5.class )
.addAnnotatedClass( Order.class )
.addAnnotatedClass( Country.class );

View File

@ -13,6 +13,7 @@ import org.hibernate.boot.registry.BootstrapServiceRegistry;
import org.hibernate.boot.registry.BootstrapServiceRegistryBuilder;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.testing.util.ServiceRegistryUtil;
import org.junit.jupiter.api.Test;
/**
@ -24,7 +25,7 @@ public class FkCircularityTest {
@Test
public void testJoinedSublcassesInPK() {
MetadataSources metadataSources = new MetadataSources()
MetadataSources metadataSources = new MetadataSources( ServiceRegistryUtil.serviceRegistry() )
.addAnnotatedClass(A.class)
.addAnnotatedClass(B.class)
.addAnnotatedClass(C.class)
@ -42,7 +43,7 @@ public class FkCircularityTest {
@Test
public void testDeepJoinedSuclassesHierachy() {
MetadataSources metadataSources = new MetadataSources()
MetadataSources metadataSources = new MetadataSources( ServiceRegistryUtil.serviceRegistry() )
.addAnnotatedClass(ClassA.class)
.addAnnotatedClass(ClassB.class)
.addAnnotatedClass(ClassC.class)

View File

@ -26,6 +26,7 @@ import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.testing.FailureExpected;
import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.junit4.BaseUnitTestCase;
import org.hibernate.testing.util.ServiceRegistryUtil;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
@ -38,7 +39,7 @@ public class JoinColumnOrFormulaTest extends BaseUnitTestCase {
@Before
public void before() {
ssr = new StandardServiceRegistryBuilder().build();
ssr = ServiceRegistryUtil.serviceRegistry();
}
@After
@ -52,17 +53,15 @@ public class JoinColumnOrFormulaTest extends BaseUnitTestCase {
@TestForIssue( jiraKey = "HHH-9897" )
@FailureExpected( jiraKey = "HHH-9897" )
public void testUseOfJoinColumnOrFormula() {
try (BootstrapServiceRegistry serviceRegistry = new BootstrapServiceRegistryBuilder().build()) {
Metadata metadata = new MetadataSources( serviceRegistry )
.addAnnotatedClass( A.class )
.addAnnotatedClass( D.class )
.buildMetadata();
Metadata metadata = new MetadataSources( ssr )
.addAnnotatedClass( A.class )
.addAnnotatedClass( D.class )
.buildMetadata();
// Binding to the mapping model works after the simple change for HHH-9897
// But building the SessionFactory fails in the collection persister trying to
// use the formula (it expects Columns too)
metadata.buildSessionFactory().close();
}
// Binding to the mapping model works after the simple change for HHH-9897
// But building the SessionFactory fails in the collection persister trying to
// use the formula (it expects Columns too)
metadata.buildSessionFactory().close();
}
@Entity( name = "A" )

View File

@ -14,6 +14,7 @@ import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.testing.orm.junit.BaseUnitTest;
import org.hibernate.testing.orm.junit.ServiceRegistry;
import org.hibernate.testing.util.ServiceRegistryUtil;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@ -37,7 +38,7 @@ public class AndFormulaTest {
@BeforeEach
public void prepareServiceRegistry() {
ssr = new StandardServiceRegistryBuilder().build();
ssr = ServiceRegistryUtil.serviceRegistry();
}
@AfterEach

View File

@ -17,6 +17,7 @@ import org.hibernate.tool.schema.internal.SchemaCreatorImpl;
import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.orm.junit.BaseUnitTest;
import org.hibernate.testing.util.ServiceRegistryUtil;
import org.hibernate.orm.test.annotations.id.entities.Bunny;
import org.hibernate.orm.test.annotations.id.entities.PointyTooth;
@ -41,7 +42,7 @@ public class JoinColumnOverrideTest {
@Test
@TestForIssue(jiraKey = "ANN-748")
public void testBlownPrecision() {
StandardServiceRegistry ssr = new StandardServiceRegistryBuilder()
StandardServiceRegistry ssr = ServiceRegistryUtil.serviceRegistryBuilder()
.applySetting( AvailableSettings.DIALECT, "SQLServer" )
.build();

View File

@ -19,6 +19,7 @@ import org.hibernate.tool.schema.internal.SchemaCreatorImpl;
import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.orm.junit.BaseUnitTest;
import org.hibernate.testing.util.ServiceRegistryUtil;
import org.hibernate.orm.test.annotations.id.sequences.entities.Bunny;
import org.hibernate.orm.test.annotations.id.sequences.entities.PointyTooth;
@ -44,7 +45,7 @@ public class JoinColumnOverrideTest {
@Test
@TestForIssue(jiraKey = "ANN-748")
public void testBlownPrecision() {
StandardServiceRegistry ssr = new StandardServiceRegistryBuilder()
StandardServiceRegistry ssr = ServiceRegistryUtil.serviceRegistryBuilder()
.applySetting( AvailableSettings.DIALECT, "SQLServer" )
.build();
try {

View File

@ -20,6 +20,7 @@ import org.hibernate.boot.registry.BootstrapServiceRegistryBuilder;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase;
import org.hibernate.testing.util.ServiceRegistryUtil;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
@ -220,7 +221,8 @@ public class ImmutableTest extends BaseCoreFunctionalTestCase {
@Test
public void testMisplacedImmutableAnnotation() {
MetadataSources metadataSources = new MetadataSources().addAnnotatedClass( Foobar.class );
MetadataSources metadataSources = new MetadataSources( ServiceRegistryUtil.serviceRegistry() )
.addAnnotatedClass( Foobar.class );
try {
metadataSources.buildMetadata();
// fail( "Expecting exception due to misplaced @Immutable annotation");

View File

@ -14,6 +14,7 @@ import org.hibernate.mapping.PersistentClass;
import org.hibernate.mapping.RootClass;
import org.hibernate.testing.orm.junit.BaseUnitTest;
import org.hibernate.testing.util.ServiceRegistryUtil;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertFalse;
@ -29,7 +30,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
public class DiscriminatorOptionsTest {
@Test
public void testNonDefaultOptions() {
final StandardServiceRegistry ssr = new StandardServiceRegistryBuilder().build();
final StandardServiceRegistry ssr = ServiceRegistryUtil.serviceRegistry();
try {
Metadata metadata = new MetadataSources( ssr )
@ -52,7 +53,7 @@ public class DiscriminatorOptionsTest {
@Test
public void testBaseline() {
final StandardServiceRegistry ssr = new StandardServiceRegistryBuilder().build();
final StandardServiceRegistry ssr = ServiceRegistryUtil.serviceRegistry();
try {
Metadata metadata = new MetadataSources( ssr )
@ -74,7 +75,7 @@ public class DiscriminatorOptionsTest {
@Test
public void testPropertyBasedDiscriminatorForcing() {
final StandardServiceRegistry ssr = new StandardServiceRegistryBuilder().build();
final StandardServiceRegistry ssr = ServiceRegistryUtil.serviceRegistry();
try {
Metadata metadata = new MetadataSources( ssr )

View File

@ -22,6 +22,7 @@ import org.hibernate.internal.SessionFactoryRegistry;
import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.orm.junit.BaseUnitTest;
import org.hibernate.testing.util.ServiceRegistryUtil;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertFalse;
@ -60,7 +61,7 @@ public class DuplicatedDiscriminatorValueTest {
private void tryBuildingSessionFactory(Class... annotatedClasses) {
SessionFactoryRegistry.INSTANCE.clearRegistrations();
final StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().build();
final StandardServiceRegistry serviceRegistry = ServiceRegistryUtil.serviceRegistry();
try {
final MetadataSources metadataSources = new MetadataSources( serviceRegistry );
for ( Class annotatedClass : annotatedClasses ) {

View File

@ -28,6 +28,7 @@ import org.hibernate.tool.schema.internal.exec.GenerationTargetToStdout;
import org.hibernate.testing.orm.junit.DomainModel;
import org.hibernate.testing.util.ServiceRegistryUtil;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
@ -49,7 +50,7 @@ public class ListMappingTest {
@BeforeEach
public void before() {
ssr = new StandardServiceRegistryBuilder()
ssr = ServiceRegistryUtil.serviceRegistryBuilder()
.applySetting( AvailableSettings.FORMAT_SQL, false )
.build();
}

View File

@ -43,6 +43,8 @@ import org.hibernate.testing.DialectChecks;
import org.hibernate.testing.RequiresDialectFeature;
import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.junit4.BaseNonConfigCoreFunctionalTestCase;
import org.hibernate.testing.util.ServiceRegistryUtil;
import org.hibernate.orm.test.annotations.Customer;
import org.hibernate.orm.test.annotations.Discount;
import org.hibernate.orm.test.annotations.Passport;
@ -386,8 +388,7 @@ public class OneToManyTest extends BaseNonConfigCoreFunctionalTestCase {
@Test
public void testOnDeleteWithoutJoinColumn() throws Exception {
StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
.build();
StandardServiceRegistry serviceRegistry = ServiceRegistryUtil.serviceRegistry();
try {
new MetadataSources( serviceRegistry )

View File

@ -8,12 +8,12 @@ import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.model.naming.Identifier;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.mapping.ForeignKey;
import org.hibernate.mapping.Table;
import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.orm.junit.BaseUnitTest;
import org.hibernate.testing.util.ServiceRegistryUtil;
import org.junit.jupiter.api.Test;
import jakarta.persistence.AssociationOverride;
@ -40,7 +40,7 @@ public class OverrideOneToOneJoinColumnTest {
@Test
public void allowIfJoinColumnIsAbsent() {
try (StandardServiceRegistry ssr = new StandardServiceRegistryBuilder().build()) {
try (StandardServiceRegistry ssr = ServiceRegistryUtil.serviceRegistry()) {
final Metadata metadata = new MetadataSources( ssr )
.addAnnotatedClass( Person.class )
.addAnnotatedClass( State.class )
@ -62,7 +62,7 @@ public class OverrideOneToOneJoinColumnTest {
@Test
public void disallowOnSideWithMappedBy() {
try (StandardServiceRegistry ssr = new StandardServiceRegistryBuilder().build()) {
try (StandardServiceRegistry ssr = ServiceRegistryUtil.serviceRegistry()) {
final AnnotationException ex = assertThrows(
AnnotationException.class, () ->
new MetadataSources( ssr )

View File

@ -7,6 +7,7 @@ import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.boot.spi.MetadataImplementor;
import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.util.ServiceRegistryUtil;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
@ -21,7 +22,7 @@ public class MappedSuperClassIdPropertyBasicAttributeOverrideTest {
@Test
public void test() {
try (StandardServiceRegistry ssr = new StandardServiceRegistryBuilder().build()) {
try (StandardServiceRegistry ssr = ServiceRegistryUtil.serviceRegistry()) {
MetadataSources metadataSources = new MetadataSources( ssr );
metadataSources.addAnnotatedClasses( MappedSuperClassWithUuidAsBasic.class );

View File

@ -27,6 +27,7 @@ import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.junit4.BaseUnitTestCase;
import org.hibernate.testing.util.ServiceRegistryUtil;
import org.junit.Test;
import static org.junit.Assert.assertFalse;
@ -41,7 +42,7 @@ public class UniqueConstraintUnitTests extends BaseUnitTestCase {
@Test
@TestForIssue( jiraKey = "HHH-8026" )
public void testUnNamedConstraints() {
StandardServiceRegistry ssr = new StandardServiceRegistryBuilder().build();
StandardServiceRegistry ssr = ServiceRegistryUtil.serviceRegistry();
try {
final Metadata metadata = new MetadataSources( ssr )
@ -75,7 +76,7 @@ public class UniqueConstraintUnitTests extends BaseUnitTestCase {
@Test
@TestForIssue( jiraKey = "HHH-8537" )
public void testNonExistentColumn() {
StandardServiceRegistry ssr = new StandardServiceRegistryBuilder().build();
StandardServiceRegistry ssr = ServiceRegistryUtil.serviceRegistry();
try {
final Metadata metadata = new MetadataSources( ssr )

View File

@ -19,6 +19,7 @@ import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.junit4.BaseUnitTestCase;
import org.hibernate.testing.util.ServiceRegistryUtil;
import org.junit.Test;
/**
@ -44,7 +45,7 @@ public class UniqueConstraintValidationTest extends BaseUnitTestCase {
}
private void buildSessionFactory(Class<?> entity) {
StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().build();
StandardServiceRegistry serviceRegistry = ServiceRegistryUtil.serviceRegistry();
try {
new MetadataSources( serviceRegistry )

View File

@ -19,6 +19,7 @@ import org.hibernate.type.StandardBasicTypes;
import org.hibernate.testing.AfterClassOnce;
import org.hibernate.testing.BeforeClassOnce;
import org.hibernate.testing.junit4.BaseUnitTestCase;
import org.hibernate.testing.util.ServiceRegistryUtil;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
@ -35,7 +36,7 @@ public class TimestampTest extends BaseUnitTestCase {
@BeforeClassOnce
public void setUp() {
ssr = new StandardServiceRegistryBuilder().build();
ssr = ServiceRegistryUtil.serviceRegistry();
metadata = (MetadataImplementor) new MetadataSources( ssr )
.addAnnotatedClass( VMTimestamped.class )
.addAnnotatedClass( DBTimestamped.class )

View File

@ -12,6 +12,7 @@ import org.hibernate.engine.config.spi.ConfigurationService;
import org.hibernate.internal.util.config.ConfigurationException;
import org.hibernate.testing.junit4.BaseUnitTestCase;
import org.hibernate.testing.util.ServiceRegistryUtil;
import org.junit.Test;
import static org.junit.Assert.assertNotNull;
@ -23,7 +24,7 @@ import static org.junit.Assert.fail;
public class CfgXmlParsingTest extends BaseUnitTestCase {
@Test
public void testCfgXmlWithSchemaLocation() {
StandardServiceRegistry ssr = new StandardServiceRegistryBuilder()
StandardServiceRegistry ssr = ServiceRegistryUtil.serviceRegistryBuilder()
.configure( "org/hibernate/orm/test/boot/cfgXml/hibernate.cfg.xml" )
.build();
try {
@ -40,7 +41,7 @@ public class CfgXmlParsingTest extends BaseUnitTestCase {
@Test(expected = ConfigurationException.class )
public void testCfgXmlWithBadNamespaceAndSchemaLocation() {
StandardServiceRegistry ssr = new StandardServiceRegistryBuilder()
StandardServiceRegistry ssr = ServiceRegistryUtil.serviceRegistryBuilder()
.configure( "org/hibernate/orm/test/boot/cfgXml/badnamespace.cfg.xml" )
.build();
StandardServiceRegistryBuilder.destroy( ssr );

View File

@ -20,6 +20,7 @@ import org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl;
import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.junit4.BaseUnitTestCase;
import org.hibernate.testing.util.ServiceRegistryUtil;
import org.junit.Test;
@ -94,7 +95,7 @@ public class CfgXmlResourceNameClosingTest extends BaseUnitTestCase {
BootstrapServiceRegistry bsr = new BootstrapServiceRegistryBuilder()
.applyClassLoaderService( classLoaderService )
.build();
StandardServiceRegistry ssr = new StandardServiceRegistryBuilder( bsr )
StandardServiceRegistry ssr = ServiceRegistryUtil.serviceRegistryBuilder( bsr )
.configure( "org/hibernate/orm/test/boot/cfgXml/hibernate.cfg.xml" )
.build();
try {

View File

@ -34,7 +34,6 @@ import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.boot.spi.BootstrapContext;
import org.hibernate.boot.spi.MetadataImplementor;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.cfg.Environment;
import org.hibernate.dialect.Dialect;
import org.hibernate.dialect.SQLServerDialect;
import org.hibernate.dialect.SybaseDialect;
@ -64,8 +63,8 @@ import org.hibernate.testing.DialectChecks;
import org.hibernate.testing.RequiresDialectFeature;
import org.hibernate.testing.SkipForDialect;
import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.jdbc.SharedDriverManagerConnectionProviderImpl;
import org.hibernate.testing.junit4.CustomParameterized;
import org.hibernate.testing.util.ServiceRegistryUtil;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
@ -287,12 +286,6 @@ public class DefaultCatalogAndSchemaTest {
settings.put( GlobalTemporaryTableStrategy.DROP_ID_TABLES, "true" );
settings.put( LocalTemporaryTableStrategy.DROP_ID_TABLES, "true" );
settings.put( AvailableSettings.JAKARTA_HBM2DDL_CREATE_SCHEMAS, "true" );
if ( !Environment.getProperties().containsKey( Environment.CONNECTION_PROVIDER ) ) {
settings.put(
AvailableSettings.CONNECTION_PROVIDER,
SharedDriverManagerConnectionProviderImpl.getInstance()
);
}
if ( defaultCatalog != null ) {
settings.put( AvailableSettings.DEFAULT_CATALOG, defaultCatalog );
}
@ -300,7 +293,7 @@ public class DefaultCatalogAndSchemaTest {
settings.put( AvailableSettings.DEFAULT_SCHEMA, defaultSchema );
}
final StandardServiceRegistryBuilder ssrb = new StandardServiceRegistryBuilder( bsr );
final StandardServiceRegistryBuilder ssrb = ServiceRegistryUtil.serviceRegistryBuilder( bsr );
ssrb.applySettings( settings );
StandardServiceRegistry registry = ssrb.build();
toClose.add( registry );

View File

@ -17,6 +17,8 @@ import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.boot.spi.XmlMappingBinderAccess;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.testing.util.ServiceRegistryUtil;
/**
* @author Jean-François Boeuf
*/
@ -32,7 +34,7 @@ public class XmlBindingChecker {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
jaxbMarshaller.marshal( hbmMapping, bos );
ByteArrayInputStream is = new ByteArrayInputStream( bos.toByteArray() );
try (ServiceRegistry sr = new StandardServiceRegistryBuilder().build()) {
try (ServiceRegistry sr = ServiceRegistryUtil.serviceRegistry()) {
new XmlMappingBinderAccess( sr ).bind( is );
}
}

View File

@ -47,6 +47,7 @@ import org.hibernate.orm.test.mapping.basic.bitset.BitSetUserType;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.spi.SessionFactoryServiceRegistry;
import org.hibernate.testing.util.ServiceRegistryUtil;
import org.junit.Test;
import jakarta.persistence.AttributeConverter;
@ -303,7 +304,7 @@ public class BootstrapTest {
properties
);
Map<String, Object> integrationSettings = new HashMap<>();
Map<String, Object> integrationSettings = ServiceRegistryUtil.createBaseSettings();
integrationSettings.put(
AvailableSettings.INTERCEPTOR,
new CustomSessionFactoryInterceptor()

View File

@ -21,6 +21,7 @@ import org.hibernate.property.access.spi.Getter;
import org.hibernate.property.access.spi.GetterFieldImpl;
import org.hibernate.property.access.spi.GetterMethodImpl;
import org.hibernate.testing.util.ServiceRegistryUtil;
import org.junit.jupiter.api.Test;
import jakarta.persistence.AccessType;
@ -168,6 +169,7 @@ public class XmlAccessTest {
for ( Class<?> clazz : classesUnderTest ) {
cfg.addAnnotatedClass( clazz );
}
ServiceRegistryUtil.applySettings( cfg.getStandardServiceRegistryBuilder() );
for ( String configFile : configFiles ) {
try (InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream( configFile )) {
cfg.addInputStream( is );

View File

@ -18,6 +18,7 @@ import org.hibernate.boot.spi.MetadataImplementor;
import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.junit4.BaseUnitTestCase;
import org.hibernate.testing.util.ServiceRegistryUtil;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
@ -30,7 +31,7 @@ public class InheritedAttributeOverridingTest extends BaseUnitTestCase {
@Before
public void buildServiceRegistry() {
standardServiceRegistry = new StandardServiceRegistryBuilder().build();
standardServiceRegistry = ServiceRegistryUtil.serviceRegistry();
}
@After

View File

@ -28,6 +28,7 @@ import org.hibernate.testing.orm.junit.DomainModel;
import org.hibernate.testing.orm.junit.DomainModelScope;
import org.hibernate.testing.orm.junit.ServiceRegistry;
import org.hibernate.testing.transaction.TransactionUtil2;
import org.hibernate.testing.util.ServiceRegistryUtil;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.fail;
@ -51,7 +52,7 @@ public class OrderByMappingComplianceTest {
}
private void check(boolean complianceEnabled) {
final StandardServiceRegistry ssr = new StandardServiceRegistryBuilder()
final StandardServiceRegistry ssr = ServiceRegistryUtil.serviceRegistryBuilder()
.applySetting( AvailableSettings.HBM2DDL_AUTO, "create-drop" )
.build();

View File

@ -13,10 +13,13 @@ import jakarta.persistence.spi.PersistenceProvider;
import javax.sql.DataSource;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.dialect.H2Dialect;
import org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl;
import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.jpa.HibernatePersistenceProvider;
import org.hibernate.testing.RequiresDialect;
import org.hibernate.testing.jdbc.DataSourceStub;
import org.hibernate.testing.FailureExpected;
@ -33,6 +36,7 @@ import static org.junit.Assert.assertEquals;
/**
* @author Steve Ebersole
*/
@RequiresDialect( H2Dialect.class )
public class PersistenceUnitInfoTests extends BaseUnitTestCase {
@Test
@TestForIssue( jiraKey = "HHH-13432" )

View File

@ -17,6 +17,7 @@ import org.hibernate.cache.spi.access.AccessType;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.dialect.DatabaseVersion;
import org.hibernate.dialect.Dialect;
import org.hibernate.dialect.H2Dialect;
import org.hibernate.dialect.SimpleDatabaseVersion;
import org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl;
import org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl;
@ -25,10 +26,12 @@ import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.jpa.HibernatePersistenceProvider;
import org.hibernate.persister.entity.EntityPersister;
import org.hibernate.testing.RequiresDialect;
import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.env.ConnectionProviderBuilder;
import org.hibernate.testing.jdbc.DataSourceStub;
import org.hibernate.testing.junit4.BaseUnitTestCase;
import org.hibernate.testing.util.ServiceRegistryUtil;
import org.hibernate.testing.util.jpa.DelegatingPersistenceUnitInfo;
import org.hibernate.testing.util.jpa.PersistenceUnitInfoAdapter;
import org.junit.Test;
@ -50,6 +53,7 @@ import static org.hamcrest.MatcherAssert.assertThat;
/**
* @author Steve Ebersole
*/
@RequiresDialect( H2Dialect.class )
public class PersistenceUnitOverridesTests extends BaseUnitTestCase {
@Test
@ -368,12 +372,12 @@ public class PersistenceUnitOverridesTests extends BaseUnitTestCase {
}
};
final Map<String,Object> integrationSettings = new HashMap<>();
final Map<String,Object> integrationSettings = ServiceRegistryUtil.createBaseSettings();
integrationSettings.put( AvailableSettings.JPA_JDBC_DRIVER, ConnectionProviderBuilder.DRIVER );
integrationSettings.put( AvailableSettings.JPA_JDBC_URL, ConnectionProviderBuilder.URL );
integrationSettings.put( AvailableSettings.JPA_JDBC_USER, ConnectionProviderBuilder.USER );
integrationSettings.put( AvailableSettings.JPA_JDBC_PASSWORD, ConnectionProviderBuilder.PASS );
integrationSettings.put( "hibernate.connection.init_sql", "" );
integrationSettings.put( DriverManagerConnectionProviderImpl.INIT_SQL, "" );
final PersistenceProvider provider = new HibernatePersistenceProvider();
@ -407,12 +411,12 @@ public class PersistenceUnitOverridesTests extends BaseUnitTestCase {
}
};
final Map<String,Object> integrationSettings = new HashMap<>();
final Map<String,Object> integrationSettings = ServiceRegistryUtil.createBaseSettings();
integrationSettings.put( AvailableSettings.JAKARTA_JDBC_DRIVER, ConnectionProviderBuilder.DRIVER );
integrationSettings.put( AvailableSettings.JAKARTA_JDBC_URL, ConnectionProviderBuilder.URL );
integrationSettings.put( AvailableSettings.JAKARTA_JDBC_USER, ConnectionProviderBuilder.USER );
integrationSettings.put( AvailableSettings.JAKARTA_JDBC_PASSWORD, ConnectionProviderBuilder.PASS );
integrationSettings.put( "hibernate.connection.init_sql", "" );
integrationSettings.put( DriverManagerConnectionProviderImpl.INIT_SQL, "" );
final PersistenceProvider provider = new HibernatePersistenceProvider();
@ -448,7 +452,7 @@ public class PersistenceUnitOverridesTests extends BaseUnitTestCase {
final PersistenceProvider provider = new HibernatePersistenceProvider();
final Map integrationSettings = Collections.emptyMap();
final Map integrationSettings = ServiceRegistryUtil.createBaseSettings();
final EntityManagerFactory emf = provider.createContainerEntityManagerFactory(
info,
@ -489,10 +493,8 @@ public class PersistenceUnitOverridesTests extends BaseUnitTestCase {
final PersistenceProvider provider = new HibernatePersistenceProvider();
final Map integrationSettings = Collections.singletonMap(
AvailableSettings.DIALECT,
IntegrationDialect.class.getName()
);
final Map<String, Object> integrationSettings = ServiceRegistryUtil.createBaseSettings();
integrationSettings.put( AvailableSettings.DIALECT, IntegrationDialect.class.getName() );
final EntityManagerFactory emf = provider.createContainerEntityManagerFactory(
info,

View File

@ -9,6 +9,7 @@ package org.hibernate.orm.test.bootstrap.scanning;
import java.io.File;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Properties;
import org.hibernate.SessionFactory;
@ -40,6 +41,7 @@ import org.hibernate.orm.test.jpa.pack.various.Seat;
import org.hibernate.stat.Statistics;
import org.hibernate.testing.transaction.TransactionUtil;
import org.hibernate.testing.util.ServiceRegistryUtil;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
@ -64,7 +66,6 @@ import static org.junit.jupiter.api.Assertions.fail;
* @author Gavin King
* @author Hardy Ferentschik
*/
@SuppressWarnings("unchecked")
public class PackagedEntityManagerTest extends PackagingTestCase {
private EntityManagerFactory emf;
@AfterEach
@ -80,7 +81,7 @@ public class PackagedEntityManagerTest extends PackagingTestCase {
addPackageToClasspath( testPackage );
// run the test
emf = Persistence.createEntityManagerFactory( "defaultpar", new HashMap() );
emf = Persistence.createEntityManagerFactory( "defaultpar", ServiceRegistryUtil.createBaseSettings() );
TransactionUtil.doInJPA( () -> emf, em -> {
ApplicationServer as = new ApplicationServer();
as.setName( "JBoss AS" );
@ -111,7 +112,7 @@ public class PackagedEntityManagerTest extends PackagingTestCase {
File testPackage = buildDefaultPar_1_0();
addPackageToClasspath( testPackage );
emf = Persistence.createEntityManagerFactory( "defaultpar_1_0", new HashMap() );
emf = Persistence.createEntityManagerFactory( "defaultpar_1_0", ServiceRegistryUtil.createBaseSettings() );
TransactionUtil.doInJPA( () -> emf, em -> {
ApplicationServer1 as = new ApplicationServer1();
as.setName( "JBoss AS" );
@ -144,7 +145,7 @@ public class PackagedEntityManagerTest extends PackagingTestCase {
IncrementListener.reset();
OtherIncrementListener.reset();
emf = Persistence.createEntityManagerFactory( "defaultpar", new HashMap() );
emf = Persistence.createEntityManagerFactory( "defaultpar", ServiceRegistryUtil.createBaseSettings() );
TransactionUtil.doInJPA( () -> emf, em -> {
ApplicationServer as = new ApplicationServer();
as.setName( "JBoss AS" );
@ -179,7 +180,7 @@ public class PackagedEntityManagerTest extends PackagingTestCase {
File testPackage = buildExplodedPar();
addPackageToClasspath( testPackage );
emf = Persistence.createEntityManagerFactory( "explodedpar", new HashMap() );
emf = Persistence.createEntityManagerFactory( "explodedpar", ServiceRegistryUtil.createBaseSettings() );
TransactionUtil.doInJPA( () -> emf, em -> {
Carpet carpet = new Carpet();
Elephant el = new Elephant();
@ -199,7 +200,7 @@ public class PackagedEntityManagerTest extends PackagingTestCase {
addPackageToClasspath( testPackage );
try {
emf = Persistence.createEntityManagerFactory( "excludehbmpar", new HashMap() );
emf = Persistence.createEntityManagerFactory( "excludehbmpar", ServiceRegistryUtil.createBaseSettings() );
}
catch ( PersistenceException e ) {
if ( emf != null ) {
@ -235,7 +236,7 @@ public class PackagedEntityManagerTest extends PackagingTestCase {
File testPackage = buildCfgXmlPar();
addPackageToClasspath( testPackage );
emf = Persistence.createEntityManagerFactory( "cfgxmlpar", new HashMap() );
emf = Persistence.createEntityManagerFactory( "cfgxmlpar", ServiceRegistryUtil.createBaseSettings() );
assertTrue( emf.getProperties().containsKey( "hibernate.test-assertable-setting" ) );
@ -261,7 +262,7 @@ public class PackagedEntityManagerTest extends PackagingTestCase {
File testPackage = buildSpacePar();
addPackageToClasspath( testPackage );
emf = Persistence.createEntityManagerFactory( "space par", new HashMap() );
emf = Persistence.createEntityManagerFactory( "space par", ServiceRegistryUtil.createBaseSettings() );
TransactionUtil.doInJPA( () -> emf, em -> {
org.hibernate.orm.test.jpa.pack.spacepar.Bug bug = new org.hibernate.orm.test.jpa.pack.spacepar.Bug();
bug.setSubject( "Spaces in directory name don't play well on Windows" );
@ -278,11 +279,12 @@ public class PackagedEntityManagerTest extends PackagingTestCase {
File testPackage = buildOverridenPar();
addPackageToClasspath( testPackage );
HashMap properties = new HashMap();
Map<String, Object> properties = ServiceRegistryUtil.createBaseSettings();
properties.put( AvailableSettings.JPA_JTA_DATASOURCE, null );
Properties p = new Properties();
p.load( ConfigHelper.getResourceAsStream( "/overridenpar.properties" ) );
properties.putAll( p );
//noinspection rawtypes
properties.putAll( (Map) p );
emf = Persistence.createEntityManagerFactory( "overridenpar", properties );
TransactionUtil.doInJPA( () -> emf, em -> {
org.hibernate.orm.test.jpa.pack.overridenpar.Bug bug = new org.hibernate.orm.test.jpa.pack.overridenpar.Bug();
@ -300,7 +302,7 @@ public class PackagedEntityManagerTest extends PackagingTestCase {
File testPackage = buildExplicitPar();
addPackageToClasspath( testPackage );
emf = Persistence.createEntityManagerFactory( "manager1", new HashMap() );
emf = Persistence.createEntityManagerFactory( "manager1", ServiceRegistryUtil.createBaseSettings() );
EntityManager em = emf.createEntityManager();
try {
EventListenerRegistry listenerRegistry = em.unwrap( SharedSessionContractImplementor.class ).getFactory()
@ -322,7 +324,7 @@ public class PackagedEntityManagerTest extends PackagingTestCase {
File testPackage = buildExplicitPar();
addPackageToClasspath( testPackage );
emf = Persistence.createEntityManagerFactory( "manager1", new HashMap() );
emf = Persistence.createEntityManagerFactory( "manager1", ServiceRegistryUtil.createBaseSettings() );
TransactionUtil.doInJPA( () -> emf, em -> {
Item item = new Item( "Mouse", "Micro$oft mouse" );
em.persist( item );
@ -368,7 +370,7 @@ public class PackagedEntityManagerTest extends PackagingTestCase {
File testPackage = buildExplicitPar();
addPackageToClasspath( testPackage );
emf = Persistence.createEntityManagerFactory( "manager1", new HashMap() );
emf = Persistence.createEntityManagerFactory( "manager1", ServiceRegistryUtil.createBaseSettings() );
Item item = new Item( "Mouse", "Micro$oft mouse" );
Distributor res = new Distributor();
res.setName( "Bruce" );
@ -413,7 +415,7 @@ public class PackagedEntityManagerTest extends PackagingTestCase {
File testPackage = buildExplicitPar();
addPackageToClasspath( testPackage, externalJar );
emf = Persistence.createEntityManagerFactory( "manager1", new HashMap() );
emf = Persistence.createEntityManagerFactory( "manager1", ServiceRegistryUtil.createBaseSettings() );
Scooter scooter = TransactionUtil.doInJPA( () -> emf, em -> {
Scooter s = new Scooter();
s.setModel( "Abadah" );
@ -435,7 +437,7 @@ public class PackagedEntityManagerTest extends PackagingTestCase {
addPackageToClasspath( testPackage, externalJar );
// if the jar cannot be resolved, this call should fail
emf = Persistence.createEntityManagerFactory( "manager1", new HashMap() );
emf = Persistence.createEntityManagerFactory( "manager1", ServiceRegistryUtil.createBaseSettings() );
// but to make sure, also verify that the entity defined in the external jar was found
emf.getMetamodel().entity( Airplane.class );
@ -461,7 +463,7 @@ public class PackagedEntityManagerTest extends PackagingTestCase {
File testPackage = buildExplicitPar();
addPackageToClasspath( testPackage );
emf = Persistence.createEntityManagerFactory( "manager1", new HashMap() );
emf = Persistence.createEntityManagerFactory( "manager1", ServiceRegistryUtil.createBaseSettings() );
TransactionUtil.doInJPA( () -> emf, em -> {
Seat seat = new Seat();
seat.setNumber( "3B" );

View File

@ -9,6 +9,8 @@ package org.hibernate.orm.test.bootstrap.scanning;
import java.io.File;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.Persistence;
@ -28,6 +30,7 @@ import org.hibernate.jpa.boot.spi.PersistenceUnitDescriptor;
import org.hibernate.orm.test.jpa.pack.defaultpar.ApplicationServer;
import org.hibernate.orm.test.jpa.pack.defaultpar.Version;
import org.hibernate.testing.util.ServiceRegistryUtil;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
@ -87,7 +90,7 @@ public class ScannerTest extends PackagingTestCase {
EntityManagerFactory emf;
CustomScanner.resetUsed();
final HashMap integration = new HashMap();
final Map<String, Object> integration = ServiceRegistryUtil.createBaseSettings();
emf = Persistence.createEntityManagerFactory( "defaultpar", integration );
assertTrue( ! CustomScanner.isUsed() );
emf.close();
@ -104,7 +107,7 @@ public class ScannerTest extends PackagingTestCase {
emf.close();
CustomScanner.resetUsed();
emf = Persistence.createEntityManagerFactory( "defaultpar", null );
emf = Persistence.createEntityManagerFactory( "defaultpar", ServiceRegistryUtil.createBaseSettings() );
assertTrue( ! CustomScanner.isUsed() );
emf.close();
}

View File

@ -23,6 +23,7 @@ import org.hibernate.service.spi.ServiceRegistryImplementor;
import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.cache.CachingRegionFactory;
import org.hibernate.testing.logger.LoggerInspectionRule;
import org.hibernate.testing.util.ServiceRegistryUtil;
import org.hibernate.testing.logger.Triggerable;
import org.junit.Rule;
import org.junit.Test;
@ -54,7 +55,7 @@ public class NonRootEntityWithCacheAnnotationTest {
settings.put( Environment.CACHE_REGION_FACTORY, CachingRegionFactory.class.getName() );
settings.put( AvailableSettings.JPA_SHARED_CACHE_MODE, SharedCacheMode.ENABLE_SELECTIVE );
try (ServiceRegistryImplementor serviceRegistry = (ServiceRegistryImplementor) new StandardServiceRegistryBuilder()
try (ServiceRegistryImplementor serviceRegistry = (ServiceRegistryImplementor) ServiceRegistryUtil.serviceRegistryBuilder()
.applySettings( settings )
.build()) {

View File

@ -22,6 +22,7 @@ import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.cache.CachingRegionFactory;
import org.hibernate.testing.logger.LoggerInspectionRule;
import org.hibernate.testing.logger.Triggerable;
import org.hibernate.testing.util.ServiceRegistryUtil;
import org.junit.Rule;
import org.junit.Test;
@ -54,7 +55,7 @@ public class NonRootEntityWithCacheableAnnotationTest {
settings.put( AvailableSettings.DEFAULT_CACHE_CONCURRENCY_STRATEGY, "read-write" );
settings.put( AvailableSettings.JPA_SHARED_CACHE_MODE, SharedCacheMode.ENABLE_SELECTIVE );
try (ServiceRegistryImplementor serviceRegistry = (ServiceRegistryImplementor) new StandardServiceRegistryBuilder()
try (ServiceRegistryImplementor serviceRegistry = (ServiceRegistryImplementor) ServiceRegistryUtil.serviceRegistryBuilder()
.applySettings( settings )
.build()) {

View File

@ -20,6 +20,7 @@ import org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionPro
import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider;
import org.hibernate.testing.junit4.BaseUnitTestCase;
import org.hibernate.testing.util.ServiceRegistryUtil;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.equalTo;
@ -32,7 +33,7 @@ import static org.hamcrest.MatcherAssert.assertThat;
public class SingleRegisteredProviderTest extends BaseUnitTestCase {
@Test
public void testCachingExplicitlyDisabled() {
try (final StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
try (final StandardServiceRegistry registry = ServiceRegistryUtil.serviceRegistryBuilder()
.applySetting( AvailableSettings.USE_SECOND_LEVEL_CACHE, "false" )
.build()) {
assertThat( registry.getService( RegionFactory.class ), instanceOf( NoCachingRegionFactory.class ) );
@ -49,7 +50,7 @@ public class SingleRegisteredProviderTest extends BaseUnitTestCase {
assertThat( implementors.size(), equalTo( 1 ) );
final StandardServiceRegistry ssr = new StandardServiceRegistryBuilder( bsr )
final StandardServiceRegistry ssr = ServiceRegistryUtil.serviceRegistryBuilder( bsr )
.applySetting( AvailableSettings.USE_SECOND_LEVEL_CACHE, "" )
.build();
@ -72,7 +73,7 @@ public class SingleRegisteredProviderTest extends BaseUnitTestCase {
implementors.iterator().next()
);
final StandardServiceRegistry ssr = new StandardServiceRegistryBuilder( bsr )
final StandardServiceRegistry ssr = ServiceRegistryUtil.serviceRegistryBuilder( bsr )
.applySetting( AvailableSettings.USE_SECOND_LEVEL_CACHE, "" )
.build();
@ -96,7 +97,7 @@ public class SingleRegisteredProviderTest extends BaseUnitTestCase {
DriverManagerConnectionProviderImpl.class
);
final StandardServiceRegistry ssr = new StandardServiceRegistryBuilder( bsr ).build();
final StandardServiceRegistry ssr = ServiceRegistryUtil.serviceRegistryBuilder( bsr ).build();
final ConnectionProvider configuredProvider = ssr.getService( ConnectionProvider.class );

View File

@ -15,6 +15,7 @@ import org.hibernate.cfg.AvailableSettings;
import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.junit4.BaseUnitTestCase;
import org.hibernate.testing.util.ServiceRegistryUtil;
import org.junit.Test;
/**
@ -27,7 +28,7 @@ public class NonAggregatedCompositeIdCachingTest extends BaseUnitTestCase {
public void testNonAggregatedCompositeId() {
// HHH-9913 reports a NPE when bootstrapping a SF with non-aggregated composite identifiers
// in org.hibernate.cache.internal.CacheDataDescriptionImpl#decode
StandardServiceRegistry ssr = new StandardServiceRegistryBuilder()
StandardServiceRegistry ssr = ServiceRegistryUtil.serviceRegistryBuilder()
.applySetting( AvailableSettings.USE_SECOND_LEVEL_CACHE, true )
.build();
@ -49,7 +50,7 @@ public class NonAggregatedCompositeIdCachingTest extends BaseUnitTestCase {
public void testNonAggregatedCompositeIdWithPkClass() {
// HHH-9913 reports a NPE when bootstrapping a SF with non-aggregated composite identifiers
// in org.hibernate.cache.internal.CacheDataDescriptionImpl#decode
StandardServiceRegistry ssr = new StandardServiceRegistryBuilder().build();
StandardServiceRegistry ssr = ServiceRegistryUtil.serviceRegistry();
try {
new MetadataSources( ssr )

View File

@ -15,7 +15,6 @@ import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.SessionFactoryBuilder;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cache.internal.CacheKeyImplementation;
import org.hibernate.cache.internal.DefaultCacheKeysFactory;
import org.hibernate.engine.spi.SessionFactoryImplementor;
@ -23,6 +22,7 @@ import org.hibernate.persister.entity.EntityPersister;
import org.hibernate.service.spi.ServiceRegistryImplementor;
import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.util.ServiceRegistryUtil;
import org.junit.Test;
import static org.junit.Assert.assertFalse;
@ -36,30 +36,28 @@ public class CacheKeyImplementationHashCodeTest {
@Test
@TestForIssue( jiraKey = "HHH-12746")
public void test() {
try (ServiceRegistryImplementor serviceRegistry = (
ServiceRegistryImplementor) new StandardServiceRegistryBuilder().build()) {
try (ServiceRegistryImplementor serviceRegistry = ServiceRegistryUtil.serviceRegistry()) {
MetadataSources ms = new MetadataSources( serviceRegistry );
ms.addAnnotatedClass( AnEntity.class ).addAnnotatedClass( AnotherEntity.class );
Metadata metadata = ms.buildMetadata();
final SessionFactoryBuilder sfb = metadata.getSessionFactoryBuilder();
SessionFactoryImplementor sessionFactory = (SessionFactoryImplementor) sfb.build();
CacheKeyImplementation anEntityCacheKey = createCacheKeyImplementation(
1,
sessionFactory.getRuntimeMetamodels()
.getMappingMetamodel()
.getEntityDescriptor( AnEntity.class ),
sessionFactory
);
CacheKeyImplementation anotherEntityCacheKey = createCacheKeyImplementation(
1,
sessionFactory.getRuntimeMetamodels()
.getMappingMetamodel()
.getEntityDescriptor( AnotherEntity.class ),
sessionFactory
);
assertFalse( anEntityCacheKey.equals( anotherEntityCacheKey ) );
try ( SessionFactoryImplementor sessionFactory = (SessionFactoryImplementor) sfb.build()) {
CacheKeyImplementation anEntityCacheKey = createCacheKeyImplementation(
1,
sessionFactory.getRuntimeMetamodels()
.getMappingMetamodel()
.getEntityDescriptor( AnEntity.class ),
sessionFactory
);
CacheKeyImplementation anotherEntityCacheKey = createCacheKeyImplementation(
1,
sessionFactory.getRuntimeMetamodels()
.getMappingMetamodel()
.getEntityDescriptor( AnotherEntity.class ),
sessionFactory
);
assertFalse( anEntityCacheKey.equals( anotherEntityCacheKey ) );
}
}
}

View File

@ -20,6 +20,7 @@ import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.hibernate.cfg.Configuration;
import org.hibernate.dialect.CockroachDialect;
import org.hibernate.dialect.DerbyDialect;
import org.hibernate.dialect.HSQLDialect;
import org.hibernate.dialect.SybaseASEDialect;
@ -67,6 +68,7 @@ public class ReadWriteCacheTest extends BaseCoreFunctionalTestCase {
@Test
@SkipForDialect(value = CockroachDialect.class, comment = "CockroachDB uses SERIALIZABLE isolation, and does not support this")
@SkipForDialect(value = HSQLDialect.class, comment = "HSQLDB seems to block on acquiring a SHARE lock when a different TX upgraded a SHARE to EXCLUSIVE lock, maybe the upgrade caused a table lock?")
@SkipForDialect(value = DerbyDialect.class, comment = "HSQLDB seems to block on acquiring a SHARE lock when a different TX upgraded a SHARE to EXCLUSIVE lock, maybe the upgrade caused a table lock?")
@SkipForDialect(value = SybaseASEDialect.class, comment = "Sybase seems to block on acquiring a SHARE lock when a different TX upgraded a SHARE to EXCLUSIVE lock, maybe the upgrade caused a table lock?")
public void testDelete() throws InterruptedException {
bookId = 1L;
@ -146,6 +148,7 @@ public class ReadWriteCacheTest extends BaseCoreFunctionalTestCase {
@Test
@SkipForDialect(value = CockroachDialect.class, comment = "CockroachDB uses SERIALIZABLE isolation, and does not support this")
@SkipForDialect(value = HSQLDialect.class, comment = "HSQLDB seems to block on acquiring a SHARE lock when a different TX upgraded a SHARE to EXCLUSIVE lock, maybe the upgrade caused a table lock?")
@SkipForDialect(value = DerbyDialect.class, comment = "HSQLDB seems to block on acquiring a SHARE lock when a different TX upgraded a SHARE to EXCLUSIVE lock, maybe the upgrade caused a table lock?")
@SkipForDialect(value = SybaseASEDialect.class, comment = "Sybase seems to block on acquiring a SHARE lock when a different TX upgraded a SHARE to EXCLUSIVE lock, maybe the upgrade caused a table lock?")
public void testUpdate() throws InterruptedException {
bookId = 4L;

View File

@ -19,6 +19,8 @@ import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.tool.schema.Action;
import org.hibernate.testing.junit4.BaseUnitTestCase;
import org.hibernate.testing.util.ServiceRegistryUtil;
import org.hibernate.orm.test.cdi.converters.ConverterBean;
import org.hibernate.orm.test.cdi.converters.MonitorBean;
import org.hibernate.orm.test.cdi.converters.TheEntity;
@ -44,7 +46,7 @@ public class DelayedCdiHostedConverterTest extends BaseUnitTestCase {
try ( final SeContainer cdiContainer = cdiInitializer.initialize() ) {
BootstrapServiceRegistry bsr = new BootstrapServiceRegistryBuilder().build();
final StandardServiceRegistry ssr = new StandardServiceRegistryBuilder( bsr )
final StandardServiceRegistry ssr = ServiceRegistryUtil.serviceRegistryBuilder( bsr )
.applySetting( AvailableSettings.HBM2DDL_AUTO, Action.CREATE_DROP )
.applySetting( AvailableSettings.CDI_BEAN_MANAGER, cdiContainer.getBeanManager() )
.applySetting( AvailableSettings.DELAY_CDI_ACCESS, "true" )

View File

@ -23,6 +23,8 @@ import org.hibernate.tool.schema.Action;
import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.junit4.BaseUnitTestCase;
import org.hibernate.testing.util.ServiceRegistryUtil;
import org.hibernate.orm.test.cdi.converters.ConverterBean;
import org.hibernate.orm.test.cdi.converters.MonitorBean;
import org.hibernate.orm.test.cdi.converters.TheEntity;
@ -47,7 +49,7 @@ public class CdiHostedConverterTest extends BaseUnitTestCase {
try ( final SeContainer cdiContainer = cdiInitializer.initialize() ) {
BootstrapServiceRegistry bsr = new BootstrapServiceRegistryBuilder().build();
final StandardServiceRegistry ssr = new StandardServiceRegistryBuilder( bsr )
final StandardServiceRegistry ssr = ServiceRegistryUtil.serviceRegistryBuilder( bsr )
.applySetting( AvailableSettings.HBM2DDL_AUTO, Action.CREATE_DROP )
.applySetting( AvailableSettings.CDI_BEAN_MANAGER, cdiContainer.getBeanManager() )
.build();
@ -115,7 +117,7 @@ public class CdiHostedConverterTest extends BaseUnitTestCase {
try ( final SeContainer cdiContainer = cdiInitializer.initialize() ) {
BootstrapServiceRegistry bsr = new BootstrapServiceRegistryBuilder().build();
final StandardServiceRegistry ssr = new StandardServiceRegistryBuilder( bsr )
final StandardServiceRegistry ssr = ServiceRegistryUtil.serviceRegistryBuilder( bsr )
.applySetting( AvailableSettings.HBM2DDL_AUTO, Action.CREATE_DROP )
.applySetting( AvailableSettings.CDI_BEAN_MANAGER, cdiContainer.getBeanManager() )
.build();

View File

@ -19,6 +19,8 @@ import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.tool.schema.Action;
import org.hibernate.testing.junit4.BaseUnitTestCase;
import org.hibernate.testing.util.ServiceRegistryUtil;
import org.hibernate.orm.test.cdi.events.Monitor;
import org.hibernate.orm.test.cdi.events.TheEntity;
import org.hibernate.orm.test.cdi.events.TheListener;
@ -47,7 +49,7 @@ public class DelayedCdiSupportTest extends BaseUnitTestCase {
try ( final SeContainer cdiContainer = cdiInitializer.initialize() ) {
BootstrapServiceRegistry bsr = new BootstrapServiceRegistryBuilder().build();
final StandardServiceRegistry ssr = new StandardServiceRegistryBuilder( bsr )
final StandardServiceRegistry ssr = ServiceRegistryUtil.serviceRegistryBuilder( bsr )
.applySetting( AvailableSettings.HBM2DDL_AUTO, Action.CREATE_DROP )
.applySetting( AvailableSettings.CDI_BEAN_MANAGER, cdiContainer.getBeanManager() )
.applySetting( AvailableSettings.DELAY_CDI_ACCESS, "true" )

View File

@ -16,6 +16,8 @@ import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.tool.schema.Action;
import org.hibernate.testing.junit4.BaseUnitTestCase;
import org.hibernate.testing.util.ServiceRegistryUtil;
import org.hibernate.orm.test.cdi.events.Monitor;
import org.hibernate.orm.test.cdi.events.TheEntity;
import org.hibernate.orm.test.cdi.testsupport.TestingExtendedBeanManager;
@ -43,7 +45,7 @@ public class InvalidExtendedCdiSupportTest extends BaseUnitTestCase {
BootstrapServiceRegistry bsr = new BootstrapServiceRegistryBuilder().build();
final StandardServiceRegistry ssr = new StandardServiceRegistryBuilder( bsr )
final StandardServiceRegistry ssr = ServiceRegistryUtil.serviceRegistryBuilder( bsr )
.applySetting( AvailableSettings.HBM2DDL_AUTO, Action.CREATE_DROP )
.applySetting( AvailableSettings.CDI_BEAN_MANAGER, beanManager )
.build();

View File

@ -19,6 +19,8 @@ import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.tool.schema.Action;
import org.hibernate.testing.junit4.BaseUnitTestCase;
import org.hibernate.testing.util.ServiceRegistryUtil;
import org.hibernate.orm.test.cdi.events.Monitor;
import org.hibernate.orm.test.cdi.events.TheEntity;
import org.hibernate.orm.test.cdi.events.TheListener;
@ -48,7 +50,7 @@ public class ValidExtendedCdiSupportTest extends BaseUnitTestCase {
BootstrapServiceRegistry bsr = new BootstrapServiceRegistryBuilder().build();
final StandardServiceRegistry ssr = new StandardServiceRegistryBuilder( bsr )
final StandardServiceRegistry ssr = ServiceRegistryUtil.serviceRegistryBuilder( bsr )
.applySetting( AvailableSettings.HBM2DDL_AUTO, Action.CREATE_DROP )
.applySetting( AvailableSettings.CDI_BEAN_MANAGER, beanManager )
.build();

View File

@ -17,6 +17,8 @@ import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.tool.schema.Action;
import org.hibernate.testing.junit4.BaseUnitTestCase;
import org.hibernate.testing.util.ServiceRegistryUtil;
import org.hibernate.orm.test.cdi.events.Monitor;
import org.hibernate.orm.test.cdi.events.TheEntity;
import org.junit.Test;
@ -37,7 +39,7 @@ public class InvalidNoCdiSupportTest extends BaseUnitTestCase {
BootstrapServiceRegistry bsr = new BootstrapServiceRegistryBuilder().build();
final StandardServiceRegistry ssr = new StandardServiceRegistryBuilder( bsr )
final StandardServiceRegistry ssr = ServiceRegistryUtil.serviceRegistryBuilder( bsr )
.applySetting( AvailableSettings.HBM2DDL_AUTO, Action.CREATE_DROP )
.build();

View File

@ -23,6 +23,7 @@ import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.tool.schema.Action;
import org.hibernate.testing.junit4.BaseUnitTestCase;
import org.hibernate.testing.util.ServiceRegistryUtil;
import org.junit.Test;
import static org.hibernate.testing.transaction.TransactionUtil2.inTransaction;
@ -43,7 +44,7 @@ public class ValidNoCdiSupportTest extends BaseUnitTestCase {
BootstrapServiceRegistry bsr = new BootstrapServiceRegistryBuilder().build();
final StandardServiceRegistry ssr = new StandardServiceRegistryBuilder( bsr )
final StandardServiceRegistry ssr = ServiceRegistryUtil.serviceRegistryBuilder( bsr )
.applySetting( AvailableSettings.HBM2DDL_AUTO, Action.CREATE_DROP )
.build();

View File

@ -19,6 +19,8 @@ import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.tool.schema.Action;
import org.hibernate.testing.junit4.BaseUnitTestCase;
import org.hibernate.testing.util.ServiceRegistryUtil;
import org.hibernate.orm.test.cdi.events.Monitor;
import org.hibernate.orm.test.cdi.events.TheEntity;
import org.hibernate.orm.test.cdi.events.TheListener;
@ -46,7 +48,7 @@ public class StandardCdiSupportTest extends BaseUnitTestCase {
try ( final SeContainer cdiContainer = cdiInitializer.initialize() ) {
BootstrapServiceRegistry bsr = new BootstrapServiceRegistryBuilder().build();
final StandardServiceRegistry ssr = new StandardServiceRegistryBuilder( bsr )
final StandardServiceRegistry ssr = ServiceRegistryUtil.serviceRegistryBuilder( bsr )
.applySetting( AvailableSettings.HBM2DDL_AUTO, Action.CREATE_DROP )
.applySetting( AvailableSettings.CDI_BEAN_MANAGER, cdiContainer.getBeanManager() )
.build();

View File

@ -20,6 +20,7 @@ import org.hibernate.resource.beans.container.spi.ContainedBean;
import org.hibernate.resource.beans.internal.FallbackBeanInstanceProducer;
import org.hibernate.tool.schema.Action;
import org.hibernate.testing.util.ServiceRegistryUtil;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.instanceOf;
@ -44,7 +45,7 @@ public class DelayedMixedAccessTest implements BeanContainer.LifecycleOptions {
public void testDelayedMixedAccess() {
try ( final SeContainer cdiContainer = Helper.createSeContainer();
final BootstrapServiceRegistry bsr = new BootstrapServiceRegistryBuilder().build();
final StandardServiceRegistry ssr = new StandardServiceRegistryBuilder( bsr )
final StandardServiceRegistry ssr = ServiceRegistryUtil.serviceRegistryBuilder( bsr )
.applySetting( AvailableSettings.HBM2DDL_AUTO, Action.CREATE_DROP )
.applySetting( AvailableSettings.CDI_BEAN_MANAGER, cdiContainer.getBeanManager() )
.applySetting( AvailableSettings.DELAY_CDI_ACCESS, "true" )

View File

@ -20,6 +20,8 @@ import org.hibernate.resource.beans.spi.ManagedBeanRegistry;
import org.hibernate.tool.schema.Action;
import org.hibernate.orm.test.cdi.testsupport.TestingExtendedBeanManager;
import org.hibernate.testing.util.ServiceRegistryUtil;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.instanceOf;
@ -37,7 +39,7 @@ public class ExtendedMixedAccessTest implements BeanContainer.LifecycleOptions {
}
private void doTest(TestingExtendedBeanManager extendedBeanManager) {
try (final StandardServiceRegistry ssr = new StandardServiceRegistryBuilder()
try (final StandardServiceRegistry ssr = ServiceRegistryUtil.serviceRegistryBuilder()
.applySetting( AvailableSettings.HBM2DDL_AUTO, Action.CREATE_DROP )
.applySetting( AvailableSettings.CDI_BEAN_MANAGER, extendedBeanManager )
.build()) {

View File

@ -20,6 +20,7 @@ import org.hibernate.resource.beans.container.spi.ContainedBean;
import org.hibernate.resource.beans.internal.FallbackBeanInstanceProducer;
import org.hibernate.tool.schema.Action;
import org.hibernate.testing.util.ServiceRegistryUtil;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.instanceOf;
@ -47,7 +48,7 @@ public class ImmediateMixedAccessTests implements BeanContainer.LifecycleOptions
try ( final SeContainer cdiContainer = Helper.createSeContainer();
BootstrapServiceRegistry bsr = new BootstrapServiceRegistryBuilder().build() ) {
final StandardServiceRegistry ssr = new StandardServiceRegistryBuilder( bsr )
final StandardServiceRegistry ssr = ServiceRegistryUtil.serviceRegistryBuilder( bsr )
.applySetting( AvailableSettings.HBM2DDL_AUTO, Action.CREATE_DROP )
.applySetting( AvailableSettings.CDI_BEAN_MANAGER, cdiContainer.getBeanManager() )
.build();

View File

@ -21,6 +21,8 @@ import org.hibernate.resource.beans.spi.ManagedBeanRegistry;
import org.hibernate.tool.schema.Action;
import org.hibernate.testing.junit4.BaseUnitTestCase;
import org.hibernate.testing.util.ServiceRegistryUtil;
import org.hibernate.orm.test.cdi.general.nonregistrymanaged.Monitor;
import org.hibernate.orm.test.cdi.general.nonregistrymanaged.NonRegistryManagedBeanConsumingIntegrator;
import org.hibernate.orm.test.cdi.general.nonregistrymanaged.TheAlternativeNamedApplicationScopedBeanImpl;
@ -172,7 +174,7 @@ public class NonRegistryManagedDelayedCdiSupportTest extends BaseUnitTestCase {
.applyIntegrator( beanConsumingIntegrator )
.build();
final StandardServiceRegistry ssr = new StandardServiceRegistryBuilder( bsr )
final StandardServiceRegistry ssr = ServiceRegistryUtil.serviceRegistryBuilder( bsr )
.applySetting( AvailableSettings.HBM2DDL_AUTO, Action.CREATE_DROP )
.applySetting( AvailableSettings.CDI_BEAN_MANAGER, cdiContainer.getBeanManager() )
.applySetting( AvailableSettings.DELAY_CDI_ACCESS, "true" )

View File

@ -21,6 +21,8 @@ import org.hibernate.resource.beans.spi.ManagedBeanRegistry;
import org.hibernate.tool.schema.Action;
import org.hibernate.testing.junit4.BaseUnitTestCase;
import org.hibernate.testing.util.ServiceRegistryUtil;
import org.hibernate.orm.test.cdi.general.nonregistrymanaged.Monitor;
import org.hibernate.orm.test.cdi.general.nonregistrymanaged.NonRegistryManagedBeanConsumingIntegrator;
import org.hibernate.orm.test.cdi.general.nonregistrymanaged.TheAlternativeNamedApplicationScopedBeanImpl;
@ -172,7 +174,7 @@ public class NonRegistryManagedExtendedCdiSupportTest extends BaseUnitTestCase {
.applyIntegrator( beanConsumingIntegrator )
.build();
final StandardServiceRegistry ssr = new StandardServiceRegistryBuilder( bsr )
final StandardServiceRegistry ssr = ServiceRegistryUtil.serviceRegistryBuilder( bsr )
.applySetting( AvailableSettings.HBM2DDL_AUTO, Action.CREATE_DROP )
.applySetting( AvailableSettings.CDI_BEAN_MANAGER, beanManager )
.build();

View File

@ -21,6 +21,8 @@ import org.hibernate.resource.beans.spi.ManagedBeanRegistry;
import org.hibernate.tool.schema.Action;
import org.hibernate.testing.junit4.BaseUnitTestCase;
import org.hibernate.testing.util.ServiceRegistryUtil;
import org.hibernate.orm.test.cdi.general.nonregistrymanaged.Monitor;
import org.hibernate.orm.test.cdi.general.nonregistrymanaged.NonRegistryManagedBeanConsumingIntegrator;
import org.hibernate.orm.test.cdi.general.nonregistrymanaged.TheAlternativeNamedApplicationScopedBeanImpl;
@ -171,7 +173,7 @@ public class NonRegistryManagedStandardCdiSupportTest extends BaseUnitTestCase {
.applyIntegrator( beanConsumingIntegrator )
.build();
final StandardServiceRegistry ssr = new StandardServiceRegistryBuilder( bsr )
final StandardServiceRegistry ssr = ServiceRegistryUtil.serviceRegistryBuilder( bsr )
.applySetting( AvailableSettings.HBM2DDL_AUTO, Action.CREATE_DROP )
.applySetting( AvailableSettings.CDI_BEAN_MANAGER, cdiContainer.getBeanManager() )
.build();

View File

@ -12,6 +12,7 @@ import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.resource.beans.container.spi.ExtendedBeanManager;
import org.hibernate.testing.util.ServiceRegistryUtil;
import org.junit.jupiter.api.Test;
import jakarta.enterprise.inject.spi.BeanManager;
@ -27,7 +28,7 @@ import jakarta.persistence.Table;
public class ExtendedBeanManagerNoCallbackTest {
@Test
public void tryIt() {
final StandardServiceRegistry ssr = new StandardServiceRegistryBuilder()
final StandardServiceRegistry ssr = ServiceRegistryUtil.serviceRegistryBuilder()
.applySetting( AvailableSettings.JAKARTA_CDI_BEAN_MANAGER, new ExtendedBeanManagerImpl() )
.build();

View File

@ -19,6 +19,8 @@ import org.hibernate.cfg.AvailableSettings;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.resource.beans.container.spi.ExtendedBeanManager;
import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.util.ServiceRegistryUtil;
import org.hibernate.usertype.DynamicParameterizedType;
import org.hibernate.usertype.UserType;
import org.junit.jupiter.api.Test;
@ -36,7 +38,7 @@ public class ExtendedBeanManagerNotAvailableDuringCustomUserTypeInitTest {
@Test
public void tryIt() {
// pass ExtendedBeanManager but never initialize it
final StandardServiceRegistry ssr = new StandardServiceRegistryBuilder()
final StandardServiceRegistry ssr = ServiceRegistryUtil.serviceRegistryBuilder()
.applySetting( AvailableSettings.JAKARTA_CDI_BEAN_MANAGER, new ExtendedBeanManagerImpl() )
.build();

View File

@ -18,6 +18,7 @@ import org.hibernate.cfg.AvailableSettings;
import org.hibernate.resource.beans.container.spi.ExtendedBeanManager;
import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.util.ServiceRegistryUtil;
import org.junit.jupiter.api.Test;
import jakarta.enterprise.inject.spi.BeanManager;
@ -27,7 +28,7 @@ public class ExtendedBeanManagerNotAvailableDuringTypeResolutionTest {
@Test
public void tryIt() throws IOException {
final StandardServiceRegistry ssr = new StandardServiceRegistryBuilder()
final StandardServiceRegistry ssr = ServiceRegistryUtil.serviceRegistryBuilder()
.applySetting(
AvailableSettings.JAKARTA_CDI_BEAN_MANAGER,
new ExtendedBeanManagerNotAvailableDuringTypeResolutionTest.ExtendedBeanManagerImpl()

View File

@ -6,6 +6,9 @@
*/
package org.hibernate.orm.test.cdi.lifecycle;
import java.util.HashMap;
import java.util.Map;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.jpa.boot.spi.EntityManagerFactoryBuilder;
import org.hibernate.resource.beans.container.internal.CdiBeanContainerExtendedAccessImpl;
@ -13,12 +16,12 @@ import org.hibernate.resource.beans.container.spi.ExtendedBeanManager;
import org.hibernate.resource.beans.spi.ManagedBeanRegistry;
import org.hibernate.testing.orm.jpa.PersistenceUnitInfoAdapter;
import org.hibernate.testing.util.ServiceRegistryUtil;
import org.junit.jupiter.api.Test;
import jakarta.enterprise.inject.spi.BeanManager;
import jakarta.persistence.EntityManagerFactory;
import static java.util.Collections.singletonMap;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hibernate.cfg.AvailableSettings.CDI_BEAN_MANAGER;
import static org.hibernate.cfg.AvailableSettings.JAKARTA_CDI_BEAN_MANAGER;
@ -41,7 +44,7 @@ public class ExtendedBeanManagerSmokeTests {
final EntityManagerFactoryBuilder emfb = getEntityManagerFactoryBuilder(
new PersistenceUnitInfoAdapter(),
singletonMap( settingName, ref )
integrationSettings( settingName, ref )
);
assertApplied( ref, emfb.build() );
@ -59,12 +62,18 @@ public class ExtendedBeanManagerSmokeTests {
final EntityManagerFactoryBuilder emfb = getEntityManagerFactoryBuilder(
new PersistenceUnitInfoAdapter(),
singletonMap( settingName, ref )
integrationSettings( settingName, ref )
);
assertApplied( ref, emfb.build() );
}
private static Map<String, Object> integrationSettings(String settingName, Object value) {
final Map<String, Object> settings = ServiceRegistryUtil.createBaseSettings();
settings.put( settingName, value );
return settings;
}
private static void assertApplied(ExtendedBeanManagerImpl ref, EntityManagerFactory emf) {
final SessionFactoryImplementor sfi = emf.unwrap( SessionFactoryImplementor.class );
final ManagedBeanRegistry beanRegistry = sfi.getServiceRegistry().getService( ManagedBeanRegistry.class );

View File

@ -21,6 +21,7 @@ import org.hibernate.mapping.PersistentClass;
import org.hibernate.mapping.Property;
import org.hibernate.tool.schema.Action;
import org.hibernate.testing.util.ServiceRegistryUtil;
import org.junit.jupiter.api.Test;
import jakarta.enterprise.inject.se.SeContainer;
@ -41,7 +42,7 @@ public class SimpleTests {
void testProperUsage() {
final ExtendedBeanManagerImpl extendedBeanManager = new ExtendedBeanManagerImpl();
final StandardServiceRegistryBuilder ssrbBuilder = new StandardServiceRegistryBuilder()
final StandardServiceRegistryBuilder ssrbBuilder = ServiceRegistryUtil.serviceRegistryBuilder()
.applySetting( AvailableSettings.HBM2DDL_AUTO, Action.CREATE_DROP )
.applySetting( AvailableSettings.JAKARTA_CDI_BEAN_MANAGER, extendedBeanManager );

View File

@ -10,12 +10,12 @@ import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.model.internal.EntityBinder;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.internal.CoreMessageLogger;
import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.logger.LoggerInspectionRule;
import org.hibernate.testing.logger.Triggerable;
import org.hibernate.testing.util.ServiceRegistryUtil;
import org.junit.Rule;
import org.junit.Test;
@ -42,7 +42,7 @@ public class AnnotationBinderTest {
Triggerable triggerable = logInspection.watchForLogMessages( "HHH000137" );
try (StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().build()) {
try (StandardServiceRegistry serviceRegistry = ServiceRegistryUtil.serviceRegistry()) {
Metadata metadata = new MetadataSources( serviceRegistry )
.addAnnotatedClass( InvalidPrimaryKeyJoinColumnAnnotationEntity.class )

View File

@ -34,6 +34,7 @@ import org.junit.Before;
import org.junit.Test;
import org.hibernate.testing.junit4.BaseUnitTestCase;
import org.hibernate.testing.util.ServiceRegistryUtil;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
@ -49,6 +50,7 @@ public class BatchVersionedDataConfigTest extends BaseUnitTestCase {
@Before
public void setUp() {
cfg = new Configuration();
ServiceRegistryUtil.applySettings( cfg.getStandardServiceRegistryBuilder() );
// HHH-10290 ignore environment property hibernate.jdbc.batch_versioned_data
if (cfg.getProperties().getProperty(AvailableSettings.BATCH_VERSIONED_DATA) != null) {

View File

@ -18,6 +18,7 @@ import org.hibernate.cfg.AvailableSettings;
import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.junit4.BaseUnitTestCase;
import org.hibernate.testing.util.ServiceRegistryUtil;
import org.junit.Test;
import static org.hibernate.internal.util.ConfigHelper.findAsResource;
@ -38,6 +39,7 @@ public class CfgFilePropertyTest extends BaseUnitTestCase {
try {
final Properties props = new Properties();
props.setProperty( AvailableSettings.CFG_XML_FILE, "/org/hibernate/orm/test/boot/cfgXml/hibernate.cfg.xml" );
ServiceRegistryUtil.applySettings( props );
Persistence.createEntityManagerFactory( "ExcludeUnlistedClassesTest1", props );
}

View File

@ -20,6 +20,7 @@ import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.junit4.BaseUnitTestCase;
import org.hibernate.testing.util.ServiceRegistryUtil;
import org.junit.Test;
import static org.junit.Assert.assertFalse;
@ -36,7 +37,7 @@ public class WrongCircularityDetectionTest extends BaseUnitTestCase {
@Test
public void testNoCircularityDetection() {
StandardServiceRegistry ssr = new StandardServiceRegistryBuilder().build();
StandardServiceRegistry ssr = ServiceRegistryUtil.serviceRegistry();
try {
final Metadata metadata = new MetadataSources( ssr )

View File

@ -7,7 +7,9 @@
package org.hibernate.orm.test.cfg.cache;
import org.hibernate.cfg.Configuration;
import org.hibernate.testing.junit4.BaseUnitTestCase;
import org.hibernate.testing.util.ServiceRegistryUtil;
import org.junit.Test;
/**
@ -22,6 +24,7 @@ public class CacheConfigurationTest extends BaseUnitTestCase {
public void testCacheConfiguration() throws Exception {
// we only care if the SF builds successfully.
Configuration cfg = new Configuration().configure(CFG_XML);
ServiceRegistryUtil.applySettings( cfg.getStandardServiceRegistryBuilder() );
cfg.buildSessionFactory().close();
}
}

View File

@ -25,6 +25,7 @@ import org.hibernate.persister.entity.EntityPersister;
import org.hibernate.testing.FailureExpected;
import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.junit4.BaseUnitTestCase;
import org.hibernate.testing.util.ServiceRegistryUtil;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
@ -42,7 +43,7 @@ public class DefaultCacheConcurrencyPropertyTest extends BaseUnitTestCase {
@FailureExpected( jiraKey = "HHH-9763" )
public void testExplicitDefault() {
final StandardServiceRegistry ssr = new StandardServiceRegistryBuilder()
final StandardServiceRegistry ssr = ServiceRegistryUtil.serviceRegistryBuilder()
.applySetting( AvailableSettings.DEFAULT_CACHE_CONCURRENCY_STRATEGY, "read-only" )
.build();
try {

View File

@ -15,6 +15,7 @@ import org.hibernate.persister.spi.PersisterClassResolver;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.testing.junit4.BaseUnitTestCase;
import org.hibernate.testing.util.ServiceRegistryUtil;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
@ -30,7 +31,7 @@ public class PersisterClassProviderTest extends BaseUnitTestCase {
Configuration cfg = new Configuration();
cfg.addAnnotatedClass( Gate.class );
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
ServiceRegistry serviceRegistry = ServiceRegistryUtil.serviceRegistryBuilder()
.applySettings( cfg.getProperties() )
.build();
//no exception as the GoofyPersisterClassProvider is not set
@ -43,7 +44,7 @@ public class PersisterClassProviderTest extends BaseUnitTestCase {
StandardServiceRegistryBuilder.destroy( serviceRegistry );
}
serviceRegistry = new StandardServiceRegistryBuilder()
serviceRegistry = ServiceRegistryUtil.serviceRegistryBuilder()
.applySettings( cfg.getProperties() )
.addService( PersisterClassResolver.class, new GoofyPersisterClassProvider() )
.build();
@ -70,7 +71,7 @@ public class PersisterClassProviderTest extends BaseUnitTestCase {
cfg = new Configuration();
cfg.addAnnotatedClass( Portal.class );
cfg.addAnnotatedClass( Window.class );
serviceRegistry = new StandardServiceRegistryBuilder()
serviceRegistry = ServiceRegistryUtil.serviceRegistryBuilder()
.applySettings( cfg.getProperties() )
.addService( PersisterClassResolver.class, new GoofyPersisterClassProvider() )
.build();
@ -93,7 +94,7 @@ public class PersisterClassProviderTest extends BaseUnitTestCase {
cfg = new Configuration();
cfg.addAnnotatedClass( Tree.class );
cfg.addAnnotatedClass( Palmtree.class );
serviceRegistry = new StandardServiceRegistryBuilder()
serviceRegistry = ServiceRegistryUtil.serviceRegistryBuilder()
.applySettings( cfg.getProperties() )
.addService( PersisterClassResolver.class, new GoofyPersisterClassProvider() )
.build();

View File

@ -23,6 +23,7 @@ import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.loader.MultipleBagFetchException;
import org.hibernate.testing.util.ServiceRegistryUtil;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.fail;
@ -31,7 +32,7 @@ public class MultipleBagFetchTest {
@Test
public void testEntityWithMultipleJoinFetchedBags() {
try (StandardServiceRegistry standardRegistry = new StandardServiceRegistryBuilder().build()) {
try (StandardServiceRegistry standardRegistry = ServiceRegistryUtil.serviceRegistry()) {
Metadata metadata = new MetadataSources( standardRegistry )
.addAnnotatedClass( Post.class )

View File

@ -12,6 +12,7 @@ import org.hibernate.cfg.AvailableSettings;
import org.hibernate.testing.orm.junit.DialectFeatureChecks;
import org.hibernate.testing.orm.junit.JiraKey;
import org.hibernate.testing.orm.junit.RequiresDialectFeature;
import org.hibernate.testing.util.ServiceRegistryUtil;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
@ -28,7 +29,7 @@ public class StructComponentCollectionError2Test {
@Test
@JiraKey( "HHH-15831" )
public void testError() {
final StandardServiceRegistry ssr = new StandardServiceRegistryBuilder()
final StandardServiceRegistry ssr = ServiceRegistryUtil.serviceRegistryBuilder()
.applySetting( AvailableSettings.HBM2DDL_AUTO, "create-drop" ).build();
try {
new MetadataSources( ssr )

View File

@ -10,6 +10,7 @@ import org.hibernate.cfg.AvailableSettings;
import org.hibernate.testing.orm.junit.DialectFeatureChecks;
import org.hibernate.testing.orm.junit.JiraKey;
import org.hibernate.testing.orm.junit.RequiresDialectFeature;
import org.hibernate.testing.util.ServiceRegistryUtil;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
@ -24,7 +25,7 @@ public class StructComponentCollectionError3Test {
@Test
@JiraKey( "HHH-15862" )
public void testError() {
final StandardServiceRegistry ssr = new StandardServiceRegistryBuilder()
final StandardServiceRegistry ssr = ServiceRegistryUtil.serviceRegistryBuilder()
.applySetting( AvailableSettings.HBM2DDL_AUTO, "create-drop" ).build();
try {
new MetadataSources( ssr )

View File

@ -11,6 +11,7 @@ import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.testing.orm.junit.DialectFeatureChecks;
import org.hibernate.testing.orm.junit.JiraKey;
import org.hibernate.testing.orm.junit.RequiresDialectFeature;
import org.hibernate.testing.util.ServiceRegistryUtil;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
@ -26,7 +27,7 @@ public class StructComponentCollectionErrorTest {
@Test
@JiraKey( "HHH-15830" )
public void testError() {
final StandardServiceRegistry ssr = new StandardServiceRegistryBuilder().build();
final StandardServiceRegistry ssr = ServiceRegistryUtil.serviceRegistry();
try {
new MetadataSources( ssr )
.addAnnotatedClass( Book.class )

View File

@ -8,6 +8,7 @@ import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.testing.orm.junit.DialectFeatureChecks;
import org.hibernate.testing.orm.junit.RequiresDialectFeature;
import org.hibernate.testing.util.ServiceRegistryUtil;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
@ -21,7 +22,7 @@ public class StructComponentErrorTest {
@Test
public void testError() {
final StandardServiceRegistry ssr = new StandardServiceRegistryBuilder().build();
final StandardServiceRegistry ssr = ServiceRegistryUtil.serviceRegistry();
try {
new MetadataSources( ssr )
.addAnnotatedClass( Book.class )

View File

@ -10,6 +10,7 @@ import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl;
import org.hibernate.testing.orm.junit.EntityManagerFactoryScope;
@ -25,7 +26,11 @@ import static org.junit.Assert.assertTrue;
*/
@Jpa(
annotatedClasses = { DriverManagerConnectionProviderValidationConfigTest.Event.class },
integrationSettings = @Setting(name = DriverManagerConnectionProviderImpl.VALIDATION_INTERVAL, value = "1")
integrationSettings = {
// Force a non-shared connection provider to avoid re-creation of the shared pool
@Setting(name = AvailableSettings.CONNECTION_PROVIDER, value = ""),
@Setting(name = DriverManagerConnectionProviderImpl.VALIDATION_INTERVAL, value = "1")
}
)
public class DriverManagerConnectionProviderValidationConfigTest {

View File

@ -13,18 +13,12 @@ import java.sql.Statement;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
import jakarta.transaction.RollbackException;
import jakarta.transaction.SystemException;
import javax.transaction.xa.XAException;
import javax.transaction.xa.XAResource;
import org.hibernate.Session;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.dialect.H2Dialect;
import org.hibernate.engine.jdbc.connections.internal.UserSuppliedConnectionProviderImpl;
import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider;
import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase;
@ -34,20 +28,26 @@ import org.hibernate.resource.jdbc.spi.PhysicalConnectionHandlingMode;
import org.hibernate.testing.RequiresDialect;
import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.env.ConnectionProviderBuilder;
import org.hibernate.testing.jdbc.ConnectionProviderDelegate;
import org.hibernate.testing.jta.TestingJtaBootstrap;
import org.hibernate.testing.jta.TestingJtaPlatformImpl;
import org.hibernate.testing.junit4.CustomParameterized;
import org.hibernate.testing.transaction.TransactionUtil2;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
import jakarta.transaction.RollbackException;
import jakarta.transaction.SystemException;
import org.mockito.InOrder;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import org.mockito.quality.Strictness;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
@ -80,6 +80,9 @@ public class BeforeCompletionReleaseTest extends BaseEntityManagerFunctionalTest
@Rule
public MockitoRule mockito = MockitoJUnit.rule().strictness( Strictness.STRICT_STUBS );
private final ConnectionProvider connectionProvider = spy(
new ConnectionProviderDelegate( ConnectionProviderBuilder.buildConnectionProvider() )
);
private final PhysicalConnectionHandlingMode connectionHandlingModeInProperties;
private final PhysicalConnectionHandlingMode connectionHandlingModeInSessionBuilder;
@ -95,7 +98,7 @@ public class BeforeCompletionReleaseTest extends BaseEntityManagerFunctionalTest
protected Map getConfig() {
Map config = super.getConfig();
TestingJtaBootstrap.prepare( config );
config.put( AvailableSettings.CONNECTION_PROVIDER, new ConnectionProviderDecorator() );
config.put( AvailableSettings.CONNECTION_PROVIDER, connectionProvider );
if ( connectionHandlingModeInProperties != null ) {
config.put( AvailableSettings.CONNECTION_HANDLING, connectionHandlingModeInProperties );
}
@ -112,7 +115,7 @@ public class BeforeCompletionReleaseTest extends BaseEntityManagerFunctionalTest
public void testResourcesReleasedThenConnectionClosedThenCommit() throws SQLException, XAException {
try (SessionImplementor s = (SessionImplementor) openSession()) {
XAResource transactionSpy = mock( XAResource.class );
Connection[] connectionSpies = new Connection[1];
Connection[] connections = new Connection[1];
Statement statementMock = Mockito.mock( Statement.class );
TransactionUtil2.inTransaction( s, session -> {
@ -124,18 +127,18 @@ public class BeforeCompletionReleaseTest extends BaseEntityManagerFunctionalTest
LogicalConnectionImplementor logicalConnection = session.getJdbcCoordinator().getLogicalConnection();
logicalConnection.getResourceRegistry().register( statementMock, true );
connectionSpies[0] = logicalConnection.getPhysicalConnection();
connections[0] = logicalConnection.getPhysicalConnection();
} );
// Note: all this must happen BEFORE the session is closed;
// it's particularly important when reusing the session.
Connection connectionSpy = connectionSpies[0];
Connection connection = connections[0];
// Must close the resources, then the connection, then commit
InOrder inOrder = inOrder( statementMock, connectionSpy, transactionSpy );
InOrder inOrder = inOrder( statementMock, connectionProvider, transactionSpy );
inOrder.verify( statementMock ).close();
inOrder.verify( connectionSpy ).close();
inOrder.verify( connectionProvider ).closeConnection( connection );
inOrder.verify( transactionSpy ).commit( any(), anyBoolean() );
}
}
@ -144,7 +147,7 @@ public class BeforeCompletionReleaseTest extends BaseEntityManagerFunctionalTest
@TestForIssue(jiraKey = {"HHH-14557"})
public void testResourcesReleasedThenConnectionClosedOnEachRollback() throws SQLException {
try (SessionImplementor s = (SessionImplementor) openSession()) {
Connection[] connectionSpies = new Connection[1];
Connection[] connections = new Connection[1];
Statement statementMock = Mockito.mock( Statement.class );
RuntimeException rollbackException = new RuntimeException("Rollback");
@ -156,7 +159,7 @@ public class BeforeCompletionReleaseTest extends BaseEntityManagerFunctionalTest
LogicalConnectionImplementor logicalConnection = session.getJdbcCoordinator().getLogicalConnection();
logicalConnection.getResourceRegistry().register( statementMock, true );
connectionSpies[0] = logicalConnection.getPhysicalConnection();
connections[0] = logicalConnection.getPhysicalConnection();
throw rollbackException;
} );
@ -171,12 +174,12 @@ public class BeforeCompletionReleaseTest extends BaseEntityManagerFunctionalTest
// Note: all this must happen BEFORE the session is closed;
// it's particularly important when reusing the session.
Connection connectionSpy = connectionSpies[0];
Connection connection = connections[0];
// Must close the resources, then the connection
InOrder inOrder = inOrder( statementMock, connectionSpy );
InOrder inOrder = inOrder( statementMock, connectionProvider );
inOrder.verify( statementMock ).close();
inOrder.verify( connectionSpy ).close();
inOrder.verify( connectionProvider ).closeConnection( connection );
// We don't check the relative ordering of the rollback here,
// because unfortunately we know it's wrong:
// we don't get a "before transaction completion" event for rollbacks,
@ -218,25 +221,5 @@ public class BeforeCompletionReleaseTest extends BaseEntityManagerFunctionalTest
}
}
// --- //
public static class ConnectionProviderDecorator extends UserSuppliedConnectionProviderImpl {
private final ConnectionProvider dataSource;
public ConnectionProviderDecorator() {
this.dataSource = ConnectionProviderBuilder.buildConnectionProvider();
}
@Override
public Connection getConnection() throws SQLException {
return spy( dataSource.getConnection() );
}
@Override
public void closeConnection(Connection connection) throws SQLException {
connection.close();
}
}
}

View File

@ -15,6 +15,7 @@ import org.hibernate.cfg.AvailableSettings;
import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider;
import org.hibernate.testing.junit4.BaseUnitTestCase;
import org.hibernate.testing.util.ServiceRegistryUtil;
import org.junit.Test;
/**
@ -23,7 +24,7 @@ import org.junit.Test;
public class ExplicitConnectionProviderInstanceTest extends BaseUnitTestCase {
@Test
public void testPassingConnectionProviderInstanceToBootstrap() {
StandardServiceRegistry ssr = new StandardServiceRegistryBuilder()
StandardServiceRegistry ssr = ServiceRegistryUtil.serviceRegistryBuilder()
.applySetting( AvailableSettings.CONNECTION_PROVIDER, TestingConnectionProviderImpl.INSTANCE )
.build();
try {

View File

@ -14,7 +14,6 @@ import org.hibernate.LockOptions;
import org.hibernate.MappingException;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.dialect.HANAColumnStoreDialect;
import org.hibernate.engine.spi.SessionFactoryImplementor;
@ -22,6 +21,7 @@ import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.junit4.BaseUnitTestCase;
import org.hibernate.testing.orm.junit.ServiceRegistryScope;
import org.hibernate.testing.util.ServiceRegistryUtil;
import org.junit.Test;
import jakarta.persistence.Entity;
@ -38,7 +38,7 @@ public class HANADialectTestCase extends BaseUnitTestCase {
@Test
public void testSqlGeneratedForIdentityInsertNoColumns() {
ServiceRegistryScope.using(
() -> new StandardServiceRegistryBuilder()
() -> ServiceRegistryUtil.serviceRegistryBuilder()
.applySetting( AvailableSettings.DIALECT, HANAColumnStoreDialect.class )
.build(),
registryScope -> {
@ -101,15 +101,15 @@ public class HANADialectTestCase extends BaseUnitTestCase {
lockOptions.setTimeOut( 500 );
sqlWithLock = dialect.applyLocksToSql( sql, lockOptions, new HashMap<>() );
assertEquals( sql + " for update nowait", sqlWithLock );
assertEquals( sql + " for update wait 1", sqlWithLock );
lockOptions.setTimeOut( 1500 );
sqlWithLock = dialect.applyLocksToSql( sql, lockOptions, new HashMap<>() );
assertEquals( sql + " for update wait 1", sqlWithLock );
assertEquals( sql + " for update wait 2", sqlWithLock );
lockOptions.setAliasSpecificLockMode( "dummy", LockMode.PESSIMISTIC_READ );
keyColumns.put( "dummy", new String[]{ "dummy" } );
sqlWithLock = dialect.applyLocksToSql( sql, lockOptions, keyColumns );
assertEquals( sql + " for update of dummy.dummy wait 1", sqlWithLock );
assertEquals( sql + " for update of dummy.dummy wait 2", sqlWithLock );
}
}

Some files were not shown because too many files have changed in this diff Show More