Merge remote-tracking branch 'upstream/master' into wip/6.0

This commit is contained in:
Christian Beikov 2021-02-03 17:36:09 +01:00
commit de1524df68
140 changed files with 3381 additions and 426 deletions

View File

@ -73,7 +73,7 @@ jobs:
with:
name: test-reports-java8-${{ matrix.rdbms }}
path: |
./**/target/reports/tests/test/
./**/target/reports/tests/
./**/target/reports/checkstyle/
- name: Omit produced artifacts from build cache
run: ./ci/before-cache.sh
@ -112,7 +112,7 @@ jobs:
with:
name: test-reports-java11
path: |
./**/target/reports/tests/test/
./**/target/reports/tests/
./**/target/reports/checkstyle/
- name: Omit produced artifacts from build cache
run: ./ci/before-cache.sh

View File

@ -64,6 +64,32 @@ oracle() {
# We need to use the defaults
# SYSTEM/Oracle18
docker run --shm-size=1536m --name oracle -d -p 1521:1521 quillbuilduser/oracle-18-xe
until [ "`docker inspect -f {{.State.Health.Status}} oracle`" == "healthy" ];
do
echo "Waiting for Oracle to start..."
sleep 10;
done
echo "Oracle successfully started"
# We increase file sizes to avoid online resizes as that requires lots of CPU which is restricted in XE
docker exec oracle bash -c "source /home/oracle/.bashrc; bash -c \"
cat <<EOF | \$ORACLE_HOME/bin/sqlplus sys/Oracle18@localhost/XE as sysdba
alter database tempfile '/opt/oracle/oradata/XE/temp01.dbf' resize 400M;
alter database datafile '/opt/oracle/oradata/XE/system01.dbf' resize 1000M;
alter database datafile '/opt/oracle/oradata/XE/sysaux01.dbf' resize 600M;
alter database datafile '/opt/oracle/oradata/XE/undotbs01.dbf' resize 300M;
alter database add logfile group 4 '/opt/oracle/oradata/XE/redo04.log' size 500M reuse;
alter database add logfile group 5 '/opt/oracle/oradata/XE/redo05.log' size 500M reuse;
alter database add logfile group 6 '/opt/oracle/oradata/XE/redo06.log' size 500M reuse;
alter system switch logfile;
alter system switch logfile;
alter system switch logfile;
alter system checkpoint;
alter database drop logfile group 1;
alter database drop logfile group 2;
alter database drop logfile group 3;
EOF\""
}
if [ -z ${1} ]; then

View File

@ -561,6 +561,9 @@ Provide a custom https://docs.jboss.org/hibernate/orm/{majorMinorVersion}/javado
`*hibernate.hql.bulk_id_strategy.global_temporary.drop_tables*` (e.g. `true` or `false` (default value))::
For databases that don't support local tables, but just global ones, this configuration property allows you to DROP the global tables used for multi-table bulk HQL operations when the `SessionFactory` or the `EntityManagerFactory` is closed.
`*hibernate.hql.bulk_id_strategy.local_temporary.drop_tables*` (e.g. `true` or `false` (default value))::
This configuration property allows you to DROP the local temporary tables used for multi-table bulk HQL operations when the `SessionFactory` or the `EntityManagerFactory` is closed. This is useful when testing with a single connection pool against different schemas.
`*hibernate.hql.bulk_id_strategy.persistent.drop_tables*` (e.g. `true` or `false` (default value))::
This configuration property is used by the https://docs.jboss.org/hibernate/orm/{majorMinorVersion}/javadocs/org/hibernate/hql/spi/id/persistent/PersistentTableBulkIdStrategy.html[`PersistentTableBulkIdStrategy`], that mimics temporary tables for databases which do not support temporary tables.
It follows a pattern similar to the ANSI SQL definition of the global temporary table using a "session id" column to segment rows from the various sessions.

View File

@ -136,7 +136,7 @@ public class ListenerTest extends BaseEntityManagerFunctionalTestCase {
}
//tag::events-jpa-callbacks-example[]
@Entity
@Entity(name = "Person")
@EntityListeners( LastUpdateListener.class )
public static class Person {

View File

@ -25,6 +25,7 @@ import org.hibernate.CacheMode;
import org.hibernate.ScrollableResults;
import org.hibernate.Session;
import org.hibernate.dialect.CockroachDialect;
import org.hibernate.dialect.DerbyDialect;
import org.hibernate.dialect.H2Dialect;
import org.hibernate.dialect.MySQL5Dialect;
import org.hibernate.dialect.Oracle8iDialect;
@ -1178,6 +1179,7 @@ public class HQLTest extends BaseEntityManagerFunctionalTestCase {
}
@Test
@SkipForDialect(value = DerbyDialect.class, comment = "See https://issues.apache.org/jira/browse/DERBY-2072")
public void test_hql_concat_function_example() {
doInJPA( this::entityManagerFactory, entityManager -> {
//tag::hql-concat-function-example[]
@ -1312,6 +1314,7 @@ public class HQLTest extends BaseEntityManagerFunctionalTestCase {
@Test
@SkipForDialect(SQLServerDialect.class)
@SkipForDialect(value = DerbyDialect.class, comment = "Comparisons between 'DATE' and 'TIMESTAMP' are not supported")
public void test_hql_current_date_function_example() {
doInJPA( this::entityManagerFactory, entityManager -> {
//tag::hql-current-date-function-example[]
@ -1383,6 +1386,7 @@ public class HQLTest extends BaseEntityManagerFunctionalTestCase {
}
@Test
@SkipForDialect(value = DerbyDialect.class, comment = "See https://issues.apache.org/jira/browse/DERBY-2072")
public void test_hql_cast_function_example() {
doInJPA( this::entityManagerFactory, entityManager -> {
//tag::hql-cast-function-example[]
@ -1396,6 +1400,7 @@ public class HQLTest extends BaseEntityManagerFunctionalTestCase {
}
@Test
@SkipForDialect(value = DerbyDialect.class, comment = "Derby doesn't support extract function")
public void test_hql_extract_function_example() {
doInJPA( this::entityManagerFactory, entityManager -> {
//tag::hql-extract-function-example[]
@ -1550,6 +1555,7 @@ public class HQLTest extends BaseEntityManagerFunctionalTestCase {
}
@Test
@SkipForDialect(value = DerbyDialect.class, comment = "Comparisons between 'DATE' and 'TIMESTAMP' are not supported")
public void test_hql_collection_expressions_example_7() {
doInJPA( this::entityManagerFactory, entityManager -> {
//tag::hql-collection-expressions-example[]
@ -1565,6 +1571,7 @@ public class HQLTest extends BaseEntityManagerFunctionalTestCase {
}
@Test
@SkipForDialect(value = DerbyDialect.class, comment = "Comparisons between 'DATE' and 'TIMESTAMP' are not supported")
public void test_hql_collection_expressions_example_8() {
doInJPA( this::entityManagerFactory, entityManager -> {
//tag::hql-collection-expressions-example[]

View File

@ -11,6 +11,7 @@ import javax.persistence.Id;
import javax.persistence.Lob;
import org.hibernate.annotations.Nationalized;
import org.hibernate.dialect.DB2Dialect;
import org.hibernate.dialect.MySQL5Dialect;
import org.hibernate.dialect.PostgreSQL81Dialect;
import org.hibernate.jpa.test.BaseEntityManagerFunctionalTestCase;
@ -27,9 +28,10 @@ import static org.junit.Assert.assertArrayEquals;
@SkipForDialect(
value = {
PostgreSQL81Dialect.class,
MySQL5Dialect.class
MySQL5Dialect.class,
DB2Dialect.class
},
comment = "@see https://hibernate.atlassian.net/browse/HHH-10693 and https://hibernate.atlassian.net/browse/HHH-10695"
comment = "@see https://hibernate.atlassian.net/browse/HHH-10693 and https://hibernate.atlassian.net/browse/HHH-10695 and https://hibernate.atlassian.net/browse/HHH-10473"
)
public class NClobCharArrayTest extends BaseEntityManagerFunctionalTestCase {

View File

@ -11,6 +11,7 @@ import javax.persistence.Id;
import javax.persistence.Lob;
import org.hibernate.annotations.Nationalized;
import org.hibernate.dialect.DB2Dialect;
import org.hibernate.dialect.MySQL5Dialect;
import org.hibernate.dialect.PostgreSQL81Dialect;
import org.hibernate.jpa.test.BaseEntityManagerFunctionalTestCase;
@ -27,9 +28,10 @@ import static org.junit.Assert.assertEquals;
@SkipForDialect(
value = {
PostgreSQL81Dialect.class,
MySQL5Dialect.class
MySQL5Dialect.class,
DB2Dialect.class
},
comment = "@see https://hibernate.atlassian.net/browse/HHH-10693 and https://hibernate.atlassian.net/browse/HHH-10695"
comment = "@see https://hibernate.atlassian.net/browse/HHH-10693 and https://hibernate.atlassian.net/browse/HHH-10695 and https://hibernate.atlassian.net/browse/HHH-10473"
)
public class NClobStringTest extends BaseEntityManagerFunctionalTestCase {

View File

@ -19,6 +19,7 @@ import org.hibernate.Session;
import org.hibernate.annotations.Nationalized;
import org.hibernate.dialect.AbstractHANADialect;
import org.hibernate.dialect.CockroachDialect;
import org.hibernate.dialect.DB2Dialect;
import org.hibernate.dialect.MySQL5Dialect;
import org.hibernate.dialect.PostgreSQL81Dialect;
import org.hibernate.engine.jdbc.NClobProxy;
@ -39,9 +40,10 @@ import static org.junit.Assert.fail;
PostgreSQL81Dialect.class,
MySQL5Dialect.class,
AbstractHANADialect.class,
CockroachDialect.class
CockroachDialect.class,
DB2Dialect.class
},
comment = "@see https://hibernate.atlassian.net/browse/HHH-10693 and https://hibernate.atlassian.net/browse/HHH-10695"
comment = "@see https://hibernate.atlassian.net/browse/HHH-10693 and https://hibernate.atlassian.net/browse/HHH-10695 and https://hibernate.atlassian.net/browse/HHH-10473"
)
public class NClobTest extends BaseEntityManagerFunctionalTestCase {

View File

@ -10,6 +10,7 @@ import javax.persistence.Entity;
import javax.persistence.Id;
import org.hibernate.annotations.Nationalized;
import org.hibernate.dialect.DerbyDialect;
import org.hibernate.dialect.PostgreSQL81Dialect;
import org.hibernate.jpa.test.BaseEntityManagerFunctionalTestCase;
@ -24,9 +25,10 @@ import static org.junit.Assert.assertEquals;
*/
@SkipForDialect(
value = {
PostgreSQL81Dialect.class
PostgreSQL81Dialect.class,
DerbyDialect.class
},
comment = "@see https://hibernate.atlassian.net/browse/HHH-10693"
comment = "@see https://hibernate.atlassian.net/browse/HHH-10693 and Derby doesn't support nationalized type"
)
public class NationalizedTest extends BaseEntityManagerFunctionalTestCase {

View File

@ -15,8 +15,10 @@ import javax.persistence.Table;
import org.hibernate.annotations.Subselect;
import org.hibernate.annotations.Synchronize;
import org.hibernate.dialect.DerbyDialect;
import org.hibernate.jpa.test.BaseEntityManagerFunctionalTestCase;
import org.hibernate.testing.SkipForDialect;
import org.junit.Test;
import static org.hibernate.testing.transaction.TransactionUtil.doInJPA;
@ -25,6 +27,7 @@ import static org.junit.Assert.assertEquals;
/**
* @author Vlad Mihalcea
*/
@SkipForDialect(value = DerbyDialect.class, comment = "Derby doesn't support a CONCAT function")
public class SubselectTest extends BaseEntityManagerFunctionalTestCase {
@Override

View File

@ -59,11 +59,11 @@ public class TypeCategoryTest extends BaseEntityManagerFunctionalTestCase {
@Embeddable
public class Name {
private String first;
private String firstName;
private String middle;
private String middleName;
private String last;
private String lastName;
// getters and setters omitted
}

View File

@ -45,7 +45,16 @@ ext {
'jdbc.driver': 'org.postgresql.Driver',
'jdbc.user' : 'hibernate_orm_test',
'jdbc.pass' : 'hibernate_orm_test',
'jdbc.url' : 'jdbc:postgresql://127.0.0.1/hibernate_orm_test'
// Disable prepared statement caching due to https://www.postgresql.org/message-id/CAEcMXhmmRd4-%2BNQbnjDT26XNdUoXdmntV9zdr8%3DTu8PL9aVCYg%40mail.gmail.com
'jdbc.url' : 'jdbc:postgresql://127.0.0.1/hibernate_orm_test?preparedStatementCacheQueries=0'
],
pgsql_ci : [
'db.dialect' : 'org.hibernate.dialect.PostgreSQL95Dialect',
'jdbc.driver': 'org.postgresql.Driver',
'jdbc.user' : 'hibernate_orm_test',
'jdbc.pass' : 'hibernate_orm_test',
// Disable prepared statement caching due to https://www.postgresql.org/message-id/CAEcMXhmmRd4-%2BNQbnjDT26XNdUoXdmntV9zdr8%3DTu8PL9aVCYg%40mail.gmail.com
'jdbc.url' : 'jdbc:postgresql://' + dbHost + '/hibernate_orm_test?preparedStatementCacheQueries=0'
],
pgsql_ci : [
'db.dialect' : 'org.hibernate.dialect.PostgreSQLDialect',
@ -175,7 +184,8 @@ ext {
'jdbc.driver': 'org.postgresql.Driver',
'jdbc.user' : 'root',
'jdbc.pass' : '',
'jdbc.url' : 'jdbc:postgresql://localhost:26257/defaultdb?sslmode=disable'
// Disable prepared statement caching due to https://www.postgresql.org/message-id/CAEcMXhmmRd4-%2BNQbnjDT26XNdUoXdmntV9zdr8%3DTu8PL9aVCYg%40mail.gmail.com
'jdbc.url' : 'jdbc:postgresql://localhost:26257/defaultdb?sslmode=disable&preparedStatementCacheQueries=0'
],
]
}

View File

@ -102,6 +102,7 @@ dependencies {
//Databases
testRuntime( libraries.h2 )
testRuntime( libraries.derby )
testRuntime( libraries.hsqldb )
testRuntime( libraries.postgresql )
testRuntime( libraries.mysql )
@ -111,13 +112,15 @@ dependencies {
testRuntime( libraries.hana )
testRuntime( libraries.cockroachdb )
if ( db.startsWith( 'oracle' ) ) {
testRuntime( libraries.oracle )
}
else if ( db.startsWith( 'db2' ) ) {
// Since both the DB2 driver and HANA have a package "net.jpountz" we have to add dependencies conditionally
// This is due to the "no split-packages" requirement of Java 9+
if ( db.startsWith( 'db2' ) ) {
testRuntime( libraries.db2 )
}
else if ( db.equalsIgnoreCase( 'hana' ) ) {
else if ( db.startsWith( 'hana' ) ) {
testRuntime( libraries.hana )
}

View File

@ -53,7 +53,7 @@ public class PreparedStatementSpyConnectionProvider extends AgroalConnectionProv
public void closeConnection(Connection conn) throws SQLException {
acquiredConnections.remove( conn );
releasedConnections.add( conn );
super.closeConnection( conn );
super.closeConnection( (Connection) MockUtil.getMockSettings( conn ).getSpiedInstance() );
}
@Override

View File

@ -22,6 +22,7 @@ hibernate.c3p0.testConnectionOnCheckout true
hibernate.show_sql false
hibernate.max_fetch_depth 5
hibernate.connection.provider_class C3P0ConnectionProvider
hibernate.cache.region_prefix hibernate.test
hibernate.cache.region.factory_class org.hibernate.testing.cache.CachingRegionFactory

View File

@ -461,7 +461,6 @@ public class SessionFactoryBuilderImpl implements SessionFactoryBuilderImplement
@Override
public SessionFactory build() {
metadata.validate();
final StandardServiceRegistry serviceRegistry = metadata.getMetadataBuildingOptions().getServiceRegistry();
BytecodeProvider bytecodeProvider = serviceRegistry.getService( BytecodeProvider.class );
addSessionFactoryObservers( new SessionFactoryObserverForBytecodeEnhancer( bytecodeProvider ) );

View File

@ -23,4 +23,20 @@ public class QualifiedTableName extends QualifiedNameImpl {
public Identifier getTableName() {
return getObjectName();
}
public QualifiedTableName quote() {
Identifier catalogName = getCatalogName();
if ( catalogName != null ) {
catalogName = new Identifier( catalogName.getText(), true );
}
Identifier schemaName = getSchemaName();
if ( schemaName != null ) {
schemaName = new Identifier( schemaName.getText(), true );
}
Identifier tableName = getTableName();
if ( tableName != null ) {
tableName = new Identifier( tableName.getText(), true );
}
return new QualifiedTableName( catalogName, schemaName, tableName );
}
}

View File

@ -652,7 +652,7 @@ public class DB2Dialect extends Dialect {
nullPrecedence == NullPrecedence.FIRST ? "0" : "1",
nullPrecedence == NullPrecedence.FIRST ? "1" : "0",
expression,
order
order == null ? "asc" : order
);
}

View File

@ -800,4 +800,9 @@ public class DerbyDialect extends Dialect {
public GroupBySummarizationRenderingStrategy getGroupBySummarizationRenderingStrategy() {
return GroupBySummarizationRenderingStrategy.FUNCTION;
}
@Override
public boolean supportsPartitionBy() {
return false;
}
}

View File

@ -0,0 +1,28 @@
/*
* 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>.
*/
package org.hibernate.engine.jdbc.connections.internal;
import java.sql.Connection;
import java.sql.SQLException;
/**
* Contract for validating JDBC Connections
*
* @author Christian Beikov
*/
public interface ConnectionValidator {
ConnectionValidator ALWAYS_VALID = connection -> true;
/**
* Checks if the connection is still valid
*
* @return <code>true</code> if the connection is valid, <code>false</code> otherwise
* @throws SQLException when an error happens due to the connection usage leading to a connection close
*/
boolean isValid(Connection connection) throws SQLException;
}

View File

@ -50,7 +50,7 @@ import static org.hibernate.internal.log.ConnectionPoolingLogger.CONNECTIONS_MES
* @author Steve Ebersole
*/
public class DriverManagerConnectionProviderImpl
implements ConnectionProvider, Configurable, Stoppable, ServiceRegistryAwareService {
implements ConnectionProvider, Configurable, Stoppable, ServiceRegistryAwareService, ConnectionValidator {
public static final String MIN_SIZE = "hibernate.connection.min_pool_size";
public static final String INITIAL_SIZE = "hibernate.connection.initial_pool_size";
@ -95,7 +95,7 @@ public class DriverManagerConnectionProviderImpl
pooledConnectionBuilder.initialSize( initialSize );
pooledConnectionBuilder.minSize( minSize );
pooledConnectionBuilder.maxSize( maxSize );
pooledConnectionBuilder.validator( this );
return pooledConnectionBuilder.build();
}
@ -247,6 +247,12 @@ public class DriverManagerConnectionProviderImpl
}
}
protected void validateConnectionsReturned() {
int allocationCount = state.pool.allConnections.size() - state.pool.availableConnections.size();
if ( allocationCount != 0 ) {
CONNECTIONS_MESSAGE_LOGGER.error( "Connection leak detected: there are " + allocationCount + " unclosed connections!");
}
}
// destroy the pool ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@ -254,6 +260,7 @@ public class DriverManagerConnectionProviderImpl
public void stop() {
if ( state != null ) {
state.stop();
validateConnectionsReturned();
}
}
@ -275,6 +282,10 @@ public class DriverManagerConnectionProviderImpl
return connectionCreator.getConnectionProperties();
}
@Override
public boolean isValid(Connection connection) throws SQLException {
return true;
}
public static class PooledConnections {
@ -282,6 +293,7 @@ public class DriverManagerConnectionProviderImpl
private final ConcurrentLinkedQueue<Connection> availableConnections = new ConcurrentLinkedQueue<>();
private final ConnectionCreator connectionCreator;
private final ConnectionValidator connectionValidator;
private final boolean autoCommit;
private final int minSize;
private final int maxSize;
@ -292,6 +304,9 @@ public class DriverManagerConnectionProviderImpl
Builder builder) {
CONNECTIONS_LOGGER.debugf( "Initializing Connection pool with %s Connections", builder.initialSize );
connectionCreator = builder.connectionCreator;
connectionValidator = builder.connectionValidator == null
? ConnectionValidator.ALWAYS_VALID
: builder.connectionValidator;
autoCommit = builder.autoCommit;
maxSize = builder.maxSize;
minSize = builder.minSize;
@ -322,13 +337,33 @@ public class DriverManagerConnectionProviderImpl
}
public void add(Connection conn) throws SQLException {
final Connection connection = releaseConnection( conn );
if ( connection != null ) {
availableConnections.offer( connection );
}
}
protected Connection releaseConnection(Connection conn) {
Exception t = null;
try {
conn.setAutoCommit( true );
conn.clearWarnings();
availableConnections.offer( conn );
if ( connectionValidator.isValid( conn ) ) {
return conn;
}
}
catch (SQLException ex) {
t = ex;
}
closeConnection( conn, t );
CONNECTIONS_MESSAGE_LOGGER.debug( "Connection release failed. Closing pooled connection", t );
return null;
}
public Connection poll() throws SQLException {
Connection conn = availableConnections.poll();
Connection conn;
do {
conn = availableConnections.poll();
if ( conn == null ) {
synchronized (allConnections) {
if ( allConnections.size() < maxSize ) {
@ -336,12 +371,45 @@ public class DriverManagerConnectionProviderImpl
return poll();
}
}
throw new HibernateException( "The internal connection pool has reached its maximum size and no connection is currently available!" );
throw new HibernateException(
"The internal connection pool has reached its maximum size and no connection is currently available!" );
}
conn.setAutoCommit( autoCommit );
conn = prepareConnection( conn );
} while ( conn == null );
return conn;
}
protected Connection prepareConnection(Connection conn) {
Exception t = null;
try {
conn.setAutoCommit( autoCommit );
if ( connectionValidator.isValid( conn ) ) {
return conn;
}
}
catch (SQLException ex) {
t = ex;
}
closeConnection( conn, t );
CONNECTIONS_MESSAGE_LOGGER.debug( "Connection preparation failed. Closing pooled connection", t );
return null;
}
protected void closeConnection(Connection conn, Throwable t) {
try {
conn.close();
}
catch (SQLException ex) {
CONNECTIONS_MESSAGE_LOGGER.unableToCloseConnection( ex );
if ( t != null ) {
t.addSuppressed( ex );
}
}
finally {
allConnections.remove( conn );
}
}
public void close() throws SQLException {
try {
int allocationCount = allConnections.size() - availableConnections.size();
@ -389,6 +457,7 @@ public class DriverManagerConnectionProviderImpl
public static class Builder {
private final ConnectionCreator connectionCreator;
private ConnectionValidator connectionValidator;
private boolean autoCommit;
private int initialSize = 1;
private int minSize = 1;
@ -414,6 +483,11 @@ public class DriverManagerConnectionProviderImpl
return this;
}
public Builder validator(ConnectionValidator connectionValidator) {
this.connectionValidator = connectionValidator;
return this;
}
public PooledConnections build() {
return new PooledConnections( this );
}

View File

@ -66,7 +66,7 @@ public class EventEngine {
for ( Iterator<Property> propertyIterator = persistentClass.getDeclaredPropertyIterator(); propertyIterator.hasNext(); ) {
final Property property = propertyIterator.next();
if ( property.getType().isComponentType() ) {
if ( property.isComposite() ) {
this.callbackBuilder.buildCallbacksForEmbeddable(
property,
persistentClass.getMappedClass(),

View File

@ -228,6 +228,15 @@ public abstract class AbstractSharedSessionContract implements SharedSessionCont
transactionCoordinator.invalidate();
}
protected void prepareForAutoClose() {
waitingForAutoClose = true;
closed = true;
// For non-shared transaction coordinators, we have to add the observer
if ( !isTransactionCoordinatorShared ) {
addSharedSessionTransactionObserver( transactionCoordinator );
}
}
@Override
public boolean shouldAutoJoinTransaction() {
return autoJoinTransactions;

View File

@ -293,6 +293,7 @@ public class SessionFactoryImpl implements SessionFactoryImplementor {
);
identifierGenerators.put( model.getEntityName(), generator );
} );
bootMetamodel.validate();
LOG.debug( "Instantiated session factory" );
@ -314,15 +315,6 @@ public class SessionFactoryImpl implements SessionFactoryImplementor {
queryEngine.getNamedObjectRepository().checkNamedQueries( queryEngine );
}
// todo (6.0) : manage old getMultiTableBulkIdStrategy
// settings.getMultiTableBulkIdStrategy().prepare(
// jdbcServices,
// buildLocalConnectionAccess(),
// metadata,
// sessionFactoryOptions
// );
SchemaManagementToolCoordinator.process(
bootMetamodel,
serviceRegistry,
@ -815,9 +807,6 @@ public class SessionFactoryImpl implements SessionFactoryImplementor {
LOG.closing();
observer.sessionFactoryClosing( this );
// todo (6.0) : manage old getMultiTableBulkIdStrategy
// settings.getMultiTableBulkIdStrategy().release( serviceRegistry.getService( JdbcServices.class ), buildLocalConnectionAccess() );
// NOTE : the null checks below handle cases where close is called from
// a failed attempt to create the SessionFactory
@ -826,6 +815,14 @@ public class SessionFactoryImpl implements SessionFactoryImplementor {
}
if ( runtimeMetamodels != null ) {
final JdbcConnectionAccess jdbcConnectionAccess = jdbcServices.getBootstrapJdbcConnectionAccess();
runtimeMetamodels.getMappingMetamodel().visitEntityDescriptors(
entityPersister -> {
if ( entityPersister.getSqmMultiTableMutationStrategy() != null ) {
entityPersister.getSqmMultiTableMutationStrategy().release( this, jdbcConnectionAccess );
}
}
);
( (MappingMetamodelImpl) runtimeMetamodels.getMappingMetamodel() ).close();
}

View File

@ -347,8 +347,7 @@ public class SessionImpl
}
else {
//Otherwise, session auto-close will be enabled by shouldAutoCloseSession().
waitingForAutoClose = true;
closed = true;
prepareForAutoClose();
}
}
else {

View File

@ -55,6 +55,7 @@ import org.hibernate.bytecode.enhance.spi.UnloadedClass;
import org.hibernate.bytecode.enhance.spi.UnloadedField;
import org.hibernate.cfg.Environment;
import org.hibernate.cfg.beanvalidation.BeanValidationIntegrator;
import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.id.factory.spi.MutableIdentifierGeneratorFactory;
import org.hibernate.integrator.spi.Integrator;
@ -78,7 +79,9 @@ import org.hibernate.resource.transaction.spi.TransactionCoordinatorBuilder;
import org.hibernate.secure.spi.GrantedPermission;
import org.hibernate.secure.spi.JaccPermissionDeclarations;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.spi.ServiceBinding;
import org.hibernate.service.spi.ServiceRegistryImplementor;
import org.hibernate.service.spi.Stoppable;
import org.hibernate.tool.schema.spi.DelayedDropRegistryNotAvailableImpl;
import org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator;
@ -1237,9 +1240,24 @@ public class EntityManagerFactoryBuilderImpl implements EntityManagerFactoryBuil
@Override
public void cancel() {
cleanup();
// todo : close the bootstrap registry (not critical, but nice to do)
}
private void cleanup() {
// Stop and de-register the ConnectionProvider to prevent connections lying around
if ( standardServiceRegistry instanceof ServiceRegistryImplementor &&
standardServiceRegistry instanceof ServiceBinding.ServiceLifecycleOwner ) {
final ServiceRegistryImplementor serviceRegistry = (ServiceRegistryImplementor) standardServiceRegistry;
final ServiceBinding.ServiceLifecycleOwner lifecycleOwner = (ServiceBinding.ServiceLifecycleOwner) serviceRegistry;
final ServiceBinding<ConnectionProvider> binding = serviceRegistry.locateServiceBinding( ConnectionProvider.class );
if ( binding != null && binding.getService() instanceof Stoppable ) {
lifecycleOwner.stopService( binding );
binding.setService( null );
}
}
}
@Override
public void generateSchema() {
// This seems overkill, but building the SF is necessary to get the Integrators to kick in.
@ -1255,23 +1273,34 @@ public class EntityManagerFactoryBuilderImpl implements EntityManagerFactoryBuil
catch (Exception e) {
throw persistenceException( "Error performing schema management", e );
}
finally {
// release this builder
cancel();
}
}
@Override
public EntityManagerFactory build() {
boolean success = false;
try {
final SessionFactoryBuilder sfBuilder = metadata().getSessionFactoryBuilder();
populateSfBuilder( sfBuilder, standardServiceRegistry );
try {
return sfBuilder.build();
final EntityManagerFactory emf = sfBuilder.build();
success = true;
return emf;
}
catch (Exception e) {
throw persistenceException( "Unable to build Hibernate SessionFactory", e );
}
}
finally {
if ( !success ) {
cleanup();
}
}
}
protected void populateSfBuilder(SessionFactoryBuilder sfBuilder, StandardServiceRegistry ssr) {

View File

@ -6044,6 +6044,12 @@ public abstract class AbstractEntityPersister
if ( sqmMultiTableMutationStrategy == null ) {
return false;
}
sqmMultiTableMutationStrategy.prepare(
creationProcess,
creationContext.getSessionFactory()
.getJdbcServices()
.getBootstrapJdbcConnectionAccess()
);
return true;
}
);

View File

@ -11,6 +11,9 @@ import java.sql.SQLException;
import java.util.function.Supplier;
import org.hibernate.boot.TempTableDdlTransactionHandling;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.engine.config.spi.ConfigurationService;
import org.hibernate.engine.config.spi.StandardConverters;
import org.hibernate.engine.jdbc.connections.spi.JdbcConnectionAccess;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.metamodel.mapping.internal.MappingModelCreationProcess;
@ -40,8 +43,7 @@ public class GlobalTemporaryTableStrategy implements SqmMultiTableMutationStrate
private final SessionFactoryImplementor sessionFactory;
private boolean prepared;
private boolean created;
private boolean released;
private boolean dropIdTables;
public GlobalTemporaryTableStrategy(
IdTable idTable,
@ -131,7 +133,14 @@ public class GlobalTemporaryTableStrategy implements SqmMultiTableMutationStrate
try {
idTableCreationWork.execute( connection );
created = true;
final ConfigurationService configService = mappingModelCreationProcess.getCreationContext()
.getBootstrapContext()
.getServiceRegistry().getService( ConfigurationService.class );
this.dropIdTables = configService.getSetting(
DROP_ID_TABLES,
StandardConverters.BOOLEAN,
false
);
}
finally {
try {
@ -140,25 +149,17 @@ public class GlobalTemporaryTableStrategy implements SqmMultiTableMutationStrate
catch (SQLException ignore) {
}
}
if ( created ) {
// todo (6.0) : register strategy for dropping of the table if requested - DROP_ID_TABLES
}
}
@Override
public void release(
SessionFactoryImplementor sessionFactory,
JdbcConnectionAccess connectionAccess) {
if ( released ) {
if ( !dropIdTables ) {
return;
}
released = true;
if ( ! created ) {
return;
}
dropIdTables = false;
log.debugf( "Dropping global-temp ID table : %s", idTable.getTableExpression() );

View File

@ -6,24 +6,35 @@
*/
package org.hibernate.query.sqm.mutation.internal.idtable;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.function.Function;
import java.util.function.Supplier;
import org.hibernate.boot.TempTableDdlTransactionHandling;
import org.hibernate.engine.config.spi.ConfigurationService;
import org.hibernate.engine.config.spi.StandardConverters;
import org.hibernate.engine.jdbc.connections.spi.JdbcConnectionAccess;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.metamodel.mapping.internal.MappingModelCreationProcess;
import org.hibernate.query.sqm.internal.DomainParameterXref;
import org.hibernate.query.sqm.mutation.spi.SqmMultiTableMutationStrategy;
import org.hibernate.query.sqm.tree.delete.SqmDeleteStatement;
import org.hibernate.query.sqm.tree.update.SqmUpdateStatement;
import org.hibernate.sql.exec.spi.ExecutionContext;
import org.jboss.logging.Logger;
/**
* Strategy based on ANSI SQL's definition of a "local temporary table" (local to each db session).
*
* @author Steve Ebersole
*/
public class LocalTemporaryTableStrategy implements SqmMultiTableMutationStrategy {
private static final Logger log = Logger.getLogger( LocalTemporaryTableStrategy.class );
public static final String SHORT_NAME = "local_temporary";
public static final String DROP_ID_TABLES = "hibernate.hql.bulk_id_strategy.local_temporary.drop_tables";
private final IdTable idTable;
private final Supplier<IdTableExporter> idTableExporterAccess;
@ -31,6 +42,8 @@ public class LocalTemporaryTableStrategy implements SqmMultiTableMutationStrateg
private final TempTableDdlTransactionHandling ddlTransactionHandling;
private final SessionFactoryImplementor sessionFactory;
private boolean dropIdTables;
public LocalTemporaryTableStrategy(
IdTable idTable,
Supplier<IdTableExporter> idTableExporterAccess,
@ -98,4 +111,61 @@ public class LocalTemporaryTableStrategy implements SqmMultiTableMutationStrateg
sessionFactory
).execute( context );
}
@Override
public void prepare(
MappingModelCreationProcess mappingModelCreationProcess,
JdbcConnectionAccess connectionAccess) {
final ConfigurationService configService = mappingModelCreationProcess.getCreationContext()
.getBootstrapContext()
.getServiceRegistry().getService( ConfigurationService.class );
this.dropIdTables = configService.getSetting(
DROP_ID_TABLES,
StandardConverters.BOOLEAN,
false
);
}
@Override
public void release(
SessionFactoryImplementor sessionFactory,
JdbcConnectionAccess connectionAccess) {
if ( !dropIdTables ) {
return;
}
dropIdTables = false;
log.debugf( "Dropping local-temp ID table : %s", idTable.getTableExpression() );
final IdTableHelper.IdTableDropWork idTableDropWork = new IdTableHelper.IdTableDropWork(
idTable,
idTableExporterAccess.get(),
sessionFactory
);
Connection connection;
try {
connection = connectionAccess.obtainConnection();
}
catch (UnsupportedOperationException e) {
// assume this comes from org.hibernate.engine.jdbc.connections.internal.UserSuppliedConnectionProviderImpl
log.debugf( "Unable to obtain JDBC connection; unable to drop local-temp ID table : %s", idTable.getTableExpression() );
return;
}
catch (SQLException e) {
log.error( "Unable obtain JDBC Connection", e );
return;
}
try {
idTableDropWork.execute( connection );
}
finally {
try {
connectionAccess.releaseConnection( connection );
}
catch (SQLException ignore) {
}
}
}
}

View File

@ -22,6 +22,7 @@ public class DdlTransactionIsolatorNonJtaImpl implements DdlTransactionIsolator
private final JdbcContext jdbcContext;
private Connection jdbcConnection;
private boolean unsetAutoCommit;
public DdlTransactionIsolatorNonJtaImpl(JdbcContext jdbcContext) {
this.jdbcContext = jdbcContext;
@ -49,6 +50,7 @@ public class DdlTransactionIsolatorNonJtaImpl implements DdlTransactionIsolator
try {
jdbcConnection.commit();
jdbcConnection.setAutoCommit( true );
unsetAutoCommit = true;
}
catch (SQLException e) {
throw jdbcContext.getSqlExceptionHelper().convert(
@ -79,11 +81,29 @@ public class DdlTransactionIsolatorNonJtaImpl implements DdlTransactionIsolator
@Override
public void release() {
if ( jdbcConnection != null ) {
try {
if ( unsetAutoCommit ) {
try {
jdbcConnection.setAutoCommit( false );
}
catch (SQLException e) {
throw jdbcContext.getSqlExceptionHelper().convert(
e,
"Unable to set auto commit to false for JDBC Connection used for DDL execution"
);
}
}
}
finally {
try {
jdbcContext.getJdbcConnectionAccess().releaseConnection( jdbcConnection );
}
catch (SQLException e) {
throw jdbcContext.getSqlExceptionHelper().convert( e, "Unable to release JDBC Connection used for DDL execution" );
throw jdbcContext.getSqlExceptionHelper().convert(
e,
"Unable to release JDBC Connection used for DDL execution"
);
}
}
}
}

View File

@ -29,8 +29,8 @@ public class DdlTransactionIsolatorJtaImpl implements DdlTransactionIsolator {
private final JdbcContext jdbcContext;
private Transaction suspendedTransaction;
private Connection jdbcConnection;
private final Transaction suspendedTransaction;
private final Connection jdbcConnection;
public DdlTransactionIsolatorJtaImpl(JdbcContext jdbcContext) {
this.jdbcContext = jdbcContext;

View File

@ -8,7 +8,9 @@ package org.hibernate.tool.schema.extract.internal;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
@ -540,62 +542,53 @@ public class InformationExtractorJdbcDatabaseMetaDataImpl implements Information
}
private void addColumns(TableInformation tableInformation) {
final QualifiedTableName tableName = tableInformation.getName();
final Identifier catalog = tableName.getCatalogName();
final Identifier schema = tableName.getSchemaName();
final String catalogFilter;
final String schemaFilter;
if ( catalog == null ) {
catalogFilter = "";
}
else {
catalogFilter = catalog.getText();
}
if ( schema == null ) {
schemaFilter = "";
}
else {
schemaFilter = schema.getText();
}
try {
ResultSet resultSet = extractionContext.getJdbcDatabaseMetaData().getColumns(
catalogFilter,
schemaFilter,
tableName.getTableName().getText(),
"%"
// We use this dummy query to retrieve the table information through the ResultSetMetaData
// This is significantly better than to use the DatabaseMetaData especially on Oracle with synonyms enabled
final String tableName = extractionContext.getJdbcEnvironment().getQualifiedObjectNameFormatter().format(
// The name comes from the database, so the case is correct
// But we quote here to avoid issues with reserved words
tableInformation.getName().quote(),
extractionContext.getJdbcEnvironment().getDialect()
);
final String query = "select * from " + tableName + " where 1=0";
try (Statement statement = extractionContext.getJdbcConnection()
.createStatement(); ResultSet resultSet = statement.executeQuery( query )) {
final ResultSetMetaData metaData = resultSet.getMetaData();
final int columnCount = metaData.getColumnCount();
try {
while ( resultSet.next() ) {
final String columnName = resultSet.getString( "COLUMN_NAME" );
for ( int i = 1; i <= columnCount; i++ ) {
final String columnName = metaData.getColumnName( i );
final ColumnInformationImpl columnInformation = new ColumnInformationImpl(
tableInformation,
DatabaseIdentifier.toIdentifier( columnName ),
resultSet.getInt( "DATA_TYPE" ),
new StringTokenizer( resultSet.getString( "TYPE_NAME" ), "() " ).nextToken(),
resultSet.getInt( "COLUMN_SIZE" ),
resultSet.getInt( "DECIMAL_DIGITS" ),
interpretTruthValue( resultSet.getString( "IS_NULLABLE" ) )
metaData.getColumnType( i ),
new StringTokenizer( metaData.getColumnTypeName( i ), "() " ).nextToken(),
metaData.getPrecision( i ),
metaData.getScale( i ),
interpretNullable( metaData.isNullable( i ) )
);
tableInformation.addColumn( columnInformation );
}
}
finally {
resultSet.close();
}
}
catch (SQLException e) {
throw convertSQLException(
e,
"Error accessing column metadata: " + tableName.toString()
"Error accessing column metadata: " + tableInformation.getName().toString()
);
}
}
private TruthValue interpretNullable(int nullable) {
switch ( nullable ) {
case ResultSetMetaData.columnNullable:
return TruthValue.TRUE;
case ResultSetMetaData.columnNoNulls:
return TruthValue.FALSE;
default:
return TruthValue.UNKNOWN;
}
}
private TruthValue interpretTruthValue(String nullable) {
if ( "yes".equalsIgnoreCase( nullable ) ) {
return TruthValue.TRUE;

View File

@ -1,60 +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
*/
package org.hibernate.type.internal;
import java.util.concurrent.ConcurrentHashMap;
import org.hibernate.type.spi.TypeConfiguration;
import org.jboss.logging.Logger;
/**
* A Registry of TypeConfiguration references based on the
* TypeConfiguration's UUID.
*
* @author Steve Ebersole
*/
public class TypeConfigurationRegistry {
private static final Logger LOG = Logger.getLogger( TypeConfigurationRegistry.class );
/**
* Singleton access
*/
public static final TypeConfigurationRegistry INSTANCE = new TypeConfigurationRegistry();
private TypeConfigurationRegistry() {
}
private ConcurrentHashMap<String,TypeConfiguration> configurationMap;
public void registerTypeConfiguration(TypeConfiguration typeConfiguration) {
if ( configurationMap == null ) {
configurationMap = new ConcurrentHashMap<>();
}
configurationMap.put( typeConfiguration.getUuid(), typeConfiguration );
}
public TypeConfiguration findTypeConfiguration(String uuid) {
if ( configurationMap == null ) {
return null;
}
return configurationMap.get( uuid );
}
public void deregisterTypeConfiguration(TypeConfiguration typeConfiguration) {
final TypeConfiguration existing = configurationMap.remove( typeConfiguration.getUuid() );
if ( existing != typeConfiguration ) {
LOG.debugf(
"Different TypeConfiguration [%s] passed to #deregisterTypeConfiguration than previously registered [%s] under that UUID [%s]",
typeConfiguration,
existing,
typeConfiguration.getUuid()
);
}
}
}

View File

@ -54,7 +54,6 @@ import org.hibernate.type.descriptor.sql.SqlTypeDescriptor;
import org.hibernate.type.descriptor.sql.SqlTypeDescriptorIndicators;
import org.hibernate.type.descriptor.sql.spi.SqlTypeDescriptorRegistry;
import org.hibernate.type.internal.StandardBasicTypeImpl;
import org.hibernate.type.internal.TypeConfigurationRegistry;
import java.sql.Time;
import java.sql.Timestamp;
@ -106,8 +105,6 @@ public class TypeConfiguration implements SessionFactoryObserver, Serializable {
this.basicTypeRegistry = new BasicTypeRegistry( this );
StandardBasicTypes.prime( this );
TypeConfigurationRegistry.INSTANCE.registerTypeConfiguration( this );
}
public String getUuid() {
@ -211,8 +208,6 @@ public class TypeConfiguration implements SessionFactoryObserver, Serializable {
public void sessionFactoryClosed(SessionFactory factory) {
log.tracef( "Handling #sessionFactoryClosed from [%s] for TypeConfiguration", factory );
TypeConfigurationRegistry.INSTANCE.deregisterTypeConfiguration( this );
scope.unsetSessionFactory( factory );
// todo (6.0) : finish this
@ -440,18 +435,6 @@ public class TypeConfiguration implements SessionFactoryObserver, Serializable {
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Custom serialization hook
private Object readResolve() throws InvalidObjectException {
log.trace( "Resolving serialized TypeConfiguration - readResolve" );
return TypeConfigurationRegistry.INSTANCE.findTypeConfiguration( getUuid() );
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

View File

@ -25,10 +25,15 @@ import org.hibernate.bytecode.enhance.spi.EnhancementContext;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.cfg.Environment;
import org.hibernate.dialect.Dialect;
import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.jpa.HibernatePersistenceProvider;
import org.hibernate.jpa.boot.spi.Bootstrap;
import org.hibernate.jpa.boot.spi.PersistenceUnitDescriptor;
import org.hibernate.query.sqm.mutation.internal.idtable.GlobalTemporaryTableStrategy;
import org.hibernate.query.sqm.mutation.internal.idtable.LocalTemporaryTableStrategy;
import org.hibernate.testing.jdbc.SharedDriverManagerConnectionProviderImpl;
import org.hibernate.testing.junit4.BaseUnitTestCase;
import org.junit.After;
import org.junit.Before;
@ -223,6 +228,14 @@ public abstract class BaseEntityManagerFunctionalTestCase extends BaseUnitTestCa
config.put( AvailableSettings.XML_FILE_NAMES, dds );
}
if ( !config.containsKey( Environment.CONNECTION_PROVIDER ) ) {
config.put( GlobalTemporaryTableStrategy.DROP_ID_TABLES, "true" );
config.put( LocalTemporaryTableStrategy.DROP_ID_TABLES, "true" );
config.put(
AvailableSettings.CONNECTION_PROVIDER,
SharedDriverManagerConnectionProviderImpl.getInstance()
);
}
addConfigOptions( config );
return config;
}

View File

@ -254,14 +254,14 @@ public class TreatKeywordTest extends BaseEntityManagerFunctionalTestCase {
em.close();
}
@Entity
@Entity(name = "TreatAnimal")
public static abstract class TreatAnimal {
@Id
@GeneratedValue
private Long id;
}
@Entity
@Entity(name = "Dog")
public static abstract class Dog extends TreatAnimal {
private boolean fast;
@ -274,14 +274,14 @@ public class TreatKeywordTest extends BaseEntityManagerFunctionalTestCase {
}
}
@Entity
@Entity(name = "Dachshund")
public static class Dachshund extends Dog {
public Dachshund() {
super( false );
}
}
@Entity
@Entity(name = "Greyhound")
public static class Greyhound extends Dog {
public Greyhound() {
super( true );

View File

@ -14,6 +14,7 @@ import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import org.hibernate.dialect.CockroachDialect;
import org.hibernate.dialect.DerbyDialect;
import org.hibernate.dialect.Oracle12cDialect;
import org.hibernate.jpa.test.metamodel.AbstractMetamodelSpecificTest;
import org.hibernate.jpa.test.metamodel.CreditCard;
@ -300,6 +301,7 @@ public class PredicateTest extends AbstractMetamodelSpecificTest {
@Test
@TestForIssue( jiraKey = "HHH-8901" )
@RequiresDialectFeature( DialectChecks.NotSupportsEmptyInListCheck.class )
@SkipForDialect(value = DerbyDialect.class, comment = "Derby doesn't like `x in (null)`")
public void testEmptyInPredicate() {
EntityManager em = getOrCreateEntityManager();
em.getTransaction().begin();

View File

@ -16,6 +16,7 @@ import javax.persistence.criteria.CriteriaQuery;
import org.hibernate.dialect.CockroachDialect;
import org.hibernate.dialect.PostgreSQL81Dialect;
import org.hibernate.dialect.SQLServerDialect;
import org.hibernate.jpa.test.BaseEntityManagerFunctionalTestCase;
import org.hibernate.testing.SkipForDialect;
@ -64,11 +65,11 @@ public class CriteriaLiteralWithSingleQuoteTest extends BaseEntityManagerFunctio
@Test
@SkipForDialects(
value = {
@SkipForDialect(value = SQLServerDialect.class, comment = "SQLServer does not support literals in group by statement"),
@SkipForDialect(value = PostgreSQL81Dialect.class, comment = "PostgreSQL does not support literals in group by statement"),
@SkipForDialect( value = CockroachDialect.class, comment = "CockroachDB does not support literals in group by statement")
}
)
@SkipForDialect(value = PostgreSQL81Dialect.class, comment = "PostgreSQL does not support literals in group by statement")
public void testLiteralProjectionAndGroupBy() throws Exception {
doInJPA(
this::entityManagerFactory,

View File

@ -17,6 +17,7 @@ import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import org.hibernate.dialect.DB2Dialect;
import org.hibernate.dialect.DerbyDialect;
import org.hibernate.dialect.PostgreSQL95Dialect;
import org.hibernate.jpa.test.BaseEntityManagerFunctionalTestCase;
import org.hibernate.jpa.test.metadata.Person_;
@ -32,6 +33,7 @@ import static org.junit.Assert.assertTrue;
@TestForIssue(jiraKey = "HHH-12230")
@SkipForDialect(value = DB2Dialect.class, comment = "We would need casts in the case clauses. See HHH-12822.")
@SkipForDialect(value = DerbyDialect.class, comment = "Derby requires either casted parameters or literals in the result arms of CASE expressions")
public class GroupBySelectCaseTest extends BaseEntityManagerFunctionalTestCase {
@Override

View File

@ -17,9 +17,12 @@ import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.dialect.DB2Dialect;
import org.hibernate.dialect.DerbyDialect;
import org.hibernate.jpa.test.BaseEntityManagerFunctionalTestCase;
import org.hibernate.query.criteria.LiteralHandlingMode;
import org.hibernate.testing.SkipForDialect;
import org.hibernate.testing.TestForIssue;
import org.junit.Test;
@ -101,6 +104,8 @@ public class SelectCaseLiteralHandlingBindTest extends BaseEntityManagerFunction
}
@Test
@SkipForDialect(value = DB2Dialect.class, comment = "We would need casts in the case clauses. See HHH-12822.")
@SkipForDialect(value = DerbyDialect.class, comment = "Derby requires either casted parameters or literals in the result arms of CASE expressions")
public void whereCaseExpression() {
doInJPA( this::entityManagerFactory, entityManager -> {

View File

@ -35,6 +35,7 @@ import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import org.hibernate.dialect.DB2Dialect;
import org.hibernate.dialect.DerbyDialect;
import org.hibernate.dialect.H2Dialect;
import org.hibernate.jpa.test.BaseEntityManagerFunctionalTestCase;
@ -45,6 +46,7 @@ import org.junit.Test;
@TestForIssue( jiraKey = "HHH-9731" )
@SkipForDialect(value = DB2Dialect.class, comment = "We would need casts in the case clauses. See HHH-12822.")
@SkipForDialect(value = DerbyDialect.class, comment = "Derby requires either casted parameters or literals in the result arms of CASE expressions")
public class SelectCaseTest extends BaseEntityManagerFunctionalTestCase {
@Override

View File

@ -10,6 +10,7 @@ import java.sql.SQLException;
import java.util.Map;
import javax.persistence.EntityManager;
import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider;
import org.hibernate.jpa.AvailableSettings;
import org.hibernate.jpa.test.BaseEntityManagerFunctionalTestCase;
import org.hibernate.jpa.test.Wallet;
@ -34,6 +35,7 @@ public class DisableDiscardPersistenceContextOnCloseTest extends BaseEntityManag
@Override
protected Map getConfig() {
Map config = super.getConfig();
connectionProvider.setConnectionProvider( (ConnectionProvider) config.get( org.hibernate.cfg.AvailableSettings.CONNECTION_PROVIDER ) );
config.put( AvailableSettings.DISCARD_PC_ON_CLOSE, "false");
config.put(
org.hibernate.cfg.AvailableSettings.CONNECTION_PROVIDER,

View File

@ -10,6 +10,7 @@ import java.util.Map;
import javax.persistence.EntityManager;
import org.hibernate.dialect.DB2Dialect;
import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider;
import org.hibernate.jpa.AvailableSettings;
import org.hibernate.jpa.test.BaseEntityManagerFunctionalTestCase;
import org.hibernate.jpa.test.Wallet;
@ -35,6 +36,7 @@ public class EnableDiscardPersistenceContextOnCloseTest extends BaseEntityManage
@Override
protected Map getConfig() {
Map config = super.getConfig();
connectionProvider.setConnectionProvider( (ConnectionProvider) config.get( org.hibernate.cfg.AvailableSettings.CONNECTION_PROVIDER ) );
config.put( AvailableSettings.DISCARD_PC_ON_CLOSE, "true");
config.put(
org.hibernate.cfg.AvailableSettings.CONNECTION_PROVIDER,

View File

@ -25,6 +25,7 @@ import org.hibernate.LockOptions;
import org.hibernate.Session;
import org.hibernate.TransactionException;
import org.hibernate.dialect.CockroachDialect;
import org.hibernate.dialect.DerbyDialect;
import org.hibernate.dialect.Dialect;
import org.hibernate.dialect.HSQLDialect;
import org.hibernate.dialect.Oracle10gDialect;
@ -38,6 +39,7 @@ import org.hibernate.testing.RequiresDialect;
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.transaction.TransactionUtil;
import org.hibernate.testing.util.ExceptionUtil;
import org.jboss.logging.Logger;
@ -56,6 +58,14 @@ public class LockTest extends BaseEntityManagerFunctionalTestCase {
private static final Logger log = Logger.getLogger( LockTest.class );
@Override
protected void addConfigOptions(Map options) {
super.addConfigOptions( options );
// Looks like Oracle Connections that experience a timeout produce different errors when they timeout again?!
SharedDriverManagerConnectionProviderImpl.getInstance().reset();
options.remove( org.hibernate.cfg.AvailableSettings.CONNECTION_PROVIDER );
}
@Test
@SkipForDialect( value = CockroachDialect.class )
public void testFindWithTimeoutHint() {
@ -557,6 +567,7 @@ public class LockTest extends BaseEntityManagerFunctionalTestCase {
// ASE15.5 will generate select...holdlock and fail at this test, but ASE15.7 passes it. Skip it for ASE15.5
// only.
@SkipForDialect(value = { SQLServerDialect.class })
@SkipForDialect(DerbyDialect.class)
public void testContendedPessimisticLock() throws Exception {
final CountDownLatch latch = new CountDownLatch( 1 );
final Lock lock = new Lock();
@ -622,7 +633,7 @@ public class LockTest extends BaseEntityManagerFunctionalTestCase {
try {
t.start();
boolean backGroundThreadCompleted = latch.await( 10, TimeUnit.SECONDS ); // should return quickly on success
boolean backGroundThreadCompleted = latch.await( 20, TimeUnit.SECONDS ); // should return quickly on success
if ( backGroundThreadCompleted ) {
// the background thread read a value. At the very least we need to assert that he did not see the
@ -646,12 +657,7 @@ public class LockTest extends BaseEntityManagerFunctionalTestCase {
} );
}
finally {
t.join(); // wait for background thread to finish before deleting entity
doInJPA( this::entityManagerFactory, em -> {
Lock _lock = em.getReference( Lock.class, lock.getId() );
em.remove( _lock );
} );
awaitThenDelete( "testContendedPessimisticLock", t, lock.getId() );
}
}
@ -720,7 +726,7 @@ public class LockTest extends BaseEntityManagerFunctionalTestCase {
try {
t.start();
boolean latchSet = latch.await( 10, TimeUnit.SECONDS ); // should return quickly on success
boolean latchSet = latch.await( 20, TimeUnit.SECONDS ); // should return quickly on success
assertTrue( "background test thread finished (lock timeout is broken)", latchSet );
assertTrue( "background test thread timed out on lock attempt", bgTask.get() );
}
@ -728,17 +734,12 @@ public class LockTest extends BaseEntityManagerFunctionalTestCase {
Thread.interrupted();
}
catch (ExecutionException e) {
fail(e.getMessage());
throw new AssertionError( e );
}
} );
}
finally {
t.join(); // wait for background thread to finish before deleting entity
doInJPA( this::entityManagerFactory, em -> {
Lock _lock = em.getReference( Lock.class, lock.getId() );
em.remove( _lock );
} );
awaitThenDelete( "testContendedPessimisticReadLockTimeout", t, lock.getId() );
}
}
@ -805,7 +806,7 @@ public class LockTest extends BaseEntityManagerFunctionalTestCase {
try {
t.start();
boolean latchSet = latch.await( 10, TimeUnit.SECONDS ); // should return quickly on success
boolean latchSet = latch.await( 20, TimeUnit.SECONDS ); // should return quickly on success
assertTrue( "background test thread finished (lock timeout is broken)", latchSet );
assertTrue( "background test thread timed out on lock attempt", bgTask.get() );
}
@ -813,17 +814,12 @@ public class LockTest extends BaseEntityManagerFunctionalTestCase {
Thread.interrupted();
}
catch (ExecutionException e) {
fail(e.getMessage());
throw new AssertionError( e );
}
} );
}
finally {
t.join(); // wait for background thread to finish before deleting entity
doInJPA( this::entityManagerFactory, em -> {
Lock _lock = em.getReference( Lock.class, lock.getId() );
em.remove( _lock );
} );
awaitThenDelete( "testContendedPessimisticWriteLockTimeout", t, lock.getId() );
}
}
@ -890,7 +886,7 @@ public class LockTest extends BaseEntityManagerFunctionalTestCase {
try {
t.start();
boolean latchSet = latch.await( 10, TimeUnit.SECONDS ); // should return quickly on success
boolean latchSet = latch.await( 20, TimeUnit.SECONDS ); // should return quickly on success
assertTrue( "background test thread finished (lock timeout is broken)", latchSet );
assertTrue( "background test thread timed out on lock attempt", bgTask.get() );
}
@ -898,17 +894,12 @@ public class LockTest extends BaseEntityManagerFunctionalTestCase {
Thread.interrupted();
}
catch (ExecutionException e) {
fail(e.getMessage());
throw new AssertionError( e );
}
} );
}
finally {
t.join(); // wait for background thread to finish before deleting entity
doInJPA( this::entityManagerFactory, em -> {
Lock _lock = em.getReference( Lock.class, lock.getId() );
em.remove( _lock );
} );
awaitThenDelete( "testContendedPessimisticWriteLockNoWait", t, lock.getId() );
}
}
@ -980,7 +971,7 @@ public class LockTest extends BaseEntityManagerFunctionalTestCase {
try {
t.start();
boolean latchSet = latch.await( 10, TimeUnit.SECONDS ); // should return quickly on success
boolean latchSet = latch.await( 20, TimeUnit.SECONDS ); // should return quickly on success
assertTrue( "background test thread finished (lock timeout is broken)", latchSet );
assertTrue( "background test thread timed out on lock attempt", bgTask.get() );
}
@ -988,17 +979,12 @@ public class LockTest extends BaseEntityManagerFunctionalTestCase {
Thread.interrupted();
}
catch (ExecutionException e) {
fail(e.getMessage());
throw new AssertionError( e );
}
} );
}
finally {
t.join(); // wait for background thread to finish before deleting entity
doInJPA( this::entityManagerFactory, em -> {
Lock _lock = em.getReference( Lock.class, lock.getId() );
em.remove( _lock );
} );
awaitThenDelete( "testQueryTimeout", t, lock.getId() );
}
}
@ -1071,7 +1057,7 @@ public class LockTest extends BaseEntityManagerFunctionalTestCase {
try {
t.start();
boolean latchSet = latch.await( 10, TimeUnit.SECONDS ); // should return quickly on success
boolean latchSet = latch.await( 20, TimeUnit.SECONDS ); // should return quickly on success
assertTrue( "background test thread finished (lock timeout is broken)", latchSet );
assertTrue( "background test thread timed out on lock attempt", bgTask.get() );
}
@ -1079,17 +1065,12 @@ public class LockTest extends BaseEntityManagerFunctionalTestCase {
Thread.interrupted();
}
catch (ExecutionException e) {
fail(e.getMessage());
throw new AssertionError( e );
}
} );
}
finally {
t.join(); // wait for background thread to finish before deleting entity
doInJPA( this::entityManagerFactory, em -> {
Lock _lock = em.getReference( Lock.class, lock.getId() );
em.remove( _lock );
} );
awaitThenDelete( "testQueryTimeoutEMProps", t, lock.getId() );
}
}
@ -1157,7 +1138,7 @@ public class LockTest extends BaseEntityManagerFunctionalTestCase {
try {
t.start();
boolean latchSet = latch.await( 10, TimeUnit.SECONDS ); // should return quickly on success
boolean latchSet = latch.await( 20, TimeUnit.SECONDS ); // should return quickly on success
assertTrue( "background test thread finished (lock timeout is broken)", latchSet );
assertTrue( "background test thread timed out on lock attempt", bgTask.get() );
}
@ -1165,17 +1146,12 @@ public class LockTest extends BaseEntityManagerFunctionalTestCase {
Thread.interrupted();
}
catch (ExecutionException e) {
fail(e.getMessage());
throw new AssertionError( e );
}
} );
}
finally {
t.join(); // wait for background thread to finish before deleting entity
doInJPA( this::entityManagerFactory, em -> {
Lock _lock = em.getReference( Lock.class, lock.getId() );
em.remove( _lock );
} );
awaitThenDelete( "testLockTimeoutEMProps", t, lock.getId() );
}
}
@ -1186,4 +1162,22 @@ public class LockTest extends BaseEntityManagerFunctionalTestCase {
UnversionedLock.class
};
}
private void awaitThenDelete(String test, Thread t, Integer lockId) throws InterruptedException {
// wait for background thread to finish before deleting entity
try {
while ( t.isAlive() ) {
t.join( TimeUnit.SECONDS.toMillis( 30 ) );
final Throwable temp = new Throwable();
temp.setStackTrace( t.getStackTrace() );
log.info( test + ": Thread seems stuck", temp );
t.interrupt();
}
} finally {
doInJPA( this::entityManagerFactory, em -> {
Lock _lock = em.getReference( Lock.class, lockId );
em.remove( _lock );
} );
}
}
}

View File

@ -12,7 +12,9 @@ import java.util.HashMap;
import java.util.Map;
import javax.persistence.LockModeType;
import org.hibernate.Session;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.dialect.CockroachDialect;
import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider;
import org.hibernate.jpa.test.BaseEntityManagerFunctionalTestCase;
import org.hibernate.test.util.jdbc.PreparedStatementSpyConnectionProvider;
import org.hibernate.testing.DialectChecks;
@ -42,6 +44,7 @@ public class StatementIsClosedAfterALockExceptionTest extends BaseEntityManagerF
@Override
protected Map getConfig() {
Map config = super.getConfig();
CONNECTION_PROVIDER.setConnectionProvider( (ConnectionProvider) config.get( AvailableSettings.CONNECTION_PROVIDER ) );
config.put(
org.hibernate.cfg.AvailableSettings.CONNECTION_PROVIDER,
CONNECTION_PROVIDER

View File

@ -8,11 +8,13 @@ package org.hibernate.jpa.test.metamodel;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* @author Steve Ebersole
*/
@Entity
@Table(name = "translation_tbl")
public class Translation {
@Id
Integer id;

View File

@ -26,6 +26,7 @@ import org.hibernate.Hibernate;
import org.hibernate.QueryException;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.dialect.CockroachDialect;
import org.hibernate.dialect.DerbyDialect;
import org.hibernate.dialect.Oracle8iDialect;
import org.hibernate.dialect.PostgreSQL9Dialect;
import org.hibernate.dialect.PostgresPlusDialect;
@ -136,6 +137,7 @@ public class QueryTest extends BaseEntityManagerFunctionalTestCase {
@Test
@SkipForDialect(value = SybaseDialect.class, comment = "Null == null on Sybase")
@SkipForDialect(value = DerbyDialect.class, comment = "Cannot convert untyped null (assumed to be VARBINARY type) to VARCHAR")
public void testNullPositionalParameter() throws Exception {
EntityManager em = getOrCreateEntityManager();
em.getTransaction().begin();
@ -166,6 +168,7 @@ public class QueryTest extends BaseEntityManagerFunctionalTestCase {
@Test
@SkipForDialect(value = SybaseDialect.class, comment = "Null == null on Sybase")
@SkipForDialect(value = DerbyDialect.class, comment = "Cannot convert untyped null (assumed to be VARBINARY type) to VARCHAR")
public void testNullPositionalParameterParameter() throws Exception {
EntityManager em = getOrCreateEntityManager();
em.getTransaction().begin();
@ -213,6 +216,7 @@ public class QueryTest extends BaseEntityManagerFunctionalTestCase {
@Test
@SkipForDialect(value = SybaseDialect.class, comment = "Null == null on Sybase")
@SkipForDialect(value = DerbyDialect.class, comment = "Cannot convert untyped null (assumed to be VARBINARY type) to VARCHAR")
public void testNullPositionalParameterParameterIncompatible() throws Exception {
EntityManager em = getOrCreateEntityManager();
em.getTransaction().begin();
@ -260,6 +264,7 @@ public class QueryTest extends BaseEntityManagerFunctionalTestCase {
@Test
@SkipForDialect(value = SybaseDialect.class, comment = "Null == null on Sybase")
@SkipForDialect(value = DerbyDialect.class, comment = "Cannot convert untyped null (assumed to be VARBINARY type) to VARCHAR")
public void testNullNamedParameter() throws Exception {
EntityManager em = getOrCreateEntityManager();
em.getTransaction().begin();
@ -290,6 +295,7 @@ public class QueryTest extends BaseEntityManagerFunctionalTestCase {
@Test
@SkipForDialect(value = SybaseDialect.class, comment = "Null == null on Sybase")
@SkipForDialect(value = DerbyDialect.class, comment = "Cannot convert untyped null (assumed to be VARBINARY type) to VARCHAR")
public void testNullNamedParameterParameter() throws Exception {
EntityManager em = getOrCreateEntityManager();
em.getTransaction().begin();
@ -336,6 +342,7 @@ public class QueryTest extends BaseEntityManagerFunctionalTestCase {
@Test
@SkipForDialect(value = SybaseDialect.class, comment = "Null == null on Sybase")
@SkipForDialect(value = DerbyDialect.class, comment = "Cannot convert untyped null (assumed to be VARBINARY type) to VARCHAR")
public void testNullNamedParameterParameterIncompatible() throws Exception {
EntityManager em = getOrCreateEntityManager();
em.getTransaction().begin();
@ -386,6 +393,7 @@ public class QueryTest extends BaseEntityManagerFunctionalTestCase {
@SkipForDialect(value = PostgresPlusDialect.class, jiraKey = "HHH-10312", comment = "Cannot convert untyped null (assumed to be bytea type) to bigint")
@SkipForDialect(value = CockroachDialect.class, jiraKey = "HHH-10312", comment = "Cannot convert untyped null (assumed to be bytea type) to bigint")
@SkipForDialect(value = SybaseDialect.class, comment = "Null == null on Sybase")
@SkipForDialect(value = DerbyDialect.class, comment = "Cannot convert untyped null (assumed to be VARBINARY type) to INTEGER")
public void testNativeQueryNullPositionalParameter() throws Exception {
EntityManager em = getOrCreateEntityManager();
em.getTransaction().begin();
@ -423,6 +431,7 @@ public class QueryTest extends BaseEntityManagerFunctionalTestCase {
@SkipForDialect(value = CockroachDialect.class, jiraKey = "HHH-10312", comment = "Cannot convert untyped null (assumed to be bytea type) to bigint")
@SkipForDialect(value = Oracle8iDialect.class, comment = "ORA-00932: inconsistent datatypes: expected NUMBER got BINARY")
@SkipForDialect(value = SybaseDialect.class, comment = "Null == null on Sybase")
@SkipForDialect(value = DerbyDialect.class, comment = "Cannot convert untyped null (assumed to be VARBINARY type) to INTEGER")
public void testNativeQueryNullPositionalParameterParameter() throws Exception {
EntityManager em = getOrCreateEntityManager();
em.getTransaction().begin();
@ -476,6 +485,7 @@ public class QueryTest extends BaseEntityManagerFunctionalTestCase {
@SkipForDialect(value = PostgresPlusDialect.class, jiraKey = "HHH-10312", comment = "Cannot convert untyped null (assumed to be bytea type) to bigint")
@SkipForDialect(value = CockroachDialect.class, jiraKey = "HHH-10312", comment = "Cannot convert untyped null (assumed to be bytea type) to bigint")
@SkipForDialect(value = SybaseDialect.class, comment = "Null == null on Sybase")
@SkipForDialect(value = DerbyDialect.class, comment = "Cannot convert untyped null (assumed to be VARBINARY type) to INTEGER")
public void testNativeQueryNullNamedParameter() throws Exception {
EntityManager em = getOrCreateEntityManager();
em.getTransaction().begin();
@ -513,6 +523,7 @@ public class QueryTest extends BaseEntityManagerFunctionalTestCase {
@SkipForDialect(value = CockroachDialect.class, jiraKey = "HHH-10312", comment = "Cannot convert untyped null (assumed to be bytea type) to bigint")
@SkipForDialect(value = Oracle8iDialect.class, comment = "ORA-00932: inconsistent datatypes: expected NUMBER got BINARY")
@SkipForDialect(value = SybaseDialect.class, comment = "Null == null on Sybase")
@SkipForDialect(value = DerbyDialect.class, comment = "Cannot convert untyped null (assumed to be VARBINARY type) to INTEGER")
public void testNativeQueryNullNamedParameterParameter() throws Exception {
EntityManager em = getOrCreateEntityManager();
em.getTransaction().begin();

View File

@ -49,7 +49,7 @@ public class JpaSchemaGeneratorTest extends BaseEntityManagerFunctionalTestCase
@TestForIssue(jiraKey = "HHH-8271")
public void testSqlLoadScriptSourceClasspath() throws Exception {
Map settings = buildSettings();
settings.put( AvailableSettings.HBM2DDL_DATABASE_ACTION, "drop-and-create" );
settings.put( AvailableSettings.HBM2DDL_DATABASE_ACTION, "create-drop" );
settings.put( AvailableSettings.HBM2DDL_LOAD_SCRIPT_SOURCE, getLoadSqlScript() );
doTest( settings );
}
@ -60,7 +60,7 @@ public class JpaSchemaGeneratorTest extends BaseEntityManagerFunctionalTestCase
@TestForIssue(jiraKey = "HHH-8271")
public void testSqlLoadScriptSourceUrl() throws Exception {
Map settings = buildSettings();
settings.put( AvailableSettings.HBM2DDL_DATABASE_ACTION, "drop-and-create" );
settings.put( AvailableSettings.HBM2DDL_DATABASE_ACTION, "create-drop" );
settings.put( AvailableSettings.HBM2DDL_LOAD_SCRIPT_SOURCE, getResourceUrlString( getLoadSqlScript() ) );
doTest( settings );
}
@ -78,7 +78,7 @@ public class JpaSchemaGeneratorTest extends BaseEntityManagerFunctionalTestCase
@TestForIssue(jiraKey = "HHH-8271")
public void testSqlCreateScriptSourceClasspath() throws Exception {
Map settings = buildSettings();
settings.put( AvailableSettings.HBM2DDL_DATABASE_ACTION, "drop-and-create" );
settings.put( AvailableSettings.HBM2DDL_DATABASE_ACTION, "create-drop" );
settings.put( AvailableSettings.HBM2DDL_CREATE_SOURCE, "metadata-then-script" );
settings.put( AvailableSettings.HBM2DDL_CREATE_SCRIPT_SOURCE, getCreateSqlScript() );
doTest( settings );
@ -89,7 +89,7 @@ public class JpaSchemaGeneratorTest extends BaseEntityManagerFunctionalTestCase
@TestForIssue(jiraKey = "HHH-8271")
public void testSqlCreateScriptSourceUrl() throws Exception {
Map settings = buildSettings();
settings.put( AvailableSettings.HBM2DDL_DATABASE_ACTION, "drop-and-create" );
settings.put( AvailableSettings.HBM2DDL_DATABASE_ACTION, "create-drop" );
settings.put( AvailableSettings.HBM2DDL_CREATE_SOURCE, "metadata-then-script" );
settings.put( AvailableSettings.HBM2DDL_CREATE_SCRIPT_SOURCE, getResourceUrlString( getCreateSqlScript() ) );
doTest( settings );

View File

@ -165,6 +165,11 @@ public class FlushAndTransactionTest extends BaseEntityManagerFunctionalTestCase
catch ( IllegalStateException e ) {
//success
}
finally {
if ( em.getTransaction().isActive() ) {
em.getTransaction().rollback();
}
}
}
@Test

View File

@ -75,7 +75,9 @@ public class JtaWithFailingBatchTest extends AbstractJtaBatchTest {
}
catch (Exception expected) {
//expected
if ( transactionManager.getStatus() == Status.STATUS_ACTIVE ) {
switch ( transactionManager.getStatus() ) {
case Status.STATUS_ACTIVE:
case Status.STATUS_MARKED_ROLLBACK:
transactionManager.rollback();
}
}
@ -89,7 +91,6 @@ public class JtaWithFailingBatchTest extends AbstractJtaBatchTest {
assertStatementsListIsCleared();
}
finally {
em.close();
}

View File

@ -14,6 +14,7 @@ import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.hibernate.testing.orm.junit.Jpa;
import org.hibernate.testing.orm.junit.EntityManagerFactoryScope;
@ -32,8 +33,8 @@ public class MergeTest {
public void tearDown(EntityManagerFactoryScope scope) {
scope.inTransaction(
entityManager -> {
entityManager.createQuery( "delete from MergeTest$Item" ).executeUpdate();
entityManager.createQuery( "delete from MergeTest$Order" ).executeUpdate();
entityManager.createQuery( "delete from Item" ).executeUpdate();
entityManager.createQuery( "delete from Order" ).executeUpdate();
}
);
}
@ -104,7 +105,8 @@ public class MergeTest {
);
}
@Entity
@Entity(name = "Order")
@Table(name = "orders")
public static class Order {
@Id
@GeneratedValue
@ -122,7 +124,7 @@ public class MergeTest {
}
}
@Entity
@Entity(name = "Item")
public static class Item {
@Id
@GeneratedValue

View File

@ -10,6 +10,9 @@ import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.ParameterExpression;
import javax.persistence.criteria.Root;
import org.hibernate.dialect.DerbyDialect;
import org.hibernate.testing.SkipForDialect;
import org.hibernate.dialect.H2Dialect;
import org.hibernate.query.criteria.HibernateCriteriaBuilder;
import org.hibernate.query.criteria.JpaCriteriaQuery;
@ -111,6 +114,7 @@ public class BasicCriteriaExecutionTests {
// Doing ... where ? = ? ... is only allowed in a few DBs. Since this is useless, we don't bother to emulate this
@Test
@RequiresDialect(H2Dialect.class)
@SkipForDialect(value = DerbyDialect.class, comment = "Derby doesn't support comparing parameters against each other")
public void testExecutingBasicCriteriaQueryParameterPredicate(SessionFactoryScope scope) {
scope.inStatelessTransaction(
session -> {
@ -130,6 +134,7 @@ public class BasicCriteriaExecutionTests {
// Doing ... where ? = ? ... is only allowed in a few DBs. Since this is useless, we don't bother to emulate this
@Test
@RequiresDialect(H2Dialect.class)
@SkipForDialect(value = DerbyDialect.class, comment = "Derby doesn't support comparing parameters against each other")
public void testExecutingBasicCriteriaQueryParameterPredicateInStatelessSession(SessionFactoryScope scope) {
scope.inStatelessTransaction(
session -> {

View File

@ -19,6 +19,7 @@ import javax.persistence.criteria.Path;
import javax.persistence.criteria.Root;
import org.hibernate.dialect.DB2Dialect;
import org.hibernate.dialect.DerbyDialect;
import org.hibernate.dialect.H2Dialect;
import org.hibernate.dialect.PostgreSQL81Dialect;
@ -65,6 +66,7 @@ public class SearchedCaseExpressionTest extends BaseCoreFunctionalTestCase {
@Test
@SkipForDialect(value = DB2Dialect.class, comment = "We would need casts in the case clauses. See HHH-12822.")
@SkipForDialect(value = DerbyDialect.class, comment = "Derby requires either casted parameters or literals in the result arms of CASE expressions")
public void testEqualClause() {
doInHibernate( this::sessionFactory, session -> {
CriteriaBuilder cb = session.getCriteriaBuilder();
@ -89,6 +91,8 @@ public class SearchedCaseExpressionTest extends BaseCoreFunctionalTestCase {
@Test
@TestForIssue(jiraKey = "HHH-13167")
@SkipForDialect(value = DB2Dialect.class, comment = "We would need casts in the case clauses. See HHH-12822.")
@SkipForDialect(value = DerbyDialect.class, comment = "Derby requires either casted parameters or literals in the result arms of CASE expressions")
public void testMissingElseClause() {
doInHibernate( this::sessionFactory, session -> {
Event event = new Event();

View File

@ -7,6 +7,10 @@ import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.Table;
import org.hibernate.dialect.DerbyDialect;
import org.hibernate.dialect.SQLServerDialect;
import org.hibernate.testing.SkipForDialect;
import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase;
import org.junit.Test;
@ -24,6 +28,8 @@ public class HHH14156Test extends BaseCoreFunctionalTestCase {
}
@Test
@SkipForDialect(value = SQLServerDialect.class, comment = "SQLServer doesn't support tuple comparisons")
@SkipForDialect(value = DerbyDialect.class, comment = "Derby doesn't support tuple comparisons")
public void testNoExceptionThrown() {
inTransaction( session ->
session.createQuery(

View File

@ -161,7 +161,7 @@ public class JaccIntegratorTest extends BaseEntityManagerFunctionalTestCase {
}
}
@Entity
@Entity(name = "Person")
public static class Person {
@Id

View File

@ -36,6 +36,7 @@ public class LobTest extends BaseCoreFunctionalTestCase {
entity.setQwerty(randomString(4000));
session.save(entity);
session.getTransaction().commit();
session.close();
}
@Override
@ -60,5 +61,7 @@ public class LobTest extends BaseCoreFunctionalTestCase {
String s = (String) query.uniqueResult();
log.debug( "Using Oracle charset " + s );
session.getTransaction().commit();
session.close();
}
}

View File

@ -23,6 +23,7 @@ import org.hibernate.Transaction;
import org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyJpaImpl;
import org.hibernate.cfg.Configuration;
import org.hibernate.dialect.AbstractHANADialect;
import org.hibernate.dialect.DerbyDialect;
import org.hibernate.dialect.Oracle8iDialect;
import org.hibernate.dialect.PostgreSQL81Dialect;
import org.hibernate.dialect.PostgreSQL9Dialect;
@ -107,6 +108,7 @@ public class QueryAndSQLTest extends BaseCoreFunctionalTestCase {
@SkipForDialect(value = PostgresPlusDialect.class, jiraKey = "HHH-10312", comment = "Cannot convert untyped null (assumed to be bytea type) to bigint")
@SkipForDialect(value = CockroachDialect.class, jiraKey = "HHH-10312", comment = "Cannot convert untyped null (assumed to be bytea type) to bigint")
@SkipForDialect(value = SybaseDialect.class, comment = "Null == null on Sybase")
@SkipForDialect(value = DerbyDialect.class, comment = "Cannot convert untyped null (assumed to be VARBINARY type) to BIGINT")
public void testQueryWithNullParameter(){
Chaos c0 = new Chaos();
c0.setId( 0L );
@ -193,6 +195,7 @@ public class QueryAndSQLTest extends BaseCoreFunctionalTestCase {
@SkipForDialect(value = PostgresPlusDialect.class, jiraKey = "HHH-10312", comment = "Cannot convert untyped null (assumed to be bytea type) to bigint")
@SkipForDialect(value = CockroachDialect.class, jiraKey = "HHH-10312", comment = "Cannot convert untyped null (assumed to be bytea type) to bigint")
@SkipForDialect(value = SybaseDialect.class, comment = "Null == null on Sybase")
@SkipForDialect(value = DerbyDialect.class, comment = "Cannot convert untyped null (assumed to be VARBINARY type) to BIGINT")
public void testNativeQueryWithNullParameter(){
Chaos c0 = new Chaos();
c0.setId( 0L );

View File

@ -178,17 +178,17 @@ public class QueryTest extends BaseEntityManagerFunctionalTestCase {
@Embeddable
public static class Name {
public String first;
public String middle;
public String last;
public String firstName;
public String middleName;
public String lastName;
public Name() {
}
public Name(String first, String middle, String last) {
this.first = first;
this.middle = middle;
this.last = last;
public Name(String firstName, String middleName, String lastName) {
this.firstName = firstName;
this.middleName = middleName;
this.lastName = lastName;
}
}

View File

@ -135,6 +135,7 @@ public class BeforeCompletionReleaseTest extends BaseEntityManagerFunctionalTest
inOrder.verify( statementMock ).close();
inOrder.verify( connectionSpy ).close();
inOrder.verify( transactionSpy ).commit( any(), anyBoolean() );
Mockito.reset( connectionSpy );
}
private void spyOnTransaction(XAResource xaResource) {

View File

@ -27,6 +27,9 @@ import org.hibernate.testing.RequiresDialect;
import org.hibernate.testing.TestForIssue;
import org.junit.Test;
import org.mockito.Mockito;
import org.mockito.internal.util.MockUtil;
import static org.hibernate.testing.transaction.TransactionUtil.doInJPA;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.spy;
@ -92,6 +95,7 @@ public class ConnectionsReleaseAutoCommitTest extends BaseEntityManagerFunctiona
assertEquals( 1, connectionProvider.getConnectionCount() );
verify( connectionProvider.connection, times( 1 ) ).close();
Mockito.reset( connectionProvider.connection );
}
@Entity(name = "Thing")

View File

@ -20,8 +20,12 @@ import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.dialect.CockroachDialect;
import org.hibernate.dialect.DB2Dialect;
import org.hibernate.dialect.DerbyDialect;
import org.hibernate.dialect.Dialect;
import org.hibernate.dialect.PostgreSQL81Dialect;
import org.hibernate.mapping.PersistentClass;
import org.hibernate.testing.SkipForDialect;
import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.junit4.BaseUnitTestCase;
import org.junit.Test;
@ -34,6 +38,7 @@ import static org.junit.Assert.assertEquals;
* @author Steve Ebersole
*/
//@SkipForDialect(value = PostgreSQL81Dialect.class, comment = "Postgres does not support ")
@SkipForDialect(value = DB2Dialect.class, comment = "DB2 jdbc driver doesn't support setNString")
public class AndNationalizedTests extends BaseUnitTestCase {
@Test
@TestForIssue( jiraKey = "HHH-9599")
@ -44,9 +49,10 @@ public class AndNationalizedTests extends BaseUnitTestCase {
( (MetadataImpl) metadata ).validate();
final PersistentClass entityBinding = metadata.getEntityBinding( TestEntity.class.getName() );
if(metadata.getDatabase().getDialect() instanceof PostgreSQL81Dialect
|| metadata.getDatabase().getDialect() instanceof DB2Dialect
|| metadata.getDatabase().getDialect() instanceof CockroachDialect ){
final Dialect dialect = metadata.getDatabase().getDialect();
if ( dialect instanceof PostgreSQL81Dialect
|| dialect instanceof DB2Dialect && !( dialect instanceof DerbyDialect )
|| dialect instanceof CockroachDialect ){
// See issue HHH-10693 for PostgreSQL and CockroachDB, HHH-12753 for DB2
assertEquals(
Types.VARCHAR,

View File

@ -23,11 +23,14 @@ import org.hibernate.cfg.AvailableSettings;
import org.hibernate.cfg.Configuration;
import org.hibernate.dialect.SQLServer2005Dialect;
import org.hibernate.dialect.SQLServerDialect;
import org.hibernate.engine.jdbc.connections.spi.JdbcConnectionAccess;
import org.hibernate.engine.jdbc.spi.JdbcServices;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.testing.RequiresDialect;
import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase;
import org.hibernate.testing.transaction.TransactionUtil;
import org.junit.Test;
import org.jboss.logging.Logger;
@ -56,20 +59,32 @@ public class SQLServerDialectCollationTest extends BaseCoreFunctionalTestCase {
StandardServiceRegistryImpl _serviceRegistry = buildServiceRegistry( bootRegistry, constructConfiguration() );
try {
try (Connection connection = _serviceRegistry.getService( JdbcServices.class ).getBootstrapJdbcConnectionAccess().obtainConnection();
Statement statement = connection.createStatement()) {
try {
TransactionUtil.doWithJDBC(
_serviceRegistry,
connection -> {
try (Statement statement = connection.createStatement()) {
connection.setAutoCommit( true );
statement.executeUpdate( "DROP DATABASE hibernate_orm_test_collation" );
}
}
);
}
catch (SQLException e) {
log.debug( e.getMessage() );
}
try (Connection connection = _serviceRegistry.getService( JdbcServices.class ).getBootstrapJdbcConnectionAccess().obtainConnection();
Statement statement = connection.createStatement()) {
try {
TransactionUtil.doWithJDBC(
_serviceRegistry,
connection -> {
try (Statement statement = connection.createStatement()) {
connection.setAutoCommit( true );
statement.executeUpdate( "CREATE DATABASE hibernate_orm_test_collation COLLATE Latin1_General_CS_AS" );
statement.executeUpdate( "ALTER DATABASE [hibernate_orm_test_collation] SET AUTO_CLOSE OFF " );
}
}
);
}
catch (SQLException e) {
log.debug( e.getMessage() );
}
@ -149,7 +164,6 @@ public class SQLServerDialectCollationTest extends BaseCoreFunctionalTestCase {
}
}
@Override
protected boolean rebuildSessionFactoryOnError() {
return false;

View File

@ -6,7 +6,6 @@
*/
package org.hibernate.test.dialect.functional;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
@ -21,12 +20,12 @@ import org.hibernate.boot.registry.internal.StandardServiceRegistryImpl;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.cfg.Configuration;
import org.hibernate.dialect.SQLServerDialect;
import org.hibernate.engine.jdbc.spi.JdbcServices;
import org.hibernate.testing.AfterClassOnce;
import org.hibernate.testing.RequiresDialect;
import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.jdbc.SharedDriverManagerConnectionProviderImpl;
import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase;
import org.hibernate.testing.transaction.TransactionUtil;
import org.junit.Assert;
import org.junit.Test;
@ -50,20 +49,34 @@ public class SQLServerDialectTempTableCollationTest extends BaseCoreFunctionalTe
return configuration;
}
@AfterClassOnce
protected void revertBackOriginalDBCollation() {
@Override
protected void releaseSessionFactory() {
super.releaseSessionFactory();
if ( originalDBCollation != null && collationChanged && !changedDBCollation.equals( originalDBCollation ) ) {
BootstrapServiceRegistry bootRegistry = buildBootstrapServiceRegistry();
StandardServiceRegistryImpl serviceRegistry = buildServiceRegistry(
bootRegistry,
constructConfiguration()
);
try (Connection connection = serviceRegistry.getService( JdbcServices.class )
.getBootstrapJdbcConnectionAccess()
.obtainConnection();
Statement statement = connection.createStatement()) {
try {
TransactionUtil.doWithJDBC(
serviceRegistry,
connection -> {
try (Statement statement = connection.createStatement()) {
connection.setAutoCommit( true );
statement.executeUpdate( "ALTER DATABASE CURRENT COLLATE " + originalDBCollation );
String dbName;
try ( ResultSet rs = statement.executeQuery( "SELECT DB_NAME()" ) ) {
rs.next();
dbName = rs.getString( 1 );
}
statement.execute( "USE master" );
statement.execute( "ALTER DATABASE " + dbName + " SET SINGLE_USER WITH ROLLBACK IMMEDIATE" );
statement.executeUpdate( "ALTER DATABASE " + dbName + " COLLATE " + originalDBCollation );
statement.execute( "ALTER DATABASE " + dbName + " SET MULTI_USER WITH ROLLBACK IMMEDIATE" );
statement.execute( "USE " + dbName );
}
}
);
}
catch (SQLException e) {
throw new RuntimeException( "Failed to revert back database collation to " + originalDBCollation, e );
@ -72,43 +85,71 @@ public class SQLServerDialectTempTableCollationTest extends BaseCoreFunctionalTe
serviceRegistry.destroy();
}
}
// The alter database calls could lead to issues with existing connections, so we reset the shared pool here
SharedDriverManagerConnectionProviderImpl.getInstance().reset();
}
@Override
protected void buildSessionFactory() {
BootstrapServiceRegistry bootRegistry = buildBootstrapServiceRegistry();
StandardServiceRegistryImpl serviceRegistry = buildServiceRegistry( bootRegistry, constructConfiguration() );
try {
try ( Connection connection = serviceRegistry.getService( JdbcServices.class ).getBootstrapJdbcConnectionAccess().obtainConnection();
Statement statement = connection.createStatement() ) {
try {
TransactionUtil.doWithJDBC(
serviceRegistry,
connection -> {
try (Statement statement = connection.createStatement()) {
connection.setAutoCommit( true );
try ( ResultSet rs = statement.executeQuery( "SELECT SERVERPROPERTY('collation')" ) ) {
try ( ResultSet rs = statement.executeQuery( "SELECT DATABASEPROPERTYEX(DB_NAME(),'collation')" ) ) {
rs.next();
String instanceCollation = rs.getString( 1 );
Assert.assertNotEquals( instanceCollation, changedDBCollation );
}
}
}
);
}
catch (SQLException e) {
log.debug( e.getMessage() );
}
try ( Connection connection = serviceRegistry.getService( JdbcServices.class ).getBootstrapJdbcConnectionAccess().obtainConnection();
Statement statement = connection.createStatement() ) {
try {
TransactionUtil.doWithJDBC(
serviceRegistry,
connection -> {
try (Statement statement = connection.createStatement()) {
connection.setAutoCommit( true );
try ( ResultSet rs = statement.executeQuery( "SELECT CONVERT (varchar(256), DATABASEPROPERTYEX(DB_NAME(),'collation'))" ) ) {
rs.next();
originalDBCollation = rs.getString( 1 );
}
}
}
);
}
catch (SQLException e) {
log.debug( e.getMessage() );
}
try ( Connection connection = serviceRegistry.getService( JdbcServices.class ).getBootstrapJdbcConnectionAccess().obtainConnection();
Statement statement = connection.createStatement() ) {
TransactionUtil.doWithJDBC(
serviceRegistry,
connection -> {
try (Statement statement = connection.createStatement()) {
connection.setAutoCommit( true );
statement.executeUpdate( "ALTER DATABASE CURRENT COLLATE " + changedDBCollation );
String dbName;
try ( ResultSet rs = statement.executeQuery( "SELECT DB_NAME()" ) ) {
rs.next();
dbName = rs.getString( 1 );
}
statement.execute( "USE master" );
statement.execute( "ALTER DATABASE " + dbName + " SET SINGLE_USER WITH ROLLBACK IMMEDIATE" );
statement.executeUpdate( "ALTER DATABASE " + dbName + " COLLATE " + changedDBCollation );
statement.execute( "ALTER DATABASE " + dbName + " SET MULTI_USER WITH ROLLBACK IMMEDIATE" );
statement.execute( "USE " + dbName );
collationChanged = true;
}
}
);
}
catch ( SQLException e ) {
throw new RuntimeException( e );
}

View File

@ -676,6 +676,7 @@ public class ASTParserLoadingTest extends BaseCoreFunctionalTestCase {
@Test
@TestForIssue( jiraKey = "HHH-8901" )
@RequiresDialectFeature(DialectChecks.NotSupportsEmptyInListCheck.class)
@SkipForDialect(value = DerbyDialect.class, comment = "Derby doesn't like `x in (null)`")
public void testEmptyInListForDialectsNotSupportsEmptyInList() {
Session session = openSession();
session.beginTransaction();
@ -704,6 +705,7 @@ public class ASTParserLoadingTest extends BaseCoreFunctionalTestCase {
@Test
@TestForIssue( jiraKey = "HHH-2851")
@SkipForDialect(value = DerbyDialect.class, comment = "Cannot convert untyped null (assumed to be VARBINARY type) to VARCHAR")
public void testMultipleRefsToSameParam() {
Session s = openSession();
s.beginTransaction();
@ -1800,6 +1802,7 @@ public class ASTParserLoadingTest extends BaseCoreFunctionalTestCase {
@Test
@TestForIssue(jiraKey = "HHH-1830")
@SkipForDialect(value = DerbyDialect.class, comment = "Derby doesn't see that the subquery is functionally dependent")
public void testAggregatedJoinAlias() {
Session s = openSession();
s.getTransaction().begin();

View File

@ -12,6 +12,7 @@ import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import org.hibernate.dialect.DerbyDialect;
import org.hibernate.dialect.Oracle8iDialect;
import org.hibernate.dialect.PostgreSQL81Dialect;
import org.hibernate.query.Query;
@ -66,6 +67,7 @@ public class CoalesceTest extends BaseCoreFunctionalTestCase {
@Test
@SkipForDialect( jiraKey = "HHH-10463", value = PostgreSQL81Dialect.class)
@SkipForDialect( jiraKey = "HHH-10463", value = Oracle8iDialect.class)
@SkipForDialect(value = DerbyDialect.class, comment = "Cannot convert untyped null (assumed to be VARBINARY type) to VARCHAR")
public void HHH_10463_NullInCoalesce() {
doInHibernate( this::sessionFactory, session -> {
Query query = session.createQuery("from Person p where p.name = coalesce(:name, p.name) ");

View File

@ -16,7 +16,9 @@ import org.hibernate.QueryException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.dialect.DerbyDialect;
import org.hibernate.testing.SkipForDialect;
import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase;
import org.junit.Test;
@ -243,6 +245,7 @@ public class WithClauseTest extends BaseCoreFunctionalTestCase {
@Test
@TestForIssue(jiraKey = "HHH-11401")
@SkipForDialect(value = DerbyDialect.class,comment = "Derby does not support cast from INTEGER to VARCHAR")
public void testWithClauseAsSubqueryWithKeyAndOtherJoinReference() {
TestData data = new TestData();
data.prepare();

View File

@ -16,7 +16,9 @@ import javax.persistence.Id;
import javax.persistence.ManyToMany;
import org.hibernate.Hibernate;
import org.hibernate.dialect.DerbyDialect;
import org.hibernate.testing.SkipForDialect;
import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.junit4.BaseNonConfigCoreFunctionalTestCase;
import org.junit.After;
@ -45,6 +47,7 @@ public class ManyToManySizeTest extends BaseNonConfigCoreFunctionalTestCase {
}
@Test
@SkipForDialect(value = DerbyDialect.class, comment = "Derby doesn't see that the subquery is functionally dependent")
public void testSizeAsCompoundSelectExpression() {
doInHibernate(
this::sessionFactory,
@ -73,6 +76,7 @@ public class ManyToManySizeTest extends BaseNonConfigCoreFunctionalTestCase {
}
@Test
@SkipForDialect(value = DerbyDialect.class, comment = "Derby doesn't see that the subquery is functionally dependent")
public void testSizeAsCtorSelectExpression() {
doInHibernate(
this::sessionFactory,
@ -102,6 +106,7 @@ public class ManyToManySizeTest extends BaseNonConfigCoreFunctionalTestCase {
}
@Test
@SkipForDialect(value = DerbyDialect.class, comment = "Derby doesn't see that the subquery is functionally dependent")
public void testSizeAsSelectExpressionWithLeftJoin() {
doInHibernate(
this::sessionFactory,
@ -131,6 +136,7 @@ public class ManyToManySizeTest extends BaseNonConfigCoreFunctionalTestCase {
}
@Test
@SkipForDialect(value = DerbyDialect.class, comment = "Derby doesn't see that the subquery is functionally dependent")
public void testSizeAsSelectExpressionWithInnerJoin() {
doInHibernate(
this::sessionFactory,
@ -156,6 +162,7 @@ public class ManyToManySizeTest extends BaseNonConfigCoreFunctionalTestCase {
}
@Test
@SkipForDialect(value = DerbyDialect.class, comment = "Derby doesn't see that the subquery is functionally dependent")
public void testSizeAsSelectExpressionOfAliasWithInnerJoin() {
doInHibernate(
this::sessionFactory,
@ -181,6 +188,7 @@ public class ManyToManySizeTest extends BaseNonConfigCoreFunctionalTestCase {
}
@Test
@SkipForDialect(value = DerbyDialect.class, comment = "Derby doesn't see that the subquery is functionally dependent")
public void testSizeAsSelectExpressionExcludeEmptyCollection() {
doInHibernate(
this::sessionFactory,

View File

@ -557,6 +557,7 @@ public class ManyToManySizeTest2 extends BaseNonConfigCoreFunctionalTestCase {
}
private static int countNumberOfJoins(String query) {
return query.toLowerCase( Locale.ROOT ).split( " join ", -1 ).length - 1;
String fromPart = query.toLowerCase( Locale.ROOT ).split( " from " )[1].split( " where " )[0];
return fromPart.split( "(\\sjoin\\s|,\\s)", -1 ).length - 1;
}
}

View File

@ -17,7 +17,9 @@ import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import org.hibernate.Hibernate;
import org.hibernate.dialect.DerbyDialect;
import org.hibernate.testing.SkipForDialect;
import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.junit4.BaseNonConfigCoreFunctionalTestCase;
import org.junit.After;
@ -32,6 +34,7 @@ import static org.hibernate.testing.transaction.TransactionUtil.doInHibernate;
public class OneToManySizeTest extends BaseNonConfigCoreFunctionalTestCase {
@Test
@SkipForDialect(value = DerbyDialect.class, comment = "Derby doesn't see that the subquery is functionally dependent")
public void testSizeAsSelectExpression() {
doInHibernate(
this::sessionFactory,
@ -61,6 +64,7 @@ public class OneToManySizeTest extends BaseNonConfigCoreFunctionalTestCase {
}
@Test
@SkipForDialect(value = DerbyDialect.class, comment = "Derby doesn't see that the subquery is functionally dependent")
public void testSizeAsSelectExpressionWithLeftJoin() {
doInHibernate(
this::sessionFactory,
@ -90,6 +94,7 @@ public class OneToManySizeTest extends BaseNonConfigCoreFunctionalTestCase {
}
@Test
@SkipForDialect(value = DerbyDialect.class, comment = "Derby doesn't see that the subquery is functionally dependent")
public void testSizeAsSelectExpressionWithInnerJoin() {
doInHibernate(
this::sessionFactory,
@ -115,6 +120,7 @@ public class OneToManySizeTest extends BaseNonConfigCoreFunctionalTestCase {
}
@Test
@SkipForDialect(value = DerbyDialect.class, comment = "Derby doesn't see that the subquery is functionally dependent")
public void testSizeAsSelectExpressionOfAliasWithInnerJoin() {
doInHibernate(
this::sessionFactory,
@ -140,6 +146,7 @@ public class OneToManySizeTest extends BaseNonConfigCoreFunctionalTestCase {
}
@Test
@SkipForDialect(value = DerbyDialect.class, comment = "Derby doesn't see that the subquery is functionally dependent")
public void testSizeAsSelectExpressionExcludeEmptyCollection() {
doInHibernate(
this::sessionFactory,

View File

@ -554,6 +554,7 @@ public class OneToManySizeTest2 extends BaseNonConfigCoreFunctionalTestCase {
}
private static int countNumberOfJoins(String query) {
return query.toLowerCase( Locale.ROOT ).split( " join ", -1 ).length - 1;
String fromPart = query.toLowerCase( Locale.ROOT ).split( " from " )[1].split( " where " )[0];
return fromPart.split( "(\\sjoin\\s|,\\s)", -1 ).length - 1;
}
}

View File

@ -78,6 +78,7 @@ public class HiLoSequenceMismatchStrategyTest extends BaseCoreFunctionalTestCase
for ( String createSequenceStatement : createSequenceStatements ) {
statement.execute( createSequenceStatement );
}
connection.commit();
}
catch (SQLException e) {
fail( e.getMessage() );

View File

@ -6,6 +6,7 @@
*/
package org.hibernate.test.inheritance;
import java.util.Comparator;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.ConstraintMode;
@ -85,6 +86,7 @@ public class TransientOverrideAsPersistentJoined extends BaseNonConfigCoreFuncti
final List<Employee> employees = session.createQuery( "from Employee", Employee.class )
.getResultList();
assertEquals( 2, employees.size() );
employees.sort( Comparator.comparing( Employee::getName ) );
assertTrue( Editor.class.isInstance( employees.get( 0 ) ) );
assertTrue( Writer.class.isInstance( employees.get( 1 ) ) );
final Editor editor = (Editor) employees.get( 0 );

View File

@ -6,6 +6,7 @@
*/
package org.hibernate.test.inheritance;
import java.util.Comparator;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.ConstraintMode;
@ -84,6 +85,7 @@ public class TransientOverrideAsPersistentTablePerClass extends BaseNonConfigCor
final List<Employee> employees = session.createQuery( "from Employee", Employee.class )
.getResultList();
assertEquals( 2, employees.size() );
employees.sort( Comparator.comparing( Employee::getName ) );
assertTrue( Editor.class.isInstance( employees.get( 0 ) ) );
assertTrue( Writer.class.isInstance( employees.get( 1 ) ) );
final Editor editor = (Editor) employees.get( 0 );

View File

@ -6,6 +6,7 @@ import java.util.Map;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.cfg.Environment;
import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider;
import org.hibernate.testing.junit4.BaseNonConfigCoreFunctionalTestCase;
import org.hibernate.test.util.jdbc.PreparedStatementSpyConnectionProvider;
@ -39,6 +40,7 @@ abstract class BaseInsertOrderingTest extends BaseNonConfigCoreFunctionalTestCas
protected void addSettings(Map settings) {
settings.put( Environment.ORDER_INSERTS, "true" );
settings.put( Environment.STATEMENT_BATCH_SIZE, "10" );
connectionProvider.setConnectionProvider( (ConnectionProvider) settings.get( AvailableSettings.CONNECTION_PROVIDER ) );
settings.put( AvailableSettings.CONNECTION_PROVIDER, connectionProvider );
}

View File

@ -16,10 +16,12 @@ import java.sql.Statement;
import org.hibernate.JDBCException;
import org.hibernate.Session;
import org.hibernate.dialect.DerbyDialect;
import org.hibernate.engine.jdbc.spi.JdbcCoordinator;
import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.resource.jdbc.ResourceRegistry;
import org.hibernate.testing.SkipForDialect;
import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase;
import org.junit.Test;
@ -50,6 +52,7 @@ public class BasicConnectionTest extends BaseCoreFunctionalTestCase {
}
@Test
@SkipForDialect(value = DerbyDialect.class,comment = "Derby can't drop tables that are still referred to from open ResultSets")
public void testBasicJdbcUsage() throws JDBCException {
Session session = openSession();
SessionImplementor sessionImpl = (SessionImplementor) session;

View File

@ -16,6 +16,7 @@ import javax.persistence.Id;
import org.hibernate.Session;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.dialect.DB2Dialect;
import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider;
import org.hibernate.testing.DialectChecks;
import org.hibernate.testing.RequiresDialectFeature;
@ -45,6 +46,7 @@ public class SessionJdbcBatchTest
@Override
protected void addSettings(Map settings) {
settings.put( AvailableSettings.STATEMENT_BATCH_SIZE, 2 );
connectionProvider.setConnectionProvider( (ConnectionProvider) settings.get( AvailableSettings.CONNECTION_PROVIDER ) );
settings.put(
AvailableSettings.CONNECTION_PROVIDER,
connectionProvider

View File

@ -12,6 +12,7 @@ import org.hibernate.Transaction;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.cfg.Configuration;
import org.hibernate.dialect.SQLServerDialect;
import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider;
import org.hibernate.testing.DialectChecks;
import org.hibernate.testing.RequiresDialectFeature;
@ -40,6 +41,7 @@ public class JPALockTest extends AbstractJPATest {
public void configure(Configuration cfg) {
super.configure( cfg );
if( SQLServerDialect.class.isAssignableFrom( DIALECT.getClass() )) {
connectionProvider.setConnectionProvider( (ConnectionProvider) cfg.getProperties().get( AvailableSettings.CONNECTION_PROVIDER ) );
cfg.getProperties().put( AvailableSettings.CONNECTION_PROVIDER, connectionProvider );
}
}

View File

@ -16,6 +16,7 @@ import org.hibernate.cfg.AvailableSettings;
import org.hibernate.cfg.Configuration;
import org.hibernate.dialect.MariaDBDialect;
import org.hibernate.dialect.SQLServerDialect;
import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider;
import org.hibernate.testing.DialectChecks;
import org.hibernate.testing.RequiresDialectFeature;
@ -37,14 +38,24 @@ import static org.junit.Assert.fail;
*/
@RequiresDialectFeature(DialectChecks.SupportNoWait.class)
public class LockExceptionTests extends AbstractJPATest {
private SQLServerSnapshotIsolationConnectionProvider connectionProvider = new SQLServerSnapshotIsolationConnectionProvider();
@Override
public void configure(Configuration cfg) {
super.configure( cfg );
if( SQLServerDialect.class.isAssignableFrom( DIALECT.getClass() )) {
cfg.getProperties().put( AvailableSettings.CONNECTION_PROVIDER, new SQLServerSnapshotIsolationConnectionProvider() );
connectionProvider.setConnectionProvider( (ConnectionProvider) cfg.getProperties().get( AvailableSettings.CONNECTION_PROVIDER ) );
cfg.getProperties().put( AvailableSettings.CONNECTION_PROVIDER, connectionProvider );
}
}
@Override
protected void releaseSessionFactory() {
super.releaseSessionFactory();
connectionProvider.stop();
}
@Test
@TestForIssue( jiraKey = "HHH-8786" )
public void testLockTimeoutFind() {

View File

@ -17,6 +17,7 @@ import org.hibernate.Transaction;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.cfg.Configuration;
import org.hibernate.dialect.SQLServerDialect;
import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider;
import org.hibernate.exception.SQLGrammarException;
import org.hibernate.test.jpa.AbstractJPATest;
import org.hibernate.test.jpa.Item;
@ -44,6 +45,7 @@ public class RepeatableReadTest extends AbstractJPATest {
public void configure(Configuration cfg) {
super.configure( cfg );
if( SQLServerDialect.class.isAssignableFrom( DIALECT.getClass() )) {
connectionProvider.setConnectionProvider( (ConnectionProvider) cfg.getProperties().get( AvailableSettings.CONNECTION_PROVIDER ) );
cfg.getProperties().put( AvailableSettings.CONNECTION_PROVIDER, connectionProvider );
}
}

View File

@ -0,0 +1,115 @@
package org.hibernate.test.orderby;
import java.util.List;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import javax.persistence.Id;
import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase;
import org.junit.Test;
import static org.hibernate.testing.transaction.TransactionUtil.doInHibernate;
import static org.junit.Assert.assertEquals;
/**
* @author Christian Beikov
*/
public class OrderByTest extends BaseCoreFunctionalTestCase {
@Override
protected Class[] getAnnotatedClasses() {
return new Class[] {
Person.class,
P1.class,
P2.class
};
}
@Override
protected void prepareTest() throws Exception {
doInHibernate(
this::sessionFactory, session -> {
session.persist( new P1( 1L, "abc" ) );
session.persist( new P1( 2L, "abc" ) );
session.persist( new P2( 3L, "def" ) );
}
);
}
@Override
protected void cleanupTest() throws Exception {
doInHibernate(
this::sessionFactory, session -> {
session.createQuery( "delete from Person" ).executeUpdate();
}
);
}
@Test
@TestForIssue( jiraKey = "HHH-14351")
public void testOrderBySqlNode() {
doInHibernate(
this::sessionFactory, session -> {
List<Person> list = session.createQuery( "from Person p order by type(p) desc, p.id", Person.class )
.getResultList();
assertEquals( 3L, list.get( 0 ).getId().longValue() );
assertEquals( 1L, list.get( 1 ).getId().longValue() );
assertEquals( 2L, list.get( 2 ).getId().longValue() );
}
);
}
@Entity(name = "Person")
public static abstract class Person {
@Id
private Long id;
private String name;
public Person() {
}
public Person(Long id, String name) {
this.id = id;
this.name = name;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
@Entity(name = "P1")
@DiscriminatorValue( "P1" )
public static class P1 extends Person {
public P1() {
}
public P1(Long id, String name) {
super( id, name );
}
}
@Entity(name = "P2")
@DiscriminatorValue( "P2" )
public static class P2 extends Person {
public P2() {
}
public P2(Long id, String name) {
super( id, name );
}
}
}

View File

@ -63,7 +63,7 @@ public class ProxyReferenceEqualityTest extends BaseCoreFunctionalTestCase {
} );
}
@Entity
@Entity(name = "A")
public static class A {
@Id
Long id;
@ -72,7 +72,7 @@ public class ProxyReferenceEqualityTest extends BaseCoreFunctionalTestCase {
B b;
}
@Entity
@Entity(name = "B")
public static class B {
@Id
Long id;

View File

@ -15,6 +15,7 @@ import javax.persistence.QueryHint;
import javax.persistence.Table;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider;
import org.hibernate.jpa.QueryHints;
import org.hibernate.query.NativeQuery;
import org.hibernate.query.Query;
@ -48,6 +49,7 @@ public class QueryTimeOutTest extends BaseNonConfigCoreFunctionalTestCase {
@Override
protected void addSettings(Map settings) {
CONNECTION_PROVIDER.setConnectionProvider( (ConnectionProvider) settings.get( AvailableSettings.CONNECTION_PROVIDER ) );
settings.put( AvailableSettings.CONNECTION_PROVIDER, CONNECTION_PROVIDER );
}

View File

@ -61,16 +61,15 @@ public class TableGeneratorQuotingTest extends BaseUnitTestCase {
final Metadata metadata = new MetadataSources( serviceRegistry ).addAnnotatedClass( TestEntity.class ).buildMetadata();
final ConnectionProvider connectionProvider = serviceRegistry.getService( ConnectionProvider.class );
final GenerationTarget target = new GenerationTargetToDatabase(
new DdlTransactionIsolatorTestingImpl(
final DdlTransactionIsolatorTestingImpl ddlTransactionIsolator = new DdlTransactionIsolatorTestingImpl(
serviceRegistry,
new JdbcEnvironmentInitiator.ConnectionProviderJdbcConnectionAccess( connectionProvider )
)
);
new SchemaCreatorImpl( serviceRegistry ).doCreation( metadata, false, target );
try {
final GenerationTarget target = new GenerationTargetToDatabase( ddlTransactionIsolator, false );
try {
new SchemaCreatorImpl( serviceRegistry ).doCreation( metadata, false, target );
new SchemaValidator().validate( metadata );
}
catch (HibernateException e) {
@ -80,6 +79,10 @@ public class TableGeneratorQuotingTest extends BaseUnitTestCase {
new SchemaDropperImpl( serviceRegistry ).doDrop( metadata, false, target );
}
}
finally {
ddlTransactionIsolator.release();
}
}
@Entity
@Table(name = "test_entity")

View File

@ -51,53 +51,77 @@ public class TestExtraPhysicalTableTypes {
@Test
public void testAddOneExtraPhysicalTableType() throws Exception {
buildMetadata( "BASE TABLE" );
InformationExtractorJdbcDatabaseMetaDataImplTest informationExtractor = buildInformationExtractorJdbcDatabaseMetaDataImplTest();
DdlTransactionIsolator ddlTransactionIsolator = buildDdlTransactionIsolator();
try {
InformationExtractorJdbcDatabaseMetaDataImplTest informationExtractor = buildInformationExtractorJdbcDatabaseMetaDataImplTest(
ddlTransactionIsolator
);
assertThat( informationExtractor.isPhysicalTableType( "BASE TABLE" ), is( true ) );
assertThat( informationExtractor.isPhysicalTableType( "TABLE" ), is( true ) );
}
finally {
ddlTransactionIsolator.release();
}
}
@Test
public void testAddingMultipleExtraPhysicalTableTypes() throws Exception {
buildMetadata( "BASE, BASE TABLE" );
InformationExtractorJdbcDatabaseMetaDataImplTest informationExtractor = buildInformationExtractorJdbcDatabaseMetaDataImplTest();
DdlTransactionIsolator ddlTransactionIsolator = buildDdlTransactionIsolator();
try {
InformationExtractorJdbcDatabaseMetaDataImplTest informationExtractor = buildInformationExtractorJdbcDatabaseMetaDataImplTest(
ddlTransactionIsolator
);
assertThat( informationExtractor.isPhysicalTableType( "BASE TABLE" ), is( true ) );
assertThat( informationExtractor.isPhysicalTableType( "BASE" ), is( true ) );
assertThat( informationExtractor.isPhysicalTableType( "TABLE" ), is( true ) );
assertThat( informationExtractor.isPhysicalTableType( "TABLE 1" ), is( false ) );
}
finally {
ddlTransactionIsolator.release();
}
}
@Test
public void testExtraPhysicalTableTypesPropertyEmptyStringValue() throws Exception {
buildMetadata( " " );
InformationExtractorJdbcDatabaseMetaDataImplTest informationExtractor = buildInformationExtractorJdbcDatabaseMetaDataImplTest();
DdlTransactionIsolator ddlTransactionIsolator = buildDdlTransactionIsolator();
try {
InformationExtractorJdbcDatabaseMetaDataImplTest informationExtractor = buildInformationExtractorJdbcDatabaseMetaDataImplTest(
ddlTransactionIsolator
);
assertThat( informationExtractor.isPhysicalTableType( "BASE TABLE" ), is( false ) );
assertThat( informationExtractor.isPhysicalTableType( "TABLE" ), is( true ) );
}
finally {
ddlTransactionIsolator.release();
}
}
@Test
public void testNoExtraPhysicalTabeTypesProperty() throws Exception {
buildMetadata( null );
InformationExtractorJdbcDatabaseMetaDataImplTest informationExtractor = buildInformationExtractorJdbcDatabaseMetaDataImplTest();
DdlTransactionIsolator ddlTransactionIsolator = buildDdlTransactionIsolator();
try {
InformationExtractorJdbcDatabaseMetaDataImplTest informationExtractor = buildInformationExtractorJdbcDatabaseMetaDataImplTest(
ddlTransactionIsolator
);
assertThat( informationExtractor.isPhysicalTableType( "BASE TABLE" ), is( false ) );
assertThat( informationExtractor.isPhysicalTableType( "TABLE" ), is( true ) );
}
finally {
ddlTransactionIsolator.release();
}
}
private InformationExtractorJdbcDatabaseMetaDataImplTest buildInformationExtractorJdbcDatabaseMetaDataImplTest()
private InformationExtractorJdbcDatabaseMetaDataImplTest buildInformationExtractorJdbcDatabaseMetaDataImplTest(DdlTransactionIsolator ddlTransactionIsolator)
throws SQLException {
Database database = metadata.getDatabase();
final ConnectionProvider connectionProvider = ssr.getService( ConnectionProvider.class );
DatabaseInformation dbInfo = new DatabaseInformationImpl(
ssr,
database.getJdbcEnvironment(),
new DdlTransactionIsolatorTestingImpl( ssr,
new JdbcEnvironmentInitiator.ConnectionProviderJdbcConnectionAccess(
connectionProvider )
),
ddlTransactionIsolator,
database.getDefaultNamespace().getName()
);
ExtractionContextImpl extractionContext = new ExtractionContextImpl(
@ -113,6 +137,14 @@ public class TestExtraPhysicalTableTypes {
extractionContext );
}
private DdlTransactionIsolator buildDdlTransactionIsolator() {
final ConnectionProvider connectionProvider = ssr.getService( ConnectionProvider.class );
return new DdlTransactionIsolatorTestingImpl(
ssr,
new JdbcEnvironmentInitiator.ConnectionProviderJdbcConnectionAccess( connectionProvider )
);
}
private void buildMetadata(String extraPhysicalTableTypes) {
if ( extraPhysicalTableTypes == null ) {
ssr = new StandardServiceRegistryBuilder().build();
@ -128,8 +160,16 @@ public class TestExtraPhysicalTableTypes {
}
public class InformationExtractorJdbcDatabaseMetaDataImplTest extends InformationExtractorJdbcDatabaseMetaDataImpl {
private final ExtractionContext extractionContext;
public InformationExtractorJdbcDatabaseMetaDataImplTest(ExtractionContext extractionContext) {
super( extractionContext );
this.extractionContext = extractionContext;
}
public ExtractionContext getExtractionContext() {
return extractionContext;
}
public boolean isPhysicalTableType(String tableType) {

View File

@ -98,8 +98,15 @@ public class PostgreSQLMultipleSchemaSequenceTest extends BaseUnitTestCase {
fail(e.getMessage());
}
String existingUrl = (String) Environment.getProperties().get( AvailableSettings.URL );
if ( existingUrl.indexOf( '?' ) == -1 ) {
existingUrl += "?";
}
else {
existingUrl += "&";
}
StandardServiceRegistry ssr2 = new StandardServiceRegistryBuilder()
.applySetting( AvailableSettings.URL, Environment.getProperties().get(AvailableSettings.URL) + "?currentSchema=" + extraSchemaName )
.applySetting( AvailableSettings.URL, existingUrl + "currentSchema=" + extraSchemaName )
.build();
try {

View File

@ -16,6 +16,7 @@ import javax.persistence.Id;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.dialect.DB2Dialect;
import org.hibernate.dialect.DerbyDialect;
import org.hibernate.jpa.test.BaseEntityManagerFunctionalTestCase;
import org.hibernate.testing.SkipForDialect;
import org.hibernate.tool.schema.spi.SchemaManagementException;
@ -25,6 +26,7 @@ import org.junit.Test;
* @author Vlad Mihalcea
*/
@SkipForDialect(value = DB2Dialect.class, comment = "DB2 is far more resistant to the reserved keyword usage. See HHH-12832.")
@SkipForDialect(value = DerbyDialect.class, comment = "Derby is far more resistant to the reserved keyword usage.")
public class SchemaMigratorHaltOnErrorTest extends BaseEntityManagerFunctionalTestCase {
@Override

View File

@ -23,6 +23,8 @@ import org.hibernate.boot.spi.MetadataImplementor;
import org.hibernate.dialect.DB2Dialect;
import org.hibernate.testing.SkipForDialect;
import org.hibernate.testing.junit4.CustomRunner;
import org.hibernate.dialect.DerbyDialect;
import org.hibernate.tool.hbm2ddl.SchemaUpdate;
import org.hibernate.tool.schema.TargetType;
import org.hibernate.tool.schema.spi.SchemaManagementException;
@ -36,6 +38,7 @@ import org.junit.runner.RunWith;
* @author Gail Badner
*/
@SkipForDialect(value = DB2Dialect.class, comment = "DB2 is far more resistant to the reserved keyword usage. See HHH-12832.")
@SkipForDialect(value = DerbyDialect.class, comment = "Derby is far more resistant to the reserved keyword usage.")
@RunWith(CustomRunner.class)
public class SchemaUpdateHaltOnErrorTest {

View File

@ -12,6 +12,7 @@ import java.util.EnumSet;
import java.util.Map;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.annotations.Type;
import org.hibernate.boot.MetadataSources;
@ -156,6 +157,7 @@ public class LongVarcharValidationTest implements ExecutionOptions {
}
@Entity(name = "Translation")
@Table(name = "translation_tbl")
public static class Translation {
@Id
public Integer id;

View File

@ -22,6 +22,7 @@ import javax.persistence.Id;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.dialect.MySQL5Dialect;
import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider;
import org.hibernate.testing.DialectChecks;
import org.hibernate.testing.RequiresDialectFeature;
@ -62,6 +63,7 @@ public class JdbcTimeCustomTimeZoneTest
@Override
protected void addSettings(Map settings) {
connectionProvider.setConnectionProvider( (ConnectionProvider) settings.get( AvailableSettings.CONNECTION_PROVIDER ) );
settings.put(
AvailableSettings.CONNECTION_PROVIDER,
connectionProvider

View File

@ -15,6 +15,7 @@ import javax.persistence.Entity;
import javax.persistence.Id;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider;
import org.hibernate.testing.DialectChecks;
import org.hibernate.testing.RequiresDialectFeature;
@ -49,6 +50,7 @@ public class JdbcTimeDefaultTimeZoneTest
@Override
protected void addSettings(Map settings) {
connectionProvider.setConnectionProvider( (ConnectionProvider) settings.get( AvailableSettings.CONNECTION_PROVIDER ) );
settings.put(
AvailableSettings.CONNECTION_PROVIDER,
connectionProvider

View File

@ -19,6 +19,7 @@ import javax.persistence.Id;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.dialect.MySQL5Dialect;
import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider;
import org.hibernate.testing.DialectChecks;
import org.hibernate.testing.RequiresDialectFeature;
@ -59,6 +60,7 @@ public class JdbcTimestampCustomSessionLevelTimeZoneTest
@Override
protected void addSettings(Map settings) {
connectionProvider.setConnectionProvider( (ConnectionProvider) settings.get( AvailableSettings.CONNECTION_PROVIDER ) );
settings.put(
AvailableSettings.CONNECTION_PROVIDER,
connectionProvider

View File

@ -19,6 +19,7 @@ import javax.persistence.Id;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.dialect.MySQL5Dialect;
import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider;
import org.hibernate.testing.DialectChecks;
import org.hibernate.testing.RequiresDialectFeature;
@ -59,6 +60,7 @@ public class JdbcTimestampCustomTimeZoneTest
@Override
protected void addSettings(Map settings) {
connectionProvider.setConnectionProvider( (ConnectionProvider) settings.get( AvailableSettings.CONNECTION_PROVIDER ) );
settings.put(
AvailableSettings.CONNECTION_PROVIDER,
connectionProvider

View File

@ -14,6 +14,7 @@ import javax.persistence.Entity;
import javax.persistence.Id;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider;
import org.hibernate.testing.DialectChecks;
import org.hibernate.testing.RequiresDialectFeature;
@ -47,6 +48,7 @@ public class JdbcTimestampDefaultTimeZoneTest
@Override
protected void addSettings(Map settings) {
connectionProvider.setConnectionProvider( (ConnectionProvider) settings.get( AvailableSettings.CONNECTION_PROVIDER ) );
settings.put(
AvailableSettings.CONNECTION_PROVIDER,
connectionProvider

View File

@ -11,6 +11,7 @@ import java.util.TimeZone;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.dialect.PostgreSQL82Dialect;
import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider;
import org.hibernate.testing.RequiresDialect;
import org.hibernate.test.util.jdbc.TimeZoneConnectionProvider;
@ -29,6 +30,7 @@ public class JdbcTimestampUTCTimeZoneTest
@Override
protected void addSettings(Map settings) {
connectionProvider.setConnectionProvider( (ConnectionProvider) settings.get( AvailableSettings.CONNECTION_PROVIDER ) );
settings.put(
AvailableSettings.CONNECTION_PROVIDER,
connectionProvider

View File

@ -10,6 +10,7 @@ import java.util.Map;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.dialect.PostgreSQL82Dialect;
import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider;
import org.hibernate.testing.RequiresDialect;
import org.hibernate.test.util.jdbc.TimeZoneConnectionProvider;
@ -26,6 +27,7 @@ public class JdbcTimestampWithDefaultUTCTimeZoneTest
@Override
protected void addSettings(Map settings) {
connectionProvider.setConnectionProvider( (ConnectionProvider) settings.get( AvailableSettings.CONNECTION_PROVIDER ) );
settings.put(
AvailableSettings.CONNECTION_PROVIDER,
connectionProvider

View File

@ -18,6 +18,7 @@ import javax.persistence.Id;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.dialect.CockroachDialect;
import org.hibernate.dialect.PostgreSQL82Dialect;
import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider;
import org.hibernate.testing.RequiresDialect;
import org.hibernate.testing.SkipForDialect;
@ -47,6 +48,7 @@ public class JdbcTimestampWithoutUTCTimeZoneTest
@Override
protected void addSettings(Map settings) {
connectionProvider.setConnectionProvider( (ConnectionProvider) settings.get( AvailableSettings.CONNECTION_PROVIDER ) );
settings.put(
AvailableSettings.CONNECTION_PROVIDER,
connectionProvider

View File

@ -13,9 +13,7 @@ import javax.persistence.Entity;
import javax.persistence.Id;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.dialect.Dialect;
import org.hibernate.dialect.MySQL5Dialect;
import org.hibernate.dialect.MySQL8Dialect;
import org.hibernate.testing.RequiresDialect;
import org.hibernate.testing.TestForIssue;

View File

@ -142,12 +142,12 @@ abstract class AbstractJavaTimeTypeTest<T, E> extends BaseCoreFunctionalTestCase
} );
inTransaction( session -> {
session.doWork( connection -> {
final PreparedStatement statement = connection.prepareStatement(
try (PreparedStatement statement = connection.prepareStatement(
"SELECT " + PROPERTY_COLUMN_NAME + " FROM " + ENTITY_NAME + " WHERE " + ID_COLUMN_NAME + " = ?"
);
)) {
statement.setInt( 1, 1 );
statement.execute();
final ResultSet resultSet = statement.getResultSet();
try (ResultSet resultSet = statement.getResultSet()) {
resultSet.next();
Object nativeRead = getActualJdbcValue( resultSet, 1 );
assertEquals(
@ -155,6 +155,8 @@ abstract class AbstractJavaTimeTypeTest<T, E> extends BaseCoreFunctionalTestCase
getExpectedJdbcValueAfterHibernateWrite(),
nativeRead
);
}
}
} );
} );
} );
@ -168,13 +170,14 @@ abstract class AbstractJavaTimeTypeTest<T, E> extends BaseCoreFunctionalTestCase
withDefaultTimeZone( () -> {
inTransaction( session -> {
session.doWork( connection -> {
final PreparedStatement statement = connection.prepareStatement(
try (PreparedStatement statement = connection.prepareStatement(
"INSERT INTO " + ENTITY_NAME + " (" + ID_COLUMN_NAME + ", " + PROPERTY_COLUMN_NAME + ") "
+ " VALUES ( ? , ? )"
);
)) {
statement.setInt( 1, 1 );
setJdbcValueForNonHibernateWrite( statement, 2 );
statement.execute();
}
} );
} );
inTransaction( session -> {

View File

@ -17,6 +17,7 @@ import org.hibernate.Hibernate;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.cfg.Configuration;
import org.hibernate.dialect.SQLServerDialect;
import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.query.Query;
import org.hibernate.resource.jdbc.spi.PhysicalConnectionHandlingMode;
@ -47,6 +48,7 @@ public class UnionSubclassTest extends BaseCoreFunctionalTestCase {
public void configure(Configuration cfg) {
super.configure( cfg );
if ( SQLServerDialect.class.isAssignableFrom( DIALECT.getClass() ) ) {
connectionProvider.setConnectionProvider( (ConnectionProvider) cfg.getProperties().get( AvailableSettings.CONNECTION_PROVIDER ) );
cfg.getProperties().put( AvailableSettings.CONNECTION_PROVIDER, connectionProvider );
}
}

View File

@ -0,0 +1,120 @@
/*
* 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>.
*/
package org.hibernate.test.usertype;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.net.URL;
import java.util.Enumeration;
import javax.persistence.Entity;
import javax.persistence.Id;
import org.hibernate.boot.registry.BootstrapServiceRegistryBuilder;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.internal.util.ConfigHelper;
import org.hibernate.type.CustomType;
import org.hibernate.type.Type;
import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase;
import org.junit.Assert;
import org.junit.Test;
/**
* @author Christian Beikov
*/
public class IntegratorProvidedUserTypeTest extends BaseCoreFunctionalTestCase {
@Override
protected Class<?>[] getAnnotatedClasses() {
return new Class[] {
StringWrapperTestEntity.class
};
}
protected void prepareBootstrapRegistryBuilder(BootstrapServiceRegistryBuilder builder) {
builder.applyClassLoader( new TestClassLoader() );
}
@Test
@TestForIssue( jiraKey = "HHH-14408" )
public void test() {
Type type = sessionFactory().getMetamodel().entityPersister( StringWrapperTestEntity.class )
.getPropertyType( "stringWrapper" );
Assert.assertTrue( "Type was initialized too early i.e. before integrators were run", type instanceof CustomType );
}
@Entity
public static class StringWrapperTestEntity implements Serializable {
@Id
private Integer id;
private StringWrapper stringWrapper;
}
private static class TestClassLoader extends ClassLoader {
/**
* testStoppableClassLoaderService() needs a custom JDK service implementation. Rather than using a real one
* on the test classpath, force it in here.
*/
@Override
protected Enumeration<URL> findResources(String name) throws IOException {
if (name.equals( "META-INF/services/org.hibernate.integrator.spi.Integrator" )) {
final URL serviceUrl = ConfigHelper.findAsResource(
"org/hibernate/test/service/org.hibernate.integrator.spi.Integrator" );
return new Enumeration<URL>() {
boolean hasMore = true;
@Override
public boolean hasMoreElements() {
return hasMore;
}
@Override
public URL nextElement() {
hasMore = false;
return serviceUrl;
}
};
}
else {
return java.util.Collections.enumeration( java.util.Collections.<URL>emptyList() );
}
}
/**
* Reloading class from binary file.
*
* @param originalClass Original class.
* @throws IOException .
*/
public void overrideClass(final Class<?> originalClass) throws IOException {
String originalPath = "/" + originalClass.getName().replaceAll("\\.", "/") + ".class";
InputStream inputStream = originalClass.getResourceAsStream( originalPath);
Assert.assertNotNull(inputStream);
try {
byte[] data = toByteArray( inputStream );
defineClass(originalClass.getName(), data, 0, data.length);
} finally {
inputStream.close();
}
}
private byte[] toByteArray(InputStream inputStream) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
int read;
byte[] slice = new byte[2000];
while ( (read = inputStream.read(slice, 0, slice.length) ) != -1) {
out.write( slice, 0, read );
}
out.flush();
return out.toByteArray();
}
}
}

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