migrate toward the new PersistenceUnitTransactionType from JPA 3.2

clean up the test base classes etc.

Signed-off-by: Gavin King <gavin@hibernate.org>
This commit is contained in:
Gavin King 2024-09-04 00:04:10 +02:00
parent 437b59a57d
commit 4781c09d0d
34 changed files with 674 additions and 718 deletions

View File

@ -9,7 +9,6 @@ package org.hibernate.boot.jaxb.cfg.internal;
import org.hibernate.internal.util.StringHelper;
import jakarta.persistence.SharedCacheMode;
import jakarta.persistence.spi.PersistenceUnitTransactionType;
/**
* @author Steve Ebersole

View File

@ -8,12 +8,12 @@ package org.hibernate.boot.jaxb.cfg.internal;
import org.hibernate.internal.util.StringHelper;
import jakarta.persistence.AccessType;
import jakarta.persistence.spi.PersistenceUnitTransactionType;
/**
* @author Steve Ebersole
*/
@SuppressWarnings("removal")
public class TransactionTypeMarshalling {
public static PersistenceUnitTransactionType fromXml(String name) {
if ( StringHelper.isEmpty( name ) ) {
@ -23,9 +23,6 @@ public class TransactionTypeMarshalling {
}
public static String toXml(PersistenceUnitTransactionType transactionType) {
if ( transactionType == null ) {
return null;
}
return transactionType.name();
return transactionType == null ? null : transactionType.name();
}
}

View File

@ -34,15 +34,15 @@ public interface PersistenceSettings {
String JAKARTA_PERSISTENCE_PROVIDER = "jakarta.persistence.provider";
/**
* Specifies the {@linkplain jakarta.persistence.spi.PersistenceUnitTransactionType
* Specifies the {@linkplain jakarta.persistence.PersistenceUnitTransactionType
* type of transactions} supported by the entity managers. The default depends on
* whether the program is considered to be executing in a Java SE or EE environment:
* <ul>
* <li>For Java SE, the default is
* {@link jakarta.persistence.spi.PersistenceUnitTransactionType#RESOURCE_LOCAL
* {@link jakarta.persistence.PersistenceUnitTransactionType#RESOURCE_LOCAL
* RESOURCE_LOCAL}.
* <li>For Java EE, the default is
* {@link jakarta.persistence.spi.PersistenceUnitTransactionType#JTA JTA}.
* {@link jakarta.persistence.PersistenceUnitTransactionType#JTA JTA}.
* </ul>
* <p>
* See JPA 2 sections 9.4.3 and 8.2.1.2

View File

@ -1255,11 +1255,11 @@ public abstract class AbstractPersistentCollection<E> implements Serializable, P
SharedSessionContractImplementor session) throws HibernateException {
// short-circuit(s)
if ( currentElements.size() == 0 ) {
if ( currentElements.isEmpty() ) {
// no new elements, the old list contains only Orphans
return oldElements;
}
if ( oldElements.size() == 0 ) {
if ( oldElements.isEmpty() ) {
// no old elements, so no Orphans neither
return oldElements;
}

View File

@ -415,7 +415,7 @@ public class PersistentBag<E> extends AbstractPersistentCollection<E> implements
@Override
public boolean addAll(Collection<? extends E> values) {
if ( values.size() == 0 ) {
if ( values.isEmpty() ) {
return false;
}
if ( !isOperationQueueEnabled() ) {

View File

@ -227,7 +227,7 @@ public class PersistentList<E> extends AbstractPersistentCollection<E> implement
@Override
public boolean addAll(Collection<? extends E> values) {
if ( values.size() == 0 ) {
if ( values.isEmpty() ) {
return false;
}
if ( !isOperationQueueEnabled() ) {
@ -238,7 +238,7 @@ public class PersistentList<E> extends AbstractPersistentCollection<E> implement
for ( E value : values ) {
queueOperation( new SimpleAdd( value ) );
}
return values.size() > 0;
return !values.isEmpty();
}
}

View File

@ -75,7 +75,6 @@ import org.hibernate.graph.spi.RootGraphImplementor;
import org.hibernate.id.Configurable;
import org.hibernate.integrator.spi.Integrator;
import org.hibernate.integrator.spi.IntegratorService;
import org.hibernate.internal.util.StringHelper;
import org.hibernate.jpa.internal.ExceptionMapperLegacyJpaImpl;
import org.hibernate.jpa.internal.PersistenceUnitUtilImpl;
import org.hibernate.mapping.Collection;
@ -146,6 +145,7 @@ import static org.hibernate.cfg.PersistenceSettings.SESSION_FACTORY_JNDI_NAME;
import static org.hibernate.engine.config.spi.StandardConverters.STRING;
import static org.hibernate.internal.FetchProfileHelper.getFetchProfiles;
import static org.hibernate.internal.log.DeprecationLogger.DEPRECATION_LOGGER;
import static org.hibernate.internal.util.StringHelper.isNotEmpty;
import static org.hibernate.jpa.HibernateHints.HINT_TENANT_ID;
import static org.hibernate.proxy.HibernateProxy.extractLazyInitializer;
import static org.hibernate.resource.jdbc.spi.PhysicalConnectionHandlingMode.DELAYED_ACQUISITION_AND_RELEASE_AFTER_STATEMENT;
@ -457,17 +457,16 @@ public class SessionFactoryImpl extends QueryParameterBindingTypeResolverImpl im
for ( PersistentClass model : bootMetamodel.getEntityBindings() ) {
if ( !model.isInherited() ) {
final KeyValue id = model.getIdentifier();
final Generator generator = id.createGenerator( dialect, (RootClass) model, model.getIdentifierProperty() );
if ( generator instanceof Configurable ) {
final Configurable identifierGenerator = (Configurable) generator;
identifierGenerator.initialize( sqlStringGenerationContext );
final Generator generator =
id.createGenerator( dialect, (RootClass) model, model.getIdentifierProperty() );
if ( generator instanceof Configurable configurable ) {
configurable.initialize( sqlStringGenerationContext );
}
//TODO: this isn't a great place to do this
if ( generator.allowAssignedIdentifiers() && id instanceof SimpleValue ) {
final SimpleValue simpleValue = (SimpleValue) id;
if ( simpleValue.getNullValue() == null ) {
simpleValue.setNullValue( "undefined" );
}
if ( generator.allowAssignedIdentifiers()
&& id instanceof SimpleValue simpleValue
&& simpleValue.getNullValue() == null ) {
simpleValue.setNullValue( "undefined" );
}
generators.put( model.getEntityName(), generator );
}
@ -559,12 +558,7 @@ public class SessionFactoryImpl extends QueryParameterBindingTypeResolverImpl im
final ConfigurationService configurationService = serviceRegistry.getService( ConfigurationService.class );
assert configurationService != null;
final String puName = configurationService.getSetting( PersistenceSettings.PERSISTENCE_UNIT_NAME, STRING );
if ( puName != null ) {
return puName;
}
return null;
return configurationService.getSetting( PersistenceSettings.PERSISTENCE_UNIT_NAME, STRING );
}
private String determineJndiName(
@ -574,19 +568,21 @@ public class SessionFactoryImpl extends QueryParameterBindingTypeResolverImpl im
final ConfigurationService cfgService = serviceRegistry.getService( ConfigurationService.class );
assert cfgService != null;
final String explicitJndiName = cfgService.getSetting( SESSION_FACTORY_JNDI_NAME, STRING );
if ( StringHelper.isNotEmpty( explicitJndiName ) ) {
if ( isNotEmpty( explicitJndiName ) ) {
return explicitJndiName;
}
final String puName = cfgService.getSetting( PERSISTENCE_UNIT_NAME, STRING );
// do not use name for JNDI if explicitly asked not to or if name comes from JPA persistence-unit name
final boolean nameIsNotJndiName = options.isSessionFactoryNameAlsoJndiName() == Boolean.FALSE || StringHelper.isNotEmpty( puName );
final boolean nameIsNotJndiName =
options.isSessionFactoryNameAlsoJndiName() == Boolean.FALSE
|| isNotEmpty( puName );
return !nameIsNotJndiName ? name : null;
}
private SessionBuilderImpl createDefaultSessionOpenOptionsIfPossible() {
final CurrentTenantIdentifierResolver<Object> currentTenantIdentifierResolver = getCurrentTenantIdentifierResolver();
if ( currentTenantIdentifierResolver == null ) {
final CurrentTenantIdentifierResolver<Object> tenantIdResolver = getCurrentTenantIdentifierResolver();
if ( tenantIdResolver == null ) {
return withOptions();
}
else {
@ -698,8 +694,8 @@ public class SessionFactoryImpl extends QueryParameterBindingTypeResolverImpl im
@Override
public StatelessSession openStatelessSession() {
if ( this.defaultStatelessOptions != null ) {
return this.defaultStatelessOptions.openStatelessSession();
if ( defaultStatelessOptions != null ) {
return defaultStatelessOptions.openStatelessSession();
}
else {
return withStatelessOptions().openStatelessSession();
@ -799,12 +795,10 @@ public class SessionFactoryImpl extends QueryParameterBindingTypeResolverImpl im
if ( map != null ) {
for ( Map.Entry<K, V> o : map.entrySet() ) {
final K key = o.getKey();
if ( key instanceof String ) {
final String sKey = (String) key;
if ( HINT_TENANT_ID.equals( sKey ) ) {
continue;
if ( key instanceof String string ) {
if ( !HINT_TENANT_ID.equals( string ) ) {
session.setProperty( string, o.getValue() );
}
session.setProperty( sKey, o.getValue() );
}
}
}
@ -849,7 +843,7 @@ public class SessionFactoryImpl extends QueryParameterBindingTypeResolverImpl im
return queryEngine.getCriteriaBuilder();
}
@Override
@Override @Deprecated
public MetamodelImplementor getMetamodel() {
validateNotClosed();
return (MetamodelImplementor) runtimeMetamodels.getMappingMetamodel();
@ -1033,7 +1027,7 @@ public class SessionFactoryImpl extends QueryParameterBindingTypeResolverImpl im
// then try as a native-SQL or JPQL query
try {
QueryImplementor<?> hibernateQuery = query.unwrap( QueryImplementor.class );
final QueryImplementor<?> hibernateQuery = query.unwrap( QueryImplementor.class );
if ( hibernateQuery != null ) {
// create and register the proper NamedQueryDefinition...
if ( hibernateQuery instanceof NativeQueryImplementor ) {
@ -1119,9 +1113,8 @@ public class SessionFactoryImpl extends QueryParameterBindingTypeResolverImpl im
return getJpaMetamodel().getNamedEntityGraphs( entityType );
}
@Override
@Override @SuppressWarnings({"unchecked", "rawtypes"})
public void runInTransaction(Consumer<EntityManager> work) {
//noinspection unchecked,rawtypes
inTransaction( (Consumer) work );
}
@ -1146,11 +1139,11 @@ public class SessionFactoryImpl extends QueryParameterBindingTypeResolverImpl im
}
public FilterDefinition getFilterDefinition(String filterName) throws HibernateException {
FilterDefinition def = filters.get( filterName );
if ( def == null ) {
final FilterDefinition filterDefinition = filters.get( filterName );
if ( filterDefinition == null ) {
throw new UnknownFilterException( filterName );
}
return def;
return filterDefinition;
}
@Override
@ -1563,7 +1556,7 @@ public class SessionFactoryImpl extends QueryParameterBindingTypeResolverImpl im
return this;
}
@Override
@Override @Deprecated
public StatelessSessionBuilder tenantIdentifier(String tenantIdentifier) {
this.tenantIdentifier = tenantIdentifier;
return this;

View File

@ -80,7 +80,7 @@ import org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator;
import jakarta.persistence.AttributeConverter;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.PersistenceException;
import jakarta.persistence.spi.PersistenceUnitTransactionType;
import jakarta.persistence.PersistenceUnitTransactionType;
import static java.lang.Boolean.parseBoolean;
import static java.util.Collections.unmodifiableMap;
@ -792,38 +792,42 @@ public class EntityManagerFactoryBuilderImpl implements EntityManagerFactoryBuil
MergedSettings mergedSettings) {
final PersistenceUnitTransactionType txnType =
determineTransactionType( persistenceUnit, integrationSettingsCopy, mergedSettings );
final boolean hasTxStrategy =
mergedSettings.getConfigurationValues().containsKey( TRANSACTION_COORDINATOR_STRATEGY );
final boolean definiteJtaCoordinator;
if ( hasTxStrategy ) {
log.overridingTransactionStrategyDangerous( TRANSACTION_COORDINATOR_STRATEGY );
// see if we can tell whether it is a JTA coordinator
final Object strategy =
mergedSettings.getConfigurationValues().get( TRANSACTION_COORDINATOR_STRATEGY );
definiteJtaCoordinator =
strategy instanceof TransactionCoordinatorBuilder transactionCoordinatorBuilder
&& transactionCoordinatorBuilder.isJta();
}
else {
if ( txnType == PersistenceUnitTransactionType.JTA ) {
mergedSettings.getConfigurationValues().put( TRANSACTION_COORDINATOR_STRATEGY,
JtaTransactionCoordinatorBuilderImpl.class );
definiteJtaCoordinator = true;
}
else if ( txnType == PersistenceUnitTransactionType.RESOURCE_LOCAL ) {
mergedSettings.getConfigurationValues().put( TRANSACTION_COORDINATOR_STRATEGY,
JdbcResourceLocalTransactionCoordinatorBuilderImpl.class );
definiteJtaCoordinator = false;
}
else {
throw new IllegalStateException( "Could not determine TransactionCoordinator strategy to use" );
}
}
final boolean definiteJtaCoordinator =
mergedSettings.getConfigurationValues().containsKey( TRANSACTION_COORDINATOR_STRATEGY )
? handeTransactionCoordinatorStrategy( mergedSettings )
: handleTransactionType( mergedSettings, txnType );
mergedSettings.getConfigurationValues().put( IS_JTA_TXN_COORD, definiteJtaCoordinator );
}
private static boolean handeTransactionCoordinatorStrategy(MergedSettings mergedSettings) {
final boolean definiteJtaCoordinator;
log.overridingTransactionStrategyDangerous( TRANSACTION_COORDINATOR_STRATEGY );
// see if we can tell whether it is a JTA coordinator
final Object strategy =
mergedSettings.getConfigurationValues().get( TRANSACTION_COORDINATOR_STRATEGY );
definiteJtaCoordinator =
strategy instanceof TransactionCoordinatorBuilder transactionCoordinatorBuilder
&& transactionCoordinatorBuilder.isJta();
return definiteJtaCoordinator;
}
private static boolean handleTransactionType(MergedSettings mergedSettings, PersistenceUnitTransactionType txnType) {
switch (txnType) {
case JTA:
mergedSettings.getConfigurationValues()
.put( TRANSACTION_COORDINATOR_STRATEGY,
JtaTransactionCoordinatorBuilderImpl.class );
return true;
case RESOURCE_LOCAL:
mergedSettings.getConfigurationValues()
.put( TRANSACTION_COORDINATOR_STRATEGY,
JdbcResourceLocalTransactionCoordinatorBuilderImpl.class );
return false;
default:
throw new IllegalStateException( "Could not determine TransactionCoordinator strategy to use" );
}
}
private static PersistenceUnitTransactionType determineTransactionType(
PersistenceUnitDescriptor persistenceUnit, Map<?, ?> integrationSettingsCopy, MergedSettings mergedSettings) {
@ -839,8 +843,8 @@ public class EntityManagerFactoryBuilderImpl implements EntityManagerFactoryBuil
if ( intgTxnType != null ) {
txnType = interpretTransactionType( intgTxnType );
}
else if ( persistenceUnit.getTransactionType() != null ) {
txnType = persistenceUnit.getTransactionType();
else if ( persistenceUnit.getPersistenceUnitTransactionType() != null ) {
txnType = persistenceUnit.getPersistenceUnitTransactionType();
}
else {
Object puPropTxnType = mergedSettings.getConfigurationValues().get( JAKARTA_TRANSACTION_TYPE );

View File

@ -12,24 +12,31 @@ import java.util.Arrays;
import java.util.List;
import java.util.Properties;
import jakarta.persistence.spi.PersistenceUnitInfo;
import org.hibernate.boot.archive.internal.ArchiveHelper;
import org.hibernate.bytecode.enhance.spi.EnhancementContext;
import org.hibernate.bytecode.spi.ClassTransformer;
import jakarta.persistence.SharedCacheMode;
import jakarta.persistence.ValidationMode;
import jakarta.persistence.spi.PersistenceUnitTransactionType;
import jakarta.persistence.PersistenceUnitTransactionType;
import org.hibernate.jpa.boot.spi.PersistenceUnitDescriptor;
import org.hibernate.jpa.internal.util.PersistenceUnitTransactionTypeHelper;
import static org.hibernate.boot.archive.internal.ArchiveHelper.getURLFromPath;
/**
* Describes the information gleaned from a {@code <persistence-unit/>} element in a {@code persistence.xml} file
* whether parsed directly by Hibernate or passed to us by an EE container as a
* {@link jakarta.persistence.spi.PersistenceUnitInfo}.
*
* Easier to consolidate both views into a single contract and extract information through that shared contract.
* Describes the information gleaned from a {@code <persistence-unit/>}
* element in a {@code persistence.xml} file whether parsed directly by
* Hibernate or passed to us by an EE container as an instance of
* {@link PersistenceUnitInfo}.
* <p>
* Easier to consolidate both views into a single contract and extract
* information through that shared contract.
*
* @author Steve Ebersole
*/
public class ParsedPersistenceXmlDescriptor implements org.hibernate.jpa.boot.spi.PersistenceUnitDescriptor {
public class ParsedPersistenceXmlDescriptor implements PersistenceUnitDescriptor {
private final URL persistenceUnitRootUrl;
private String name;
@ -94,10 +101,15 @@ public class ParsedPersistenceXmlDescriptor implements org.hibernate.jpa.boot.sp
}
@Override
public PersistenceUnitTransactionType getTransactionType() {
public PersistenceUnitTransactionType getPersistenceUnitTransactionType() {
return transactionType;
}
@Override @SuppressWarnings("removal")
public jakarta.persistence.spi.PersistenceUnitTransactionType getTransactionType() {
return PersistenceUnitTransactionTypeHelper.toDeprecatedForm( transactionType );
}
public void setTransactionType(PersistenceUnitTransactionType transactionType) {
this.transactionType = transactionType;
}
@ -187,9 +199,7 @@ public class ParsedPersistenceXmlDescriptor implements org.hibernate.jpa.boot.sp
}
public void addJarFileUrls(List<String> jarFiles) {
jarFiles.forEach( (jarFile) -> {
addJarFileUrl( ArchiveHelper.getURLFromPath( jarFile ) );
} );
jarFiles.forEach( jarFile -> addJarFileUrl( getURLFromPath( jarFile ) ) );
}
@Override

View File

@ -14,12 +14,13 @@ import jakarta.persistence.PersistenceException;
import jakarta.persistence.SharedCacheMode;
import jakarta.persistence.ValidationMode;
import jakarta.persistence.spi.PersistenceUnitInfo;
import jakarta.persistence.spi.PersistenceUnitTransactionType;
import jakarta.persistence.PersistenceUnitTransactionType;
import org.hibernate.bytecode.enhance.spi.EnhancementContext;
import org.hibernate.bytecode.spi.ClassTransformer;
import org.hibernate.jpa.boot.spi.PersistenceUnitDescriptor;
import org.hibernate.jpa.internal.enhance.EnhancingClassTransformerImpl;
import org.hibernate.jpa.internal.util.PersistenceUnitTransactionTypeHelper;
/**
* @author Steve Ebersole
@ -58,7 +59,12 @@ public class PersistenceUnitInfoDescriptor implements PersistenceUnitDescriptor
}
@Override
public PersistenceUnitTransactionType getTransactionType() {
public PersistenceUnitTransactionType getPersistenceUnitTransactionType() {
return PersistenceUnitTransactionTypeHelper.toNewForm( getTransactionType() );
}
@Override @SuppressWarnings("removal")
public jakarta.persistence.spi.PersistenceUnitTransactionType getTransactionType() {
return persistenceUnitInfo.getTransactionType();
}
@ -115,11 +121,15 @@ public class PersistenceUnitInfoDescriptor implements PersistenceUnitDescriptor
@Override
public void pushClassTransformer(EnhancementContext enhancementContext) {
if ( this.classTransformer != null ) {
throw new PersistenceException( "Persistence unit [" + persistenceUnitInfo.getPersistenceUnitName() + "] can only have a single class transformer." );
throw new PersistenceException( "Persistence unit ["
+ persistenceUnitInfo.getPersistenceUnitName()
+ "] can only have a single class transformer." );
}
// During testing, we will return a null temp class loader in cases where we don't care about enhancement
// During testing, we will return a null temp class loader
// in cases where we don't care about enhancement
if ( persistenceUnitInfo.getNewTempClassLoader() != null ) {
final EnhancingClassTransformerImpl classTransformer = new EnhancingClassTransformerImpl( enhancementContext );
final EnhancingClassTransformerImpl classTransformer =
new EnhancingClassTransformerImpl( enhancementContext );
this.classTransformer = classTransformer;
persistenceUnitInfo.addTransformer( classTransformer );
}

View File

@ -18,7 +18,7 @@ import org.hibernate.jpa.boot.internal.MergedSettings;
import org.hibernate.jpa.boot.internal.PersistenceUnitInfoDescriptor;
import jakarta.persistence.spi.PersistenceUnitInfo;
import jakarta.persistence.spi.PersistenceUnitTransactionType;
import jakarta.persistence.PersistenceUnitTransactionType;
/**
* Entry into the bootstrap process.
@ -64,7 +64,6 @@ public final class Bootstrap {
public static EntityManagerFactoryBuilder getEntityManagerFactoryBuilder(
URL persistenceXmlUrl,
String persistenceUnitName,
@SuppressWarnings("removal")
PersistenceUnitTransactionType transactionType,
Map integration) {
return new EntityManagerFactoryBuilderImpl(

View File

@ -19,7 +19,8 @@ import org.hibernate.jpa.HibernatePersistenceProvider;
import jakarta.persistence.PersistenceConfiguration;
import jakarta.persistence.SharedCacheMode;
import jakarta.persistence.ValidationMode;
import jakarta.persistence.spi.PersistenceUnitTransactionType;
import jakarta.persistence.PersistenceUnitTransactionType;
import org.hibernate.jpa.internal.util.PersistenceUnitTransactionTypeHelper;
/**
* PersistenceUnitDescriptor wrapper around {@linkplain PersistenceConfiguration}
@ -34,7 +35,6 @@ public class PersistenceConfigurationDescriptor implements PersistenceUnitDescri
public PersistenceConfigurationDescriptor(PersistenceConfiguration persistenceConfiguration) {
this.persistenceConfiguration = persistenceConfiguration;
this.properties = CollectionHelper.asProperties( persistenceConfiguration.properties() );
this.managedClassNames = persistenceConfiguration.managedClasses().stream().map( Class::getName ).toList();
}
@ -65,13 +65,14 @@ public class PersistenceConfigurationDescriptor implements PersistenceUnitDescri
return true;
}
@SuppressWarnings("removal")
@Override @SuppressWarnings("removal")
public jakarta.persistence.spi.PersistenceUnitTransactionType getTransactionType() {
return PersistenceUnitTransactionTypeHelper.toDeprecatedForm( getPersistenceUnitTransactionType() );
}
@Override
public PersistenceUnitTransactionType getTransactionType() {
return switch ( persistenceConfiguration.transactionType() ) {
case JTA -> PersistenceUnitTransactionType.JTA;
case RESOURCE_LOCAL -> PersistenceUnitTransactionType.RESOURCE_LOCAL;
};
public PersistenceUnitTransactionType getPersistenceUnitTransactionType() {
return persistenceConfiguration.transactionType();
}
@Override

View File

@ -11,15 +11,19 @@ import java.util.List;
import java.util.Properties;
import jakarta.persistence.SharedCacheMode;
import jakarta.persistence.ValidationMode;
import jakarta.persistence.spi.PersistenceUnitTransactionType;
import jakarta.persistence.PersistenceUnitTransactionType;
import org.hibernate.bytecode.enhance.spi.EnhancementContext;
import org.hibernate.bytecode.spi.ClassTransformer;
/**
* Abstraction for dealing with either {@code <persistence-unit/>} information whether that comes from
* an EE container in the form of {@link jakarta.persistence.spi.PersistenceUnitInfo} or in an SE environment
* where Hibernate has parsed the {@code persistence.xml} file itself.
* Abstraction for dealing with {@code <persistence-unit/>} information
* specified in the {@code persistence.xml} file, which might be:
* <ul>
* <li>passed by the Jakarta EE container as an instance of
* {@link jakarta.persistence.spi.PersistenceUnitInfo}, or,
* <li>in an SE environment, parsed by Hibernate itself.
* </ul>
*
* @author Steve Ebersole
*/
@ -63,7 +67,14 @@ public interface PersistenceUnitDescriptor {
*/
boolean isExcludeUnlistedClasses();
PersistenceUnitTransactionType getTransactionType();
PersistenceUnitTransactionType getPersistenceUnitTransactionType();
/**
* @deprecated since {@link jakarta.persistence.spi.PersistenceUnitTransactionType}
* will be removed in JPA 4
*/
@Deprecated(since = "7", forRemoval = true) @SuppressWarnings("removal")
jakarta.persistence.spi.PersistenceUnitTransactionType getTransactionType();
ValidationMode getValidationMode();

View File

@ -22,6 +22,7 @@ import org.hibernate.boot.archive.internal.ArchiveHelper;
import org.hibernate.boot.jaxb.Origin;
import org.hibernate.boot.jaxb.SourceType;
import org.hibernate.boot.jaxb.configuration.spi.JaxbPersistenceImpl;
import org.hibernate.boot.jaxb.configuration.spi.JaxbPersistenceImpl.JaxbPersistenceUnitImpl;
import org.hibernate.boot.jaxb.configuration.spi.JaxbPersistenceImpl.JaxbPersistenceUnitImpl.JaxbPropertiesImpl;
import org.hibernate.boot.jaxb.configuration.spi.JaxbPersistenceImpl.JaxbPersistenceUnitImpl.JaxbPropertiesImpl.JaxbPropertyImpl;
import org.hibernate.boot.jaxb.internal.ConfigurationBinder;
@ -38,7 +39,12 @@ import org.hibernate.jpa.boot.internal.ParsedPersistenceXmlDescriptor;
import org.hibernate.jpa.internal.util.ConfigurationHelper;
import jakarta.persistence.PersistenceException;
import jakarta.persistence.spi.PersistenceUnitTransactionType;
import jakarta.persistence.PersistenceUnitTransactionType;
import org.hibernate.jpa.internal.util.PersistenceUnitTransactionTypeHelper;
import static jakarta.persistence.PersistenceUnitTransactionType.JTA;
import static jakarta.persistence.PersistenceUnitTransactionType.RESOURCE_LOCAL;
import static org.hibernate.internal.util.StringHelper.isEmpty;
/**
* Used by Hibernate to parse {@code persistence.xml} files in SE environments.
@ -124,10 +130,9 @@ public final class PersistenceXmlParser {
*
* @return Map of persistence-unit descriptors keyed by the PU name
*/
@SuppressWarnings("removal")
public Map<String, PersistenceUnitDescriptor> parse(List<URL> persistenceXmlUrls) {
Map<String, PersistenceUnitDescriptor> persistenceUnits = new HashMap<>();
parsePersistenceXml( persistenceUnits, persistenceXmlUrls, PersistenceUnitTransactionType.RESOURCE_LOCAL );
final Map<String, PersistenceUnitDescriptor> persistenceUnits = new HashMap<>();
parsePersistenceXml( persistenceUnits, persistenceXmlUrls, RESOURCE_LOCAL );
return persistenceUnits;
}
@ -142,7 +147,6 @@ public final class PersistenceXmlParser {
*/
public Map<String, PersistenceUnitDescriptor> parse(
List<URL> persistenceXmlUrls,
@SuppressWarnings("removal")
PersistenceUnitTransactionType transactionType) {
Map<String, PersistenceUnitDescriptor> persistenceUnits = new HashMap<>();
parsePersistenceXml( persistenceUnits, persistenceXmlUrls, transactionType );
@ -151,14 +155,12 @@ public final class PersistenceXmlParser {
private void parsePersistenceXml(Map<String, PersistenceUnitDescriptor> persistenceUnits,
List<URL> xmlUrls,
@SuppressWarnings("removal")
PersistenceUnitTransactionType defaultTransactionType) {
for ( URL xmlUrl : xmlUrls ) {
parsePersistenceXml( persistenceUnits, xmlUrl, defaultTransactionType );
}
}
@SuppressWarnings("removal")
private void parsePersistenceXml(Map<String, PersistenceUnitDescriptor> persistenceUnits,
URL xmlUrl, PersistenceUnitTransactionType defaultTransactionType) {
if ( log.isTraceEnabled() ) {
@ -168,10 +170,10 @@ public final class PersistenceXmlParser {
final URL persistenceUnitRootUrl = ArchiveHelper.getJarURLFromURLEntry( xmlUrl, "/META-INF/persistence.xml" );
final JaxbPersistenceImpl jaxbPersistence = loadUrlWithJaxb( xmlUrl );
final List<JaxbPersistenceImpl.JaxbPersistenceUnitImpl> jaxbPersistenceUnits = jaxbPersistence.getPersistenceUnit();
final List<JaxbPersistenceUnitImpl> jaxbPersistenceUnits = jaxbPersistence.getPersistenceUnit();
for ( int i = 0; i < jaxbPersistenceUnits.size(); i++ ) {
final JaxbPersistenceImpl.JaxbPersistenceUnitImpl jaxbPersistenceUnit = jaxbPersistenceUnits.get( i );
final JaxbPersistenceUnitImpl jaxbPersistenceUnit = jaxbPersistenceUnits.get( i );
if ( persistenceUnits.containsKey( jaxbPersistenceUnit.getName() ) ) {
log.duplicatedPersistenceUnitName( jaxbPersistenceUnit.getName() );
@ -191,7 +193,7 @@ public final class PersistenceXmlParser {
}
private void bindPersistenceUnit(
JaxbPersistenceImpl.JaxbPersistenceUnitImpl jaxbPersistenceUnit,
JaxbPersistenceUnitImpl jaxbPersistenceUnit,
ParsedPersistenceXmlDescriptor persistenceUnitDescriptor) {
final String name = jaxbPersistenceUnit.getName();
if ( StringHelper.isNotEmpty( name ) ) {
@ -199,11 +201,7 @@ public final class PersistenceXmlParser {
persistenceUnitDescriptor.setName( name );
}
//noinspection removal
final PersistenceUnitTransactionType transactionType = jaxbPersistenceUnit.getTransactionType();
if ( transactionType != null ) {
persistenceUnitDescriptor.setTransactionType( transactionType );
}
setTransactionType( jaxbPersistenceUnit, persistenceUnitDescriptor );
persistenceUnitDescriptor.setProviderClassName( jaxbPersistenceUnit.getProvider() );
persistenceUnitDescriptor.setNonJtaDataSource( jaxbPersistenceUnit.getNonJtaDataSource() );
@ -218,14 +216,24 @@ public final class PersistenceXmlParser {
final JaxbPropertiesImpl propertyContainer = jaxbPersistenceUnit.getPropertyContainer();
if ( propertyContainer != null ) {
for ( JaxbPropertyImpl property : propertyContainer.getProperties() ) {
persistenceUnitDescriptor.getProperties().put(
property.getName(),
property.getValue()
);
persistenceUnitDescriptor.getProperties()
.put( property.getName(), property.getValue() );
}
}
}
@SuppressWarnings("removal")
private static void setTransactionType(
JaxbPersistenceUnitImpl jaxbPersistenceUnit,
ParsedPersistenceXmlDescriptor persistenceUnitDescriptor) {
final jakarta.persistence.spi.PersistenceUnitTransactionType transactionType =
jaxbPersistenceUnit.getTransactionType();
if ( transactionType != null ) {
persistenceUnitDescriptor.setTransactionType(
PersistenceUnitTransactionTypeHelper.toNewForm( transactionType ) );
}
}
private boolean handleBoolean(Boolean incoming) {
if ( incoming != null ) {
return incoming;
@ -233,18 +241,20 @@ public final class PersistenceXmlParser {
return false;
}
@SuppressWarnings({"deprecation", "removal"})
@SuppressWarnings("deprecation")
private void applyIntegrationOverrides(Map<?,?> integration, PersistenceUnitTransactionType defaultTransactionType,
ParsedPersistenceXmlDescriptor persistenceUnitDescriptor) {
if ( integration.containsKey( AvailableSettings.JAKARTA_PERSISTENCE_PROVIDER ) ) {
persistenceUnitDescriptor.setProviderClassName( (String) integration.get( AvailableSettings.JAKARTA_PERSISTENCE_PROVIDER ) );
persistenceUnitDescriptor.setProviderClassName( (String)
integration.get( AvailableSettings.JAKARTA_PERSISTENCE_PROVIDER ) );
}
else if ( integration.containsKey( AvailableSettings.JPA_PERSISTENCE_PROVIDER ) ) {
DeprecationLogger.DEPRECATION_LOGGER.deprecatedSetting(
AvailableSettings.JPA_PERSISTENCE_PROVIDER,
AvailableSettings.JAKARTA_PERSISTENCE_PROVIDER
);
persistenceUnitDescriptor.setProviderClassName( (String) integration.get( AvailableSettings.JPA_PERSISTENCE_PROVIDER ) );
persistenceUnitDescriptor.setProviderClassName( (String)
integration.get( AvailableSettings.JPA_PERSISTENCE_PROVIDER ) );
}
if ( integration.containsKey( AvailableSettings.JPA_TRANSACTION_TYPE ) ) {
@ -288,11 +298,10 @@ public final class PersistenceXmlParser {
ConfigurationHelper.overrideProperties( properties, integration );
}
@SuppressWarnings("removal")
private void applyTransactionTypeOverride(ParsedPersistenceXmlDescriptor persistenceUnitDescriptor,
PersistenceUnitTransactionType defaultTransactionType) {
// if transaction type is set already, use that value
if ( persistenceUnitDescriptor.getTransactionType() == null ) {
if ( persistenceUnitDescriptor.getPersistenceUnitTransactionType() == null ) {
// else
// if JTA DS
// use JTA
@ -301,10 +310,10 @@ public final class PersistenceXmlParser {
// else
// use defaultTransactionType
if ( persistenceUnitDescriptor.getJtaDataSource() != null ) {
persistenceUnitDescriptor.setTransactionType( PersistenceUnitTransactionType.JTA );
persistenceUnitDescriptor.setTransactionType( JTA );
}
else if ( persistenceUnitDescriptor.getNonJtaDataSource() != null ) {
persistenceUnitDescriptor.setTransactionType( PersistenceUnitTransactionType.RESOURCE_LOCAL );
persistenceUnitDescriptor.setTransactionType( RESOURCE_LOCAL );
}
else {
persistenceUnitDescriptor.setTransactionType( defaultTransactionType );
@ -312,16 +321,15 @@ public final class PersistenceXmlParser {
}
}
@SuppressWarnings("removal")
private static PersistenceUnitTransactionType parseTransactionType(String value) {
if ( StringHelper.isEmpty( value ) ) {
if ( isEmpty( value ) ) {
return null;
}
else if ( value.equalsIgnoreCase( "JTA" ) ) {
return PersistenceUnitTransactionType.JTA;
else if ( JTA.name().equalsIgnoreCase( value ) ) {
return JTA;
}
else if ( value.equalsIgnoreCase( "RESOURCE_LOCAL" ) ) {
return PersistenceUnitTransactionType.RESOURCE_LOCAL;
else if ( RESOURCE_LOCAL.name().equalsIgnoreCase( value ) ) {
return RESOURCE_LOCAL;
}
else {
throw new PersistenceException( "Unknown persistence unit transaction type : " + value );
@ -335,13 +343,11 @@ public final class PersistenceXmlParser {
// avoid JAR locking on Windows and Tomcat
conn.setUseCaches( false );
try (InputStream inputStream = conn.getInputStream()) {
try ( InputStream inputStream = conn.getInputStream() ) {
final StreamSource inputSource = new StreamSource( inputStream );
final ConfigurationBinder configurationBinder = new ConfigurationBinder( classLoaderService );
final Binding<JaxbPersistenceImpl> binding = configurationBinder.bind(
inputSource,
new Origin( SourceType.URL, resourceName )
);
final Binding<JaxbPersistenceImpl> binding =
configurationBinder.bind( inputSource, new Origin( SourceType.URL, resourceName ) );
return binding.getRoot();
}
catch (IOException e) {

View File

@ -54,7 +54,7 @@ public final class LogHelper {
.append( descriptor.getNonJtaDataSource() )
.append( "\n\t" )
.append( "Transaction type: " )
.append( descriptor.getTransactionType() )
.append( descriptor.getPersistenceUnitTransactionType() )
.append( "\n\t" )
.append( "PU root URL: " )
.append( descriptor.getPersistenceUnitRootUrl() )

View File

@ -7,10 +7,14 @@
package org.hibernate.jpa.internal.util;
import jakarta.persistence.PersistenceException;
import jakarta.persistence.spi.PersistenceUnitTransactionType;
import jakarta.persistence.PersistenceUnitTransactionType;
import static jakarta.persistence.PersistenceUnitTransactionType.JTA;
import static jakarta.persistence.PersistenceUnitTransactionType.RESOURCE_LOCAL;
/**
* @author Steve Ebersole
* @author Gavin King
*/
public class PersistenceUnitTransactionTypeHelper {
private PersistenceUnitTransactionTypeHelper() {
@ -20,23 +24,39 @@ public class PersistenceUnitTransactionTypeHelper {
if ( value == null ) {
return null;
}
if ( value instanceof PersistenceUnitTransactionType ) {
return (PersistenceUnitTransactionType) value;
}
final String stringValue = value.toString().trim();
if ( stringValue.isEmpty() ) {
return null;
}
else if ( stringValue.equalsIgnoreCase( "JTA" ) ) {
return PersistenceUnitTransactionType.JTA;
}
else if ( stringValue.equalsIgnoreCase( "RESOURCE_LOCAL" ) ) {
return PersistenceUnitTransactionType.RESOURCE_LOCAL;
else if ( value instanceof PersistenceUnitTransactionType transactionType ) {
return transactionType;
}
else {
throw new PersistenceException( "Unknown TransactionType: '" + stringValue + '\'' );
final String stringValue = value.toString().trim();
if ( stringValue.isEmpty() ) {
return null;
}
else if ( JTA.name().equalsIgnoreCase( stringValue ) ) {
return JTA;
}
else if ( RESOURCE_LOCAL.name().equalsIgnoreCase( stringValue ) ) {
return RESOURCE_LOCAL;
}
else {
throw new PersistenceException( "Unknown TransactionType: '" + stringValue + "'" );
}
}
}
@SuppressWarnings("removal")
public static jakarta.persistence.spi.PersistenceUnitTransactionType toDeprecatedForm(PersistenceUnitTransactionType type) {
return type == null ? null : switch (type) {
case JTA -> jakarta.persistence.spi.PersistenceUnitTransactionType.JTA;
case RESOURCE_LOCAL -> jakarta.persistence.spi.PersistenceUnitTransactionType.RESOURCE_LOCAL;
};
}
@SuppressWarnings("removal")
public static PersistenceUnitTransactionType toNewForm(jakarta.persistence.spi.PersistenceUnitTransactionType type) {
return type == null ? null : switch (type) {
case JTA -> PersistenceUnitTransactionType.JTA;
case RESOURCE_LOCAL -> PersistenceUnitTransactionType.RESOURCE_LOCAL;
};
}
}

View File

@ -10,7 +10,6 @@ import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
@ -43,7 +42,6 @@ import org.hibernate.integrator.spi.Integrator;
import org.hibernate.jpa.HibernatePersistenceProvider;
import org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl;
import org.hibernate.jpa.boot.internal.PersistenceUnitInfoDescriptor;
import org.hibernate.jpa.boot.spi.EntityManagerFactoryBuilder;
import org.hibernate.orm.test.mapping.basic.bitset.BitSetType;
import org.hibernate.orm.test.mapping.basic.bitset.BitSetUserType;
import org.hibernate.service.ServiceRegistry;
@ -637,7 +635,7 @@ public class BootstrapTest {
}
@Override
public PersistenceUnitTransactionType getTransactionType() {
public jakarta.persistence.spi.PersistenceUnitTransactionType getTransactionType() {
return transactionType;
}

View File

@ -7,10 +7,6 @@
package org.hibernate.orm.test.exceptionhandling;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@ -19,6 +15,7 @@ import java.util.Properties;
import org.hibernate.HibernateException;
import org.hibernate.Interceptor;
import org.hibernate.Session;
import org.hibernate.boot.cfgxml.spi.LoadedConfig;
import org.hibernate.boot.registry.BootstrapServiceRegistry;
import org.hibernate.boot.registry.BootstrapServiceRegistryBuilder;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
@ -32,11 +29,8 @@ import org.hibernate.dialect.Dialect;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.internal.util.PropertiesHelper;
import org.hibernate.internal.util.config.ConfigurationHelper;
import org.hibernate.jpa.HibernatePersistenceProvider;
import org.hibernate.jpa.boot.spi.Bootstrap;
import org.hibernate.jpa.boot.spi.PersistenceUnitDescriptor;
import org.hibernate.resource.transaction.spi.TransactionCoordinator;
import org.hibernate.testing.AfterClassOnce;
import org.hibernate.testing.BeforeClassOnce;
@ -49,8 +43,10 @@ import org.junit.After;
import jakarta.persistence.EntityManager;
import jakarta.persistence.SharedCacheMode;
import jakarta.persistence.ValidationMode;
import jakarta.persistence.spi.PersistenceUnitTransactionType;
import jakarta.persistence.PersistenceUnitTransactionType;
import static org.hibernate.internal.util.config.ConfigurationHelper.resolvePlaceHolders;
import static org.hibernate.jpa.boot.spi.Bootstrap.getEntityManagerFactoryBuilder;
import static org.junit.Assert.fail;
/**
@ -106,7 +102,6 @@ public abstract class BaseJpaOrNativeBootstrapFunctionalTestCase extends BaseUni
}
@BeforeClassOnce
@SuppressWarnings( {"UnusedDeclaration"})
public void buildSessionOrEntityManagerFactory() {
switch ( bootstrapMethod ) {
case JPA:
@ -116,44 +111,38 @@ public abstract class BaseJpaOrNativeBootstrapFunctionalTestCase extends BaseUni
buildSessionFactory();
break;
}
afterSessionOrEntityManagerFactoryBuilt();
}
private void buildEntityManagerFactory() {
log.trace( "Building EntityManagerFactory" );
Properties properties = buildProperties();
ArrayList<Class> classes = new ArrayList<Class>();
classes.addAll( Arrays.asList( getAnnotatedClasses() ) );
properties.put( org.hibernate.cfg.AvailableSettings.LOADED_CLASSES, classes );
final Properties properties = buildProperties();
properties.put( AvailableSettings.LOADED_CLASSES, List.of( getAnnotatedClasses() ) );
ServiceRegistryUtil.applySettings( properties );
sessionFactory = Bootstrap.getEntityManagerFactoryBuilder(
buildPersistenceUnitDescriptor(),
properties
).build().unwrap( SessionFactoryImplementor.class );
sessionFactory =
getEntityManagerFactoryBuilder( buildPersistenceUnitDescriptor(), properties )
.build().unwrap( SessionFactoryImplementor.class );
serviceRegistry = (StandardServiceRegistryImpl) sessionFactory.getServiceRegistry()
.getParentServiceRegistry();
serviceRegistry = (StandardServiceRegistryImpl)
sessionFactory.getServiceRegistry().getParentServiceRegistry();
}
private void buildSessionFactory() {
// for now, build the configuration to get all the property settings
Configuration configuration = new Configuration();
final Configuration configuration = new Configuration();
configuration.setProperties( buildProperties() );
Class<?>[] annotatedClasses = getAnnotatedClasses();
final Class<?>[] annotatedClasses = getAnnotatedClasses();
if ( annotatedClasses != null ) {
for ( Class<?> annotatedClass : annotatedClasses ) {
configuration.addAnnotatedClass( annotatedClass );
}
}
BootstrapServiceRegistry bootRegistry = buildBootstrapServiceRegistry();
serviceRegistry = buildServiceRegistry( bootRegistry, configuration );
sessionFactory = ( SessionFactoryImplementor ) configuration.buildSessionFactory( serviceRegistry );
serviceRegistry = buildServiceRegistry( buildBootstrapServiceRegistry(), configuration );
sessionFactory = (SessionFactoryImplementor) configuration.buildSessionFactory( serviceRegistry );
afterSessionOrEntityManagerFactoryBuilt();
}
@ -196,7 +185,12 @@ public abstract class BaseJpaOrNativeBootstrapFunctionalTestCase extends BaseUni
}
@Override
public PersistenceUnitTransactionType getTransactionType() {
public PersistenceUnitTransactionType getPersistenceUnitTransactionType() {
return null;
}
@Override @SuppressWarnings("removal")
public jakarta.persistence.spi.PersistenceUnitTransactionType getTransactionType() {
return null;
}
@ -270,25 +264,24 @@ public abstract class BaseJpaOrNativeBootstrapFunctionalTestCase extends BaseUni
protected void prepareBootstrapRegistryBuilder(BootstrapServiceRegistryBuilder builder) {
}
private StandardServiceRegistryImpl buildServiceRegistry(BootstrapServiceRegistry bootRegistry, Configuration configuration) {
Properties properties = new Properties();
private StandardServiceRegistryImpl buildServiceRegistry(
BootstrapServiceRegistry bootRegistry, Configuration configuration) {
final Properties properties = new Properties();
properties.putAll( configuration.getProperties() );
ConfigurationHelper.resolvePlaceHolders( properties );
StandardServiceRegistryBuilder cfgRegistryBuilder = configuration.getStandardServiceRegistryBuilder();
StandardServiceRegistryBuilder registryBuilder = new StandardServiceRegistryBuilder( bootRegistry, cfgRegistryBuilder.getAggregatedCfgXml() )
.applySettings( properties );
resolvePlaceHolders( properties );
final LoadedConfig loadedConfig =
configuration.getStandardServiceRegistryBuilder().getAggregatedCfgXml();
final StandardServiceRegistryBuilder registryBuilder =
new StandardServiceRegistryBuilder( bootRegistry, loadedConfig )
.applySettings( properties );
ServiceRegistryUtil.applySettings( registryBuilder );
return (StandardServiceRegistryImpl) registryBuilder.build();
}
private Properties buildProperties() {
Properties properties = Environment.getProperties();
final Properties properties = Environment.getProperties();
properties.put( AvailableSettings.CACHE_REGION_FACTORY, CachingRegionFactory.class.getName() );
for ( Map.Entry<Class, String> entry : getCachedClasses().entrySet() ) {
for ( Map.Entry<Class<?>, String> entry : getCachedClasses().entrySet() ) {
properties.put( AvailableSettings.CLASS_CACHE_PREFIX + "." + entry.getKey().getName(), entry.getValue() );
}
for ( Map.Entry<String, String> entry : getCachedCollections().entrySet() ) {
@ -314,7 +307,7 @@ public abstract class BaseJpaOrNativeBootstrapFunctionalTestCase extends BaseUni
return NO_CLASSES;
}
public Map<Class, String> getCachedClasses() {
public Map<Class<?>, String> getCachedClasses() {
return new HashMap<>();
}
@ -330,15 +323,13 @@ public abstract class BaseJpaOrNativeBootstrapFunctionalTestCase extends BaseUni
}
@After
public final void afterTest() throws Exception {
public final void afterTest() {
completeStrayTransaction();
cleanupSession();
}
@AfterClassOnce
@SuppressWarnings( {"UnusedDeclaration"})
@SuppressWarnings("UnusedDeclaration")
protected void releaseSessionFactory() {
if ( sessionFactory == null ) {
return;
@ -364,7 +355,9 @@ public abstract class BaseJpaOrNativeBootstrapFunctionalTestCase extends BaseUni
return;
}
if ( ( (SessionImplementor) session ).isClosed() ) {
final SessionImplementor sessionImplementor = (SessionImplementor) session;
if ( sessionImplementor.isClosed() ) {
// nothing to do
return;
}
@ -374,15 +367,17 @@ public abstract class BaseJpaOrNativeBootstrapFunctionalTestCase extends BaseUni
return;
}
final TransactionCoordinator.TransactionDriver tdc =
( (SessionImplementor) session ).getTransactionCoordinator().getTransactionDriverControl();
if ( tdc.getStatus().canRollback() ) {
if ( canRollBack( sessionImplementor ) ) {
session.getTransaction().rollback();
}
session.close();
}
private static boolean canRollBack(SessionImplementor sessionImplementor) {
return sessionImplementor.getTransactionCoordinator()
.getTransactionDriverControl().getStatus().canRollback();
}
private void cleanupSession() {
if ( session != null && ! ( (SessionImplementor) session ).isClosed() ) {
session.close();

View File

@ -9,7 +9,6 @@ package org.hibernate.orm.test.jpa;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@ -18,7 +17,7 @@ import java.util.Properties;
import jakarta.persistence.EntityManager;
import jakarta.persistence.SharedCacheMode;
import jakarta.persistence.ValidationMode;
import jakarta.persistence.spi.PersistenceUnitTransactionType;
import jakarta.persistence.PersistenceUnitTransactionType;
import org.hibernate.boot.registry.internal.StandardServiceRegistryImpl;
import org.hibernate.boot.spi.MetadataImplementor;
@ -42,6 +41,8 @@ import org.hibernate.testing.util.ServiceRegistryUtil;
import org.junit.After;
import org.junit.Before;
import static java.util.Collections.emptyMap;
/**
* A base class for all ejb tests.
*
@ -58,8 +59,8 @@ public abstract class BaseEntityManagerFunctionalTestCase extends BaseUnitTestCa
private StandardServiceRegistryImpl serviceRegistry;
private SessionFactoryImplementor entityManagerFactory;
private EntityManager em;
private ArrayList<EntityManager> isolatedEms = new ArrayList<EntityManager>();
private EntityManager entityManager;
private final List<EntityManager> isolatedEntityManagers = new ArrayList<>();
protected Dialect getDialect() {
return dialect;
@ -74,24 +75,18 @@ public abstract class BaseEntityManagerFunctionalTestCase extends BaseUnitTestCa
}
@Before
@SuppressWarnings( {"UnusedDeclaration"})
public void buildEntityManagerFactory() {
log.trace( "Building EntityManagerFactory" );
EntityManagerFactoryBuilder entityManagerFactoryBuilder = Bootstrap.getEntityManagerFactoryBuilder(
buildPersistenceUnitDescriptor(),
buildSettings()
);
final EntityManagerFactoryBuilder entityManagerFactoryBuilder =
Bootstrap.getEntityManagerFactoryBuilder( buildPersistenceUnitDescriptor(), buildSettings() );
applyMetadataImplementor( entityManagerFactoryBuilder.metadata() );
entityManagerFactory = entityManagerFactoryBuilder.build().unwrap( SessionFactoryImplementor.class );
serviceRegistry = (StandardServiceRegistryImpl) entityManagerFactory.getServiceRegistry()
.getParentServiceRegistry();
serviceRegistry = (StandardServiceRegistryImpl)
entityManagerFactory.getServiceRegistry().getParentServiceRegistry();
afterEntityManagerFactoryBuilt();
}
protected void applyMetadataImplementor(MetadataImplementor metadataImplementor) {
}
protected PersistenceUnitDescriptor buildPersistenceUnitDescriptor() {
@ -131,7 +126,12 @@ public abstract class BaseEntityManagerFunctionalTestCase extends BaseUnitTestCa
}
@Override
public PersistenceUnitTransactionType getTransactionType() {
public PersistenceUnitTransactionType getPersistenceUnitTransactionType() {
return null;
}
@Override @SuppressWarnings("removal")
public jakarta.persistence.spi.PersistenceUnitTransactionType getTransactionType() {
return null;
}
@ -195,11 +195,9 @@ public abstract class BaseEntityManagerFunctionalTestCase extends BaseUnitTestCa
}
}
@SuppressWarnings("unchecked")
protected Map buildSettings() {
Map settings = getConfig();
protected Map<Object,Object> buildSettings() {
final Map<Object,Object> settings = getConfig();
addMappings( settings );
if ( createSchema() ) {
settings.put( AvailableSettings.HBM2DDL_AUTO, "create-drop" );
}
@ -208,9 +206,8 @@ public abstract class BaseEntityManagerFunctionalTestCase extends BaseUnitTestCa
return settings;
}
@SuppressWarnings("unchecked")
protected void addMappings(Map settings) {
String[] mappings = getMappings();
protected void addMappings(Map<Object,Object> settings) {
final String[] mappings = getMappings();
if ( mappings != null ) {
settings.put( AvailableSettings.HBM_XML_FILES, String.join( ",", mappings ) );
}
@ -222,24 +219,22 @@ public abstract class BaseEntityManagerFunctionalTestCase extends BaseUnitTestCa
return NO_MAPPINGS;
}
protected Map getConfig() {
Map<Object, Object> config = Environment.getProperties();
ArrayList<Class> classes = new ArrayList<Class>();
protected Map<Object,Object> getConfig() {
final Map<Object, Object> config = Environment.getProperties();
config.put( AvailableSettings.CLASSLOADERS, getClass().getClassLoader() );
classes.addAll( Arrays.asList( getAnnotatedClasses() ) );
List<Class<?>> classes = new ArrayList<>( Arrays.asList( getAnnotatedClasses() ) );
config.put( AvailableSettings.LOADED_CLASSES, classes );
for ( Map.Entry<Class, String> entry : getCachedClasses().entrySet() ) {
for ( Map.Entry<Class<?>, String> entry : getCachedClasses().entrySet() ) {
config.put( AvailableSettings.CLASS_CACHE_PREFIX + "." + entry.getKey().getName(), entry.getValue() );
}
for ( Map.Entry<String, String> entry : getCachedCollections().entrySet() ) {
config.put( AvailableSettings.COLLECTION_CACHE_PREFIX + "." + entry.getKey(), entry.getValue() );
}
if ( getEjb3DD().length > 0 ) {
ArrayList<String> dds = new ArrayList<>();
dds.addAll( Arrays.asList( getEjb3DD() ) );
config.put( AvailableSettings.ORM_XML_FILES, dds );
config.put( AvailableSettings.ORM_XML_FILES,
new ArrayList<>( Arrays.asList( getEjb3DD() ) ) );
}
config.put( PersistentTableStrategy.DROP_ID_TABLES, "true" );
@ -250,7 +245,7 @@ public abstract class BaseEntityManagerFunctionalTestCase extends BaseUnitTestCa
return config;
}
protected void addConfigOptions(Map options) {
protected void addConfigOptions(Map<Object,Object> options) {
}
protected static final Class<?>[] NO_CLASSES = new Class[0];
@ -259,12 +254,12 @@ public abstract class BaseEntityManagerFunctionalTestCase extends BaseUnitTestCa
return NO_CLASSES;
}
public Map<Class, String> getCachedClasses() {
return new HashMap<Class, String>();
public Map<Class<?>, String> getCachedClasses() {
return new HashMap<>();
}
public Map<String, String> getCachedCollections() {
return new HashMap<String, String>();
return new HashMap<>();
}
public String[] getEjb3DD() {
@ -294,9 +289,9 @@ public abstract class BaseEntityManagerFunctionalTestCase extends BaseUnitTestCa
}
private void releaseUnclosedEntityManagers() {
releaseUnclosedEntityManager( this.em );
releaseUnclosedEntityManager( this.entityManager);
for ( EntityManager isolatedEm : isolatedEms ) {
for ( EntityManager isolatedEm : isolatedEntityManagers) {
releaseUnclosedEntityManager( isolatedEm );
}
}
@ -322,34 +317,34 @@ public abstract class BaseEntityManagerFunctionalTestCase extends BaseUnitTestCa
}
protected EntityManager getOrCreateEntityManager() {
if ( em == null || !em.isOpen() ) {
em = entityManagerFactory.createEntityManager();
if ( entityManager == null || !entityManager.isOpen() ) {
entityManager = entityManagerFactory.createEntityManager();
}
return em;
return entityManager;
}
protected EntityManager createIsolatedEntityManager() {
EntityManager isolatedEm = entityManagerFactory.createEntityManager();
isolatedEms.add( isolatedEm );
return isolatedEm;
final EntityManager isolatedEntityManager = entityManagerFactory.createEntityManager();
isolatedEntityManagers.add( isolatedEntityManager );
return isolatedEntityManager;
}
protected EntityManager createIsolatedEntityManager(Map props) {
EntityManager isolatedEm = entityManagerFactory.createEntityManager(props);
isolatedEms.add( isolatedEm );
return isolatedEm;
protected EntityManager createIsolatedEntityManager(Map<?,?> properties) {
final EntityManager isolatedEntityManager = entityManagerFactory.createEntityManager( properties );
isolatedEntityManagers.add( isolatedEntityManager );
return isolatedEntityManager;
}
protected EntityManager createEntityManager() {
return createEntityManager( Collections.emptyMap() );
return createEntityManager( emptyMap() );
}
protected EntityManager createEntityManager(Map properties) {
protected EntityManager createEntityManager(Map<?,?> properties) {
// always reopen a new EM and close the existing one
if ( em != null && em.isOpen() ) {
em.close();
if ( entityManager != null && entityManager.isOpen() ) {
entityManager.close();
}
em = entityManagerFactory.createEntityManager( properties );
return em;
entityManager = entityManagerFactory.createEntityManager( properties );
return entityManager;
}
}

View File

@ -62,8 +62,8 @@ public class EntityManagerTest extends BaseEntityManagerFunctionalTestCase {
}
@Override
public Map<Class, String> getCachedClasses() {
Map<Class, String> result = new HashMap<Class, String>();
public Map<Class<?>, String> getCachedClasses() {
Map<Class<?>, String> result = new HashMap<>();
result.put( Item.class, "read-write" );
return result;
}

View File

@ -14,7 +14,6 @@ import java.util.Set;
import org.hibernate.HibernateException;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.boot.registry.internal.StandardServiceRegistryImpl;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.dialect.Dialect;
@ -25,7 +24,6 @@ import org.hibernate.internal.util.collections.CollectionHelper;
import org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl;
import org.hibernate.jpa.boot.spi.Bootstrap;
import org.hibernate.orm.test.dialect.resolver.TestingDialectResolutionInfo;
import org.hibernate.service.spi.ServiceRegistryImplementor;
import org.hibernate.tool.schema.Action;
import org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.ActionGrouping;

View File

@ -32,9 +32,8 @@ import org.junit.jupiter.api.Test;
import org.jboss.logging.Logger;
import jakarta.persistence.spi.PersistenceUnitTransactionType;
import jakarta.persistence.PersistenceUnitTransactionType;
@SuppressWarnings("removal")
@JiraKey("HHH-18231")
public class PersistenceXmlParserTest {
@ -81,30 +80,38 @@ public class PersistenceXmlParserTest {
assertThat( result.get( "multipu1" ) )
.returns( "multipu1", PersistenceUnitDescriptor::getName )
.returns(
PersistenceUnitTransactionType.RESOURCE_LOCAL, PersistenceUnitDescriptor::getTransactionType );
PersistenceUnitTransactionType.RESOURCE_LOCAL,
PersistenceUnitDescriptor::getPersistenceUnitTransactionType );
assertThat( result.get( "multipu2" ) )
.returns( "multipu2", PersistenceUnitDescriptor::getName )
.returns(
PersistenceUnitTransactionType.RESOURCE_LOCAL, PersistenceUnitDescriptor::getTransactionType );
PersistenceUnitTransactionType.RESOURCE_LOCAL,
PersistenceUnitDescriptor::getPersistenceUnitTransactionType );
assertThat( result.get( "multipu3" ) )
.returns( "multipu3", PersistenceUnitDescriptor::getName )
.returns( PersistenceUnitTransactionType.JTA, PersistenceUnitDescriptor::getTransactionType );
.returns( PersistenceUnitTransactionType.JTA,
PersistenceUnitDescriptor::getPersistenceUnitTransactionType );
}
@Test
public void parse_defaultTransactionType() {
var parser = PersistenceXmlParser.create();
var result = parser.parse( List.of( findPuResource( "multipu" ) ), PersistenceUnitTransactionType.JTA );
var result =
parser.parse( List.of( findPuResource( "multipu" ) ),
PersistenceUnitTransactionType.JTA );
assertThat( result.get( "multipu1" ) )
.returns( "multipu1", PersistenceUnitDescriptor::getName )
.returns(
PersistenceUnitTransactionType.JTA, PersistenceUnitDescriptor::getTransactionType );
PersistenceUnitTransactionType.JTA,
PersistenceUnitDescriptor::getPersistenceUnitTransactionType );
assertThat( result.get( "multipu2" ) )
.returns( "multipu2", PersistenceUnitDescriptor::getName )
.returns( PersistenceUnitTransactionType.RESOURCE_LOCAL, PersistenceUnitDescriptor::getTransactionType );
.returns( PersistenceUnitTransactionType.RESOURCE_LOCAL,
PersistenceUnitDescriptor::getPersistenceUnitTransactionType );
assertThat( result.get( "multipu3" ) )
.returns( "multipu3", PersistenceUnitDescriptor::getName )
.returns( PersistenceUnitTransactionType.JTA, PersistenceUnitDescriptor::getTransactionType );
.returns( PersistenceUnitTransactionType.JTA,
PersistenceUnitDescriptor::getPersistenceUnitTransactionType );
}
private static URL findPuResource(String resourceName) {

View File

@ -42,12 +42,8 @@ public class JpaXsdVersionsTest {
PersistenceUnitInfoImpl pui = new PersistenceUnitInfoImpl( "orm1-test", "1.0" )
.addMappingFileName( "org/hibernate/orm/test/jpa/xml/versions/valid-orm-1_0.xml" );
HibernatePersistenceProvider hp = new HibernatePersistenceProvider();
EntityManagerFactory emf = hp.createContainerEntityManagerFactory( pui, getDefaultPuConfig() );
try {
emf.getMetamodel().entity( Lighter1.class ); // exception if not entity
}
finally {
emf.close();
try ( EntityManagerFactory emf = hp.createContainerEntityManagerFactory( pui, getDefaultPuConfig() ) ) {
emf.getMetamodel().entity(Lighter1.class); // exception if not entity
}
}
@ -62,12 +58,8 @@ public class JpaXsdVersionsTest {
PersistenceUnitInfoImpl pui = new PersistenceUnitInfoImpl( "orm2-test", "2.0" )
.addMappingFileName( "org/hibernate/orm/test/jpa/xml/versions/valid-orm-2_0.xml" );
HibernatePersistenceProvider hp = new HibernatePersistenceProvider();
EntityManagerFactory emf = hp.createContainerEntityManagerFactory( pui, getDefaultPuConfig() );
try {
emf.getMetamodel().entity( Lighter.class ); // exception if not entity
}
finally {
emf.close();
try ( EntityManagerFactory emf = hp.createContainerEntityManagerFactory( pui, getDefaultPuConfig() ) ) {
emf.getMetamodel().entity(Lighter.class); // exception if not entity
}
}
@ -76,12 +68,8 @@ public class JpaXsdVersionsTest {
PersistenceUnitInfoImpl pui = new PersistenceUnitInfoImpl( "orm2-test", "2.1" )
.addMappingFileName( "org/hibernate/orm/test/jpa/xml/versions/valid-orm-2_1.xml" );
HibernatePersistenceProvider hp = new HibernatePersistenceProvider();
EntityManagerFactory emf = hp.createContainerEntityManagerFactory( pui, getDefaultPuConfig() );
try {
emf.getMetamodel().entity( Lighter.class ); // exception if not entity
}
finally {
emf.close();
try ( EntityManagerFactory emf = hp.createContainerEntityManagerFactory( pui, getDefaultPuConfig() ) ) {
emf.getMetamodel().entity(Lighter.class); // exception if not entity
}
}
@ -90,12 +78,8 @@ public class JpaXsdVersionsTest {
PersistenceUnitInfoImpl pui = new PersistenceUnitInfoImpl( "orm2-test", "2.2")
.addMappingFileName( "org/hibernate/orm/test/jpa/xml/versions/valid-orm-2_2.xml" );
HibernatePersistenceProvider hp = new HibernatePersistenceProvider();
EntityManagerFactory emf = hp.createContainerEntityManagerFactory( pui, getDefaultPuConfig() );
try {
emf.getMetamodel().entity( Lighter.class ); // exception if not entity
}
finally {
emf.close();
try ( EntityManagerFactory emf = hp.createContainerEntityManagerFactory( pui, getDefaultPuConfig() ) ) {
emf.getMetamodel().entity(Lighter.class); // exception if not entity
}
}
@ -104,13 +88,8 @@ public class JpaXsdVersionsTest {
PersistenceUnitInfoImpl pui = new PersistenceUnitInfoImpl( "invalid-orm1-test", "1.0" )
.addMappingFileName( "org/hibernate/orm/test/jpa/xml/versions/invalid-orm-1_0.xml" );
HibernatePersistenceProvider hp = new HibernatePersistenceProvider();
EntityManagerFactory emf = null;
try {
emf = hp.createContainerEntityManagerFactory(
pui,
getDefaultPuConfig()
);
Assert.fail( "expecting 'invalid content' error" );
try ( EntityManagerFactory emf = hp.createContainerEntityManagerFactory( pui, getDefaultPuConfig() ) ) {
Assert.fail("expecting 'invalid content' error");
}
catch (InvalidMappingException | AnnotationException expected) {
// expected condition
@ -118,11 +97,6 @@ public class JpaXsdVersionsTest {
catch (PersistenceException expected) {
// expected condition
}
finally {
if ( emf != null ) {
emf.close();
}
}
}
public static class PersistenceUnitInfoImpl implements PersistenceUnitInfo {
@ -156,13 +130,13 @@ public class JpaXsdVersionsTest {
return List.of();
}
private final List<String> mappingFileNames = new ArrayList<String>();
private final List<String> mappingFileNames = new ArrayList<>();
public List<String> getMappingFileNames() {
return mappingFileNames;
}
private final List<String> managedClassNames = new ArrayList<String>();
private final List<String> managedClassNames = new ArrayList<>();
private PersistenceUnitInfoImpl addMappingFileName(String mappingFileName) {
mappingFileNames.add( mappingFileName );
@ -189,7 +163,7 @@ public class JpaXsdVersionsTest {
return null;
}
private final List<URL> jarFileUrls = new ArrayList<URL>();
private final List<URL> jarFileUrls = new ArrayList<>();
public List<URL> getJarFileUrls() {
return jarFileUrls;

View File

@ -23,6 +23,7 @@ import org.hibernate.Interceptor;
import org.hibernate.Session;
import org.hibernate.StatelessSession;
import org.hibernate.Transaction;
import org.hibernate.boot.cfgxml.spi.LoadedConfig;
import org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyJpaImpl;
import org.hibernate.boot.registry.BootstrapServiceRegistry;
import org.hibernate.boot.registry.BootstrapServiceRegistryBuilder;
@ -38,13 +39,11 @@ import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.internal.build.AllowSysOut;
import org.hibernate.internal.util.ReflectHelper;
import org.hibernate.internal.util.StringHelper;
import org.hibernate.internal.util.config.ConfigurationHelper;
import org.hibernate.jdbc.AbstractReturningWork;
import org.hibernate.jdbc.Work;
import org.hibernate.query.sqm.mutation.internal.temptable.GlobalTemporaryTableMutationStrategy;
import org.hibernate.query.sqm.mutation.internal.temptable.LocalTemporaryTableMutationStrategy;
import org.hibernate.query.sqm.mutation.internal.temptable.PersistentTableStrategy;
import org.hibernate.resource.transaction.spi.TransactionCoordinator;
import org.hibernate.testing.AfterClassOnce;
import org.hibernate.testing.BeforeClassOnce;
@ -58,6 +57,8 @@ import org.hibernate.testing.util.ServiceRegistryUtil;
import org.junit.After;
import org.junit.Before;
import static java.lang.Thread.currentThread;
import static org.hibernate.internal.util.config.ConfigurationHelper.resolvePlaceHolders;
import static org.hibernate.testing.transaction.TransactionUtil.doInHibernate;
import static org.junit.Assert.fail;
@ -66,7 +67,7 @@ import static org.junit.Assert.fail;
*
* @author Steve Ebersole
*/
@SuppressWarnings( {"deprecation"} )
@SuppressWarnings("deprecation")
public abstract class BaseCoreFunctionalTestCase extends BaseUnitTestCase {
public static final String VALIDATE_DATA_CLEANUP = "hibernate.test.validateDataCleanup";
@ -178,7 +179,7 @@ public abstract class BaseCoreFunctionalTestCase extends BaseUnitTestCase {
}
protected Configuration constructConfiguration(BootstrapServiceRegistry bootstrapServiceRegistry) {
Configuration configuration = new Configuration( bootstrapServiceRegistry );
final Configuration configuration = new Configuration( bootstrapServiceRegistry );
configuration.setProperty( AvailableSettings.CACHE_REGION_FACTORY, CachingRegionFactory.class.getName() );
if ( createSchema() ) {
configuration.setProperty( Environment.HBM2DDL_AUTO, "create-drop" );
@ -203,7 +204,7 @@ public abstract class BaseCoreFunctionalTestCase extends BaseUnitTestCase {
}
protected void addMappings(Configuration configuration) {
String[] mappings = getMappings();
final String[] mappings = getMappings();
if ( mappings != null ) {
for ( String mapping : mappings ) {
if ( mapping.startsWith( "/" ) ) {
@ -214,22 +215,22 @@ public abstract class BaseCoreFunctionalTestCase extends BaseUnitTestCase {
}
}
}
Class<?>[] annotatedClasses = getAnnotatedClasses();
final Class<?>[] annotatedClasses = getAnnotatedClasses();
if ( annotatedClasses != null ) {
for ( Class<?> annotatedClass : annotatedClasses ) {
configuration.addAnnotatedClass( annotatedClass );
}
}
String[] annotatedPackages = getAnnotatedPackages();
final String[] annotatedPackages = getAnnotatedPackages();
if ( annotatedPackages != null ) {
for ( String annotatedPackage : annotatedPackages ) {
configuration.addPackage( annotatedPackage );
}
}
String[] xmlFiles = getOrmXmlFiles();
final String[] xmlFiles = getOrmXmlFiles();
if ( xmlFiles != null ) {
for ( String xmlFile : xmlFiles ) {
try ( InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream( xmlFile ) ) {
try ( InputStream is = currentThread().getContextClassLoader().getResourceAsStream( xmlFile ) ) {
configuration.addInputStream( is );
}
catch (IOException e) {
@ -265,7 +266,8 @@ public abstract class BaseCoreFunctionalTestCase extends BaseUnitTestCase {
protected void applyCacheSettings(Configuration configuration) {
if ( getCacheConcurrencyStrategy() != null ) {
configuration.setProperty( AvailableSettings.DEFAULT_CACHE_CONCURRENCY_STRATEGY, getCacheConcurrencyStrategy() );
configuration.setProperty( AvailableSettings.DEFAULT_CACHE_CONCURRENCY_STRATEGY,
getCacheConcurrencyStrategy() );
configuration.setSharedCacheMode( SharedCacheMode.ALL );
}
}
@ -287,18 +289,18 @@ public abstract class BaseCoreFunctionalTestCase extends BaseUnitTestCase {
protected void prepareBootstrapRegistryBuilder(BootstrapServiceRegistryBuilder builder) {
}
protected StandardServiceRegistryImpl buildServiceRegistry(BootstrapServiceRegistry bootRegistry, Configuration configuration) {
protected StandardServiceRegistryImpl buildServiceRegistry(
BootstrapServiceRegistry bootRegistry, Configuration configuration) {
try {
Properties properties = new Properties();
final Properties properties = new Properties();
properties.putAll( configuration.getProperties() );
ConfigurationHelper.resolvePlaceHolders( properties );
StandardServiceRegistryBuilder cfgRegistryBuilder = configuration.getStandardServiceRegistryBuilder();
StandardServiceRegistryBuilder registryBuilder = new StandardServiceRegistryBuilder( bootRegistry, cfgRegistryBuilder.getAggregatedCfgXml() )
.applySettings( properties );
resolvePlaceHolders( properties );
final LoadedConfig loadedConfig =
configuration.getStandardServiceRegistryBuilder().getAggregatedCfgXml();
final StandardServiceRegistryBuilder registryBuilder =
new StandardServiceRegistryBuilder( bootRegistry, loadedConfig )
.applySettings( properties );
ServiceRegistryUtil.applySettings( registryBuilder );
prepareBasicRegistryBuilder( registryBuilder );
return (StandardServiceRegistryImpl) registryBuilder.build();
}
@ -333,7 +335,7 @@ public abstract class BaseCoreFunctionalTestCase extends BaseUnitTestCase {
}
@AfterClassOnce
@SuppressWarnings( {"UnusedDeclaration"})
@SuppressWarnings("UnusedDeclaration")
protected void releaseSessionFactory() {
if ( sessionFactory == null ) {
return;
@ -356,7 +358,7 @@ public abstract class BaseCoreFunctionalTestCase extends BaseUnitTestCase {
@OnFailure
@OnExpectedFailure
@SuppressWarnings( {"UnusedDeclaration"})
@SuppressWarnings("UnusedDeclaration")
public void onFailure() {
if ( rebuildSessionFactoryOnError() ) {
rebuildSessionFactory();
@ -381,18 +383,13 @@ public abstract class BaseCoreFunctionalTestCase extends BaseUnitTestCase {
ReflectHelper.getMethod( Class.forName( "org.h2.util.DateTimeUtils" ), "resetCalendar" )
.invoke( null );
}
completeStrayTransaction();
if ( isCleanupTestDataRequired() ) {
cleanupTestData();
}
cleanupTest();
cleanupSession();
assertAllDataRemoved();
}
private void completeStrayTransaction() {
@ -401,7 +398,9 @@ public abstract class BaseCoreFunctionalTestCase extends BaseUnitTestCase {
return;
}
if ( ( (SessionImplementor) session ).isClosed() ) {
final SessionImplementor sessionImplementor = (SessionImplementor) session;
if ( sessionImplementor.isClosed() ) {
// nothing to do
return;
}
@ -411,15 +410,17 @@ public abstract class BaseCoreFunctionalTestCase extends BaseUnitTestCase {
return;
}
final TransactionCoordinator.TransactionDriver tdc =
( (SessionImplementor) session ).getTransactionCoordinator().getTransactionDriverControl();
if ( tdc.getStatus().canRollback() ) {
if ( canRollback( sessionImplementor ) ) {
session.getTransaction().rollback();
}
session.close();
}
private static boolean canRollback(SessionImplementor sessionImplementor) {
return sessionImplementor.getTransactionCoordinator()
.getTransactionDriverControl().getStatus().canRollback();
}
protected void cleanupCache() {
if ( sessionFactory != null ) {
sessionFactory.getCache().evictAllRegions();
@ -435,18 +436,22 @@ public abstract class BaseCoreFunctionalTestCase extends BaseUnitTestCase {
}
protected void cleanupTestData() throws Exception {
if(isCleanupTestDataUsingBulkDelete()) {
doInHibernate( this::sessionFactory, s -> {
s.createQuery( "delete from java.lang.Object" ).executeUpdate();
} );
}
else {
// Because of https://hibernate.atlassian.net/browse/HHH-5529,
// we can't rely on a Bulk Delete query which will not clear the link tables in @ElementCollection or unidirectional collections
doInHibernate( this::sessionFactory, s -> {
s.createQuery( "from java.lang.Object", Object.class ).list().forEach( s::remove );
} );
}
sessionFactory.getSchemaManager().truncateMappedObjects();
// if ( isCleanupTestDataUsingBulkDelete() ) {
// doInHibernate( this::sessionFactory, session -> {
// session.createMutationQuery( "delete from java.lang.Object" )
// .executeUpdate();
// } );
// }
// else {
// // Because of https://hibernate.atlassian.net/browse/HHH-5529,
// // we can't rely on a Bulk Delete query which will not clear the link tables in @ElementCollection or unidirectional collections
// doInHibernate( this::sessionFactory, session -> {
// session.createSelectionQuery( "from java.lang.Object", Object.class )
// .getResultList()
// .forEach( session::remove );
// } );
// }
}
private void cleanupSession() {
@ -457,7 +462,6 @@ public abstract class BaseCoreFunctionalTestCase extends BaseUnitTestCase {
}
public static class RollbackWork implements Work {
@Override
public void execute(Connection connection) throws SQLException {
connection.rollback();
@ -476,13 +480,13 @@ public abstract class BaseCoreFunctionalTestCase extends BaseUnitTestCase {
return;
}
Session tmpSession = sessionFactory.openSession();
Transaction transaction = tmpSession.beginTransaction();
final Session tmpSession = sessionFactory.openSession();
final Transaction transaction = tmpSession.beginTransaction();
try {
List<?> list = tmpSession.createQuery( "select o from java.lang.Object o" ).list();
Map<String,Integer> items = new HashMap<>();
final List<?> list =
tmpSession.createSelectionQuery( "select o from java.lang.Object o", Object.class )
.getResultList();
final Map<String,Integer> items = new HashMap<>();
if ( !list.isEmpty() ) {
for ( Object element : list ) {
Integer l = items.get( tmpSession.getEntityName( element ) );
@ -500,12 +504,12 @@ public abstract class BaseCoreFunctionalTestCase extends BaseUnitTestCase {
}
finally {
try {
if(transaction.getStatus().canRollback()){
if ( transaction.getStatus().canRollback() ) {
transaction.rollback();
}
tmpSession.close();
}
catch( Throwable t ) {
catch ( Throwable t ) {
// intentionally empty
}
}

View File

@ -38,7 +38,6 @@ import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.internal.build.AllowPrintStacktrace;
import org.hibernate.internal.build.AllowSysOut;
import org.hibernate.internal.util.ReflectHelper;
import org.hibernate.internal.util.StringHelper;
import org.hibernate.jdbc.Work;
import org.hibernate.mapping.Collection;
import org.hibernate.mapping.PersistentClass;
@ -48,7 +47,6 @@ import org.hibernate.mapping.SimpleValue;
import org.hibernate.query.sqm.mutation.internal.temptable.GlobalTemporaryTableMutationStrategy;
import org.hibernate.query.sqm.mutation.internal.temptable.LocalTemporaryTableMutationStrategy;
import org.hibernate.query.sqm.mutation.internal.temptable.PersistentTableStrategy;
import org.hibernate.resource.transaction.spi.TransactionCoordinator;
import org.hibernate.testing.AfterClassOnce;
import org.hibernate.testing.BeforeClassOnce;
@ -56,11 +54,13 @@ import org.hibernate.testing.OnExpectedFailure;
import org.hibernate.testing.OnFailure;
import org.hibernate.testing.cache.CachingRegionFactory;
import org.hibernate.testing.transaction.TransactionUtil2;
import org.hibernate.testing.util.ServiceRegistryUtil;
import org.junit.After;
import org.junit.Before;
import static java.lang.Thread.currentThread;
import static org.hibernate.internal.util.StringHelper.isNotEmpty;
import static org.hibernate.testing.transaction.TransactionUtil.doInHibernate;
import static org.hibernate.testing.util.ServiceRegistryUtil.serviceRegistryBuilder;
import static org.junit.Assert.fail;
/**
@ -81,12 +81,9 @@ public class BaseNonConfigCoreFunctionalTestCase extends BaseUnitTestCase {
private Session session;
protected Dialect getDialect() {
if ( serviceRegistry != null ) {
return serviceRegistry.getService( JdbcEnvironment.class ).getDialect();
}
else {
return BaseCoreFunctionalTestCase.getDialect();
}
return serviceRegistry != null
? serviceRegistry.getService(JdbcEnvironment.class).getDialect()
: BaseCoreFunctionalTestCase.getDialect();
}
protected StandardServiceRegistry serviceRegistry() {
@ -130,15 +127,14 @@ public class BaseNonConfigCoreFunctionalTestCase extends BaseUnitTestCase {
// JUNIT hooks
@BeforeClassOnce
@SuppressWarnings( {"UnusedDeclaration"})
protected void startUp() {
buildResources();
}
protected void buildResources() {
final StandardServiceRegistryBuilder ssrb = constructStandardServiceRegistryBuilder();
final StandardServiceRegistryBuilder serviceRegistryBuilder = constructStandardServiceRegistryBuilder();
serviceRegistry = ssrb.build();
serviceRegistry = serviceRegistryBuilder.build();
afterStandardServiceRegistryBuilt( serviceRegistry );
final MetadataSources metadataSources = new MetadataSources( serviceRegistry );
@ -149,7 +145,9 @@ public class BaseNonConfigCoreFunctionalTestCase extends BaseUnitTestCase {
initialize( metadataBuilder );
configureMetadataBuilder( metadataBuilder );
metadata = (MetadataImplementor) metadataBuilder.build();
applyCacheSettings( metadata );
if ( overrideCacheStrategy() && getCacheConcurrencyStrategy() != null ) {
applyCacheSettings( metadata );
}
afterMetadataBuilt( metadata );
final SessionFactoryBuilder sfb = metadata.getSessionFactoryBuilder();
@ -161,28 +159,31 @@ public class BaseNonConfigCoreFunctionalTestCase extends BaseUnitTestCase {
}
protected final StandardServiceRegistryBuilder constructStandardServiceRegistryBuilder() {
final BootstrapServiceRegistryBuilder bsrb = new BootstrapServiceRegistryBuilder();
bsrb.applyClassLoader( getClass().getClassLoader() );
// by default we do not share the BootstrapServiceRegistry nor the StandardServiceRegistry,
final BootstrapServiceRegistryBuilder builder = new BootstrapServiceRegistryBuilder();
builder.applyClassLoader( getClass().getClassLoader() );
// by default, we do not share the BootstrapServiceRegistry nor the StandardServiceRegistry,
// so we want the BootstrapServiceRegistry to be automatically closed when the
// StandardServiceRegistry is closed.
bsrb.enableAutoClose();
configureBootstrapServiceRegistryBuilder( bsrb );
final BootstrapServiceRegistry bsr = bsrb.build();
afterBootstrapServiceRegistryBuilt( bsr );
builder.enableAutoClose();
configureBootstrapServiceRegistryBuilder( builder );
final BootstrapServiceRegistry bootstrapServiceRegistry = builder.build();
afterBootstrapServiceRegistryBuilt( bootstrapServiceRegistry );
final Map<String, Object> settings = defaultSettings();
addSettings( settings );
final StandardServiceRegistryBuilder registryBuilder =
serviceRegistryBuilder( bootstrapServiceRegistry );
initialize( registryBuilder );
registryBuilder.applySettings( settings );
configureStandardServiceRegistryBuilder( registryBuilder );
return registryBuilder;
}
private static Map<String, Object> defaultSettings() {
final Map<String,Object> settings = new HashMap<>();
settings.put( PersistentTableStrategy.DROP_ID_TABLES, "true" );
settings.put( GlobalTemporaryTableMutationStrategy.DROP_ID_TABLES, "true" );
settings.put( LocalTemporaryTableMutationStrategy.DROP_ID_TABLES, "true" );
addSettings( settings );
final StandardServiceRegistryBuilder ssrb = ServiceRegistryUtil.serviceRegistryBuilder( bsr );
initialize( ssrb );
ssrb.applySettings( settings );
configureStandardServiceRegistryBuilder( ssrb );
return ssrb;
return settings;
}
protected void addSettings(Map<String,Object> settings) {
@ -192,41 +193,39 @@ public class BaseNonConfigCoreFunctionalTestCase extends BaseUnitTestCase {
* Apply any desired config to the BootstrapServiceRegistryBuilder to be incorporated
* into the built BootstrapServiceRegistry
*
* @param bsrb The BootstrapServiceRegistryBuilder
* @param registryBuilder The BootstrapServiceRegistryBuilder
*/
@SuppressWarnings({"SpellCheckingInspection", "UnusedParameters"})
protected void configureBootstrapServiceRegistryBuilder(BootstrapServiceRegistryBuilder bsrb) {
@SuppressWarnings("UnusedParameters")
protected void configureBootstrapServiceRegistryBuilder(BootstrapServiceRegistryBuilder registryBuilder) {
}
/**
* Hook to allow tests to use the BootstrapServiceRegistry if they wish
*
* @param bsr The BootstrapServiceRegistry
* @param bootstrapServiceRegistry The BootstrapServiceRegistry
*/
@SuppressWarnings("UnusedParameters")
protected void afterBootstrapServiceRegistryBuilt(BootstrapServiceRegistry bsr) {
protected void afterBootstrapServiceRegistryBuilt(BootstrapServiceRegistry bootstrapServiceRegistry) {
}
@SuppressWarnings("SpellCheckingInspection")
private void initialize(StandardServiceRegistryBuilder ssrb) {
private void initialize(StandardServiceRegistryBuilder builder) {
final Dialect dialect = BaseCoreFunctionalTestCase.getDialect();
ssrb.applySetting( AvailableSettings.CACHE_REGION_FACTORY, CachingRegionFactory.class.getName() );
builder.applySetting( AvailableSettings.CACHE_REGION_FACTORY, CachingRegionFactory.class.getName() );
if ( createSchema() ) {
ssrb.applySetting( AvailableSettings.HBM2DDL_AUTO, "create-drop" );
builder.applySetting( AvailableSettings.HBM2DDL_AUTO, "create-drop" );
final String secondSchemaName = createSecondSchema();
if ( StringHelper.isNotEmpty( secondSchemaName ) ) {
if ( !H2Dialect.class.isInstance( dialect ) ) {
if ( isNotEmpty( secondSchemaName ) ) {
if ( !( dialect instanceof H2Dialect ) ) {
// while it may be true that only H2 supports creation of a second schema via
// URL (no idea whether that is accurate), every db should support creation of schemas
// via DDL which SchemaExport can create for us. See how this is used and
// whether that usage could not just leverage that capability
throw new UnsupportedOperationException( "Only H2 dialect supports creation of second schema." );
}
Helper.createH2Schema( secondSchemaName, ssrb.getSettings() );
Helper.createH2Schema( secondSchemaName, builder.getSettings() );
}
}
ssrb.applySetting( AvailableSettings.DIALECT, dialect.getClass().getName() );
builder.applySetting( AvailableSettings.DIALECT, dialect.getClass().getName() );
}
protected boolean createSchema() {
@ -243,36 +242,33 @@ public class BaseNonConfigCoreFunctionalTestCase extends BaseUnitTestCase {
* Apply any desired config to the StandardServiceRegistryBuilder to be incorporated
* into the built StandardServiceRegistry
*
* @param ssrb The StandardServiceRegistryBuilder
* @param serviceRegistryBuilder The StandardServiceRegistryBuilder
*/
@SuppressWarnings({"SpellCheckingInspection", "UnusedParameters"})
protected void configureStandardServiceRegistryBuilder(StandardServiceRegistryBuilder ssrb) {
@SuppressWarnings("UnusedParameters")
protected void configureStandardServiceRegistryBuilder(StandardServiceRegistryBuilder serviceRegistryBuilder) {
}
/**
* Hook to allow tests to use the StandardServiceRegistry if they wish
*
* @param ssr The StandardServiceRegistry
* @param standardServiceRegistry The StandardServiceRegistry
*/
@SuppressWarnings("UnusedParameters")
protected void afterStandardServiceRegistryBuilt(StandardServiceRegistry ssr) {
protected void afterStandardServiceRegistryBuilt(StandardServiceRegistry standardServiceRegistry) {
}
protected void applyMetadataSources(MetadataSources sources) {
for ( String mapping : getMappings() ) {
sources.addResource( getBaseForMappings() + mapping );
}
for ( Class annotatedClass : getAnnotatedClasses() ) {
for ( Class<?> annotatedClass : getAnnotatedClasses() ) {
sources.addAnnotatedClass( annotatedClass );
}
for ( String annotatedPackage : getAnnotatedPackages() ) {
sources.addPackage( annotatedPackage );
}
for ( String ormXmlFile : getXmlFiles() ) {
sources.addInputStream( Thread.currentThread().getContextClassLoader().getResourceAsStream( ormXmlFile ) );
sources.addInputStream( currentThread().getContextClassLoader().getResourceAsStream( ormXmlFile ) );
}
}
@ -286,9 +282,9 @@ public class BaseNonConfigCoreFunctionalTestCase extends BaseUnitTestCase {
return "org/hibernate/test/";
}
protected static final Class[] NO_CLASSES = new Class[0];
protected static final Class<?>[] NO_CLASSES = new Class[0];
protected Class[] getAnnotatedClasses() {
protected Class<?>[] getAnnotatedClasses() {
return NO_CLASSES;
}
@ -319,54 +315,45 @@ public class BaseNonConfigCoreFunctionalTestCase extends BaseUnitTestCase {
}
protected final void applyCacheSettings(Metadata metadata) {
if ( !overrideCacheStrategy() ) {
return;
}
if ( getCacheConcurrencyStrategy() == null ) {
return;
}
for ( PersistentClass entityBinding : metadata.getEntityBindings() ) {
if ( entityBinding.isInherited() ) {
continue;
}
boolean hasLob = false;
for ( Property prop : entityBinding.getPropertyClosure() ) {
if ( prop.getValue().isSimpleValue() ) {
if ( isLob( (SimpleValue) prop.getValue() ) ) {
hasLob = true;
break;
}
if ( !entityBinding.isInherited() ) {
if ( !hasLob( entityBinding ) ) {
final RootClass rootClass = (RootClass) entityBinding;
rootClass.setCacheConcurrencyStrategy( getCacheConcurrencyStrategy() );
entityBinding.setCached( true );
}
}
if ( !hasLob ) {
( ( RootClass) entityBinding ).setCacheConcurrencyStrategy( getCacheConcurrencyStrategy() );
entityBinding.setCached( true );
}
}
for ( Collection collectionBinding : metadata.getCollectionBindings() ) {
boolean isLob = false;
if ( collectionBinding.getElement().isSimpleValue() ) {
isLob = isLob( (SimpleValue) collectionBinding.getElement() );
}
if ( !isLob ) {
if ( !isLob( collectionBinding ) ) {
collectionBinding.setCacheConcurrencyStrategy( getCacheConcurrencyStrategy() );
}
}
}
private static boolean isLob(Collection collectionBinding) {
return collectionBinding.getElement().isSimpleValue()
&& isLob( (SimpleValue) collectionBinding.getElement() );
}
private static boolean hasLob(PersistentClass entityBinding) {
for ( Property prop : entityBinding.getPropertyClosure() ) {
if ( prop.getValue().isSimpleValue() ) {
if ( isLob( (SimpleValue) prop.getValue() ) ) {
return true;
}
}
}
return false;
}
private static boolean isLob(SimpleValue value) {
final String typeName = value.getTypeName();
if ( typeName != null ) {
String significantTypeNamePart = typeName.substring( typeName.lastIndexOf( '.' ) + 1 )
.toLowerCase( Locale.ROOT );
final String significantTypeNamePart =
typeName.substring( typeName.lastIndexOf( '.' ) + 1 )
.toLowerCase( Locale.ROOT );
switch ( significantTypeNamePart ) {
case "blob":
case "blobtype":
@ -383,7 +370,7 @@ public class BaseNonConfigCoreFunctionalTestCase extends BaseUnitTestCase {
protected void afterMetadataBuilt(Metadata metadata) {
}
private void initialize(SessionFactoryBuilder sfb, Metadata metadata) {
private void initialize(SessionFactoryBuilder sessionFactoryBuilder, Metadata metadata) {
// todo : this is where we need to apply cache settings to be like BaseCoreFunctionalTestCase
// it reads the class/collection mappings and creates corresponding
// CacheRegionDescription references.
@ -400,7 +387,7 @@ public class BaseNonConfigCoreFunctionalTestCase extends BaseUnitTestCase {
}
@AfterClassOnce
@SuppressWarnings( {"UnusedDeclaration"})
@SuppressWarnings("UnusedDeclaration")
protected void shutDown() {
releaseResources();
}
@ -433,7 +420,7 @@ public class BaseNonConfigCoreFunctionalTestCase extends BaseUnitTestCase {
@OnFailure
@OnExpectedFailure
@SuppressWarnings( {"UnusedDeclaration"})
@SuppressWarnings("UnusedDeclaration")
public void onFailure() {
if ( rebuildSessionFactoryOnError() ) {
rebuildSessionFactory();
@ -456,18 +443,15 @@ public class BaseNonConfigCoreFunctionalTestCase extends BaseUnitTestCase {
public final void afterTest() throws Exception {
// see https://github.com/hibernate/hibernate-orm/pull/3412#issuecomment-678338398
if ( getDialect() instanceof H2Dialect ) {
ReflectHelper.getMethod( Class.forName( "org.h2.util.DateTimeUtils" ), "resetCalendar" ).invoke( null );
ReflectHelper.getMethod( Class.forName( "org.h2.util.DateTimeUtils" ), "resetCalendar" )
.invoke( null );
}
completeStrayTransaction();
if ( isCleanupTestDataRequired() ) {
cleanupTestData();
}
cleanupTest();
cleanupSession();
assertAllDataRemoved();
}
@ -477,7 +461,9 @@ public class BaseNonConfigCoreFunctionalTestCase extends BaseUnitTestCase {
return;
}
if ( ( (SessionImplementor) session ).isClosed() ) {
final SessionImplementor sessionImplementor = (SessionImplementor) session;
if ( sessionImplementor.isClosed() ) {
// nothing to do
return;
}
@ -487,22 +473,27 @@ public class BaseNonConfigCoreFunctionalTestCase extends BaseUnitTestCase {
return;
}
final TransactionCoordinator.TransactionDriver tdc =
( (SessionImplementor) session ).getTransactionCoordinator().getTransactionDriverControl();
if ( tdc.getStatus().canRollback() ) {
if ( canRollback( sessionImplementor ) ) {
session.getTransaction().rollback();
}
}
private static boolean canRollback(SessionImplementor sessionImplementor) {
return sessionImplementor.getTransactionCoordinator()
.getTransactionDriverControl().getStatus().canRollback();
}
protected boolean isCleanupTestDataRequired() {
return false;
}
protected void cleanupTestData() throws Exception {
doInHibernate(this::sessionFactory, s -> {
s.createQuery( "from java.lang.Object" ).getResultList().forEach( s::remove );
});
sessionFactory.getSchemaManager().truncateMappedObjects();
// doInHibernate( this::sessionFactory, session -> {
// session.createSelectionQuery( "from java.lang.Object", Object.class )
// .getResultList()
// .forEach( session::remove );
// } );
}
@ -524,7 +515,6 @@ public class BaseNonConfigCoreFunctionalTestCase extends BaseUnitTestCase {
protected void cleanupTest() throws Exception {
}
@SuppressWarnings( {"UnnecessaryBoxing", "UnnecessaryUnboxing"})
@AllowSysOut
protected void assertAllDataRemoved() {
if ( !createSchema() ) {
@ -534,32 +524,25 @@ public class BaseNonConfigCoreFunctionalTestCase extends BaseUnitTestCase {
return;
}
Session tmpSession = sessionFactory.openSession();
try {
List list = tmpSession.createQuery( "select o from java.lang.Object o" ).list();
Map<String,Integer> items = new HashMap<String,Integer>();
try ( Session tmpSession = sessionFactory.openSession() ) {
final List<Object> list =
tmpSession.createSelectionQuery( "select o from java.lang.Object o", Object.class )
.getResultList();
final Map<String, Integer> items = new HashMap<>();
if ( !list.isEmpty() ) {
for ( Object element : list ) {
Integer l = items.get( tmpSession.getEntityName( element ) );
if ( l == null ) {
if (l == null) {
l = 0;
}
l = l + 1 ;
l = l + 1;
items.put( tmpSession.getEntityName( element ), l );
System.out.println( "Data left: " + element );
}
fail( "Data is left in the database: " + items.toString() );
}
}
finally {
try {
tmpSession.close();
}
catch( Throwable t ) {
// intentionally empty
fail( "Data is left in the database: " + items );
}
}
// intentionally empty
}

View File

@ -7,13 +7,12 @@
package org.hibernate.testing.orm.jpa;
import java.net.URL;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Properties;
import jakarta.persistence.SharedCacheMode;
import jakarta.persistence.ValidationMode;
import jakarta.persistence.spi.PersistenceUnitTransactionType;
import jakarta.persistence.PersistenceUnitTransactionType;
import javax.sql.DataSource;
import org.hibernate.bytecode.enhance.spi.EnhancementContext;
@ -44,7 +43,12 @@ public class PersistenceUnitDescriptorAdapter implements PersistenceUnitDescript
}
@Override
public PersistenceUnitTransactionType getTransactionType() {
public PersistenceUnitTransactionType getPersistenceUnitTransactionType() {
return null;
}
@Override @SuppressWarnings("removal")
public jakarta.persistence.spi.PersistenceUnitTransactionType getTransactionType() {
return null;
}

View File

@ -7,7 +7,6 @@
package org.hibernate.testing.orm.jpa;
import java.net.URL;
import java.util.Collections;
import java.util.List;
import java.util.Properties;
import jakarta.persistence.SharedCacheMode;
@ -19,17 +18,20 @@ import javax.sql.DataSource;
import org.hibernate.jpa.HibernatePersistenceProvider;
import static java.lang.System.identityHashCode;
import static java.util.Collections.emptyList;
/**
* Implementation of {@link PersistenceUnitInfo} for testing use.
*
* <p>
* Expected usage is to override methods relevant to their specific tests.
*
* <p>
* See {@link PersistenceUnitInfoImpl} for a more bean-like implementation
*
* @author Steve Ebersole
*/
public class PersistenceUnitInfoAdapter implements PersistenceUnitInfo {
private final String name = "persistenceUnitInfoAdapter@" + System.identityHashCode( this );
private final String name = "persistenceUnitInfoAdapter@" + identityHashCode( this );
private Properties properties;
public String getPersistenceUnitName() {
@ -50,6 +52,7 @@ public class PersistenceUnitInfoAdapter implements PersistenceUnitInfo {
return List.of();
}
@Override @SuppressWarnings("removal")
public PersistenceUnitTransactionType getTransactionType() {
return null;
}
@ -63,11 +66,11 @@ public class PersistenceUnitInfoAdapter implements PersistenceUnitInfo {
}
public List<String> getMappingFileNames() {
return Collections.emptyList();
return emptyList();
}
public List<URL> getJarFileUrls() {
return Collections.emptyList();
return emptyList();
}
public URL getPersistenceUnitRootUrl() {
@ -75,7 +78,7 @@ public class PersistenceUnitInfoAdapter implements PersistenceUnitInfo {
}
public List<String> getManagedClassNames() {
return Collections.emptyList();
return emptyList();
}
public boolean excludeUnlistedClasses() {

View File

@ -20,11 +20,13 @@ import javax.sql.DataSource;
import org.hibernate.jpa.HibernatePersistenceProvider;
import static java.util.Collections.emptyList;
/**
* Implementation of {@link PersistenceUnitInfo} for testing use.
*
* <p>
* This implementation provides a bean-like contract for providing PU information.
*
* <p>
* See {@link PersistenceUnitInfoAdapter} for an override-based solution
*
* @author Steve Ebersole
@ -36,9 +38,10 @@ public class PersistenceUnitInfoImpl implements PersistenceUnitInfo {
private String scopeAnnotationName;
private List<String> qualifierAnnotationNames = List.of();
private PersistenceUnitTransactionType transactionType;
private SharedCacheMode cacheMode;
private ValidationMode validationMode;
@SuppressWarnings("removal")
private PersistenceUnitTransactionType transactionType;
private List<String> mappingFiles;
private List<String> managedClassNames;
@ -81,12 +84,12 @@ public class PersistenceUnitInfoImpl implements PersistenceUnitInfo {
return HibernatePersistenceProvider.class.getName();
}
@Override
@Override @SuppressWarnings("removal")
public PersistenceUnitTransactionType getTransactionType() {
return transactionType;
}
public void setTransactionType(PersistenceUnitTransactionType transactionType) {
public void setTransactionType(@SuppressWarnings("removal") PersistenceUnitTransactionType transactionType) {
this.transactionType = transactionType;
}
@ -110,7 +113,7 @@ public class PersistenceUnitInfoImpl implements PersistenceUnitInfo {
@Override
public List<String> getMappingFileNames() {
return mappingFiles == null ? Collections.emptyList() : mappingFiles;
return mappingFiles == null ? emptyList() : mappingFiles;
}
public void applyMappingFiles(String... mappingFiles) {
@ -122,7 +125,7 @@ public class PersistenceUnitInfoImpl implements PersistenceUnitInfo {
@Override
public List<String> getManagedClassNames() {
return managedClassNames == null ? Collections.emptyList() : managedClassNames;
return managedClassNames == null ? emptyList() : managedClassNames;
}
public void applyManagedClassNames(String... managedClassNames) {

View File

@ -58,12 +58,11 @@ public abstract class BaseSessionFactoryFunctionalTest
protected static final Dialect DIALECT = DialectContext.getDialect();
protected static final Class[] NO_CLASSES = new Class[0];
protected static final Class<?>[] NO_CLASSES = new Class[0];
protected static final String[] NO_MAPPINGS = new String[0];
private static final Logger log = Logger.getLogger( BaseSessionFactoryFunctionalTest.class );
private ServiceRegistryScope registryScope;
private DomainModelScope modelScope;
private SessionFactoryScope sessionFactoryScope;
@ -103,7 +102,6 @@ public abstract class BaseSessionFactoryFunctionalTest
@Override
public void injectServiceRegistryScope(ServiceRegistryScope registryScope) {
this.registryScope = registryScope;
}
@Override
@ -113,51 +111,46 @@ public abstract class BaseSessionFactoryFunctionalTest
applyMetadataBuilder( metadataBuilder );
applyMetadataSources( metadataSources );
final MetadataImplementor metadata = (MetadataImplementor) metadataBuilder.build();
if ( !overrideCacheStrategy() || getCacheConcurrencyStrategy() == null ) {
return metadata;
if ( overrideCacheStrategy() && getCacheConcurrencyStrategy() != null ) {
applyCacheSettings( metadata );
}
applyCacheSettings( metadata );
return metadata;
}
protected final void applyCacheSettings(Metadata metadata) {
for ( PersistentClass entityBinding : metadata.getEntityBindings() ) {
if ( entityBinding.isInherited() ) {
continue;
}
boolean hasLob = false;
for ( Property prop : entityBinding.getPropertyClosure() ) {
if ( prop.getValue().isSimpleValue() ) {
if ( isLob( (SimpleValue) prop.getValue() ) ) {
hasLob = true;
break;
}
if ( !entityBinding.isInherited() ) {
if ( !hasLob( entityBinding ) ) {
final RootClass rootClass = (RootClass) entityBinding;
rootClass.setCacheConcurrencyStrategy( getCacheConcurrencyStrategy() );
entityBinding.setCached( true );
}
}
if ( !hasLob ) {
( (RootClass) entityBinding ).setCacheConcurrencyStrategy( getCacheConcurrencyStrategy() );
entityBinding.setCached( true );
}
}
for ( Collection collectionBinding : metadata.getCollectionBindings() ) {
boolean isLob = false;
if ( collectionBinding.getElement().isSimpleValue() ) {
isLob = isLob( (SimpleValue) collectionBinding.getElement() );
}
if ( !isLob ) {
if ( !isLob( collectionBinding ) ) {
collectionBinding.setCacheConcurrencyStrategy( getCacheConcurrencyStrategy() );
}
}
}
private static boolean isLob(Collection collectionBinding) {
return collectionBinding.getElement().isSimpleValue()
&& isLob( (SimpleValue) collectionBinding.getElement() );
}
private static boolean hasLob(PersistentClass entityBinding) {
for ( Property prop : entityBinding.getPropertyClosure() ) {
if ( prop.getValue().isSimpleValue() ) {
if ( isLob( (SimpleValue) prop.getValue() ) ) {
return true;
}
}
}
return false;
}
protected boolean overrideCacheStrategy() {
return true;
}

View File

@ -16,6 +16,7 @@ import java.util.Properties;
import java.util.function.Consumer;
import java.util.function.Function;
import jakarta.persistence.PersistenceUnitTransactionType;
import org.hibernate.bytecode.enhance.spi.EnhancementContext;
import org.hibernate.bytecode.spi.ClassTransformer;
import org.hibernate.cfg.AvailableSettings;
@ -34,7 +35,6 @@ import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.SharedCacheMode;
import jakarta.persistence.ValidationMode;
import jakarta.persistence.spi.PersistenceUnitTransactionType;
import static org.hibernate.testing.transaction.TransactionUtil.doInJPA;
@ -201,8 +201,13 @@ public class EntityManagerFactoryBasedFunctionalTest
return false;
}
@Override @SuppressWarnings("removal")
public jakarta.persistence.spi.PersistenceUnitTransactionType getTransactionType() {
return null;
}
@Override
public PersistenceUnitTransactionType getTransactionType() {
public PersistenceUnitTransactionType getPersistenceUnitTransactionType() {
return null;
}

View File

@ -11,25 +11,18 @@ import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.Properties;
import jakarta.persistence.spi.PersistenceUnitInfo;
import org.hibernate.SessionFactoryObserver;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.spi.MetadataImplementor;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.cfg.Environment;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.internal.util.ReflectHelper;
import org.hibernate.jpa.boot.internal.PersistenceUnitInfoDescriptor;
import org.hibernate.jpa.boot.spi.Bootstrap;
import org.hibernate.jpa.boot.spi.EntityManagerFactoryBuilder;
import org.hibernate.query.sqm.mutation.internal.temptable.GlobalTemporaryTableMutationStrategy;
import org.hibernate.query.sqm.mutation.internal.temptable.LocalTemporaryTableMutationStrategy;
import org.hibernate.query.sqm.mutation.internal.temptable.PersistentTableStrategy;
import org.hibernate.tool.schema.Action;
import org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator;
import org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.ActionGrouping;
import org.hibernate.testing.jdbc.SQLStatementInspector;
import org.hibernate.testing.orm.domain.DomainModelDescriptor;
@ -40,10 +33,12 @@ import org.junit.jupiter.api.extension.BeforeEachCallback;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.api.extension.TestExecutionExceptionHandler;
import org.junit.jupiter.api.extension.TestInstancePostProcessor;
import org.junit.platform.commons.support.AnnotationSupport;
import org.jboss.logging.Logger;
import static org.hibernate.jpa.boot.spi.Bootstrap.getEntityManagerFactoryBuilder;
import static org.junit.platform.commons.support.AnnotationSupport.findAnnotation;
/**
* hibernate-testing implementation of a few JUnit5 contracts to support SessionFactory-based testing,
* including argument injection (or see {@link SessionFactoryScopeAware})
@ -64,11 +59,9 @@ public class EntityManagerFactoryExtension
}
public static EntityManagerFactoryScope findEntityManagerFactoryScope(
Object testScope,
Optional<Jpa> emfAnnWrapper,
ExtensionContext context) {
Object testScope, Optional<Jpa> optionalJpa, ExtensionContext context) {
if ( emfAnnWrapper.isEmpty() ) {
if ( optionalJpa.isEmpty() ) {
// No annotation on the test class, should be on the test methods
return null;
}
@ -78,149 +71,151 @@ public class EntityManagerFactoryExtension
if ( existing != null ) {
return existing;
}
if ( !context.getElement().isPresent() ) {
throw new RuntimeException( "Unable to determine how to handle given ExtensionContext : " + context.getDisplayName() );
if ( context.getElement().isEmpty() ) {
throw new RuntimeException( "Unable to determine how to handle given ExtensionContext : "
+ context.getDisplayName() );
}
final Jpa emfAnn = emfAnnWrapper.get();
final PersistenceUnitInfoImpl pui = new PersistenceUnitInfoImpl( emfAnn.persistenceUnitName() );
( (Map<Object, Object>) Environment.getProperties() ).forEach(
(key, value) ->
pui.getProperties().put( key, value )
);
pui.setTransactionType( emfAnn.transactionType() );
pui.setCacheMode( emfAnn.sharedCacheMode() );
pui.setValidationMode( emfAnn.validationMode() );
pui.setExcludeUnlistedClasses( emfAnn.excludeUnlistedClasses() );
final Jpa jpa = optionalJpa.get();
final PersistenceUnitInfoImpl pui = createPersistenceUnitInfo( jpa );
collectProperties( pui, jpa );
managedClassesAndMappings( jpa, pui );
final Map<String, Object> integrationSettings = collectIntegrationSettings( jpa );
// statement inspector
setupStatementInspector( jpa, integrationSettings );
ServiceRegistryUtil.applySettings( integrationSettings );
final EntityManagerFactoryScopeImpl scope =
new EntityManagerFactoryScopeImpl( pui, integrationSettings );
store.put( EMF_KEY, scope );
return scope;
}
private static void collectProperties(PersistenceUnitInfoImpl pui, Jpa jpa) {
final Properties properties = pui.getProperties();
properties.putAll( Environment.getProperties() );
// JpaCompliance
pui.getProperties().put( AvailableSettings.JPA_COMPLIANCE, emfAnn.jpaComplianceEnabled() );
pui.getProperties().put( AvailableSettings.JPA_QUERY_COMPLIANCE, emfAnn.queryComplianceEnabled() );
pui.getProperties().put( AvailableSettings.JPA_TRANSACTION_COMPLIANCE, emfAnn.transactionComplianceEnabled() );
pui.getProperties().put( AvailableSettings.JPA_CLOSED_COMPLIANCE, emfAnn.closedComplianceEnabled() );
pui.getProperties().put( AvailableSettings.JPA_PROXY_COMPLIANCE, emfAnn.proxyComplianceEnabled() );
pui.getProperties().put( AvailableSettings.JPA_CACHING_COMPLIANCE, emfAnn.cacheComplianceEnabled() );
pui.getProperties().put( AvailableSettings.JPA_ID_GENERATOR_GLOBAL_SCOPE_COMPLIANCE, emfAnn.generatorScopeComplianceEnabled() );
pui.getProperties().put( AvailableSettings.JPA_ORDER_BY_MAPPING_COMPLIANCE, emfAnn.orderByMappingComplianceEnabled() );
pui.getProperties().put( AvailableSettings.JPA_LOAD_BY_ID_COMPLIANCE, emfAnn.loadByIdComplianceEnabled() );
final Setting[] properties = emfAnn.properties();
for ( int i = 0; i < properties.length; i++ ) {
final Setting property = properties[i];
pui.getProperties().setProperty( property.name(), property.value() );
setJpaComplianceProperties( properties, jpa );
for ( Setting property : jpa.properties() ) {
properties.setProperty( property.name(), property.value() );
}
pui.getProperties().setProperty(
properties.setProperty(
AvailableSettings.GENERATE_STATISTICS,
Boolean.toString( emfAnn.generateStatistics() )
Boolean.toString( jpa.generateStatistics() )
);
if ( emfAnn.exportSchema() ) {
pui.getProperties().setProperty(
if ( jpa.exportSchema() ) {
properties.setProperty(
AvailableSettings.JAKARTA_HBM2DDL_DATABASE_ACTION,
Action.CREATE_DROP.getExternalHbm2ddlName()
);
}
}
if ( emfAnn.annotatedPackageNames().length > 0 ) {
pui.applyManagedClassNames( emfAnn.annotatedPackageNames() );
private static PersistenceUnitInfoImpl createPersistenceUnitInfo(Jpa jpa) {
final PersistenceUnitInfoImpl pui =
new PersistenceUnitInfoImpl( jpa.persistenceUnitName() );
pui.setTransactionType( jpa.transactionType() );
pui.setCacheMode( jpa.sharedCacheMode() );
pui.setValidationMode( jpa.validationMode() );
pui.setExcludeUnlistedClasses( jpa.excludeUnlistedClasses() );
return pui;
}
private static void managedClassesAndMappings(Jpa jpa, PersistenceUnitInfoImpl pui) {
if ( jpa.annotatedPackageNames().length > 0 ) {
pui.applyManagedClassNames( jpa.annotatedPackageNames() );
}
if ( emfAnn.annotatedClassNames().length > 0 ) {
pui.applyManagedClassNames( emfAnn.annotatedClassNames() );
if ( jpa.annotatedClassNames().length > 0 ) {
pui.applyManagedClassNames( jpa.annotatedClassNames() );
}
if ( emfAnn.annotatedClasses().length > 0 ) {
for ( int i = 0; i < emfAnn.annotatedClasses().length; i++ ) {
pui.applyManagedClassNames( emfAnn.annotatedClasses()[i].getName() );
if ( jpa.annotatedClasses().length > 0 ) {
for (int i = 0; i < jpa.annotatedClasses().length; i++ ) {
pui.applyManagedClassNames( jpa.annotatedClasses()[i].getName() );
}
}
if ( emfAnn.xmlMappings().length > 0 ) {
pui.applyMappingFiles( emfAnn.xmlMappings() );
if ( jpa.xmlMappings().length > 0 ) {
pui.applyMappingFiles( jpa.xmlMappings() );
}
if ( emfAnn.standardModels().length > 0 ) {
for ( int i = 0; i < emfAnn.standardModels().length; i++ ) {
final StandardDomainModel standardDomainModel = emfAnn.standardModels()[i];
for ( int i1 = 0; i1 < standardDomainModel.getDescriptor().getAnnotatedClasses().length; i1++ ) {
final Class<?> annotatedClass = standardDomainModel.getDescriptor().getAnnotatedClasses()[i1];
pui.applyManagedClassNames( annotatedClass.getName() );
}
for ( StandardDomainModel standardDomainModel : jpa.standardModels() ) {
for ( Class<?> annotatedClass : standardDomainModel.getDescriptor().getAnnotatedClasses() ) {
pui.applyManagedClassNames( annotatedClass.getName() );
}
}
if ( emfAnn.modelDescriptorClasses().length > 0 ) {
for ( int i = 0; i < emfAnn.modelDescriptorClasses().length; i++ ) {
final Class<? extends DomainModelDescriptor> modelDescriptorClass = emfAnn.modelDescriptorClasses()[i];
final DomainModelDescriptor domainModelDescriptor = instantiateDomainModelDescriptor(
modelDescriptorClass );
for ( int i1 = 0; i1 < domainModelDescriptor.getAnnotatedClasses().length; i1++ ) {
final Class<?> annotatedClass = domainModelDescriptor.getAnnotatedClasses()[i1];
pui.applyManagedClassNames( annotatedClass.getName() );
}
for ( Class<? extends DomainModelDescriptor> modelDescriptorClass :
jpa.modelDescriptorClasses() ) {
final DomainModelDescriptor domainModelDescriptor =
instantiateDomainModelDescriptor( modelDescriptorClass );
final Class<?>[] annotatedClasses = domainModelDescriptor.getAnnotatedClasses();
for ( Class<?> annotatedClass : annotatedClasses ) {
pui.applyManagedClassNames( annotatedClass.getName() );
}
}
}
private static Map<String, Object> collectIntegrationSettings(Jpa jpa) {
final Map<String, Object> integrationSettings = new HashMap<>();
integrationSettings.put( PersistentTableStrategy.DROP_ID_TABLES, "true" );
integrationSettings.put( GlobalTemporaryTableMutationStrategy.DROP_ID_TABLES, "true" );
integrationSettings.put( LocalTemporaryTableMutationStrategy.DROP_ID_TABLES, "true" );
for ( int i = 0; i < emfAnn.integrationSettings().length; i++ ) {
final Setting setting = emfAnn.integrationSettings()[i];
final Setting[] settings = jpa.integrationSettings();
for ( Setting setting : settings ) {
integrationSettings.put( setting.name(), setting.value() );
}
for ( SettingProvider providerAnn : emfAnn.settingProviders() ) {
for ( SettingProvider providerAnn : jpa.settingProviders() ) {
final Class<? extends SettingProvider.Provider<?>> providerImpl = providerAnn.provider();
try {
final SettingProvider.Provider<?> provider = providerImpl.getConstructor().newInstance();
integrationSettings.put( providerAnn.settingName(), provider.getSetting() );
integrationSettings.put( providerAnn.settingName(),
providerImpl.getConstructor().newInstance().getSetting() );
}
catch (Exception e) {
log.error( "Error obtaining setting provider for " + providerImpl.getName(), e );
}
}
return integrationSettings;
}
// statement inspector
if ( emfAnn.useCollectingStatementInspector() ) {
String inspectorSetting = (String) integrationSettings.get( AvailableSettings.STATEMENT_INSPECTOR );
if ( !(inspectorSetting == null || inspectorSetting.isBlank()) ) {
private static void setupStatementInspector(Jpa jpa, Map<String, Object> integrationSettings) {
if ( jpa.useCollectingStatementInspector() ) {
final String inspectorSetting = (String) integrationSettings.get( AvailableSettings.STATEMENT_INSPECTOR );
if ( inspectorSetting != null && !inspectorSetting.isBlank() ) {
log.warn( String.format( "Overriding the explicit \"%1s\" statement inspector setting", inspectorSetting ) );
}
integrationSettings.put( AvailableSettings.STATEMENT_INSPECTOR, new SQLStatementInspector() );
}
ServiceRegistryUtil.applySettings( integrationSettings );
final EntityManagerFactoryScopeImpl scope = new EntityManagerFactoryScopeImpl( pui, integrationSettings );
store.put( EMF_KEY, scope );
return scope;
}
private static DomainModelDescriptor instantiateDomainModelDescriptor(Class<? extends DomainModelDescriptor> modelDescriptorClass) {
private static void setJpaComplianceProperties(Properties properties, Jpa jpa) {
properties.put( AvailableSettings.JPA_COMPLIANCE, jpa.jpaComplianceEnabled() );
properties.put( AvailableSettings.JPA_QUERY_COMPLIANCE, jpa.queryComplianceEnabled() );
properties.put( AvailableSettings.JPA_TRANSACTION_COMPLIANCE, jpa.transactionComplianceEnabled() );
properties.put( AvailableSettings.JPA_CLOSED_COMPLIANCE, jpa.closedComplianceEnabled() );
properties.put( AvailableSettings.JPA_PROXY_COMPLIANCE, jpa.proxyComplianceEnabled() );
properties.put( AvailableSettings.JPA_CACHING_COMPLIANCE, jpa.cacheComplianceEnabled() );
properties.put( AvailableSettings.JPA_ID_GENERATOR_GLOBAL_SCOPE_COMPLIANCE, jpa.generatorScopeComplianceEnabled() );
properties.put( AvailableSettings.JPA_ORDER_BY_MAPPING_COMPLIANCE, jpa.orderByMappingComplianceEnabled() );
properties.put( AvailableSettings.JPA_LOAD_BY_ID_COMPLIANCE, jpa.loadByIdComplianceEnabled() );
}
private static DomainModelDescriptor instantiateDomainModelDescriptor(
Class<? extends DomainModelDescriptor> modelDescriptorClass) {
// first, see if it has a static singleton reference and use that if so
try {
final Field[] declaredFields = modelDescriptorClass.getDeclaredFields();
for ( int i = 0; i < declaredFields.length; i++ ) {
final Field field = declaredFields[i];
if ( ReflectHelper.isStaticField( field ) ) {
for ( Field field : modelDescriptorClass.getDeclaredFields() ) {
if ( ReflectHelper.isStaticField(field) ) {
final Object value = field.get( null );
if ( value instanceof DomainModelDescriptor ) {
return (DomainModelDescriptor) value;
if ( value instanceof DomainModelDescriptor descriptor ) {
return descriptor;
}
}
}
}
catch (IllegalAccessException e) {
throw new RuntimeException(
"Problem accessing DomainModelDescriptor fields : " + modelDescriptorClass.getName(),
e
);
throw new RuntimeException( "Problem accessing DomainModelDescriptor fields : "
+ modelDescriptorClass.getName(), e );
}
// no singleton field, try to instantiate it via reflection
@ -228,86 +223,38 @@ public class EntityManagerFactoryExtension
return modelDescriptorClass.getConstructor( null ).newInstance( null );
}
catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
throw new RuntimeException(
"Problem instantiation DomainModelDescriptor : " + modelDescriptorClass.getName(),
e
);
throw new RuntimeException( "Problem instantiation DomainModelDescriptor : "
+ modelDescriptorClass.getName(), e );
}
}
private static void prepareSchemaExport(
SessionFactoryImplementor sessionFactory,
MetadataImplementor model) {
final Map<String, Object> baseProperties = sessionFactory.getProperties();
final Set<ActionGrouping> groupings = ActionGrouping.interpret( model, baseProperties );
if ( !groupings.isEmpty() ) {
// the properties contained explicit settings for auto schema tooling - skip the annotation
return;
}
final HashMap<String,Object> settings = new HashMap<>( baseProperties );
settings.put( AvailableSettings.JAKARTA_HBM2DDL_DATABASE_ACTION, Action.CREATE_DROP );
final StandardServiceRegistry serviceRegistry = model.getMetadataBuildingOptions().getServiceRegistry();
SchemaManagementToolCoordinator.process(
model,
serviceRegistry,
settings,
action -> sessionFactory.addObserver(
new SessionFactoryObserver() {
@Override
public void sessionFactoryClosing(org.hibernate.SessionFactory factory) {
action.perform( serviceRegistry );
}
}
)
);
}
@Override
public void beforeEach(ExtensionContext context) {
log.tracef( "#beforeEach(%s)", context.getDisplayName() );
final Optional<Jpa> emfAnnWrapper = AnnotationSupport.findAnnotation(
context.getRequiredTestMethod(),
Jpa.class
);
if ( emfAnnWrapper.isEmpty() ) {
// assume the annotation is defined on the class-level...
return;
final Optional<Jpa> optionalJpa = findAnnotation( context.getRequiredTestMethod(), Jpa.class );
if ( optionalJpa.isPresent() ) {
findEntityManagerFactoryScope( context.getRequiredTestMethod(), optionalJpa, context );
}
findEntityManagerFactoryScope( context.getRequiredTestMethod(), emfAnnWrapper, context );
// else assume the annotation is defined on the class-level...
}
@Override
public void postProcessTestInstance(Object testInstance, ExtensionContext context) {
log.tracef( "#postProcessTestInstance(%s, %s)", testInstance, context.getDisplayName() );
final Optional<Jpa> emfAnnWrapper = AnnotationSupport.findAnnotation(
context.getRequiredTestClass(),
Jpa.class
);
findEntityManagerFactoryScope( testInstance, emfAnnWrapper, context );
final Optional<Jpa> optionalJpa = findAnnotation( context.getRequiredTestClass(), Jpa.class );
findEntityManagerFactoryScope( testInstance, optionalJpa, context );
}
@Override
public void handleTestExecutionException(ExtensionContext context, Throwable throwable) throws Throwable {
log.tracef( "#handleTestExecutionException(%s, %s)", context.getDisplayName(), throwable );
try {
final Object testInstance = context.getRequiredTestInstance();
final ExtensionContext.Store store = locateExtensionStore( testInstance, context );
final ExtensionContext.Store store = locateExtensionStore( context.getRequiredTestInstance(), context );
final EntityManagerFactoryScopeImpl scope = (EntityManagerFactoryScopeImpl) store.get( EMF_KEY );
scope.releaseEntityManagerFactory();
}
catch (Exception ignore) {
}
throw throwable;
}
@ -323,12 +270,8 @@ public class EntityManagerFactoryExtension
}
protected jakarta.persistence.EntityManagerFactory createEntityManagerFactory() {
final EntityManagerFactoryBuilder emfBuilder = Bootstrap.getEntityManagerFactoryBuilder(
new PersistenceUnitInfoDescriptor( persistenceUnitInfo ),
integrationSettings
);
return emfBuilder.build();
final PersistenceUnitInfoDescriptor descriptor = new PersistenceUnitInfoDescriptor( persistenceUnitInfo );
return getEntityManagerFactoryBuilder( descriptor, integrationSettings ).build();
}
}
}

View File

@ -43,7 +43,7 @@ public class DelegatingPersistenceUnitInfo implements PersistenceUnitInfo {
return delegate.getQualifierAnnotationNames();
}
@Override
@Override @SuppressWarnings("removal")
public PersistenceUnitTransactionType getTransactionType() {
return delegate.getTransactionType();
}

View File

@ -50,7 +50,7 @@ public class PersistenceUnitInfoAdapter implements PersistenceUnitInfo {
return List.of();
}
@Override
@Override @SuppressWarnings("removal")
public PersistenceUnitTransactionType getTransactionType() {
return PersistenceUnitTransactionType.RESOURCE_LOCAL;
}

View File

@ -43,15 +43,18 @@ import javax.sql.DataSource;
import org.hibernate.jpa.HibernatePersistenceProvider;
import static java.lang.Thread.currentThread;
/**
* TODO : javadoc
*
* @author Steve Ebersole
*/
public class PersistenceUnitInfoPropertiesWrapper implements PersistenceUnitInfo {
private Properties properties;
private final Properties properties;
public PersistenceUnitInfoPropertiesWrapper() {
properties = new Properties();
}
public PersistenceUnitInfoPropertiesWrapper(Properties properties) {
@ -76,6 +79,7 @@ public class PersistenceUnitInfoPropertiesWrapper implements PersistenceUnitInfo
return List.of();
}
@SuppressWarnings("removal")
public PersistenceUnitTransactionType getTransactionType() {
return null;
}
@ -117,9 +121,6 @@ public class PersistenceUnitInfoPropertiesWrapper implements PersistenceUnitInfo
}
public Properties getProperties() {
if ( properties == null ) {
properties = new Properties();
}
return properties;
}
@ -128,7 +129,7 @@ public class PersistenceUnitInfoPropertiesWrapper implements PersistenceUnitInfo
}
public ClassLoader getClassLoader() {
return Thread.currentThread().getContextClassLoader();
return currentThread().getContextClassLoader();
}
public void addTransformer(ClassTransformer transformer) {