diff --git a/hibernate-community-dialects/src/main/java/org/hibernate/community/dialect/PostgreSQLLegacyDialect.java b/hibernate-community-dialects/src/main/java/org/hibernate/community/dialect/PostgreSQLLegacyDialect.java index 219079710b..fa348e59c5 100644 --- a/hibernate-community-dialects/src/main/java/org/hibernate/community/dialect/PostgreSQLLegacyDialect.java +++ b/hibernate-community-dialects/src/main/java/org/hibernate/community/dialect/PostgreSQLLegacyDialect.java @@ -1349,7 +1349,7 @@ public class PostgreSQLLegacyDialect extends Dialect { tableTypesList.add( "MATERIALIZED VIEW" ); /* - PostgreSQL 10 and later adds support for Partition table. + PostgreSQL 10 and later adds support for Partition table. */ if ( getVersion().isSameOrAfter( 10 ) ) { tableTypesList.add( "PARTITIONED TABLE" ); diff --git a/hibernate-community-dialects/src/main/java/org/hibernate/community/dialect/TeradataDialect.java b/hibernate-community-dialects/src/main/java/org/hibernate/community/dialect/TeradataDialect.java index 5d9d2a7cb3..651788ec7f 100644 --- a/hibernate-community-dialects/src/main/java/org/hibernate/community/dialect/TeradataDialect.java +++ b/hibernate-community-dialects/src/main/java/org/hibernate/community/dialect/TeradataDialect.java @@ -201,7 +201,7 @@ public class TeradataDialect extends Dialect { @Override public long getFractionalSecondPrecisionInNanos() { - // Do duration arithmetic in a seconds, but + // Do duration arithmetic in a seconds, but // with the fractional part return 1_000_000_000; //seconds!! } diff --git a/hibernate-community-dialects/src/test/java/org/hibernate/community/dialect/AltibaseDialectTestCase.java b/hibernate-community-dialects/src/test/java/org/hibernate/community/dialect/AltibaseDialectTestCase.java index 369b0f488e..b07f752d7a 100644 --- a/hibernate-community-dialects/src/test/java/org/hibernate/community/dialect/AltibaseDialectTestCase.java +++ b/hibernate-community-dialects/src/test/java/org/hibernate/community/dialect/AltibaseDialectTestCase.java @@ -46,22 +46,22 @@ public class AltibaseDialectTestCase extends BaseUnitTestCase { @Test public void testSelectWithLimitOnly() { assertEquals( "select c1, c2 from t1 order by c1, c2 desc limit ?", - dialect.getLimitHandler().processSql("select c1, c2 from t1 order by c1, c2 desc", - toRowSelection( 0, 15 ) ).toLowerCase( Locale.ROOT)); + dialect.getLimitHandler().processSql("select c1, c2 from t1 order by c1, c2 desc", + toRowSelection( 0, 15 ) ).toLowerCase( Locale.ROOT)); } @Test public void testSelectWithOffsetLimit() { assertEquals( "select c1, c2 from t1 order by c1, c2 desc limit 1+?,?", - dialect.getLimitHandler().processSql("select c1, c2 from t1 order by c1, c2 desc", - toRowSelection( 5, 15 ) ).toLowerCase(Locale.ROOT)); + dialect.getLimitHandler().processSql("select c1, c2 from t1 order by c1, c2 desc", + toRowSelection( 5, 15 ) ).toLowerCase(Locale.ROOT)); } @Test public void testSelectWithNoLimit() { assertEquals( "select c1, c2 from t1 order by c1, c2 desc", - dialect.getLimitHandler().processSql("select c1, c2 from t1 order by c1, c2 desc", - null ).toLowerCase(Locale.ROOT)); + dialect.getLimitHandler().processSql("select c1, c2 from t1 order by c1, c2 desc", + null ).toLowerCase(Locale.ROOT)); } private Limit toRowSelection(int firstRow, int maxRows) { diff --git a/hibernate-community-dialects/src/test/java/org/hibernate/community/dialect/SQLServer2008DialectTestCase.java b/hibernate-community-dialects/src/test/java/org/hibernate/community/dialect/SQLServer2008DialectTestCase.java index 4386930c1a..a402912123 100644 --- a/hibernate-community-dialects/src/test/java/org/hibernate/community/dialect/SQLServer2008DialectTestCase.java +++ b/hibernate-community-dialects/src/test/java/org/hibernate/community/dialect/SQLServer2008DialectTestCase.java @@ -135,9 +135,9 @@ public class SQLServer2008DialectTestCase extends BaseUnitTestCase { public void testPagingWithColumnNameStartingWithFrom() { final String sql = "select column1 c1, from_column c2 from table1"; assertEquals( "with query_ as (select row_.*,row_number() over (order by current_timestamp) as rownumber_ from (" + - "select column1 c1, from_column c2 from table1) row_) " + - "select c1,c2 from query_ where rownumber_>=? and rownumber_=? and rownumber_=? and rownumber_=? and rownumber_=? and rownumber_=? and rownumber_=? and rownumber_=? and rownumber_= 16*4); - diff = (Double) s2.createQuery( + assertTrue(diff.doubleValue() >= 16*4); + diff = (Double) s2.createQuery( "select timestampdiff(SQL_TSI_YEAR, o.date3, o.date1) from TestInterSystemsFunctionsClass as o" ).list() .get(0); - assertTrue(diff.doubleValue() == 1.0); + assertTrue(diff.doubleValue() == 1.0); - s2.getTransaction().commit(); - s2.close(); - } + s2.getTransaction().commit(); + s2.close(); + } } diff --git a/hibernate-community-dialects/src/test/java/org/hibernate/community/dialect/functional/cache/TestInterSystemsFunctionsClass.java b/hibernate-community-dialects/src/test/java/org/hibernate/community/dialect/functional/cache/TestInterSystemsFunctionsClass.java index 35531ca200..10445aaa7e 100644 --- a/hibernate-community-dialects/src/test/java/org/hibernate/community/dialect/functional/cache/TestInterSystemsFunctionsClass.java +++ b/hibernate-community-dialects/src/test/java/org/hibernate/community/dialect/functional/cache/TestInterSystemsFunctionsClass.java @@ -14,10 +14,10 @@ import java.util.Date; */ public class TestInterSystemsFunctionsClass { private Long id; - private Date date3; - private Date date1; - private Date date; - private String dateText; + private Date date3; + private Date date1; + private Date date; + private String dateText; public TestInterSystemsFunctionsClass() { } @@ -35,38 +35,38 @@ public class TestInterSystemsFunctionsClass { } public Date getDate() { - return date; - } + return date; + } - public void setDate(Date date) { - this.date = date; - } + public void setDate(Date date) { + this.date = date; + } - public String getDateText() { - return dateText; - } + public String getDateText() { + return dateText; + } - public void setDateText(String dateText) { - this.dateText = dateText; - } + public void setDateText(String dateText) { + this.dateText = dateText; + } - public Date getDate1() { - return date1; - } + public Date getDate1() { + return date1; + } - public void setDate1(Date date1) { - this.date1 = date1; - } + public void setDate1(Date date1) { + this.date1 = date1; + } - public Date getDate3() { - return date3; - } + public Date getDate3() { + return date3; + } - public void setDate3(Date date3) { - this.date3 = date3; - } + public void setDate3(Date date3) { + this.date3 = date3; + } } diff --git a/hibernate-core/src/main/java/org/hibernate/Hibernate.java b/hibernate-core/src/main/java/org/hibernate/Hibernate.java index 45b21f2b84..e3c6a1e403 100644 --- a/hibernate-core/src/main/java/org/hibernate/Hibernate.java +++ b/hibernate-core/src/main/java/org/hibernate/Hibernate.java @@ -365,8 +365,8 @@ public final class Hibernate { } } - /** - * If the given object is not a proxy, return it. But, if it is a proxy, ensure + /** + * If the given object is not a proxy, return it. But, if it is a proxy, ensure * that the proxy is initialized, and return a direct reference to its proxied * entity object. * @@ -375,7 +375,7 @@ public final class Hibernate { * * @throws LazyInitializationException if this operation is called on an * uninitialized proxy that is not associated with an open session. - */ + */ public static Object unproxy(Object proxy) { final LazyInitializer lazyInitializer = extractLazyInitializer( proxy ); return lazyInitializer != null ? lazyInitializer.getImplementation() : proxy; diff --git a/hibernate-core/src/main/java/org/hibernate/annotations/MapKeyJdbcType.java b/hibernate-core/src/main/java/org/hibernate/annotations/MapKeyJdbcType.java index 89d24e1dd5..4763ce0ada 100644 --- a/hibernate-core/src/main/java/org/hibernate/annotations/MapKeyJdbcType.java +++ b/hibernate-core/src/main/java/org/hibernate/annotations/MapKeyJdbcType.java @@ -24,7 +24,7 @@ import static java.lang.annotation.RetentionPolicy.RUNTIME; @Inherited @Retention(RUNTIME) public @interface MapKeyJdbcType { - /** + /** * The descriptor to use for the map-key column * * @see org.hibernate.annotations.JdbcType#value diff --git a/hibernate-core/src/main/java/org/hibernate/annotations/MapKeyJdbcTypeCode.java b/hibernate-core/src/main/java/org/hibernate/annotations/MapKeyJdbcTypeCode.java index a60c55ec92..4b0dd294d5 100644 --- a/hibernate-core/src/main/java/org/hibernate/annotations/MapKeyJdbcTypeCode.java +++ b/hibernate-core/src/main/java/org/hibernate/annotations/MapKeyJdbcTypeCode.java @@ -24,7 +24,7 @@ import static java.lang.annotation.RetentionPolicy.RUNTIME; @Inherited @Retention(RUNTIME) public @interface MapKeyJdbcTypeCode { - /** + /** * The code for the descriptor to use for the map-key column * * @see JdbcTypeCode#value diff --git a/hibernate-core/src/main/java/org/hibernate/annotations/SourceType.java b/hibernate-core/src/main/java/org/hibernate/annotations/SourceType.java index 80f2b6a7b5..203405f382 100644 --- a/hibernate-core/src/main/java/org/hibernate/annotations/SourceType.java +++ b/hibernate-core/src/main/java/org/hibernate/annotations/SourceType.java @@ -29,7 +29,7 @@ public enum SourceType { /** * Indicates that values are generated by the database. *

- * For a generated timestamp, the {@code current_timestamp} function + * For a generated timestamp, the {@code current_timestamp} function * might be the source. */ DB diff --git a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/EntityBinder.java b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/EntityBinder.java index 293f294be3..46eebb1723 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/EntityBinder.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/EntityBinder.java @@ -1855,8 +1855,8 @@ public class EntityBinder { } public void finalSecondaryTableBinding(PropertyHolder propertyHolder) { - // This operation has to be done after the id definition of the persistence class. - // ie after the properties parsing + // This operation has to be done after the id definition of the persistence class. + // ie after the properties parsing final Iterator joinColumns = secondaryTableJoins.values().iterator(); for ( Map.Entry entrySet : secondaryTables.entrySet() ) { if ( !secondaryTablesFromAnnotation.containsKey( entrySet.getKey() ) ) { @@ -1866,8 +1866,8 @@ public class EntityBinder { } public void finalSecondaryTableFromAnnotationBinding(PropertyHolder propertyHolder) { - // This operation has to be done before the end of the FK second pass processing in order - // to find the join columns belonging to secondary tables + // This operation has to be done before the end of the FK second pass processing in order + // to find the join columns belonging to secondary tables Iterator joinColumns = secondaryTableFromAnnotationJoins.values().iterator(); for ( Map.Entry entrySet : secondaryTables.entrySet() ) { if ( secondaryTablesFromAnnotation.containsKey( entrySet.getKey() ) ) { diff --git a/hibernate-core/src/main/java/org/hibernate/boot/model/naming/ImplicitCollectionTableNameSource.java b/hibernate-core/src/main/java/org/hibernate/boot/model/naming/ImplicitCollectionTableNameSource.java index 2ca375712c..0c9433ec85 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/model/naming/ImplicitCollectionTableNameSource.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/model/naming/ImplicitCollectionTableNameSource.java @@ -17,10 +17,10 @@ import org.hibernate.boot.model.source.spi.AttributePath; */ public interface ImplicitCollectionTableNameSource extends ImplicitNameSource { /** - * Access to the physical name of the owning entity's table. - * - * @return Owning entity's table name. - */ + * Access to the physical name of the owning entity's table. + * + * @return Owning entity's table name. + */ Identifier getOwningPhysicalTableName(); /** diff --git a/hibernate-core/src/main/java/org/hibernate/bytecode/enhance/spi/interceptor/LazyFetchGroupMetadata.java b/hibernate-core/src/main/java/org/hibernate/bytecode/enhance/spi/interceptor/LazyFetchGroupMetadata.java index f0a468d1f9..882e18c522 100644 --- a/hibernate-core/src/main/java/org/hibernate/bytecode/enhance/spi/interceptor/LazyFetchGroupMetadata.java +++ b/hibernate-core/src/main/java/org/hibernate/bytecode/enhance/spi/interceptor/LazyFetchGroupMetadata.java @@ -7,7 +7,7 @@ package org.hibernate.bytecode.enhance.spi.interceptor; /** - * Information about a particular bytecode lazy attribute grouping. + * Information about a particular bytecode lazy attribute grouping. * * @author Steve Ebersole */ diff --git a/hibernate-core/src/main/java/org/hibernate/cache/spi/RegionFactory.java b/hibernate-core/src/main/java/org/hibernate/cache/spi/RegionFactory.java index b651ddc55b..166e36c988 100644 --- a/hibernate-core/src/main/java/org/hibernate/cache/spi/RegionFactory.java +++ b/hibernate-core/src/main/java/org/hibernate/cache/spi/RegionFactory.java @@ -118,9 +118,9 @@ public interface RegionFactory extends Service, Stoppable { */ QueryResultsRegion buildQueryResultsRegion(String regionName, SessionFactoryImplementor sessionFactory); - /** - * Create a named {@link Region} for holding timestamps used to - * determine when a cached query result set is stale. - */ + /** + * Create a named {@link Region} for holding timestamps used to + * determine when a cached query result set is stale. + */ TimestampsRegion buildTimestampsRegion(String regionName, SessionFactoryImplementor sessionFactory); } diff --git a/hibernate-core/src/main/java/org/hibernate/cfg/Environment.java b/hibernate-core/src/main/java/org/hibernate/cfg/Environment.java index 56911b54d2..99ab41face 100644 --- a/hibernate-core/src/main/java/org/hibernate/cfg/Environment.java +++ b/hibernate-core/src/main/java/org/hibernate/cfg/Environment.java @@ -166,8 +166,8 @@ public final class Environment implements AvailableSettings { try { Properties systemProperties = System.getProperties(); - // Must be thread-safe in case an application changes System properties during Hibernate initialization. - // See HHH-8383. + // Must be thread-safe in case an application changes System properties during Hibernate initialization. + // See HHH-8383. synchronized (systemProperties) { GLOBAL_PROPERTIES.putAll(systemProperties); } diff --git a/hibernate-core/src/main/java/org/hibernate/collection/spi/AbstractPersistentCollection.java b/hibernate-core/src/main/java/org/hibernate/collection/spi/AbstractPersistentCollection.java index a4dd8614dc..f3c7c69e84 100644 --- a/hibernate-core/src/main/java/org/hibernate/collection/spi/AbstractPersistentCollection.java +++ b/hibernate-core/src/main/java/org/hibernate/collection/spi/AbstractPersistentCollection.java @@ -285,10 +285,8 @@ public abstract class AbstractPersistentCollection implements Serializable, P } } else { - /* - Whenever the collection lazy loading is triggered during the loading process, - closing the connection will cause an error when RowProcessingStateStandardImpl#next() will be called. - */ + // Whenever the collection lazy loading is triggered during the loading process, + // closing the connection will cause an error when RowProcessingStateStandardImpl#next() will be called. final PersistenceContext persistenceContext = session.getPersistenceContext(); if ( !session.isTransactionInProgress() && ( !persistenceContext.hasLoadContext() diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/Dialect.java b/hibernate-core/src/main/java/org/hibernate/dialect/Dialect.java index d3f4045102..3a18caaa81 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/Dialect.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/Dialect.java @@ -1646,7 +1646,6 @@ public abstract class Dialect implements ConversionContext, TypeContributor, Fun *

* An implementation may set configuration properties from * {@link #initDefaultProperties()}, though it is discouraged. - the * @return the Hibernate configuration properties * * @see #initDefaultProperties() diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/DialectDelegateWrapper.java b/hibernate-core/src/main/java/org/hibernate/dialect/DialectDelegateWrapper.java index 42c21aedcb..4f3f23ed38 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/DialectDelegateWrapper.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/DialectDelegateWrapper.java @@ -124,7 +124,7 @@ public class DialectDelegateWrapper extends Dialect { } } - /** + /** * Exposed so to allow code needing to know the implementation. * @return the wrapped Dialect */ diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/H2Dialect.java b/hibernate-core/src/main/java/org/hibernate/dialect/H2Dialect.java index 92011616a5..17aa32401c 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/H2Dialect.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/H2Dialect.java @@ -343,11 +343,11 @@ public class H2Dialect extends Dialect { } /** - * H2 requires a very special emulation, because {@code unnest} is pretty much useless, - * due to issue 1815. - * This emulation uses {@code array_get}, {@code array_length} and {@code system_range} functions to roughly achieve the same, - * but requires that {@code system_range} is fed with a "maximum array size". - */ + * H2 requires a very special emulation, because {@code unnest} is pretty much useless, + * due to issue 1815. + * This emulation uses {@code array_get}, {@code array_length} and {@code system_range} functions to roughly achieve the same, + * but requires that {@code system_range} is fed with a "maximum array size". + */ protected int getMaximumArraySize() { return 1000; } diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/lock/SelectLockingStrategy.java b/hibernate-core/src/main/java/org/hibernate/dialect/lock/SelectLockingStrategy.java index 90a240b32c..efa3075587 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/lock/SelectLockingStrategy.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/lock/SelectLockingStrategy.java @@ -12,9 +12,9 @@ import org.hibernate.LockMode; import org.hibernate.LockOptions; import org.hibernate.persister.entity.EntityPersister; - /** +/** * A locking strategy where an optimistic lock is obtained via a select - * statement. + * statement. *

* Differs from {@link PessimisticWriteSelectLockingStrategy} and * {@link PessimisticReadSelectLockingStrategy} in throwing diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/pagination/AbstractLimitHandler.java b/hibernate-core/src/main/java/org/hibernate/dialect/pagination/AbstractLimitHandler.java index 164f0b2dfd..6108638240 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/pagination/AbstractLimitHandler.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/pagination/AbstractLimitHandler.java @@ -120,7 +120,7 @@ public abstract class AbstractLimitHandler implements LimitHandler { * Does this dialect require a one-based offset to be specified in the offset clause? * * @implNote The value passed into {@link AbstractLimitHandler#processSql(String, Limit)} - * has a zero-based offset. Handlers which do not {@link #supportsVariableLimit} + * has a zero-based offset. Handlers which do not {@link #supportsVariableLimit} * should take care to perform any needed first-row-conversion calls prior to * injecting the limit values into the SQL string. * diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/pagination/SQLServer2012LimitHandler.java b/hibernate-core/src/main/java/org/hibernate/dialect/pagination/SQLServer2012LimitHandler.java index 985208a1ce..7775e47645 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/pagination/SQLServer2012LimitHandler.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/pagination/SQLServer2012LimitHandler.java @@ -24,7 +24,7 @@ public class SQLServer2012LimitHandler extends OffsetFetchLimitHandler { // ORDER BY ... // [ // OFFSET m {ROW|ROWS} - // [FETCH {FIRST|NEXT} n {ROW|ROWS} ONLY] + // [FETCH {FIRST|NEXT} n {ROW|ROWS} ONLY] // ] public static final SQLServer2012LimitHandler INSTANCE = new SQLServer2012LimitHandler(); diff --git a/hibernate-core/src/main/java/org/hibernate/engine/internal/Collections.java b/hibernate-core/src/main/java/org/hibernate/engine/internal/Collections.java index dea48d26c7..b5cecbf10a 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/internal/Collections.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/internal/Collections.java @@ -134,14 +134,14 @@ public final class Collections { } - /** - * Initialize the role of the collection. - * - * @param collection The collection to be updated by reachability. - * @param type The type of the collection. - * @param entity The owner of the collection. + /** + * Initialize the role of the collection. + * + * @param collection The collection to be updated by reachability. + * @param type The type of the collection. + * @param entity The owner of the collection. * @param session The session from which this request originates - */ + */ public static void processReachableCollection( PersistentCollection collection, CollectionType type, diff --git a/hibernate-core/src/main/java/org/hibernate/engine/internal/ManagedTypeHelper.java b/hibernate-core/src/main/java/org/hibernate/engine/internal/ManagedTypeHelper.java index 5c849ad63d..c3909eac28 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/internal/ManagedTypeHelper.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/internal/ManagedTypeHelper.java @@ -226,8 +226,8 @@ public final class ManagedTypeHelper { } } - // Not using Consumer because of JDK-8180450: - // use a custom functional interface with explicit type. + // Not using Consumer because of JDK-8180450: + // use a custom functional interface with explicit type. @FunctionalInterface public interface SelfDirtinessTrackerConsumer { void accept(SelfDirtinessTracker tracker); diff --git a/hibernate-core/src/main/java/org/hibernate/engine/internal/Nullability.java b/hibernate-core/src/main/java/org/hibernate/engine/internal/Nullability.java index dd6c06cc08..71b2ffe5db 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/internal/Nullability.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/internal/Nullability.java @@ -74,22 +74,22 @@ public final class Nullability { */ if ( checkNullability ) { /* - * Algorithm - * Check for any level one nullability breaks - * Look at non-null components to - * recursively check next level of nullability breaks - * Look at Collections containing components to - * recursively check next level of nullability breaks - * - * - * In the previous implementation, not-null stuffs where checked - * filtering by level one only updatable - * or insertable columns. So setting a subcomponent as update="false" - * has no effect on not-null check if the main component had good checkability - * In this implementation, we keep this feature. - * However, I never see any documentation mentioning that, but it's for - * sure a limitation. - */ + * Algorithm + * Check for any level one nullability breaks + * Look at non-null components to + * recursively check next level of nullability breaks + * Look at Collections containing components to + * recursively check next level of nullability breaks + * + * + * In the previous implementation, not-null stuffs where checked + * filtering by level one only updatable + * or insertable columns. So setting a subcomponent as update="false" + * has no effect on not-null check if the main component had good checkability + * In this implementation, we keep this feature. + * However, I never see any documentation mentioning that, but it's for + * sure a limitation. + */ final boolean[] nullability = persister.getPropertyNullability(); final boolean[] checkability = checkType == NullabilityCheckType.CREATE diff --git a/hibernate-core/src/main/java/org/hibernate/engine/internal/StatefulPersistenceContext.java b/hibernate-core/src/main/java/org/hibernate/engine/internal/StatefulPersistenceContext.java index b696303ae1..c9aa875350 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/internal/StatefulPersistenceContext.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/internal/StatefulPersistenceContext.java @@ -777,7 +777,7 @@ public class StatefulPersistenceContext implements PersistenceContext { session.getFactory().getMappingMetamodel() .getEntityDescriptor( li.getEntityName() ); final EntityKey key = session.generateEntityKey( li.getInternalIdentifier(), persister ); - // any earlier proxy takes precedence + // any earlier proxy takes precedence final Map entityHolderMap = getOrInitializeEntitiesByKey(); final EntityHolderImpl oldHolder = entityHolderMap.get( key ); if ( oldHolder != null ) { @@ -1463,7 +1463,7 @@ public class StatefulPersistenceContext implements PersistenceContext { final EntityPersister persister = mappingMetamodel.getEntityDescriptor( entityName ); final CollectionPersister collectionPersister = mappingMetamodel.getCollectionDescriptor( collectionRole ); - // try cache lookup first + // try cache lookup first final Object parent = getParentsByChild( childEntity ); if ( parent != null ) { final EntityEntry entityEntry = entityEntryContext.getEntityEntry( parent ); diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/BlobProxy.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/BlobProxy.java index fa70329ce4..50b68e7235 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/BlobProxy.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/BlobProxy.java @@ -33,8 +33,8 @@ import org.hibernate.type.descriptor.java.DataHelper; */ @Internal public final class BlobProxy implements Blob, BlobImplementer { - // In previous versions this used to be implemented by using a java.lang.reflect.Proxy to deal with - // incompatibilities across various JDBC versions, hence the class name, but using a real Proxy is + // In previous versions this used to be implemented by using a java.lang.reflect.Proxy to deal with + // incompatibilities across various JDBC versions, hence the class name, but using a real Proxy is // no longer necessary. The class name could be updated to reflect this but that would break APIs. private final BinaryStream binaryStream; diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/spi/JdbcCoordinator.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/spi/JdbcCoordinator.java index ae46eb873d..8c7d50dc35 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/spi/JdbcCoordinator.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/spi/JdbcCoordinator.java @@ -136,7 +136,7 @@ public interface JdbcCoordinator extends Serializable, TransactionCoordinatorOwn */ void cancelLastQuery(); - /** + /** * Calculate the amount of time, in seconds, still remaining before transaction timeout occurs. * * @return The number of seconds remaining until a transaction timeout occurs. A negative value indicates diff --git a/hibernate-core/src/main/java/org/hibernate/engine/spi/SharedSessionContractImplementor.java b/hibernate-core/src/main/java/org/hibernate/engine/spi/SharedSessionContractImplementor.java index 09c8c7d6de..17b835bc02 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/spi/SharedSessionContractImplementor.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/spi/SharedSessionContractImplementor.java @@ -242,7 +242,7 @@ public interface SharedSessionContractImplementor * This method is primarily for internal or integrator use. * * @return the {@link Transaction} - */ + */ Transaction accessTransaction(); /** diff --git a/hibernate-core/src/main/java/org/hibernate/event/spi/AbstractEvent.java b/hibernate-core/src/main/java/org/hibernate/event/spi/AbstractEvent.java index a070b10711..b35a1c4df5 100644 --- a/hibernate-core/src/main/java/org/hibernate/event/spi/AbstractEvent.java +++ b/hibernate-core/src/main/java/org/hibernate/event/spi/AbstractEvent.java @@ -19,21 +19,21 @@ public abstract class AbstractEvent implements Serializable { private final EventSource session; - /** - * Constructs an event from the given event session. - * - * @param source The session event source. - */ + /** + * Constructs an event from the given event session. + * + * @param source The session event source. + */ public AbstractEvent(EventSource source) { this.session = source; } - /** - * Returns the session event source for this event. This is the underlying - * session from which this event was generated. - * - * @return The session event source. - */ + /** + * Returns the session event source for this event. This is the underlying + * session from which this event was generated. + * + * @return The session event source. + */ public final EventSource getSession() { return session; } diff --git a/hibernate-core/src/main/java/org/hibernate/event/spi/DeleteEvent.java b/hibernate-core/src/main/java/org/hibernate/event/spi/DeleteEvent.java index 46e6ec1983..4e3fcdc4ab 100644 --- a/hibernate-core/src/main/java/org/hibernate/event/spi/DeleteEvent.java +++ b/hibernate-core/src/main/java/org/hibernate/event/spi/DeleteEvent.java @@ -55,10 +55,10 @@ public class DeleteEvent extends AbstractEvent { } /** - * Returns the encapsulated entity to be deleted. - * - * @return The entity to be deleted. - */ + * Returns the encapsulated entity to be deleted. + * + * @return The entity to be deleted. + */ public Object getObject() { return object; } diff --git a/hibernate-core/src/main/java/org/hibernate/event/spi/DeleteEventListener.java b/hibernate-core/src/main/java/org/hibernate/event/spi/DeleteEventListener.java index 955ac6c458..da35606f61 100644 --- a/hibernate-core/src/main/java/org/hibernate/event/spi/DeleteEventListener.java +++ b/hibernate-core/src/main/java/org/hibernate/event/spi/DeleteEventListener.java @@ -16,11 +16,11 @@ import org.hibernate.HibernateException; */ public interface DeleteEventListener { - /** + /** * Handle the given delete event. - * - * @param event The delete event to be handled. - */ + * + * @param event The delete event to be handled. + */ void onDelete(DeleteEvent event) throws HibernateException; void onDelete(DeleteEvent event, DeleteContext transientEntities) throws HibernateException; diff --git a/hibernate-core/src/main/java/org/hibernate/event/spi/FlushEventListener.java b/hibernate-core/src/main/java/org/hibernate/event/spi/FlushEventListener.java index fb77ed011d..f85fa5b14f 100644 --- a/hibernate-core/src/main/java/org/hibernate/event/spi/FlushEventListener.java +++ b/hibernate-core/src/main/java/org/hibernate/event/spi/FlushEventListener.java @@ -14,10 +14,10 @@ import org.hibernate.HibernateException; * @author Steve Ebersole */ public interface FlushEventListener { - /** + /** * Handle the given flush event. - * - * @param event The flush event to be handled. - */ + * + * @param event The flush event to be handled. + */ void onFlush(FlushEvent event) throws HibernateException; } diff --git a/hibernate-core/src/main/java/org/hibernate/event/spi/MergeContext.java b/hibernate-core/src/main/java/org/hibernate/event/spi/MergeContext.java index c9a83e3e45..bcb2e23f2e 100644 --- a/hibernate-core/src/main/java/org/hibernate/event/spi/MergeContext.java +++ b/hibernate-core/src/main/java/org/hibernate/event/spi/MergeContext.java @@ -90,8 +90,8 @@ public class MergeContext implements Map { // TODO: merge mergeEntityToOperatedOnFlagMap into mergeToManagedEntityXref, since they have the same key. // need to check if this would hurt performance. private final Map mergeEntityToOperatedOnFlagMap = new IdentityHashMap<>( 10 ); - // key is a merge entity; - // value is a flag indicating if the merge entity is currently in the merge process. + // key is a merge entity; + // value is a flag indicating if the merge entity is currently in the merge process. public MergeContext(EventSource session, EntityCopyObserver entityCopyObserver){ this.session = session; diff --git a/hibernate-core/src/main/java/org/hibernate/event/spi/PreUpdateEvent.java b/hibernate-core/src/main/java/org/hibernate/event/spi/PreUpdateEvent.java index 940fd90bdc..5c64cfd1e4 100644 --- a/hibernate-core/src/main/java/org/hibernate/event/spi/PreUpdateEvent.java +++ b/hibernate-core/src/main/java/org/hibernate/event/spi/PreUpdateEvent.java @@ -25,7 +25,7 @@ public class PreUpdateEvent extends AbstractPreDatabaseOperationEvent { * @param id The id of the entity to use for updating. * @param state The state to be updated. * @param oldState The state of the entity at the time it was loaded from - * the database. + * the database. * @param persister The entity's persister. * @param source The session from which the event originated. */ diff --git a/hibernate-core/src/main/java/org/hibernate/event/spi/RefreshEventListener.java b/hibernate-core/src/main/java/org/hibernate/event/spi/RefreshEventListener.java index 474b0efc0b..80987bbdc7 100644 --- a/hibernate-core/src/main/java/org/hibernate/event/spi/RefreshEventListener.java +++ b/hibernate-core/src/main/java/org/hibernate/event/spi/RefreshEventListener.java @@ -16,11 +16,11 @@ import org.hibernate.HibernateException; */ public interface RefreshEventListener { - /** - * Handle the given refresh event. - * - * @param event The refresh event to be handled. - */ + /** + * Handle the given refresh event. + * + * @param event The refresh event to be handled. + */ void onRefresh(RefreshEvent event) throws HibernateException; void onRefresh(RefreshEvent event, RefreshContext refreshedAlready) throws HibernateException; diff --git a/hibernate-core/src/main/java/org/hibernate/internal/util/BytesHelper.java b/hibernate-core/src/main/java/org/hibernate/internal/util/BytesHelper.java index 18eaa0268d..f21f91cff6 100644 --- a/hibernate-core/src/main/java/org/hibernate/internal/util/BytesHelper.java +++ b/hibernate-core/src/main/java/org/hibernate/internal/util/BytesHelper.java @@ -77,7 +77,7 @@ public final class BytesHelper { * * @param longValue The long to interpret to binary * @param dest the destination array. - * @param destPos starting position in the destination array. + * @param destPos starting position in the destination array. */ public static void fromLong(long longValue, byte[] dest, int destPos) { diff --git a/hibernate-core/src/main/java/org/hibernate/internal/util/collections/BoundedConcurrentHashMap.java b/hibernate-core/src/main/java/org/hibernate/internal/util/collections/BoundedConcurrentHashMap.java index 8ef5d48588..f5f5d32938 100644 --- a/hibernate-core/src/main/java/org/hibernate/internal/util/collections/BoundedConcurrentHashMap.java +++ b/hibernate-core/src/main/java/org/hibernate/internal/util/collections/BoundedConcurrentHashMap.java @@ -1065,41 +1065,41 @@ public class BoundedConcurrentHashMap extends AbstractMap */ static final class Segment extends ReentrantLock { /* - * Segments maintain a table of entry lists that are ALWAYS - * kept in a consistent state, so can be read without locking. - * Next fields of nodes are immutable (final). All list - * additions are performed at the front of each bin. This - * makes it easy to check changes, and also fast to traverse. - * When nodes would otherwise be changed, new nodes are - * created to replace them. This works well for hash tables - * since the bin lists tend to be short. (The average length - * is less than two for the default load factor threshold.) - * - * Read operations can thus proceed without locking, but rely - * on selected uses of volatiles to ensure that completed - * write operations performed by other threads are - * noticed. For most purposes, the "count" field, tracking the - * number of elements, serves as that volatile variable - * ensuring visibility. This is convenient because this field - * needs to be read in many read operations anyway: - * - * - All (unsynchronized) read operations must first read the - * "count" field, and should not look at table entries if - * it is 0. - * - * - All (synchronized) write operations should write to - * the "count" field after structurally changing any bin. - * The operations must not take any action that could even - * momentarily cause a concurrent read operation to see - * inconsistent data. This is made easier by the nature of - * the read operations in Map. For example, no operation - * can reveal that the table has grown but the threshold - * has not yet been updated, so there are no atomicity - * requirements for this with respect to reads. - * - * As a guide, all critical volatile reads and writes to the - * count field are marked in code comments. - */ + * Segments maintain a table of entry lists that are ALWAYS + * kept in a consistent state, so can be read without locking. + * Next fields of nodes are immutable (final). All list + * additions are performed at the front of each bin. This + * makes it easy to check changes, and also fast to traverse. + * When nodes would otherwise be changed, new nodes are + * created to replace them. This works well for hash tables + * since the bin lists tend to be short. (The average length + * is less than two for the default load factor threshold.) + * + * Read operations can thus proceed without locking, but rely + * on selected uses of volatiles to ensure that completed + * write operations performed by other threads are + * noticed. For most purposes, the "count" field, tracking the + * number of elements, serves as that volatile variable + * ensuring visibility. This is convenient because this field + * needs to be read in many read operations anyway: + * + * - All (unsynchronized) read operations must first read the + * "count" field, and should not look at table entries if + * it is 0. + * + * - All (synchronized) write operations should write to + * the "count" field after structurally changing any bin. + * The operations must not take any action that could even + * momentarily cause a concurrent read operation to see + * inconsistent data. This is made easier by the nature of + * the read operations in Map. For example, no operation + * can reveal that the table has grown but the threshold + * has not yet been updated, so there are no atomicity + * requirements for this with respect to reads. + * + * As a guide, all critical volatile reads and writes to the + * count field are marked in code comments. + */ private static final long serialVersionUID = 2249069246763182397L; @@ -1515,14 +1515,14 @@ public class BoundedConcurrentHashMap extends AbstractMap public boolean isEmpty() { final Segment[] segments = this.segments; /* - * We keep track of per-segment modCounts to avoid ABA - * problems in which an element in one segment was added and - * in another removed during traversal, in which case the - * table was never actually empty at any point. Note the - * similar use of modCounts in the size() and containsValue() - * methods, which are the only other methods also susceptible - * to ABA problems. - */ + * We keep track of per-segment modCounts to avoid ABA + * problems in which an element in one segment was added and + * in another removed during traversal, in which case the + * table was never actually empty at any point. Note the + * similar use of modCounts in the size() and containsValue() + * methods, which are the only other methods also susceptible + * to ABA problems. + */ int[] mc = new int[segments.length]; int mcsum = 0; for ( int i = 0; i < segments.length; ++i ) { diff --git a/hibernate-core/src/main/java/org/hibernate/internal/util/collections/ConcurrentReferenceHashMap.java b/hibernate-core/src/main/java/org/hibernate/internal/util/collections/ConcurrentReferenceHashMap.java index d66fdc30dd..ebc494131e 100644 --- a/hibernate-core/src/main/java/org/hibernate/internal/util/collections/ConcurrentReferenceHashMap.java +++ b/hibernate-core/src/main/java/org/hibernate/internal/util/collections/ConcurrentReferenceHashMap.java @@ -1639,9 +1639,9 @@ public class ConcurrentReferenceHashMap extends AbstractMap } } - /* - * This class is needed for JDK5 compatibility. - */ + /** + * This class is needed for JDK5 compatibility. + */ static class SimpleEntry implements Entry, Serializable { private static final long serialVersionUID = -8499721149061103585L; diff --git a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/DiscriminatorValueDetails.java b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/DiscriminatorValueDetails.java index 98c73697ce..daf89b7ebd 100644 --- a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/DiscriminatorValueDetails.java +++ b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/DiscriminatorValueDetails.java @@ -19,8 +19,8 @@ package org.hibernate.metamodel.mapping; */ public interface DiscriminatorValueDetails { /** - * The discriminator value - */ + * The discriminator value + */ Object getValue(); /** @@ -32,6 +32,6 @@ public interface DiscriminatorValueDetails { /** * Form of {@link #getIndicatedEntityName()} returning the matched {@link EntityMappingType} - */ + */ EntityMappingType getIndicatedEntity(); } diff --git a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/AbstractAttributeMapping.java b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/AbstractAttributeMapping.java index bd66d87721..c5dd4ca898 100644 --- a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/AbstractAttributeMapping.java +++ b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/AbstractAttributeMapping.java @@ -43,7 +43,7 @@ public abstract class AbstractAttributeMapping implements AttributeMapping { /** * For Hibernate Reactive - */ + */ protected AbstractAttributeMapping(AbstractAttributeMapping original) { this( original.name, diff --git a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/ToOneAttributeMapping.java b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/ToOneAttributeMapping.java index 1eb962d390..4b027cf558 100644 --- a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/ToOneAttributeMapping.java +++ b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/ToOneAttributeMapping.java @@ -140,19 +140,19 @@ public class ToOneAttributeMapping private final boolean isNullable; private final boolean isLazy; /* - The nullability of the table on which the FK column is located - Note that this can be null although the FK column is not nullable e.g. in the case of a join table + The nullability of the table on which the FK column is located + Note that this can be null although the FK column is not nullable e.g. in the case of a join table - @Entity - public class Entity1 { - @OneToOne - @JoinTable(name = "key_table") - Entity2 association; - } + @Entity + public class Entity1 { + @OneToOne + @JoinTable(name = "key_table") + Entity2 association; + } - Here the join to "key_table" is nullable, but the FK column is not null. - Choosing an inner join for the association would be wrong though, because of the nullability of the key table, - hence this flag is also controlling the default join type. + Here the join to "key_table" is nullable, but the FK column is not null. + Choosing an inner join for the association would be wrong though, because of the nullability of the key table, + hence this flag is also controlling the default join type. */ private final boolean isKeyTableNullable; private final boolean isInternalLoadNullable; @@ -168,8 +168,8 @@ public class ToOneAttributeMapping private final Cardinality cardinality; private final boolean hasJoinTable; /* - Capture the other side's name of a possibly bidirectional association to allow resolving circular fetches. - It may be null if the referenced property is a non-entity. + Capture the other side's name of a possibly bidirectional association to allow resolving circular fetches. + It may be null if the referenced property is a non-entity. */ private final SelectablePath bidirectionalAttributePath; private final TableGroupProducer declaringTableGroupProducer; @@ -379,9 +379,9 @@ public class ToOneAttributeMapping hasJoinTable = false; /* - The otherSidePropertyName value is used to determine bidirectionality based on the navigablePath string + The otherSidePropertyName value is used to determine bidirectionality based on the navigablePath string - e.g. + e.g. class Card{ @OneToMany( mappedBy = "card") @@ -420,7 +420,7 @@ public class ToOneAttributeMapping in such case the mappedBy is "primaryKey.card" the navigable path is NavigablePath(Card.fields.{element}.{id}.card) and it does not contain the "primaryKey" part, so in order to recognize the bidirectionality the "primaryKey." is removed from the otherSidePropertyName value. - */ + */ final OneToOne oneToOne = (OneToOne) bootValue; if ( oneToOne.getMappedByProperty() == null ) { this.bidirectionalAttributePath = SelectablePath.parse( referencedPropertyName ); @@ -1476,20 +1476,20 @@ public class ToOneAttributeMapping DerivedLevel2 level2Child; } - class Level2 { - @OneToOne(mappedBy = "level2Parent") + class Level2 { + @OneToOne(mappedBy = "level2Parent") Level3 level3Child; - } + } - class DerivedLevel2 extends Level2 { - @OneToOne + class DerivedLevel2 extends Level2 { + @OneToOne Level1 level1Parent; - } + } - class Level3 { - @OneToOne + class Level3 { + @OneToOne Level2 level2Parent; - } + } We have Level1->leve2Child->level3Child->level2Parent @@ -1532,15 +1532,15 @@ public class ToOneAttributeMapping && parentNavigablePath.equals( fetchParent.getNavigablePath().getRealParent() ); /* - In case of selected we are going to add a fetch for the `fetchablePath` only if there is not already a `TableGroupJoin`. + In case of selected we are going to add a fetch for the `fetchablePath` only if there is not already a `TableGroupJoin`. - e.g. given : - public static class EntityA { + e.g. given : + public static class EntityA { ... @ManyToOne(fetch = FetchType.EAGER) private EntityB entityB; - } + } @Entity(name = "EntityB") public static class EntityB { @@ -1549,11 +1549,11 @@ public class ToOneAttributeMapping private String name; } - and the HQL query : + and the HQL query : - `Select a From EntityA a Left Join a.entityB b Where ( b.name IS NOT NULL )` + `Select a From EntityA a Left Join a.entityB b Where ( b.name IS NOT NULL )` - having the left join we don't want to add an extra implicit join that will be translated into an SQL inner join (see HHH-15342) + having the left join we don't want to add an extra implicit join that will be translated into an SQL inner join (see HHH-15342) */ if ( fetchTiming == FetchTiming.IMMEDIATE && selected ) { final TableGroup tableGroup = determineTableGroupForFetch( diff --git a/hibernate-core/src/main/java/org/hibernate/persister/entity/EntityPersister.java b/hibernate-core/src/main/java/org/hibernate/persister/entity/EntityPersister.java index 8bd4b3023a..c076ff7cdb 100644 --- a/hibernate-core/src/main/java/org/hibernate/persister/entity/EntityPersister.java +++ b/hibernate-core/src/main/java/org/hibernate/persister/entity/EntityPersister.java @@ -154,7 +154,7 @@ public interface EntityPersister extends EntityMappingType, EntityMutationTarget } // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - // stuff that is persister-centric and/or EntityInfo-centric ~~~~~~~~~~~~~~ + // stuff that is persister-centric and/or EntityInfo-centric ~~~~~~~~~~~~~~ // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ /** @@ -1131,8 +1131,8 @@ public interface EntityPersister extends EntityMappingType, EntityMutationTarget */ Object getIdentifier(Object entity, SharedSessionContractImplementor session); - /** - * Inject the identifier value into the given entity. + /** + * Inject the identifier value into the given entity. */ void setIdentifier(Object entity, Object id, SharedSessionContractImplementor session); diff --git a/hibernate-core/src/main/java/org/hibernate/query/spi/QueryParameterBinding.java b/hibernate-core/src/main/java/org/hibernate/query/spi/QueryParameterBinding.java index 208362f7db..46b8d13cbf 100644 --- a/hibernate-core/src/main/java/org/hibernate/query/spi/QueryParameterBinding.java +++ b/hibernate-core/src/main/java/org/hibernate/query/spi/QueryParameterBinding.java @@ -16,7 +16,6 @@ import org.hibernate.query.QueryParameter; import org.hibernate.type.spi.TypeConfiguration; /** - /** * The value/type binding information for a particular query parameter. Supports * both single-valued and multivalued binds * diff --git a/hibernate-core/src/main/java/org/hibernate/query/sqm/sql/BaseSqmToSqlAstConverter.java b/hibernate-core/src/main/java/org/hibernate/query/sqm/sql/BaseSqmToSqlAstConverter.java index abf381bce9..acf60478b5 100644 --- a/hibernate-core/src/main/java/org/hibernate/query/sqm/sql/BaseSqmToSqlAstConverter.java +++ b/hibernate-core/src/main/java/org/hibernate/query/sqm/sql/BaseSqmToSqlAstConverter.java @@ -8941,10 +8941,10 @@ public abstract class BaseSqmToSqlAstConverter extends Base @Override public boolean isRegisteringVisitedAssociationKeys() { /* - We need to avoid loops in case of eager self-referencing associations + We need to avoid loops in case of eager self-referencing associations - E.g. - @NamedEntityGraphs({ + E.g. + @NamedEntityGraphs({ @NamedEntityGraph( name = "User.overview", attributeNodes = { @NamedAttributeNode("name") }) diff --git a/hibernate-core/src/main/java/org/hibernate/sql/results/graph/DomainResultCreationState.java b/hibernate-core/src/main/java/org/hibernate/sql/results/graph/DomainResultCreationState.java index a2234c65c3..a0c50e9024 100644 --- a/hibernate-core/src/main/java/org/hibernate/sql/results/graph/DomainResultCreationState.java +++ b/hibernate-core/src/main/java/org/hibernate/sql/results/graph/DomainResultCreationState.java @@ -152,7 +152,7 @@ public interface DomainResultCreationState { * We walk fetches via the SqlAstCreationContext because each "context" * will define differently what should be fetched (HQL versus load) */ - /* + /* * todo (6.0) : centralize the implementation of this * most of the logic in the impls of this is identical. variations include: * 1) given a Fetchable, determine the FetchTiming and `selected`[1]. Tricky as functional @@ -176,7 +176,7 @@ public interface DomainResultCreationState { * todo (6.0) : wrt the "trickiness" of `selected[1]`, that may no longer be an issue given how TableGroups * are built/accessed. Comes down to how we'd know whether to join fetch or select fetch. Simply pass * along FetchStyle? - */ + */ ImmutableFetchList visitFetches(FetchParent fetchParent); default ImmutableFetchList visitNestedFetches(FetchParent fetchParent) { diff --git a/hibernate-core/src/main/java/org/hibernate/sql/results/graph/entity/internal/BatchEntityInsideEmbeddableSelectFetchInitializer.java b/hibernate-core/src/main/java/org/hibernate/sql/results/graph/entity/internal/BatchEntityInsideEmbeddableSelectFetchInitializer.java index d199be6a4d..8b559588ec 100644 --- a/hibernate-core/src/main/java/org/hibernate/sql/results/graph/entity/internal/BatchEntityInsideEmbeddableSelectFetchInitializer.java +++ b/hibernate-core/src/main/java/org/hibernate/sql/results/graph/entity/internal/BatchEntityInsideEmbeddableSelectFetchInitializer.java @@ -189,11 +189,11 @@ public class BatchEntityInsideEmbeddableSelectFetchInitializer extends AbstractB final Object[] loadedState = parentEntityEntry.getLoadedState(); if ( loadedState != null ) { /* - E.g. + E.g. - ParentEntity -> RootEmbeddable -> ParentEmbeddable -> toOneAttributeMapping + ParentEntity -> RootEmbeddable -> ParentEmbeddable -> toOneAttributeMapping - The value of RootEmbeddable is needed to update the ParentEntity loaded state + The value of RootEmbeddable is needed to update the ParentEntity loaded state */ final int parentEntitySubclassId = parentInfo.parentEntitySubclassId; final Object rootEmbeddable = rootEmbeddableGetters[parentEntitySubclassId].get( parentEntityInstance ); diff --git a/hibernate-core/src/main/java/org/hibernate/stat/Statistics.java b/hibernate-core/src/main/java/org/hibernate/stat/Statistics.java index 99ea603bb1..c5cbda7763 100644 --- a/hibernate-core/src/main/java/org/hibernate/stat/Statistics.java +++ b/hibernate-core/src/main/java/org/hibernate/stat/Statistics.java @@ -51,7 +51,7 @@ public interface Statistics { void logSummary(); - /** + /** * Obtain the statistics for the entity with the given name. * * @param entityName the entity name @@ -125,39 +125,39 @@ public interface Statistics { */ @Nullable CacheRegionStatistics getCacheRegionStatistics(String regionName); - /** - * The global number of entity deletes. + /** + * The global number of entity deletes. */ long getEntityDeleteCount(); - /** - * The global number of entity inserts. + /** + * The global number of entity inserts. */ long getEntityInsertCount(); - /** - * The global number of entity loads. + /** + * The global number of entity loads. */ long getEntityLoadCount(); /** - * The global number of entity fetches. + * The global number of entity fetches. */ long getEntityFetchCount(); /** - * The global number of entity updates. + * The global number of entity updates. */ long getEntityUpdateCount(); - /** - * The global number of executed queries. + /** + * The global number of executed queries. */ long getQueryExecutionCount(); - /** - * The time in milliseconds of the slowest query. - */ + /** + * The time in milliseconds of the slowest query. + */ long getQueryExecutionMaxTime(); /** @@ -165,21 +165,21 @@ public interface Statistics { */ @Nullable String getQueryExecutionMaxTimeQueryString(); - /** - * The global number of cached queries successfully retrieved from + /** + * The global number of cached queries successfully retrieved from * the cache. - */ + */ long getQueryCacheHitCount(); - /** - * The global number of cached queries notnot found in the + /** + * The global number of cached queries notnot found in the * cache. - */ + */ long getQueryCacheMissCount(); - /** - * The global number of cacheable queries put in cache. - */ + /** + * The global number of cacheable queries put in cache. + */ long getQueryCachePutCount(); /** @@ -204,43 +204,43 @@ public interface Statistics { */ @Nullable String getNaturalIdQueryExecutionMaxTimeEntity(); - /** - * The global number of cached natural id lookups successfully + /** + * The global number of cached natural id lookups successfully * retrieved from the cache. - */ + */ long getNaturalIdCacheHitCount(); - /** - * The global number of cached natural id lookups not found + /** + * The global number of cached natural id lookups not found * in the cache. - */ + */ long getNaturalIdCacheMissCount(); - /** - * The global number of cacheable natural id lookups put in cache. - */ + /** + * The global number of cacheable natural id lookups put in cache. + */ long getNaturalIdCachePutCount(); - /** - * The global number of timestamps successfully retrieved from cache. - */ + /** + * The global number of timestamps successfully retrieved from cache. + */ long getUpdateTimestampsCacheHitCount(); - /** - * The global number of timestamp requests that were not found in the + /** + * The global number of timestamp requests that were not found in the * cache. - */ + */ long getUpdateTimestampsCacheMissCount(); - /** - * The global number of timestamps put in cache. - */ + /** + * The global number of timestamps put in cache. + */ long getUpdateTimestampsCachePutCount(); /** - * The global number of flush operations executed, including automatic + * The global number of flush operations executed, including automatic * (either manual or automatic). - */ + */ long getFlushCount(); /** @@ -252,15 +252,15 @@ public interface Statistics { long getConnectCount(); /** - * The global number of cacheable entities and collections successfully + * The global number of cacheable entities and collections successfully * retrieved from the cache. - */ + */ long getSecondLevelCacheHitCount(); /** - * The global number of cacheable entities collections not found in the + * The global number of cacheable entities collections not found in the * cache and loaded from the database. - */ + */ long getSecondLevelCacheMissCount(); /** @@ -297,7 +297,7 @@ public interface Statistics { /** * The global number of collections removed. */ - //even on inverse="true" + //even on inverse="true" long getCollectionRemoveCount(); /** diff --git a/hibernate-core/src/main/java/org/hibernate/type/EntityType.java b/hibernate-core/src/main/java/org/hibernate/type/EntityType.java index d6fc5b0028..ca8d365ba7 100644 --- a/hibernate-core/src/main/java/org/hibernate/type/EntityType.java +++ b/hibernate-core/src/main/java/org/hibernate/type/EntityType.java @@ -474,9 +474,9 @@ public abstract class EntityType extends AbstractType implements AssociationType if ( lazyInitializer != null ) { /* If the value is a Proxy and the property access is field, the value returned by - `attributeMapping.getAttributeMetadata().getPropertyAccess().getGetter().get( object )` - is always null except for the id, we need the to use the proxy implementation to - extract the property value. + `attributeMapping.getAttributeMetadata().getPropertyAccess().getGetter().get( object )` + is always null except for the id, we need the to use the proxy implementation to + extract the property value. */ value = lazyInitializer.getImplementation(); } diff --git a/hibernate-core/src/main/java/org/hibernate/type/descriptor/converter/internal/ArrayConverter.java b/hibernate-core/src/main/java/org/hibernate/type/descriptor/converter/internal/ArrayConverter.java index ff24f3172c..1870b0a436 100644 --- a/hibernate-core/src/main/java/org/hibernate/type/descriptor/converter/internal/ArrayConverter.java +++ b/hibernate-core/src/main/java/org/hibernate/type/descriptor/converter/internal/ArrayConverter.java @@ -83,7 +83,7 @@ public class ArrayConverter implements BasicValueConverter { } private S convertFrom(E[] domainArray, Class elementClass) { - //TODO: the following implementation only handles conversion between non-primitive arrays! + //TODO: the following implementation only handles conversion between non-primitive arrays! //noinspection unchecked final F[] relationalArray = (F[]) Array.newInstance( elementClass, domainArray.length ); for ( int i = 0; i < domainArray.length; i++ ) { diff --git a/hibernate-core/src/main/java/org/hibernate/type/descriptor/jdbc/spi/JdbcTypeRegistry.java b/hibernate-core/src/main/java/org/hibernate/type/descriptor/jdbc/spi/JdbcTypeRegistry.java index 2760d96659..7e7603b032 100644 --- a/hibernate-core/src/main/java/org/hibernate/type/descriptor/jdbc/spi/JdbcTypeRegistry.java +++ b/hibernate-core/src/main/java/org/hibernate/type/descriptor/jdbc/spi/JdbcTypeRegistry.java @@ -53,7 +53,7 @@ public class JdbcTypeRegistry implements JdbcTypeBaseline.BaselineTarget, Serial * {@link JdbcTypeConstructor#resolveType(TypeConfiguration, Dialect, JdbcType, ColumnTypeInformation)} and * {@link JdbcTypeConstructor#resolveType(TypeConfiguration, Dialect, BasicType, ColumnTypeInformation)} in a single * map. - */ + */ private final ConcurrentHashMap typeConstructorDescriptorMap = new ConcurrentHashMap<>(); private final ConcurrentHashMap sqlTypedDescriptorMap = new ConcurrentHashMap<>(); diff --git a/hibernate-core/src/test/java/org/hibernate/bytecode/internal/bytebuddy/mappedsuperclass/BaseMappedSuperclass.java b/hibernate-core/src/test/java/org/hibernate/bytecode/internal/bytebuddy/mappedsuperclass/BaseMappedSuperclass.java index 376a136e32..d4cade80c5 100644 --- a/hibernate-core/src/test/java/org/hibernate/bytecode/internal/bytebuddy/mappedsuperclass/BaseMappedSuperclass.java +++ b/hibernate-core/src/test/java/org/hibernate/bytecode/internal/bytebuddy/mappedsuperclass/BaseMappedSuperclass.java @@ -12,8 +12,8 @@ import jakarta.persistence.MappedSuperclass; @MappedSuperclass public abstract class BaseMappedSuperclass { - @Id - protected Long id; +@Id +protected Long id; - protected long value; +protected long value; } diff --git a/hibernate-core/src/test/java/org/hibernate/dialect/DB2iDialectTest.java b/hibernate-core/src/test/java/org/hibernate/dialect/DB2iDialectTest.java index c62a37ac93..2a73976271 100644 --- a/hibernate-core/src/test/java/org/hibernate/dialect/DB2iDialectTest.java +++ b/hibernate-core/src/test/java/org/hibernate/dialect/DB2iDialectTest.java @@ -14,62 +14,62 @@ import static org.junit.jupiter.api.Assertions.assertEquals; class DB2iDialectTest { - private static final String EXPECTED_FOR_UPDATE = " for update with rs"; - private static final String EXPECTED_FOR_UPDATE_SKIP_LOCK = " for update with rs skip locked data"; + private static final String EXPECTED_FOR_UPDATE = " for update with rs"; + private static final String EXPECTED_FOR_UPDATE_SKIP_LOCK = " for update with rs skip locked data"; - private DB2iDialect dialect; + private DB2iDialect dialect; - @BeforeEach - void setUp() { - dialect = new DB2iDialect(); - } + @BeforeEach + void setUp() { + dialect = new DB2iDialect(); + } - @Test - @JiraKey("HHH-18560") - void getForUpdateString() { - String actual = dialect.getForUpdateString(); - assertEquals(EXPECTED_FOR_UPDATE, actual); - } + @Test + @JiraKey("HHH-18560") + void getForUpdateString() { + String actual = dialect.getForUpdateString(); + assertEquals(EXPECTED_FOR_UPDATE, actual); + } - @Test - @JiraKey("HHH-18560") - void getForUpdateSkipLockedString() { - String actual = dialect.getForUpdateSkipLockedString(); - assertEquals(EXPECTED_FOR_UPDATE_SKIP_LOCK, actual); - } + @Test + @JiraKey("HHH-18560") + void getForUpdateSkipLockedString() { + String actual = dialect.getForUpdateSkipLockedString(); + assertEquals(EXPECTED_FOR_UPDATE_SKIP_LOCK, actual); + } - @Test - @JiraKey("HHH-18560") - void testGetForUpdateSkipLockedString() { - String actual = dialect.getForUpdateSkipLockedString("alias"); - assertEquals(EXPECTED_FOR_UPDATE_SKIP_LOCK, actual); - } + @Test + @JiraKey("HHH-18560") + void testGetForUpdateSkipLockedString() { + String actual = dialect.getForUpdateSkipLockedString("alias"); + assertEquals(EXPECTED_FOR_UPDATE_SKIP_LOCK, actual); + } - @Test - @JiraKey("HHH-18560") - void getWriteLockString_skiplocked() { - String actual = dialect.getWriteLockString(-2); - assertEquals(EXPECTED_FOR_UPDATE_SKIP_LOCK, actual); - } + @Test + @JiraKey("HHH-18560") + void getWriteLockString_skiplocked() { + String actual = dialect.getWriteLockString(-2); + assertEquals(EXPECTED_FOR_UPDATE_SKIP_LOCK, actual); + } - @Test - @JiraKey("HHH-18560") - void getWriteLockString() { - String actual = dialect.getWriteLockString(0); - assertEquals(EXPECTED_FOR_UPDATE, actual); - } + @Test + @JiraKey("HHH-18560") + void getWriteLockString() { + String actual = dialect.getWriteLockString(0); + assertEquals(EXPECTED_FOR_UPDATE, actual); + } - @Test - @JiraKey("HHH-18560") - void getReadLockString() { - String actual = dialect.getReadLockString(0); - assertEquals(EXPECTED_FOR_UPDATE, actual); - } + @Test + @JiraKey("HHH-18560") + void getReadLockString() { + String actual = dialect.getReadLockString(0); + assertEquals(EXPECTED_FOR_UPDATE, actual); + } - @Test - @JiraKey("HHH-18560") - void getReadLockString_skipLocked() { - String actual = dialect.getReadLockString(-2); - assertEquals(EXPECTED_FOR_UPDATE_SKIP_LOCK, actual); - } + @Test + @JiraKey("HHH-18560") + void getReadLockString_skipLocked() { + String actual = dialect.getReadLockString(-2); + assertEquals(EXPECTED_FOR_UPDATE_SKIP_LOCK, actual); + } } diff --git a/hibernate-core/src/test/java/org/hibernate/engine/jdbc/BlobProxyTest.java b/hibernate-core/src/test/java/org/hibernate/engine/jdbc/BlobProxyTest.java index 1c110479ef..a3562037ae 100644 --- a/hibernate-core/src/test/java/org/hibernate/engine/jdbc/BlobProxyTest.java +++ b/hibernate-core/src/test/java/org/hibernate/engine/jdbc/BlobProxyTest.java @@ -17,10 +17,10 @@ import static org.junit.jupiter.api.Assertions.assertEquals; @JiraKey("HHH-17770") class BlobProxyTest { - @Test - void testLengthIsNotTruncated() throws SQLException { - long THREE_GB = 3 * 1024 * 1024 * 1024L; - Blob blob = BlobProxy.generateProxy(null, THREE_GB); - assertEquals(THREE_GB, blob.length()); - } + @Test + void testLengthIsNotTruncated() throws SQLException { + long THREE_GB = 3 * 1024 * 1024 * 1024L; + Blob blob = BlobProxy.generateProxy(null, THREE_GB); + assertEquals(THREE_GB, blob.length()); + } } diff --git a/hibernate-core/src/test/java/org/hibernate/event/PreUpdateEventListenerVetoTest.java b/hibernate-core/src/test/java/org/hibernate/event/PreUpdateEventListenerVetoTest.java index 371af41c94..9feaa35c1b 100644 --- a/hibernate-core/src/test/java/org/hibernate/event/PreUpdateEventListenerVetoTest.java +++ b/hibernate-core/src/test/java/org/hibernate/event/PreUpdateEventListenerVetoTest.java @@ -38,7 +38,7 @@ public class PreUpdateEventListenerVetoTest extends BaseSessionFactoryFunctional @Override protected void sessionFactoryBuilt(SessionFactoryImplementor factory) { - factory.getServiceRegistry().requireService( EventListenerRegistry.class ) + factory.getServiceRegistry().requireService( EventListenerRegistry.class ) .appendListeners( EventType.PRE_UPDATE, event -> true ); } diff --git a/hibernate-core/src/test/java/org/hibernate/event/service/internal/EventListenerGroupAppendListenerTest.java b/hibernate-core/src/test/java/org/hibernate/event/service/internal/EventListenerGroupAppendListenerTest.java index aafebf6384..80b992bde0 100644 --- a/hibernate-core/src/test/java/org/hibernate/event/service/internal/EventListenerGroupAppendListenerTest.java +++ b/hibernate-core/src/test/java/org/hibernate/event/service/internal/EventListenerGroupAppendListenerTest.java @@ -63,7 +63,7 @@ public class EventListenerGroupAppendListenerTest extends BaseSessionFactoryFunc DefaultMergeEventListener mergeEventListener) { inTransaction( session -> { - EventListenerGroup group = + EventListenerGroup group = sessionFactory().getServiceRegistry() .requireService( EventListenerRegistry.class ) .getEventListenerGroup( EventType.MERGE ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/Company.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/Company.java index d3834b7d1b..ded05f6df2 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/Company.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/Company.java @@ -45,6 +45,6 @@ public class Company implements Serializable { //should be treated as getter private int[] getWorkingHoursPerWeek(Set holidayDays) { - return null; - } + return null; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/CreationTimestampTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/CreationTimestampTest.java index f88c7a8c8d..25349efd46 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/CreationTimestampTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/CreationTimestampTest.java @@ -32,188 +32,188 @@ import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; */ public class CreationTimestampTest extends BaseEntityManagerFunctionalTestCase { - @Override - protected Class[] getAnnotatedClasses() { - return new Class[]{ - Event.class - }; - } + @Override + protected Class[] getAnnotatedClasses() { + return new Class[]{ + Event.class + }; + } - @Entity(name = "Event") - private static class Event { + @Entity(name = "Event") + private static class Event { - @Id - @GeneratedValue - private Long id; + @Id + @GeneratedValue + private Long id; - @Column(name = "`date`") - @CreationTimestamp - private Date date; + @Column(name = "`date`") + @CreationTimestamp + private Date date; - @Column(name = "`calendar`") - @CreationTimestamp - private Calendar calendar; + @Column(name = "`calendar`") + @CreationTimestamp + private Calendar calendar; - @Column(name = "`sqlDate`") - @CreationTimestamp - private java.sql.Date sqlDate; + @Column(name = "`sqlDate`") + @CreationTimestamp + private java.sql.Date sqlDate; - @Column(name = "`time`") - @CreationTimestamp - private Time time; + @Column(name = "`time`") + @CreationTimestamp + private Time time; - @Column(name = "`timestamp`") - @CreationTimestamp - private Timestamp timestamp; + @Column(name = "`timestamp`") + @CreationTimestamp + private Timestamp timestamp; - @Column(name = "`instant`") - @CreationTimestamp - private Instant instant; + @Column(name = "`instant`") + @CreationTimestamp + private Instant instant; - @Column(name = "`localDate`") - @CreationTimestamp - private LocalDate localDate; + @Column(name = "`localDate`") + @CreationTimestamp + private LocalDate localDate; - @Column(name = "`localDateTime`") - @CreationTimestamp - private LocalDateTime localDateTime; + @Column(name = "`localDateTime`") + @CreationTimestamp + private LocalDateTime localDateTime; - @Column(name = "`localTime`") - @CreationTimestamp - private LocalTime localTime; + @Column(name = "`localTime`") + @CreationTimestamp + private LocalTime localTime; - @Column(name = "`monthDay`") - @CreationTimestamp - private MonthDay monthDay; + @Column(name = "`monthDay`") + @CreationTimestamp + private MonthDay monthDay; - @Column(name = "`offsetDateTime`") - @CreationTimestamp - private OffsetDateTime offsetDateTime; + @Column(name = "`offsetDateTime`") + @CreationTimestamp + private OffsetDateTime offsetDateTime; - @Column(name = "`offsetTime`") - @CreationTimestamp - private OffsetTime offsetTime; + @Column(name = "`offsetTime`") + @CreationTimestamp + private OffsetTime offsetTime; - @Column(name = "`year`") - @CreationTimestamp - private Year year; + @Column(name = "`year`") + @CreationTimestamp + private Year year; - @Column(name = "`yearMonth`") - @CreationTimestamp - private YearMonth yearMonth; + @Column(name = "`yearMonth`") + @CreationTimestamp + private YearMonth yearMonth; - @Column(name = "`zonedDateTime`") - @CreationTimestamp - private ZonedDateTime zonedDateTime; + @Column(name = "`zonedDateTime`") + @CreationTimestamp + private ZonedDateTime zonedDateTime; - public Event() { - } + public Event() { + } - public Long getId() { - return id; - } + public Long getId() { + return id; + } - public Date getDate() { - return date; - } + public Date getDate() { + return date; + } - public Calendar getCalendar() { - return calendar; - } + public Calendar getCalendar() { + return calendar; + } - public java.sql.Date getSqlDate() { - return sqlDate; - } + public java.sql.Date getSqlDate() { + return sqlDate; + } - public Time getTime() { - return time; - } + public Time getTime() { + return time; + } - public Timestamp getTimestamp() { - return timestamp; - } + public Timestamp getTimestamp() { + return timestamp; + } - public Instant getInstant() { - return instant; - } + public Instant getInstant() { + return instant; + } - public LocalDate getLocalDate() { - return localDate; - } + public LocalDate getLocalDate() { + return localDate; + } - public LocalDateTime getLocalDateTime() { - return localDateTime; - } + public LocalDateTime getLocalDateTime() { + return localDateTime; + } - public LocalTime getLocalTime() { - return localTime; - } + public LocalTime getLocalTime() { + return localTime; + } - public MonthDay getMonthDay() { - return monthDay; - } + public MonthDay getMonthDay() { + return monthDay; + } - public OffsetDateTime getOffsetDateTime() { - return offsetDateTime; - } + public OffsetDateTime getOffsetDateTime() { + return offsetDateTime; + } - public OffsetTime getOffsetTime() { - return offsetTime; - } + public OffsetTime getOffsetTime() { + return offsetTime; + } - public Year getYear() { - return year; - } + public Year getYear() { + return year; + } - public YearMonth getYearMonth() { - return yearMonth; - } + public YearMonth getYearMonth() { + return yearMonth; + } - public ZonedDateTime getZonedDateTime() { - return zonedDateTime; - } - } + public ZonedDateTime getZonedDateTime() { + return zonedDateTime; + } + } - @Test - public void generatesCurrentTimestamp() { - doInJPA(this::entityManagerFactory, entityManager -> { - Event event = new Event(); - entityManager.persist(event); - entityManager.flush(); - check( event ); - }); - } + @Test + public void generatesCurrentTimestamp() { + doInJPA(this::entityManagerFactory, entityManager -> { + Event event = new Event(); + entityManager.persist(event); + entityManager.flush(); + check( event ); + }); + } - @Test - @JiraKey( value = "HHH-16240") - public void generatesCurrentTimestampInStatelessSession() { - doInJPA(this::entityManagerFactory, entityManager -> { - Session session = entityManager.unwrap( Session.class); - try (StatelessSession statelessSession = session.getSessionFactory().openStatelessSession()) { - Event event = new Event(); - statelessSession.getTransaction().begin(); - statelessSession.insert(event); - statelessSession.getTransaction().commit(); - check( event ); - } - }); - } + @Test + @JiraKey( value = "HHH-16240") + public void generatesCurrentTimestampInStatelessSession() { + doInJPA(this::entityManagerFactory, entityManager -> { + Session session = entityManager.unwrap( Session.class); + try (StatelessSession statelessSession = session.getSessionFactory().openStatelessSession()) { + Event event = new Event(); + statelessSession.getTransaction().begin(); + statelessSession.insert(event); + statelessSession.getTransaction().commit(); + check( event ); + } + }); + } - private void check(Event event) { - Assert.assertNotNull(event.getDate()); - Assert.assertNotNull(event.getCalendar()); - Assert.assertNotNull(event.getSqlDate()); - Assert.assertNotNull(event.getTime()); - Assert.assertNotNull(event.getTimestamp()); - Assert.assertNotNull(event.getInstant()); - Assert.assertNotNull(event.getLocalDate()); - Assert.assertNotNull(event.getLocalDateTime()); - Assert.assertNotNull(event.getLocalTime()); - Assert.assertNotNull(event.getMonthDay()); - Assert.assertNotNull(event.getOffsetDateTime()); - Assert.assertNotNull(event.getOffsetTime()); - Assert.assertNotNull(event.getYear()); - Assert.assertNotNull(event.getYearMonth()); - Assert.assertNotNull(event.getZonedDateTime()); - } + private void check(Event event) { + Assert.assertNotNull(event.getDate()); + Assert.assertNotNull(event.getCalendar()); + Assert.assertNotNull(event.getSqlDate()); + Assert.assertNotNull(event.getTime()); + Assert.assertNotNull(event.getTimestamp()); + Assert.assertNotNull(event.getInstant()); + Assert.assertNotNull(event.getLocalDate()); + Assert.assertNotNull(event.getLocalDateTime()); + Assert.assertNotNull(event.getLocalTime()); + Assert.assertNotNull(event.getMonthDay()); + Assert.assertNotNull(event.getOffsetDateTime()); + Assert.assertNotNull(event.getOffsetTime()); + Assert.assertNotNull(event.getYear()); + Assert.assertNotNull(event.getYearMonth()); + Assert.assertNotNull(event.getZonedDateTime()); + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/DatabaseCreationTimestampNullableColumnTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/DatabaseCreationTimestampNullableColumnTest.java index 63b93e1de6..4fa58a34e7 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/DatabaseCreationTimestampNullableColumnTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/DatabaseCreationTimestampNullableColumnTest.java @@ -38,81 +38,81 @@ import jakarta.persistence.Id; @JiraKey( "HHH-11096" ) @RequiresDialectFeature( feature = DialectFeatureChecks.UsesStandardCurrentTimestampFunction.class ) @Jpa( - annotatedClasses = { - DatabaseCreationTimestampNullableColumnTest.Person.class - } + annotatedClasses = { + DatabaseCreationTimestampNullableColumnTest.Person.class + } ) public class DatabaseCreationTimestampNullableColumnTest { - @Entity(name = "Person") - public static class Person { + @Entity(name = "Person") + public static class Person { - @Id - @GeneratedValue - private Long id; + @Id + @GeneratedValue + private Long id; - @NaturalId - private String name; + @NaturalId + private String name; - @Column(nullable = false) - @FunctionCreationTimestamp - private Date creationDate; + @Column(nullable = false) + @FunctionCreationTimestamp + private Date creationDate; - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - public Date getCreationDate() { - return creationDate; - } + public Date getCreationDate() { + return creationDate; + } - public void setCreationDate(Date creationDate) { - this.creationDate = creationDate; - } + public void setCreationDate(Date creationDate) { + this.creationDate = creationDate; + } - } + } - @ValueGenerationType(generatedBy = FunctionCreationValueGeneration.class) - @Retention(RetentionPolicy.RUNTIME) - public @interface FunctionCreationTimestamp {} + @ValueGenerationType(generatedBy = FunctionCreationValueGeneration.class) + @Retention(RetentionPolicy.RUNTIME) + public @interface FunctionCreationTimestamp {} - public static class FunctionCreationValueGeneration implements OnExecutionGenerator { - @Override - public EnumSet getEventTypes() { - return EventTypeSets.INSERT_ONLY; - } + public static class FunctionCreationValueGeneration implements OnExecutionGenerator { + @Override + public EnumSet getEventTypes() { + return EventTypeSets.INSERT_ONLY; + } - @Override - public boolean referenceColumnsInSql(Dialect dialect) { - return true; - } + @Override + public boolean referenceColumnsInSql(Dialect dialect) { + return true; + } - @Override - public boolean writePropertyValue() { - return false; - } + @Override + public boolean writePropertyValue() { + return false; + } - @Override - public String[] getReferencedColumnValues(Dialect dialect) { - return new String[] { dialect.currentTimestamp() }; - } - } + @Override + public String[] getReferencedColumnValues(Dialect dialect) { + return new String[] { dialect.currentTimestamp() }; + } + } - @Test - public void generatesCurrentTimestamp(EntityManagerFactoryScope scope) { - scope.inTransaction( - entityManager -> { - Person person = new Person(); - person.setName("John Doe"); - entityManager.persist(person); + @Test + public void generatesCurrentTimestamp(EntityManagerFactoryScope scope) { + scope.inTransaction( + entityManager -> { + Person person = new Person(); + person.setName("John Doe"); + entityManager.persist(person); - entityManager.flush(); - Assertions.assertNotNull(person.getCreationDate()); - } - ); - } + entityManager.flush(); + Assertions.assertNotNull(person.getCreationDate()); + } + ); + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/DatabaseTimestampsColumnTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/DatabaseTimestampsColumnTest.java index f451baf06e..b5ee1f1756 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/DatabaseTimestampsColumnTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/DatabaseTimestampsColumnTest.java @@ -34,107 +34,107 @@ import jakarta.persistence.Id; @Jpa(annotatedClasses = DatabaseTimestampsColumnTest.Person.class) public class DatabaseTimestampsColumnTest { - @Entity(name = "Person") - public static class Person { + @Entity(name = "Person") + public static class Person { - @Id - @GeneratedValue - private Long id; + @Id + @GeneratedValue + private Long id; - @NaturalId(mutable = true) - private String name; + @NaturalId(mutable = true) + private String name; - @Column(nullable = false) - @Timestamp - private Date creationDate; + @Column(nullable = false) + @Timestamp + private Date creationDate; - @Column(nullable = true) - @Timestamp(EventType.UPDATE) - private Date editionDate; + @Column(nullable = true) + @Timestamp(EventType.UPDATE) + private Date editionDate; - @Column(nullable = false, name="version") - @Timestamp({ EventType.INSERT, EventType.UPDATE }) - private Date timestamp; + @Column(nullable = false, name="version") + @Timestamp({ EventType.INSERT, EventType.UPDATE }) + private Date timestamp; - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - public Date getCreationDate() { - return creationDate; - } + public Date getCreationDate() { + return creationDate; + } - public Date getEditionDate() { - return editionDate; - } + public Date getEditionDate() { + return editionDate; + } - public Date getTimestamp() { - return timestamp; - } - } + public Date getTimestamp() { + return timestamp; + } + } - @ValueGenerationType(generatedBy = TimestampValueGeneration.class) - @Retention(RetentionPolicy.RUNTIME) - public @interface Timestamp { EventType[] value() default EventType.INSERT; } + @ValueGenerationType(generatedBy = TimestampValueGeneration.class) + @Retention(RetentionPolicy.RUNTIME) + public @interface Timestamp { EventType[] value() default EventType.INSERT; } - public static class TimestampValueGeneration implements OnExecutionGenerator { - private EnumSet events; + public static class TimestampValueGeneration implements OnExecutionGenerator { + private EnumSet events; - public TimestampValueGeneration(Timestamp annotation, Member member, GeneratorCreationContext context) { - events = EventTypeSets.fromArray( annotation.value() ); - } + public TimestampValueGeneration(Timestamp annotation, Member member, GeneratorCreationContext context) { + events = EventTypeSets.fromArray( annotation.value() ); + } - @Override - public EnumSet getEventTypes() { - return events; - } + @Override + public EnumSet getEventTypes() { + return events; + } - @Override - public boolean referenceColumnsInSql(Dialect dialect) { - return true; - } + @Override + public boolean referenceColumnsInSql(Dialect dialect) { + return true; + } - @Override - public String[] getReferencedColumnValues(Dialect dialect) { - return new String[] { dialect.currentTimestamp() }; - } + @Override + public String[] getReferencedColumnValues(Dialect dialect) { + return new String[] { dialect.currentTimestamp() }; + } - @Override - public boolean writePropertyValue() { - return false; - } - } + @Override + public boolean writePropertyValue() { + return false; + } + } - @Test - public void generatesCurrentTimestamp(EntityManagerFactoryScope scope) { - scope.inEntityManager( - entityManager -> { - entityManager.getTransaction().begin(); - Person person = new Person(); - person.setName("John Doe"); - entityManager.persist(person); - entityManager.getTransaction().commit(); - Date creationDate = person.getCreationDate(); - Assertions.assertNotNull(creationDate); - Assertions.assertNull(person.getEditionDate()); - Date timestamp = person.getTimestamp(); - Assertions.assertNotNull(timestamp); + @Test + public void generatesCurrentTimestamp(EntityManagerFactoryScope scope) { + scope.inEntityManager( + entityManager -> { + entityManager.getTransaction().begin(); + Person person = new Person(); + person.setName("John Doe"); + entityManager.persist(person); + entityManager.getTransaction().commit(); + Date creationDate = person.getCreationDate(); + Assertions.assertNotNull(creationDate); + Assertions.assertNull(person.getEditionDate()); + Date timestamp = person.getTimestamp(); + Assertions.assertNotNull(timestamp); - try { Thread.sleep(1_000); } catch (InterruptedException ie) {}; + try { Thread.sleep(1_000); } catch (InterruptedException ie) {}; - entityManager.getTransaction().begin(); - person.setName("Jane Doe"); - entityManager.getTransaction().commit(); - Assertions.assertNotNull(person.getCreationDate()); - Assertions.assertEquals(creationDate, person.getCreationDate()); - Assertions.assertNotNull(person.getEditionDate()); - Assertions.assertNotNull(person.getTimestamp()); - Assertions.assertNotEquals(timestamp, person.getTimestamp()); - } - ); - } + entityManager.getTransaction().begin(); + person.setName("Jane Doe"); + entityManager.getTransaction().commit(); + Assertions.assertNotNull(person.getCreationDate()); + Assertions.assertEquals(creationDate, person.getCreationDate()); + Assertions.assertNotNull(person.getEditionDate()); + Assertions.assertNotNull(person.getTimestamp()); + Assertions.assertNotEquals(timestamp, person.getTimestamp()); + } + ); + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/HHH16122Test.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/HHH16122Test.java index 08a022cade..07f1b9e250 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/HHH16122Test.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/HHH16122Test.java @@ -17,48 +17,48 @@ import org.junit.Test; @JiraKey( value = "HHH-16122" ) public class HHH16122Test extends BaseEntityManagerFunctionalTestCase { - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { ValueConverter.class, SuperClass.class, SubClass.class }; - } + @Override + protected Class[] getAnnotatedClasses() { + return new Class[] { ValueConverter.class, SuperClass.class, SubClass.class }; + } - @Test - public void testGenericSuperClassWithConverter() { - // The test is successful if the entity manager factory can be built. - } + @Test + public void testGenericSuperClassWithConverter() { + // The test is successful if the entity manager factory can be built. + } - public static class ConvertedValue { - public final long value; - public ConvertedValue(long value) { - this.value = value; - } - } + public static class ConvertedValue { + public final long value; + public ConvertedValue(long value) { + this.value = value; + } + } - @Converter(autoApply = true) - public static class ValueConverter implements AttributeConverter { - @Override - public Long convertToDatabaseColumn( ConvertedValue value ) { - return value.value; - } - @Override - public ConvertedValue convertToEntityAttribute( Long value ) { - return new ConvertedValue(value); - } - } + @Converter(autoApply = true) + public static class ValueConverter implements AttributeConverter { + @Override + public Long convertToDatabaseColumn( ConvertedValue value ) { + return value.value; + } + @Override + public ConvertedValue convertToEntityAttribute( Long value ) { + return new ConvertedValue(value); + } + } - @MappedSuperclass - public static abstract class SuperClass { - @Id - private String id; - public ConvertedValue convertedValue = new ConvertedValue( 1 ); - public ConvertedValue getConvertedValue() { - return convertedValue; - } - public void setConvertedValue(ConvertedValue convertedValue) { - this.convertedValue = convertedValue; - } - } + @MappedSuperclass + public static abstract class SuperClass { + @Id + private String id; + public ConvertedValue convertedValue = new ConvertedValue( 1 ); + public ConvertedValue getConvertedValue() { + return convertedValue; + } + public void setConvertedValue(ConvertedValue convertedValue) { + this.convertedValue = convertedValue; + } + } - @Entity(name = "SubClass") - public static class SubClass extends SuperClass {} + @Entity(name = "SubClass") + public static class SubClass extends SuperClass {} } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/SafeMappingTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/SafeMappingTest.java index ce53af4711..ff42071c49 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/SafeMappingTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/SafeMappingTest.java @@ -22,7 +22,7 @@ import static org.junit.Assert.fail; * @author Emmanuel Bernard */ public class SafeMappingTest { - @Test + @Test public void testDeclarativeMix() { Configuration cfg = new Configuration(); cfg.addAnnotatedClass( IncorrectEntity.class ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/UpdateTimestampTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/UpdateTimestampTest.java index 0c9d9c3e4f..c34652956e 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/UpdateTimestampTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/UpdateTimestampTest.java @@ -32,188 +32,188 @@ import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; */ public class UpdateTimestampTest extends BaseEntityManagerFunctionalTestCase { - @Override - protected Class[] getAnnotatedClasses() { - return new Class[]{ - Event.class - }; - } + @Override + protected Class[] getAnnotatedClasses() { + return new Class[]{ + Event.class + }; + } - @Entity(name = "Event") - private static class Event { + @Entity(name = "Event") + private static class Event { - @Id - @GeneratedValue - private Long id; + @Id + @GeneratedValue + private Long id; - @Column(name = "`date`") - @UpdateTimestamp - private Date date; + @Column(name = "`date`") + @UpdateTimestamp + private Date date; - @Column(name = "`calendar`") - @UpdateTimestamp - private Calendar calendar; + @Column(name = "`calendar`") + @UpdateTimestamp + private Calendar calendar; - @Column(name = "`sqlDate`") - @UpdateTimestamp - private java.sql.Date sqlDate; + @Column(name = "`sqlDate`") + @UpdateTimestamp + private java.sql.Date sqlDate; - @Column(name = "`time`") - @UpdateTimestamp - private Time time; + @Column(name = "`time`") + @UpdateTimestamp + private Time time; - @Column(name = "`timestamp`") - @UpdateTimestamp - private Timestamp timestamp; + @Column(name = "`timestamp`") + @UpdateTimestamp + private Timestamp timestamp; - @Column(name = "`instant`") - @UpdateTimestamp - private Instant instant; + @Column(name = "`instant`") + @UpdateTimestamp + private Instant instant; - @Column(name = "`localDate`") - @UpdateTimestamp - private LocalDate localDate; + @Column(name = "`localDate`") + @UpdateTimestamp + private LocalDate localDate; - @Column(name = "`localDateTime`") - @UpdateTimestamp - private LocalDateTime localDateTime; + @Column(name = "`localDateTime`") + @UpdateTimestamp + private LocalDateTime localDateTime; - @Column(name = "`localTime`") - @UpdateTimestamp - private LocalTime localTime; + @Column(name = "`localTime`") + @UpdateTimestamp + private LocalTime localTime; - @Column(name = "`monthDay`") - @UpdateTimestamp - private MonthDay monthDay; + @Column(name = "`monthDay`") + @UpdateTimestamp + private MonthDay monthDay; - @Column(name = "`offsetDateTime`") - @UpdateTimestamp - private OffsetDateTime offsetDateTime; + @Column(name = "`offsetDateTime`") + @UpdateTimestamp + private OffsetDateTime offsetDateTime; - @Column(name = "`offsetTime`") - @UpdateTimestamp - private OffsetTime offsetTime; + @Column(name = "`offsetTime`") + @UpdateTimestamp + private OffsetTime offsetTime; - @Column(name = "`year`") - @UpdateTimestamp - private Year year; + @Column(name = "`year`") + @UpdateTimestamp + private Year year; - @Column(name = "`yearMonth`") - @UpdateTimestamp - private YearMonth yearMonth; + @Column(name = "`yearMonth`") + @UpdateTimestamp + private YearMonth yearMonth; - @Column(name = "`zonedDateTime`") - @UpdateTimestamp - private ZonedDateTime zonedDateTime; + @Column(name = "`zonedDateTime`") + @UpdateTimestamp + private ZonedDateTime zonedDateTime; - public Event() { - } + public Event() { + } - public Long getId() { - return id; - } + public Long getId() { + return id; + } - public Date getDate() { - return date; - } + public Date getDate() { + return date; + } - public Calendar getCalendar() { - return calendar; - } + public Calendar getCalendar() { + return calendar; + } - public java.sql.Date getSqlDate() { - return sqlDate; - } + public java.sql.Date getSqlDate() { + return sqlDate; + } - public Time getTime() { - return time; - } + public Time getTime() { + return time; + } - public Timestamp getTimestamp() { - return timestamp; - } + public Timestamp getTimestamp() { + return timestamp; + } - public Instant getInstant() { - return instant; - } + public Instant getInstant() { + return instant; + } - public LocalDate getLocalDate() { - return localDate; - } + public LocalDate getLocalDate() { + return localDate; + } - public LocalDateTime getLocalDateTime() { - return localDateTime; - } + public LocalDateTime getLocalDateTime() { + return localDateTime; + } - public LocalTime getLocalTime() { - return localTime; - } + public LocalTime getLocalTime() { + return localTime; + } - public MonthDay getMonthDay() { - return monthDay; - } + public MonthDay getMonthDay() { + return monthDay; + } - public OffsetDateTime getOffsetDateTime() { - return offsetDateTime; - } + public OffsetDateTime getOffsetDateTime() { + return offsetDateTime; + } - public OffsetTime getOffsetTime() { - return offsetTime; - } + public OffsetTime getOffsetTime() { + return offsetTime; + } - public Year getYear() { - return year; - } + public Year getYear() { + return year; + } - public YearMonth getYearMonth() { - return yearMonth; - } + public YearMonth getYearMonth() { + return yearMonth; + } - public ZonedDateTime getZonedDateTime() { - return zonedDateTime; - } - } + public ZonedDateTime getZonedDateTime() { + return zonedDateTime; + } + } - @Test - public void generatesCurrentTimestamp() { - doInJPA(this::entityManagerFactory, entityManager -> { - Event event = new Event(); - entityManager.persist(event); - entityManager.flush(); - check( event ); - }); - } + @Test + public void generatesCurrentTimestamp() { + doInJPA(this::entityManagerFactory, entityManager -> { + Event event = new Event(); + entityManager.persist(event); + entityManager.flush(); + check( event ); + }); + } - @Test - @JiraKey( value = "HHH-16240") - public void generatesCurrentTimestampInStatelessSession() { - doInJPA(this::entityManagerFactory, entityManager -> { - Session session = entityManager.unwrap( Session.class); - try (StatelessSession statelessSession = session.getSessionFactory().openStatelessSession()) { - Event event = new Event(); - statelessSession.getTransaction().begin(); - statelessSession.insert(event); - statelessSession.getTransaction().commit(); - check( event ); - } - }); - } + @Test + @JiraKey( value = "HHH-16240") + public void generatesCurrentTimestampInStatelessSession() { + doInJPA(this::entityManagerFactory, entityManager -> { + Session session = entityManager.unwrap( Session.class); + try (StatelessSession statelessSession = session.getSessionFactory().openStatelessSession()) { + Event event = new Event(); + statelessSession.getTransaction().begin(); + statelessSession.insert(event); + statelessSession.getTransaction().commit(); + check( event ); + } + }); + } - private void check(Event event) { - Assert.assertNotNull(event.getDate()); - Assert.assertNotNull(event.getCalendar()); - Assert.assertNotNull(event.getSqlDate()); - Assert.assertNotNull(event.getTime()); - Assert.assertNotNull(event.getTimestamp()); - Assert.assertNotNull(event.getInstant()); - Assert.assertNotNull(event.getLocalDate()); - Assert.assertNotNull(event.getLocalDateTime()); - Assert.assertNotNull(event.getLocalTime()); - Assert.assertNotNull(event.getMonthDay()); - Assert.assertNotNull(event.getOffsetDateTime()); - Assert.assertNotNull(event.getOffsetTime()); - Assert.assertNotNull(event.getYear()); - Assert.assertNotNull(event.getYearMonth()); - Assert.assertNotNull(event.getZonedDateTime()); - } + private void check(Event event) { + Assert.assertNotNull(event.getDate()); + Assert.assertNotNull(event.getCalendar()); + Assert.assertNotNull(event.getSqlDate()); + Assert.assertNotNull(event.getTime()); + Assert.assertNotNull(event.getTimestamp()); + Assert.assertNotNull(event.getInstant()); + Assert.assertNotNull(event.getLocalDate()); + Assert.assertNotNull(event.getLocalDateTime()); + Assert.assertNotNull(event.getLocalTime()); + Assert.assertNotNull(event.getMonthDay()); + Assert.assertNotNull(event.getOffsetDateTime()); + Assert.assertNotNull(event.getOffsetTime()); + Assert.assertNotNull(event.getYear()); + Assert.assertNotNull(event.getYearMonth()); + Assert.assertNotNull(event.getZonedDateTime()); + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/backquotes/Printer.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/backquotes/Printer.java index 25e76624b6..5bb6a35e1f 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/backquotes/Printer.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/backquotes/Printer.java @@ -13,14 +13,14 @@ import jakarta.persistence.Table; @Entity @Table(name="`Printer`") public class Printer { - private Long id; + private Long id; - @Id - public Long getId() { - return id; - } + @Id + public Long getId() { + return id; + } - public void setId(Long id) { - this.id = id; - } + public void setId(Long id) { + this.id = id; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/beanvalidation/MinMax.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/beanvalidation/MinMax.java index 2e09fe0c22..2fd8f212d7 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/beanvalidation/MinMax.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/beanvalidation/MinMax.java @@ -24,7 +24,7 @@ public class MinMax { @Max(10) @Min(2) - @Column(name = "`value`") + @Column(name = "`value`") private Integer value; private MinMax() { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/beanvalidation/Tv.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/beanvalidation/Tv.java index 21f932c6d4..16550072e5 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/beanvalidation/Tv.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/beanvalidation/Tv.java @@ -64,7 +64,7 @@ public class Tv { @Embeddable public static class Recorder { @NotNull - @Column(name = "`time`") + @Column(name = "`time`") public BigDecimal time; } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/Tooth.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/Tooth.java index 49039d3704..1ee8797e7e 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/Tooth.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/Tooth.java @@ -20,7 +20,7 @@ public class Tooth { @Id @GeneratedValue public Integer id; - @Column(name = "`type`") + @Column(name = "`type`") public String type; @ManyToOne(cascade = CascadeType.PERSIST) public Tooth leftNeighbour; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/circle/identity/A.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/circle/identity/A.java index 4cbf1b810a..d04c8e4bcb 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/circle/identity/A.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/circle/identity/A.java @@ -11,56 +11,56 @@ package org.hibernate.orm.test.annotations.cascade.circle.identity; */ @jakarta.persistence.Entity public class A extends AbstractEntity { - private static final long serialVersionUID = 864804063L; + private static final long serialVersionUID = 864804063L; - /** - * No documentation - */ - @jakarta.persistence.OneToMany(cascade = { - jakarta.persistence.CascadeType.MERGE, jakarta.persistence.CascadeType.PERSIST, jakarta.persistence.CascadeType.REFRESH} - , mappedBy = "a") - private java.util.Set bCollection = new java.util.HashSet(); + /** + * No documentation + */ + @jakarta.persistence.OneToMany(cascade = { + jakarta.persistence.CascadeType.MERGE, jakarta.persistence.CascadeType.PERSIST, jakarta.persistence.CascadeType.REFRESH} + , mappedBy = "a") + private java.util.Set bCollection = new java.util.HashSet(); - /** - * No documentation - */ - @jakarta.persistence.ManyToMany(cascade = { - jakarta.persistence.CascadeType.MERGE, jakarta.persistence.CascadeType.PERSIST, jakarta.persistence.CascadeType.REFRESH} - , mappedBy = "aCollection") - private java.util.Set dCollection = new java.util.HashSet(); + /** + * No documentation + */ + @jakarta.persistence.ManyToMany(cascade = { + jakarta.persistence.CascadeType.MERGE, jakarta.persistence.CascadeType.PERSIST, jakarta.persistence.CascadeType.REFRESH} + , mappedBy = "aCollection") + private java.util.Set dCollection = new java.util.HashSet(); - /** - * No documentation - */ - @jakarta.persistence.OneToMany(cascade = { - jakarta.persistence.CascadeType.MERGE, jakarta.persistence.CascadeType.PERSIST, jakarta.persistence.CascadeType.REFRESH} - , mappedBy = "a") - private java.util.Set cCollection = new java.util.HashSet(); + /** + * No documentation + */ + @jakarta.persistence.OneToMany(cascade = { + jakarta.persistence.CascadeType.MERGE, jakarta.persistence.CascadeType.PERSIST, jakarta.persistence.CascadeType.REFRESH} + , mappedBy = "a") + private java.util.Set cCollection = new java.util.HashSet(); - public java.util.Set getBCollection() { - return bCollection; - } + public java.util.Set getBCollection() { + return bCollection; + } - public void setBCollection( - java.util.Set parameter) { - this.bCollection = parameter; - } + public void setBCollection( + java.util.Set parameter) { + this.bCollection = parameter; + } - public java.util.Set getDCollection() { - return dCollection; - } + public java.util.Set getDCollection() { + return dCollection; + } - public void setDCollection( - java.util.Set parameter) { - this.dCollection = parameter; - } + public void setDCollection( + java.util.Set parameter) { + this.dCollection = parameter; + } - public java.util.Set getCCollection() { - return cCollection; - } + public java.util.Set getCCollection() { + return cCollection; + } - public void setCCollection( - java.util.Set parameter) { - this.cCollection = parameter; - } + public void setCCollection( + java.util.Set parameter) { + this.cCollection = parameter; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/circle/identity/B.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/circle/identity/B.java index 9f2116cf6b..93826f0f89 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/circle/identity/B.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/circle/identity/B.java @@ -11,54 +11,54 @@ package org.hibernate.orm.test.annotations.cascade.circle.identity; */ @jakarta.persistence.Entity public class B extends AbstractEntity { - private static final long serialVersionUID = 325417243L; + private static final long serialVersionUID = 325417243L; - /** - * No documentation - */ - @jakarta.persistence.OneToMany(cascade = { - jakarta.persistence.CascadeType.MERGE, jakarta.persistence.CascadeType.PERSIST, jakarta.persistence.CascadeType.REFRESH} - , mappedBy = "b") - private java.util.Set cCollection = new java.util.HashSet(); + /** + * No documentation + */ + @jakarta.persistence.OneToMany(cascade = { + jakarta.persistence.CascadeType.MERGE, jakarta.persistence.CascadeType.PERSIST, jakarta.persistence.CascadeType.REFRESH} + , mappedBy = "b") + private java.util.Set cCollection = new java.util.HashSet(); - /** - * No documentation - */ - @jakarta.persistence.ManyToOne(cascade = { - jakarta.persistence.CascadeType.MERGE, jakarta.persistence.CascadeType.PERSIST, jakarta.persistence.CascadeType.REFRESH} - , optional = false) - private A a; + /** + * No documentation + */ + @jakarta.persistence.ManyToOne(cascade = { + jakarta.persistence.CascadeType.MERGE, jakarta.persistence.CascadeType.PERSIST, jakarta.persistence.CascadeType.REFRESH} + , optional = false) + private A a; - /** - * No documentation - */ - @jakarta.persistence.ManyToOne(cascade = { - jakarta.persistence.CascadeType.MERGE, jakarta.persistence.CascadeType.PERSIST, jakarta.persistence.CascadeType.REFRESH} - , optional = false) - private F f; + /** + * No documentation + */ + @jakarta.persistence.ManyToOne(cascade = { + jakarta.persistence.CascadeType.MERGE, jakarta.persistence.CascadeType.PERSIST, jakarta.persistence.CascadeType.REFRESH} + , optional = false) + private F f; - public java.util.Set getCCollection() { - return cCollection; - } + public java.util.Set getCCollection() { + return cCollection; + } - public void setCCollection( - java.util.Set parameter) { - this.cCollection = parameter; - } + public void setCCollection( + java.util.Set parameter) { + this.cCollection = parameter; + } - public A getA() { - return a; - } + public A getA() { + return a; + } - public void setA(A parameter) { - this.a = parameter; - } + public void setA(A parameter) { + this.a = parameter; + } - public F getF() { - return f; - } + public F getF() { + return f; + } - public void setF(F parameter) { - this.f = parameter; - } + public void setF(F parameter) { + this.f = parameter; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/circle/identity/C.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/circle/identity/C.java index 2308e69d18..dfd22cd3dc 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/circle/identity/C.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/circle/identity/C.java @@ -11,53 +11,53 @@ package org.hibernate.orm.test.annotations.cascade.circle.identity; */ @jakarta.persistence.Entity public class C extends AbstractEntity { - private static final long serialVersionUID = 1226955752L; + private static final long serialVersionUID = 1226955752L; - /** - * No documentation - */ - @jakarta.persistence.ManyToOne(cascade = { - jakarta.persistence.CascadeType.MERGE, jakarta.persistence.CascadeType.PERSIST, jakarta.persistence.CascadeType.REFRESH} - , optional = false) - private A a; + /** + * No documentation + */ + @jakarta.persistence.ManyToOne(cascade = { + jakarta.persistence.CascadeType.MERGE, jakarta.persistence.CascadeType.PERSIST, jakarta.persistence.CascadeType.REFRESH} + , optional = false) + private A a; - /** - * No documentation - */ - @jakarta.persistence.ManyToOne(cascade = { - jakarta.persistence.CascadeType.MERGE, jakarta.persistence.CascadeType.PERSIST, jakarta.persistence.CascadeType.REFRESH} - ) - private G g; + /** + * No documentation + */ + @jakarta.persistence.ManyToOne(cascade = { + jakarta.persistence.CascadeType.MERGE, jakarta.persistence.CascadeType.PERSIST, jakarta.persistence.CascadeType.REFRESH} + ) + private G g; - /** - * No documentation - */ - @jakarta.persistence.ManyToOne(cascade = { - jakarta.persistence.CascadeType.MERGE, jakarta.persistence.CascadeType.PERSIST, jakarta.persistence.CascadeType.REFRESH} - , optional = false) - private B b; + /** + * No documentation + */ + @jakarta.persistence.ManyToOne(cascade = { + jakarta.persistence.CascadeType.MERGE, jakarta.persistence.CascadeType.PERSIST, jakarta.persistence.CascadeType.REFRESH} + , optional = false) + private B b; - public A getA() { - return a; - } + public A getA() { + return a; + } - public void setA(A parameter) { - this.a = parameter; - } + public void setA(A parameter) { + this.a = parameter; + } - public G getG() { - return g; - } + public G getG() { + return g; + } - public void setG(G parameter) { - this.g = parameter; - } + public void setG(G parameter) { + this.g = parameter; + } - public B getB() { - return b; - } + public B getB() { + return b; + } - public void setB(B parameter) { - this.b = parameter; - } + public void setB(B parameter) { + this.b = parameter; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/circle/identity/D.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/circle/identity/D.java index be28846419..7c1711ee82 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/circle/identity/D.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/circle/identity/D.java @@ -11,39 +11,39 @@ package org.hibernate.orm.test.annotations.cascade.circle.identity; */ @jakarta.persistence.Entity public class D extends AbstractEntity { - private static final long serialVersionUID = 2417176961L; + private static final long serialVersionUID = 2417176961L; - /** - * No documentation - */ - @jakarta.persistence.ManyToMany(cascade = { - jakarta.persistence.CascadeType.MERGE, jakarta.persistence.CascadeType.PERSIST, jakarta.persistence.CascadeType.REFRESH} - ) - private java.util.Set aCollection = new java.util.HashSet(); + /** + * No documentation + */ + @jakarta.persistence.ManyToMany(cascade = { + jakarta.persistence.CascadeType.MERGE, jakarta.persistence.CascadeType.PERSIST, jakarta.persistence.CascadeType.REFRESH} + ) + private java.util.Set aCollection = new java.util.HashSet(); - /** - * No documentation - */ - @jakarta.persistence.OneToMany(cascade = { - jakarta.persistence.CascadeType.MERGE, jakarta.persistence.CascadeType.PERSIST, jakarta.persistence.CascadeType.REFRESH} - ) - private java.util.Set eCollection = new java.util.HashSet(); + /** + * No documentation + */ + @jakarta.persistence.OneToMany(cascade = { + jakarta.persistence.CascadeType.MERGE, jakarta.persistence.CascadeType.PERSIST, jakarta.persistence.CascadeType.REFRESH} + ) + private java.util.Set eCollection = new java.util.HashSet(); - public java.util.Set getACollection() { - return aCollection; - } + public java.util.Set getACollection() { + return aCollection; + } - public void setACollection( - java.util.Set parameter) { - this.aCollection = parameter; - } + public void setACollection( + java.util.Set parameter) { + this.aCollection = parameter; + } - public java.util.Set getECollection() { - return eCollection; - } + public java.util.Set getECollection() { + return eCollection; + } - public void setECollection( - java.util.Set parameter) { - this.eCollection = parameter; - } + public void setECollection( + java.util.Set parameter) { + this.eCollection = parameter; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/circle/identity/E.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/circle/identity/E.java index cf242af44a..51a25e4ce1 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/circle/identity/E.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/circle/identity/E.java @@ -11,21 +11,21 @@ package org.hibernate.orm.test.annotations.cascade.circle.identity; */ @jakarta.persistence.Entity public class E extends AbstractEntity { - private static final long serialVersionUID = 1226955558L; + private static final long serialVersionUID = 1226955558L; - /** - * No documentation - */ - @jakarta.persistence.ManyToOne(cascade = { - jakarta.persistence.CascadeType.MERGE, jakarta.persistence.CascadeType.PERSIST, jakarta.persistence.CascadeType.REFRESH} - , optional = false) - private F f; + /** + * No documentation + */ + @jakarta.persistence.ManyToOne(cascade = { + jakarta.persistence.CascadeType.MERGE, jakarta.persistence.CascadeType.PERSIST, jakarta.persistence.CascadeType.REFRESH} + , optional = false) + private F f; - public F getF() { - return f; - } + public F getF() { + return f; + } - public void setF(F parameter) { - this.f = parameter; - } + public void setF(F parameter) { + this.f = parameter; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/circle/identity/F.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/circle/identity/F.java index 55a7a1d75a..0441bdb960 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/circle/identity/F.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/circle/identity/F.java @@ -11,38 +11,38 @@ package org.hibernate.orm.test.annotations.cascade.circle.identity; */ @jakarta.persistence.Entity public class F extends AbstractEntity { - private static final long serialVersionUID = 1471534025L; + private static final long serialVersionUID = 1471534025L; - /** - * No documentation - */ - @jakarta.persistence.OneToMany(cascade = { - jakarta.persistence.CascadeType.MERGE, jakarta.persistence.CascadeType.PERSIST, jakarta.persistence.CascadeType.REFRESH} - , mappedBy = "f") - private java.util.Set bCollection = new java.util.HashSet(); + /** + * No documentation + */ + @jakarta.persistence.OneToMany(cascade = { + jakarta.persistence.CascadeType.MERGE, jakarta.persistence.CascadeType.PERSIST, jakarta.persistence.CascadeType.REFRESH} + , mappedBy = "f") + private java.util.Set bCollection = new java.util.HashSet(); - /** - * No documentation - */ - @jakarta.persistence.OneToOne(cascade = { - jakarta.persistence.CascadeType.MERGE, jakarta.persistence.CascadeType.PERSIST, jakarta.persistence.CascadeType.REFRESH} - ) - private H h; + /** + * No documentation + */ + @jakarta.persistence.OneToOne(cascade = { + jakarta.persistence.CascadeType.MERGE, jakarta.persistence.CascadeType.PERSIST, jakarta.persistence.CascadeType.REFRESH} + ) + private H h; - public java.util.Set getBCollection() { - return bCollection; - } + public java.util.Set getBCollection() { + return bCollection; + } - public void setBCollection( - java.util.Set parameter) { - this.bCollection = parameter; - } + public void setBCollection( + java.util.Set parameter) { + this.bCollection = parameter; + } - public H getH() { - return h; - } + public H getH() { + return h; + } - public void setH(H parameter) { - this.h = parameter; - } + public void setH(H parameter) { + this.h = parameter; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/circle/identity/G.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/circle/identity/G.java index fe5d9f969f..827a272479 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/circle/identity/G.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/circle/identity/G.java @@ -11,22 +11,22 @@ package org.hibernate.orm.test.annotations.cascade.circle.identity; */ @jakarta.persistence.Entity public class G extends AbstractEntity { - private static final long serialVersionUID = 325417437L; + private static final long serialVersionUID = 325417437L; - /** - * No documentation - */ - @jakarta.persistence.OneToMany(cascade = { - jakarta.persistence.CascadeType.MERGE, jakarta.persistence.CascadeType.PERSIST, jakarta.persistence.CascadeType.REFRESH} - , mappedBy = "g") - private java.util.Set cCollection = new java.util.HashSet(); + /** + * No documentation + */ + @jakarta.persistence.OneToMany(cascade = { + jakarta.persistence.CascadeType.MERGE, jakarta.persistence.CascadeType.PERSIST, jakarta.persistence.CascadeType.REFRESH} + , mappedBy = "g") + private java.util.Set cCollection = new java.util.HashSet(); - public java.util.Set getCCollection() { - return cCollection; - } + public java.util.Set getCCollection() { + return cCollection; + } - public void setCCollection( - java.util.Set parameter) { - this.cCollection = parameter; - } + public void setCCollection( + java.util.Set parameter) { + this.cCollection = parameter; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/circle/identity/H.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/circle/identity/H.java index 8d5d45cb95..a610496067 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/circle/identity/H.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/circle/identity/H.java @@ -11,21 +11,21 @@ package org.hibernate.orm.test.annotations.cascade.circle.identity; */ @jakarta.persistence.Entity public class H extends AbstractEntity { - private static final long serialVersionUID = 1226955562L; + private static final long serialVersionUID = 1226955562L; - /** - * No documentation - */ - @jakarta.persistence.OneToOne(cascade = { - jakarta.persistence.CascadeType.MERGE, jakarta.persistence.CascadeType.PERSIST, jakarta.persistence.CascadeType.REFRESH} - ) - private G g; + /** + * No documentation + */ + @jakarta.persistence.OneToOne(cascade = { + jakarta.persistence.CascadeType.MERGE, jakarta.persistence.CascadeType.PERSIST, jakarta.persistence.CascadeType.REFRESH} + ) + private G g; - public G getG() { - return g; - } + public G getG() { + return g; + } - public void setG(G parameter) { - this.g = parameter; - } + public void setG(G parameter) { + this.g = parameter; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/circle/sequence/A.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/circle/sequence/A.java index e4b38fa078..09712c4f67 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/circle/sequence/A.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/circle/sequence/A.java @@ -11,56 +11,56 @@ package org.hibernate.orm.test.annotations.cascade.circle.sequence; */ @jakarta.persistence.Entity public class A extends AbstractEntity { - private static final long serialVersionUID = 864804063L; + private static final long serialVersionUID = 864804063L; - /** - * No documentation - */ - @jakarta.persistence.OneToMany(cascade = { - jakarta.persistence.CascadeType.MERGE, jakarta.persistence.CascadeType.PERSIST, jakarta.persistence.CascadeType.REFRESH} - , mappedBy = "a") - private java.util.Set bCollection = new java.util.HashSet(); + /** + * No documentation + */ + @jakarta.persistence.OneToMany(cascade = { + jakarta.persistence.CascadeType.MERGE, jakarta.persistence.CascadeType.PERSIST, jakarta.persistence.CascadeType.REFRESH} + , mappedBy = "a") + private java.util.Set bCollection = new java.util.HashSet(); - /** - * No documentation - */ - @jakarta.persistence.ManyToMany(cascade = { - jakarta.persistence.CascadeType.MERGE, jakarta.persistence.CascadeType.PERSIST, jakarta.persistence.CascadeType.REFRESH} - , mappedBy = "aCollection") - private java.util.Set dCollection = new java.util.HashSet(); + /** + * No documentation + */ + @jakarta.persistence.ManyToMany(cascade = { + jakarta.persistence.CascadeType.MERGE, jakarta.persistence.CascadeType.PERSIST, jakarta.persistence.CascadeType.REFRESH} + , mappedBy = "aCollection") + private java.util.Set dCollection = new java.util.HashSet(); - /** - * No documentation - */ - @jakarta.persistence.OneToMany(cascade = { - jakarta.persistence.CascadeType.MERGE, jakarta.persistence.CascadeType.PERSIST, jakarta.persistence.CascadeType.REFRESH} - , mappedBy = "a") - private java.util.Set cCollection = new java.util.HashSet(); + /** + * No documentation + */ + @jakarta.persistence.OneToMany(cascade = { + jakarta.persistence.CascadeType.MERGE, jakarta.persistence.CascadeType.PERSIST, jakarta.persistence.CascadeType.REFRESH} + , mappedBy = "a") + private java.util.Set cCollection = new java.util.HashSet(); - public java.util.Set getBCollection() { - return bCollection; - } + public java.util.Set getBCollection() { + return bCollection; + } - public void setBCollection( - java.util.Set parameter) { - this.bCollection = parameter; - } + public void setBCollection( + java.util.Set parameter) { + this.bCollection = parameter; + } - public java.util.Set getDCollection() { - return dCollection; - } + public java.util.Set getDCollection() { + return dCollection; + } - public void setDCollection( - java.util.Set parameter) { - this.dCollection = parameter; - } + public void setDCollection( + java.util.Set parameter) { + this.dCollection = parameter; + } - public java.util.Set getCCollection() { - return cCollection; - } + public java.util.Set getCCollection() { + return cCollection; + } - public void setCCollection( - java.util.Set parameter) { - this.cCollection = parameter; - } + public void setCCollection( + java.util.Set parameter) { + this.cCollection = parameter; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/circle/sequence/B.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/circle/sequence/B.java index 5ada1556d8..8437f4ece3 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/circle/sequence/B.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/circle/sequence/B.java @@ -11,54 +11,54 @@ package org.hibernate.orm.test.annotations.cascade.circle.sequence; */ @jakarta.persistence.Entity public class B extends AbstractEntity { - private static final long serialVersionUID = 325417243L; + private static final long serialVersionUID = 325417243L; - /** - * No documentation - */ - @jakarta.persistence.OneToMany(cascade = { - jakarta.persistence.CascadeType.MERGE, jakarta.persistence.CascadeType.PERSIST, jakarta.persistence.CascadeType.REFRESH} - , mappedBy = "b") - private java.util.Set cCollection = new java.util.HashSet(); + /** + * No documentation + */ + @jakarta.persistence.OneToMany(cascade = { + jakarta.persistence.CascadeType.MERGE, jakarta.persistence.CascadeType.PERSIST, jakarta.persistence.CascadeType.REFRESH} + , mappedBy = "b") + private java.util.Set cCollection = new java.util.HashSet(); - /** - * No documentation - */ - @jakarta.persistence.ManyToOne(cascade = { - jakarta.persistence.CascadeType.MERGE, jakarta.persistence.CascadeType.PERSIST, jakarta.persistence.CascadeType.REFRESH} - , optional = false) - private A a; + /** + * No documentation + */ + @jakarta.persistence.ManyToOne(cascade = { + jakarta.persistence.CascadeType.MERGE, jakarta.persistence.CascadeType.PERSIST, jakarta.persistence.CascadeType.REFRESH} + , optional = false) + private A a; - /** - * No documentation - */ - @jakarta.persistence.ManyToOne(cascade = { - jakarta.persistence.CascadeType.MERGE, jakarta.persistence.CascadeType.PERSIST, jakarta.persistence.CascadeType.REFRESH} - , optional = false) - private F f; + /** + * No documentation + */ + @jakarta.persistence.ManyToOne(cascade = { + jakarta.persistence.CascadeType.MERGE, jakarta.persistence.CascadeType.PERSIST, jakarta.persistence.CascadeType.REFRESH} + , optional = false) + private F f; - public java.util.Set getCCollection() { - return cCollection; - } + public java.util.Set getCCollection() { + return cCollection; + } - public void setCCollection( - java.util.Set parameter) { - this.cCollection = parameter; - } + public void setCCollection( + java.util.Set parameter) { + this.cCollection = parameter; + } - public A getA() { - return a; - } + public A getA() { + return a; + } - public void setA(A parameter) { - this.a = parameter; - } + public void setA(A parameter) { + this.a = parameter; + } - public F getF() { - return f; - } + public F getF() { + return f; + } - public void setF(F parameter) { - this.f = parameter; - } + public void setF(F parameter) { + this.f = parameter; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/circle/sequence/C.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/circle/sequence/C.java index a4ad25a6bb..84d0d901f7 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/circle/sequence/C.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/circle/sequence/C.java @@ -11,53 +11,53 @@ package org.hibernate.orm.test.annotations.cascade.circle.sequence; */ @jakarta.persistence.Entity public class C extends AbstractEntity { - private static final long serialVersionUID = 1226955752L; + private static final long serialVersionUID = 1226955752L; - /** - * No documentation - */ - @jakarta.persistence.ManyToOne(cascade = { - jakarta.persistence.CascadeType.MERGE, jakarta.persistence.CascadeType.PERSIST, jakarta.persistence.CascadeType.REFRESH} - , optional = false) - private A a; + /** + * No documentation + */ + @jakarta.persistence.ManyToOne(cascade = { + jakarta.persistence.CascadeType.MERGE, jakarta.persistence.CascadeType.PERSIST, jakarta.persistence.CascadeType.REFRESH} + , optional = false) + private A a; - /** - * No documentation - */ - @jakarta.persistence.ManyToOne(cascade = { - jakarta.persistence.CascadeType.MERGE, jakarta.persistence.CascadeType.PERSIST, jakarta.persistence.CascadeType.REFRESH} - ) - private G g; + /** + * No documentation + */ + @jakarta.persistence.ManyToOne(cascade = { + jakarta.persistence.CascadeType.MERGE, jakarta.persistence.CascadeType.PERSIST, jakarta.persistence.CascadeType.REFRESH} + ) + private G g; - /** - * No documentation - */ - @jakarta.persistence.ManyToOne(cascade = { - jakarta.persistence.CascadeType.MERGE, jakarta.persistence.CascadeType.PERSIST, jakarta.persistence.CascadeType.REFRESH} - , optional = false) - private B b; + /** + * No documentation + */ + @jakarta.persistence.ManyToOne(cascade = { + jakarta.persistence.CascadeType.MERGE, jakarta.persistence.CascadeType.PERSIST, jakarta.persistence.CascadeType.REFRESH} + , optional = false) + private B b; - public A getA() { - return a; - } + public A getA() { + return a; + } - public void setA(A parameter) { - this.a = parameter; - } + public void setA(A parameter) { + this.a = parameter; + } - public G getG() { - return g; - } + public G getG() { + return g; + } - public void setG(G parameter) { - this.g = parameter; - } + public void setG(G parameter) { + this.g = parameter; + } - public B getB() { - return b; - } + public B getB() { + return b; + } - public void setB(B parameter) { - this.b = parameter; - } + public void setB(B parameter) { + this.b = parameter; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/circle/sequence/D.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/circle/sequence/D.java index ca27c8d288..9eb3160a1a 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/circle/sequence/D.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/circle/sequence/D.java @@ -11,39 +11,39 @@ package org.hibernate.orm.test.annotations.cascade.circle.sequence; */ @jakarta.persistence.Entity public class D extends AbstractEntity { - private static final long serialVersionUID = 2417176961L; + private static final long serialVersionUID = 2417176961L; - /** - * No documentation - */ - @jakarta.persistence.ManyToMany(cascade = { - jakarta.persistence.CascadeType.MERGE, jakarta.persistence.CascadeType.PERSIST, jakarta.persistence.CascadeType.REFRESH} - ) - private java.util.Set aCollection = new java.util.HashSet(); + /** + * No documentation + */ + @jakarta.persistence.ManyToMany(cascade = { + jakarta.persistence.CascadeType.MERGE, jakarta.persistence.CascadeType.PERSIST, jakarta.persistence.CascadeType.REFRESH} + ) + private java.util.Set aCollection = new java.util.HashSet(); - /** - * No documentation - */ - @jakarta.persistence.OneToMany(cascade = { - jakarta.persistence.CascadeType.MERGE, jakarta.persistence.CascadeType.PERSIST, jakarta.persistence.CascadeType.REFRESH} - ) - private java.util.Set eCollection = new java.util.HashSet(); + /** + * No documentation + */ + @jakarta.persistence.OneToMany(cascade = { + jakarta.persistence.CascadeType.MERGE, jakarta.persistence.CascadeType.PERSIST, jakarta.persistence.CascadeType.REFRESH} + ) + private java.util.Set eCollection = new java.util.HashSet(); - public java.util.Set getACollection() { - return aCollection; - } + public java.util.Set getACollection() { + return aCollection; + } - public void setACollection( - java.util.Set parameter) { - this.aCollection = parameter; - } + public void setACollection( + java.util.Set parameter) { + this.aCollection = parameter; + } - public java.util.Set getECollection() { - return eCollection; - } + public java.util.Set getECollection() { + return eCollection; + } - public void setECollection( - java.util.Set parameter) { - this.eCollection = parameter; - } + public void setECollection( + java.util.Set parameter) { + this.eCollection = parameter; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/circle/sequence/E.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/circle/sequence/E.java index ed58c24a86..a6389c15cd 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/circle/sequence/E.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/circle/sequence/E.java @@ -11,21 +11,21 @@ package org.hibernate.orm.test.annotations.cascade.circle.sequence; */ @jakarta.persistence.Entity public class E extends AbstractEntity { - private static final long serialVersionUID = 1226955558L; + private static final long serialVersionUID = 1226955558L; - /** - * No documentation - */ - @jakarta.persistence.ManyToOne(cascade = { - jakarta.persistence.CascadeType.MERGE, jakarta.persistence.CascadeType.PERSIST, jakarta.persistence.CascadeType.REFRESH} - , optional = false) - private F f; + /** + * No documentation + */ + @jakarta.persistence.ManyToOne(cascade = { + jakarta.persistence.CascadeType.MERGE, jakarta.persistence.CascadeType.PERSIST, jakarta.persistence.CascadeType.REFRESH} + , optional = false) + private F f; - public F getF() { - return f; - } + public F getF() { + return f; + } - public void setF(F parameter) { - this.f = parameter; - } + public void setF(F parameter) { + this.f = parameter; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/circle/sequence/F.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/circle/sequence/F.java index 108851bcb6..1b178fe83f 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/circle/sequence/F.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/circle/sequence/F.java @@ -11,38 +11,38 @@ package org.hibernate.orm.test.annotations.cascade.circle.sequence; */ @jakarta.persistence.Entity public class F extends AbstractEntity { - private static final long serialVersionUID = 1471534025L; + private static final long serialVersionUID = 1471534025L; - /** - * No documentation - */ - @jakarta.persistence.OneToMany(cascade = { - jakarta.persistence.CascadeType.MERGE, jakarta.persistence.CascadeType.PERSIST, jakarta.persistence.CascadeType.REFRESH} - , mappedBy = "f") - private java.util.Set bCollection = new java.util.HashSet(); + /** + * No documentation + */ + @jakarta.persistence.OneToMany(cascade = { + jakarta.persistence.CascadeType.MERGE, jakarta.persistence.CascadeType.PERSIST, jakarta.persistence.CascadeType.REFRESH} + , mappedBy = "f") + private java.util.Set bCollection = new java.util.HashSet(); - /** - * No documentation - */ - @jakarta.persistence.OneToOne(cascade = { - jakarta.persistence.CascadeType.MERGE, jakarta.persistence.CascadeType.PERSIST, jakarta.persistence.CascadeType.REFRESH} - ) - private H h; + /** + * No documentation + */ + @jakarta.persistence.OneToOne(cascade = { + jakarta.persistence.CascadeType.MERGE, jakarta.persistence.CascadeType.PERSIST, jakarta.persistence.CascadeType.REFRESH} + ) + private H h; - public java.util.Set getBCollection() { - return bCollection; - } + public java.util.Set getBCollection() { + return bCollection; + } - public void setBCollection( - java.util.Set parameter) { - this.bCollection = parameter; - } + public void setBCollection( + java.util.Set parameter) { + this.bCollection = parameter; + } - public H getH() { - return h; - } + public H getH() { + return h; + } - public void setH(H parameter) { - this.h = parameter; - } + public void setH(H parameter) { + this.h = parameter; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/circle/sequence/G.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/circle/sequence/G.java index d9f0a3dffd..51c346b172 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/circle/sequence/G.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/circle/sequence/G.java @@ -11,22 +11,22 @@ package org.hibernate.orm.test.annotations.cascade.circle.sequence; */ @jakarta.persistence.Entity public class G extends AbstractEntity { - private static final long serialVersionUID = 325417437L; + private static final long serialVersionUID = 325417437L; - /** - * No documentation - */ - @jakarta.persistence.OneToMany(cascade = { - jakarta.persistence.CascadeType.MERGE, jakarta.persistence.CascadeType.PERSIST, jakarta.persistence.CascadeType.REFRESH} - , mappedBy = "g") - private java.util.Set cCollection = new java.util.HashSet(); + /** + * No documentation + */ + @jakarta.persistence.OneToMany(cascade = { + jakarta.persistence.CascadeType.MERGE, jakarta.persistence.CascadeType.PERSIST, jakarta.persistence.CascadeType.REFRESH} + , mappedBy = "g") + private java.util.Set cCollection = new java.util.HashSet(); - public java.util.Set getCCollection() { - return cCollection; - } + public java.util.Set getCCollection() { + return cCollection; + } - public void setCCollection( - java.util.Set parameter) { - this.cCollection = parameter; - } + public void setCCollection( + java.util.Set parameter) { + this.cCollection = parameter; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/circle/sequence/H.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/circle/sequence/H.java index a18c813be8..d81ef5d896 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/circle/sequence/H.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/circle/sequence/H.java @@ -11,21 +11,21 @@ package org.hibernate.orm.test.annotations.cascade.circle.sequence; */ @jakarta.persistence.Entity public class H extends AbstractEntity { - private static final long serialVersionUID = 1226955562L; + private static final long serialVersionUID = 1226955562L; - /** - * No documentation - */ - @jakarta.persistence.OneToOne(cascade = { - jakarta.persistence.CascadeType.MERGE, jakarta.persistence.CascadeType.PERSIST, jakarta.persistence.CascadeType.REFRESH} - ) - private G g; + /** + * No documentation + */ + @jakarta.persistence.OneToOne(cascade = { + jakarta.persistence.CascadeType.MERGE, jakarta.persistence.CascadeType.PERSIST, jakarta.persistence.CascadeType.REFRESH} + ) + private G g; - public G getG() { - return g; - } + public G getG() { + return g; + } - public void setG(G parameter) { - this.g = parameter; - } + public void setG(G parameter) { + this.g = parameter; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/multicircle/jpa/identity/EntityB.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/multicircle/jpa/identity/EntityB.java index 90bc210e85..93ff2fd12d 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/multicircle/jpa/identity/EntityB.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/multicircle/jpa/identity/EntityB.java @@ -11,15 +11,15 @@ package org.hibernate.orm.test.annotations.cascade.multicircle.jpa.identity; */ @jakarta.persistence.Entity public class EntityB extends AbstractEntity { - private static final long serialVersionUID = 325417243L; + private static final long serialVersionUID = 325417243L; - /** - * No documentation - */ - @jakarta.persistence.OneToMany(cascade = { - jakarta.persistence.CascadeType.MERGE, jakarta.persistence.CascadeType.PERSIST, jakarta.persistence.CascadeType.REFRESH} - , mappedBy = "b") - private java.util.Set gCollection = new java.util.HashSet(); + /** + * No documentation + */ + @jakarta.persistence.OneToMany(cascade = { + jakarta.persistence.CascadeType.MERGE, jakarta.persistence.CascadeType.PERSIST, jakarta.persistence.CascadeType.REFRESH} + , mappedBy = "b") + private java.util.Set gCollection = new java.util.HashSet(); /** @@ -32,30 +32,30 @@ public class EntityB extends AbstractEntity { - /** - * No documentation - */ - @jakarta.persistence.ManyToOne(cascade = { - jakarta.persistence.CascadeType.MERGE, jakarta.persistence.CascadeType.PERSIST, jakarta.persistence.CascadeType.REFRESH} - , optional = false) - private EntityD d; + /** + * No documentation + */ + @jakarta.persistence.ManyToOne(cascade = { + jakarta.persistence.CascadeType.MERGE, jakarta.persistence.CascadeType.PERSIST, jakarta.persistence.CascadeType.REFRESH} + , optional = false) + private EntityD d; - public java.util.Set getGCollection() { - return gCollection; - } + public java.util.Set getGCollection() { + return gCollection; + } - public void setGCollection( - java.util.Set parameter) { - this.gCollection = parameter; - } + public void setGCollection( + java.util.Set parameter) { + this.gCollection = parameter; + } - public EntityC getC() { - return c; - } + public EntityC getC() { + return c; + } - public void setC(EntityC parameter) { - this.c = parameter; - } + public void setC(EntityC parameter) { + this.c = parameter; + } public EntityD getD() { return d; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/multicircle/jpa/identity/EntityC.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/multicircle/jpa/identity/EntityC.java index 8d199ebe41..db099b4b72 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/multicircle/jpa/identity/EntityC.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/multicircle/jpa/identity/EntityC.java @@ -13,7 +13,7 @@ import java.util.Set; */ @jakarta.persistence.Entity public class EntityC extends AbstractEntity { - private static final long serialVersionUID = 1226955752L; + private static final long serialVersionUID = 1226955752L; @jakarta.persistence.OneToMany(mappedBy = "c") private Set bCollection = new java.util.HashSet(); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/multicircle/jpa/identity/EntityD.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/multicircle/jpa/identity/EntityD.java index d7cf03215c..384a08c1a4 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/multicircle/jpa/identity/EntityD.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/multicircle/jpa/identity/EntityD.java @@ -11,7 +11,7 @@ package org.hibernate.orm.test.annotations.cascade.multicircle.jpa.identity; */ @jakarta.persistence.Entity public class EntityD extends AbstractEntity { - private static final long serialVersionUID = 2417176961L; + private static final long serialVersionUID = 2417176961L; @jakarta.persistence.OneToMany(mappedBy = "d") private java.util.Set bCollection = new java.util.HashSet(); @@ -22,13 +22,13 @@ public class EntityD extends AbstractEntity { @jakarta.persistence.ManyToOne(optional = false) private EntityE e; - @jakarta.persistence.OneToMany(cascade = { - jakarta.persistence.CascadeType.MERGE, + @jakarta.persistence.OneToMany(cascade = { + jakarta.persistence.CascadeType.MERGE, jakarta.persistence.CascadeType.PERSIST, jakarta.persistence.CascadeType.REFRESH}, mappedBy = "d" - ) - private java.util.Set fCollection = new java.util.HashSet(); + ) + private java.util.Set fCollection = new java.util.HashSet(); public java.util.Set getBCollection() { return bCollection; @@ -52,12 +52,12 @@ public class EntityD extends AbstractEntity { this.e = e; } - public java.util.Set getFCollection() { - return fCollection; - } - public void setFCollection( + public java.util.Set getFCollection() { + return fCollection; + } + public void setFCollection( java.util.Set parameter) { - this.fCollection = parameter; - } + this.fCollection = parameter; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/multicircle/jpa/identity/EntityE.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/multicircle/jpa/identity/EntityE.java index 99881cdb58..aa87e51988 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/multicircle/jpa/identity/EntityE.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/multicircle/jpa/identity/EntityE.java @@ -11,7 +11,7 @@ package org.hibernate.orm.test.annotations.cascade.multicircle.jpa.identity; */ @jakarta.persistence.Entity public class EntityE extends AbstractEntity { - private static final long serialVersionUID = 1226955558L; + private static final long serialVersionUID = 1226955558L; @jakarta.persistence.OneToMany(mappedBy = "e") private java.util.Set dCollection = new java.util.HashSet(); @@ -26,10 +26,10 @@ public class EntityE extends AbstractEntity { this.dCollection = dCollection; } - public EntityF getF() { - return f; - } - public void setF(EntityF parameter) { - this.f = parameter; - } + public EntityF getF() { + return f; + } + public void setF(EntityF parameter) { + this.f = parameter; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/multicircle/jpa/identity/EntityF.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/multicircle/jpa/identity/EntityF.java index 574f24d3d8..c483699e59 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/multicircle/jpa/identity/EntityF.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/multicircle/jpa/identity/EntityF.java @@ -11,15 +11,15 @@ package org.hibernate.orm.test.annotations.cascade.multicircle.jpa.identity; */ @jakarta.persistence.Entity public class EntityF extends AbstractEntity { - private static final long serialVersionUID = 1471534025L; + private static final long serialVersionUID = 1471534025L; - /** - * No documentation - */ - @jakarta.persistence.OneToMany(cascade = { - jakarta.persistence.CascadeType.MERGE, jakarta.persistence.CascadeType.PERSIST, jakarta.persistence.CascadeType.REFRESH} - , mappedBy = "f") - private java.util.Set eCollection = new java.util.HashSet(); + /** + * No documentation + */ + @jakarta.persistence.OneToMany(cascade = { + jakarta.persistence.CascadeType.MERGE, jakarta.persistence.CascadeType.PERSIST, jakarta.persistence.CascadeType.REFRESH} + , mappedBy = "f") + private java.util.Set eCollection = new java.util.HashSet(); @jakarta.persistence.ManyToOne(optional = false) private EntityD d; @@ -27,20 +27,20 @@ public class EntityF extends AbstractEntity { @jakarta.persistence.ManyToOne(optional = false) private EntityG g; - public java.util.Set getECollection() { - return eCollection; - } - public void setECollection( - java.util.Set parameter) { - this.eCollection = parameter; - } + public java.util.Set getECollection() { + return eCollection; + } + public void setECollection( + java.util.Set parameter) { + this.eCollection = parameter; + } - public EntityD getD() { - return d; - } - public void setD(EntityD parameter) { - this.d = parameter; - } + public EntityD getD() { + return d; + } + public void setD(EntityD parameter) { + this.d = parameter; + } public EntityG getG() { return g; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/multicircle/jpa/identity/EntityG.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/multicircle/jpa/identity/EntityG.java index 9aeec6a55a..53c1b0e3f6 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/multicircle/jpa/identity/EntityG.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/multicircle/jpa/identity/EntityG.java @@ -11,13 +11,13 @@ package org.hibernate.orm.test.annotations.cascade.multicircle.jpa.identity; */ @jakarta.persistence.Entity public class EntityG extends AbstractEntity { - private static final long serialVersionUID = 325417437L; + private static final long serialVersionUID = 325417437L; @jakarta.persistence.ManyToOne(optional = false) private EntityB b; - @jakarta.persistence.OneToMany(mappedBy = "g") - private java.util.Set fCollection = new java.util.HashSet(); + @jakarta.persistence.OneToMany(mappedBy = "g") + private java.util.Set fCollection = new java.util.HashSet(); public EntityB getB() { return b; @@ -26,11 +26,11 @@ public class EntityG extends AbstractEntity { this.b = parameter; } - public java.util.Set getFCollection() { - return fCollection; - } - public void setFCollection( - java.util.Set parameter) { - this.fCollection = parameter; - } + public java.util.Set getFCollection() { + return fCollection; + } + public void setFCollection( + java.util.Set parameter) { + this.fCollection = parameter; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/multicircle/jpa/sequence/B.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/multicircle/jpa/sequence/B.java index 9af65e7b43..ccc174d0e1 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/multicircle/jpa/sequence/B.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/multicircle/jpa/sequence/B.java @@ -11,15 +11,15 @@ package org.hibernate.orm.test.annotations.cascade.multicircle.jpa.sequence; */ @jakarta.persistence.Entity public class B extends AbstractEntity { - private static final long serialVersionUID = 325417243L; + private static final long serialVersionUID = 325417243L; - /** - * No documentation - */ - @jakarta.persistence.OneToMany(cascade = { - jakarta.persistence.CascadeType.MERGE, jakarta.persistence.CascadeType.PERSIST, jakarta.persistence.CascadeType.REFRESH} - , mappedBy = "b") - private java.util.Set gCollection = new java.util.HashSet(); + /** + * No documentation + */ + @jakarta.persistence.OneToMany(cascade = { + jakarta.persistence.CascadeType.MERGE, jakarta.persistence.CascadeType.PERSIST, jakarta.persistence.CascadeType.REFRESH} + , mappedBy = "b") + private java.util.Set gCollection = new java.util.HashSet(); /** @@ -32,30 +32,30 @@ public class B extends AbstractEntity { - /** - * No documentation - */ - @jakarta.persistence.ManyToOne(cascade = { - jakarta.persistence.CascadeType.MERGE, jakarta.persistence.CascadeType.PERSIST, jakarta.persistence.CascadeType.REFRESH} - , optional = false) - private D d; + /** + * No documentation + */ + @jakarta.persistence.ManyToOne(cascade = { + jakarta.persistence.CascadeType.MERGE, jakarta.persistence.CascadeType.PERSIST, jakarta.persistence.CascadeType.REFRESH} + , optional = false) + private D d; - public java.util.Set getGCollection() { - return gCollection; - } + public java.util.Set getGCollection() { + return gCollection; + } - public void setGCollection( - java.util.Set parameter) { - this.gCollection = parameter; - } + public void setGCollection( + java.util.Set parameter) { + this.gCollection = parameter; + } - public C getC() { - return c; - } + public C getC() { + return c; + } - public void setC(C parameter) { - this.c = parameter; - } + public void setC(C parameter) { + this.c = parameter; + } public D getD() { return d; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/multicircle/jpa/sequence/C.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/multicircle/jpa/sequence/C.java index 7f206bb137..cd1a45eeb3 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/multicircle/jpa/sequence/C.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/multicircle/jpa/sequence/C.java @@ -13,7 +13,7 @@ import java.util.Set; */ @jakarta.persistence.Entity public class C extends AbstractEntity { - private static final long serialVersionUID = 1226955752L; + private static final long serialVersionUID = 1226955752L; @jakarta.persistence.OneToMany(mappedBy = "c") private Set bCollection = new java.util.HashSet(); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/multicircle/jpa/sequence/D.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/multicircle/jpa/sequence/D.java index a1e518eccc..82fbb32114 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/multicircle/jpa/sequence/D.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/multicircle/jpa/sequence/D.java @@ -11,7 +11,7 @@ package org.hibernate.orm.test.annotations.cascade.multicircle.jpa.sequence; */ @jakarta.persistence.Entity public class D extends AbstractEntity { - private static final long serialVersionUID = 2417176961L; + private static final long serialVersionUID = 2417176961L; @jakarta.persistence.OneToMany(mappedBy = "d") private java.util.Set bCollection = new java.util.HashSet(); @@ -22,11 +22,11 @@ public class D extends AbstractEntity { @jakarta.persistence.ManyToOne(optional = false) private E e; - @jakarta.persistence.OneToMany(cascade = { - jakarta.persistence.CascadeType.MERGE, jakarta.persistence.CascadeType.PERSIST, jakarta.persistence.CascadeType.REFRESH}, + @jakarta.persistence.OneToMany(cascade = { + jakarta.persistence.CascadeType.MERGE, jakarta.persistence.CascadeType.PERSIST, jakarta.persistence.CascadeType.REFRESH}, mappedBy = "d" - ) - private java.util.Set fCollection = new java.util.HashSet(); + ) + private java.util.Set fCollection = new java.util.HashSet(); public java.util.Set getBCollection() { return bCollection; @@ -50,12 +50,12 @@ public class D extends AbstractEntity { this.e = e; } - public java.util.Set getFCollection() { - return fCollection; - } - public void setFCollection( + public java.util.Set getFCollection() { + return fCollection; + } + public void setFCollection( java.util.Set parameter) { - this.fCollection = parameter; - } + this.fCollection = parameter; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/multicircle/jpa/sequence/E.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/multicircle/jpa/sequence/E.java index 96c071d500..2a0141ca0f 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/multicircle/jpa/sequence/E.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/multicircle/jpa/sequence/E.java @@ -11,7 +11,7 @@ package org.hibernate.orm.test.annotations.cascade.multicircle.jpa.sequence; */ @jakarta.persistence.Entity public class E extends AbstractEntity { - private static final long serialVersionUID = 1226955558L; + private static final long serialVersionUID = 1226955558L; @jakarta.persistence.OneToMany(mappedBy = "e") private java.util.Set dCollection = new java.util.HashSet(); @@ -26,10 +26,10 @@ public class E extends AbstractEntity { this.dCollection = dCollection; } - public F getF() { - return f; - } - public void setF(F parameter) { - this.f = parameter; - } + public F getF() { + return f; + } + public void setF(F parameter) { + this.f = parameter; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/multicircle/jpa/sequence/F.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/multicircle/jpa/sequence/F.java index 8ea2d592cc..4e7da2ce97 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/multicircle/jpa/sequence/F.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/multicircle/jpa/sequence/F.java @@ -11,15 +11,15 @@ package org.hibernate.orm.test.annotations.cascade.multicircle.jpa.sequence; */ @jakarta.persistence.Entity public class F extends AbstractEntity { - private static final long serialVersionUID = 1471534025L; + private static final long serialVersionUID = 1471534025L; - /** - * No documentation - */ - @jakarta.persistence.OneToMany(cascade = { - jakarta.persistence.CascadeType.MERGE, jakarta.persistence.CascadeType.PERSIST, jakarta.persistence.CascadeType.REFRESH} - , mappedBy = "f") - private java.util.Set eCollection = new java.util.HashSet(); + /** + * No documentation + */ + @jakarta.persistence.OneToMany(cascade = { + jakarta.persistence.CascadeType.MERGE, jakarta.persistence.CascadeType.PERSIST, jakarta.persistence.CascadeType.REFRESH} + , mappedBy = "f") + private java.util.Set eCollection = new java.util.HashSet(); @jakarta.persistence.ManyToOne(optional = false) private D d; @@ -27,20 +27,20 @@ public class F extends AbstractEntity { @jakarta.persistence.ManyToOne(optional = false) private G g; - public java.util.Set getECollection() { - return eCollection; - } - public void setECollection( - java.util.Set parameter) { - this.eCollection = parameter; - } + public java.util.Set getECollection() { + return eCollection; + } + public void setECollection( + java.util.Set parameter) { + this.eCollection = parameter; + } - public D getD() { - return d; - } - public void setD(D parameter) { - this.d = parameter; - } + public D getD() { + return d; + } + public void setD(D parameter) { + this.d = parameter; + } public G getG() { return g; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/multicircle/jpa/sequence/G.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/multicircle/jpa/sequence/G.java index 318fb1795a..2b2204c868 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/multicircle/jpa/sequence/G.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/multicircle/jpa/sequence/G.java @@ -11,13 +11,13 @@ package org.hibernate.orm.test.annotations.cascade.multicircle.jpa.sequence; */ @jakarta.persistence.Entity public class G extends AbstractEntity { - private static final long serialVersionUID = 325417437L; + private static final long serialVersionUID = 325417437L; @jakarta.persistence.ManyToOne(optional = false) private B b; - @jakarta.persistence.OneToMany(mappedBy = "g") - private java.util.Set fCollection = new java.util.HashSet(); + @jakarta.persistence.OneToMany(mappedBy = "g") + private java.util.Set fCollection = new java.util.HashSet(); public B getB() { return b; @@ -26,11 +26,11 @@ public class G extends AbstractEntity { this.b = parameter; } - public java.util.Set getFCollection() { - return fCollection; - } - public void setFCollection( - java.util.Set parameter) { - this.fCollection = parameter; - } + public java.util.Set getFCollection() { + return fCollection; + } + public void setFCollection( + java.util.Set parameter) { + this.fCollection = parameter; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/multicircle/nonjpa/identity/EntityB.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/multicircle/nonjpa/identity/EntityB.java index 471d54a779..0d1b2b0ffe 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/multicircle/nonjpa/identity/EntityB.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/multicircle/nonjpa/identity/EntityB.java @@ -8,15 +8,15 @@ package org.hibernate.orm.test.annotations.cascade.multicircle.nonjpa.identity; @jakarta.persistence.Entity public class EntityB extends AbstractEntity { - private static final long serialVersionUID = 325417243L; + private static final long serialVersionUID = 325417243L; - @jakarta.persistence.OneToMany(mappedBy = "b") + @jakarta.persistence.OneToMany(mappedBy = "b") @org.hibernate.annotations.Cascade({ org.hibernate.annotations.CascadeType.PERSIST, org.hibernate.annotations.CascadeType.MERGE, org.hibernate.annotations.CascadeType.REFRESH }) - private java.util.Set gCollection = new java.util.HashSet(); + private java.util.Set gCollection = new java.util.HashSet(); @jakarta.persistence.ManyToOne(optional = false) @@ -33,24 +33,24 @@ public class EntityB extends AbstractEntity { org.hibernate.annotations.CascadeType.MERGE, org.hibernate.annotations.CascadeType.REFRESH }) - private EntityD d; + private EntityD d; - public java.util.Set getGCollection() { - return gCollection; - } + public java.util.Set getGCollection() { + return gCollection; + } - public void setGCollection( - java.util.Set parameter) { - this.gCollection = parameter; - } + public void setGCollection( + java.util.Set parameter) { + this.gCollection = parameter; + } - public EntityC getC() { - return c; - } + public EntityC getC() { + return c; + } - public void setC(EntityC parameter) { - this.c = parameter; - } + public void setC(EntityC parameter) { + this.c = parameter; + } public EntityD getD() { return d; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/multicircle/nonjpa/identity/EntityC.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/multicircle/nonjpa/identity/EntityC.java index 3d3bb85c33..363b8dc9ce 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/multicircle/nonjpa/identity/EntityC.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/multicircle/nonjpa/identity/EntityC.java @@ -13,7 +13,7 @@ import java.util.Set; */ @jakarta.persistence.Entity public class EntityC extends AbstractEntity { - private static final long serialVersionUID = 1226955752L; + private static final long serialVersionUID = 1226955752L; @jakarta.persistence.OneToMany(mappedBy = "c") private Set bCollection = new java.util.HashSet(); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/multicircle/nonjpa/identity/EntityD.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/multicircle/nonjpa/identity/EntityD.java index 17c881996e..d0fe0f34b3 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/multicircle/nonjpa/identity/EntityD.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/multicircle/nonjpa/identity/EntityD.java @@ -11,7 +11,7 @@ package org.hibernate.orm.test.annotations.cascade.multicircle.nonjpa.identity; */ @jakarta.persistence.Entity public class EntityD extends AbstractEntity { - private static final long serialVersionUID = 2417176961L; + private static final long serialVersionUID = 2417176961L; @jakarta.persistence.OneToMany(mappedBy = "d") private java.util.Set bCollection = new java.util.HashSet(); @@ -22,13 +22,13 @@ public class EntityD extends AbstractEntity { @jakarta.persistence.ManyToOne(optional = false) private EntityE e; - @jakarta.persistence.OneToMany(mappedBy = "d") + @jakarta.persistence.OneToMany(mappedBy = "d") @org.hibernate.annotations.Cascade({ org.hibernate.annotations.CascadeType.PERSIST, org.hibernate.annotations.CascadeType.MERGE, org.hibernate.annotations.CascadeType.REFRESH }) - private java.util.Set fCollection = new java.util.HashSet(); + private java.util.Set fCollection = new java.util.HashSet(); public java.util.Set getBCollection() { return bCollection; @@ -52,12 +52,12 @@ public class EntityD extends AbstractEntity { this.e = e; } - public java.util.Set getFCollection() { - return fCollection; - } - public void setFCollection( + public java.util.Set getFCollection() { + return fCollection; + } + public void setFCollection( java.util.Set parameter) { - this.fCollection = parameter; - } + this.fCollection = parameter; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/multicircle/nonjpa/identity/EntityE.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/multicircle/nonjpa/identity/EntityE.java index 3a872b21a0..b3254efd6b 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/multicircle/nonjpa/identity/EntityE.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/multicircle/nonjpa/identity/EntityE.java @@ -11,7 +11,7 @@ package org.hibernate.orm.test.annotations.cascade.multicircle.nonjpa.identity; */ @jakarta.persistence.Entity public class EntityE extends AbstractEntity { - private static final long serialVersionUID = 1226955558L; + private static final long serialVersionUID = 1226955558L; @jakarta.persistence.OneToMany(mappedBy = "e") private java.util.Set dCollection = new java.util.HashSet(); @@ -26,10 +26,10 @@ public class EntityE extends AbstractEntity { this.dCollection = dCollection; } - public EntityF getF() { - return f; - } - public void setF(EntityF parameter) { - this.f = parameter; - } + public EntityF getF() { + return f; + } + public void setF(EntityF parameter) { + this.f = parameter; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/multicircle/nonjpa/identity/EntityF.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/multicircle/nonjpa/identity/EntityF.java index aca37331a9..5e40d04c22 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/multicircle/nonjpa/identity/EntityF.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/multicircle/nonjpa/identity/EntityF.java @@ -11,18 +11,18 @@ package org.hibernate.orm.test.annotations.cascade.multicircle.nonjpa.identity; */ @jakarta.persistence.Entity public class EntityF extends AbstractEntity { - private static final long serialVersionUID = 1471534025L; + private static final long serialVersionUID = 1471534025L; - /** - * No documentation - */ - @jakarta.persistence.OneToMany(mappedBy = "f") + /** + * No documentation + */ + @jakarta.persistence.OneToMany(mappedBy = "f") @org.hibernate.annotations.Cascade({ org.hibernate.annotations.CascadeType.PERSIST, org.hibernate.annotations.CascadeType.MERGE, org.hibernate.annotations.CascadeType.REFRESH }) - private java.util.Set eCollection = new java.util.HashSet(); + private java.util.Set eCollection = new java.util.HashSet(); @jakarta.persistence.ManyToOne(optional = false) private EntityD d; @@ -30,20 +30,20 @@ public class EntityF extends AbstractEntity { @jakarta.persistence.ManyToOne(optional = false) private EntityG g; - public java.util.Set getECollection() { - return eCollection; - } - public void setECollection( - java.util.Set parameter) { - this.eCollection = parameter; - } + public java.util.Set getECollection() { + return eCollection; + } + public void setECollection( + java.util.Set parameter) { + this.eCollection = parameter; + } - public EntityD getD() { - return d; - } - public void setD(EntityD parameter) { - this.d = parameter; - } + public EntityD getD() { + return d; + } + public void setD(EntityD parameter) { + this.d = parameter; + } public EntityG getG() { return g; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/multicircle/nonjpa/identity/EntityG.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/multicircle/nonjpa/identity/EntityG.java index 1357c03416..1beaad2ea2 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/multicircle/nonjpa/identity/EntityG.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/multicircle/nonjpa/identity/EntityG.java @@ -11,13 +11,13 @@ package org.hibernate.orm.test.annotations.cascade.multicircle.nonjpa.identity; */ @jakarta.persistence.Entity public class EntityG extends AbstractEntity { - private static final long serialVersionUID = 325417437L; + private static final long serialVersionUID = 325417437L; @jakarta.persistence.ManyToOne(optional = false) private EntityB b; - @jakarta.persistence.OneToMany(mappedBy = "g") - private java.util.Set fCollection = new java.util.HashSet(); + @jakarta.persistence.OneToMany(mappedBy = "g") + private java.util.Set fCollection = new java.util.HashSet(); public EntityB getB() { return b; @@ -26,11 +26,11 @@ public class EntityG extends AbstractEntity { this.b = parameter; } - public java.util.Set getFCollection() { - return fCollection; - } - public void setFCollection( - java.util.Set parameter) { - this.fCollection = parameter; - } + public java.util.Set getFCollection() { + return fCollection; + } + public void setFCollection( + java.util.Set parameter) { + this.fCollection = parameter; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/multicircle/nonjpa/sequence/B.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/multicircle/nonjpa/sequence/B.java index b50f2330ad..6cefa925b8 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/multicircle/nonjpa/sequence/B.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/multicircle/nonjpa/sequence/B.java @@ -8,15 +8,15 @@ package org.hibernate.orm.test.annotations.cascade.multicircle.nonjpa.sequence; @jakarta.persistence.Entity public class B extends AbstractEntity { - private static final long serialVersionUID = 325417243L; + private static final long serialVersionUID = 325417243L; - @jakarta.persistence.OneToMany(mappedBy = "b") + @jakarta.persistence.OneToMany(mappedBy = "b") @org.hibernate.annotations.Cascade({ org.hibernate.annotations.CascadeType.PERSIST, org.hibernate.annotations.CascadeType.MERGE, org.hibernate.annotations.CascadeType.REFRESH }) - private java.util.Set gCollection = new java.util.HashSet(); + private java.util.Set gCollection = new java.util.HashSet(); @jakarta.persistence.ManyToOne(optional = false) @@ -33,24 +33,24 @@ public class B extends AbstractEntity { org.hibernate.annotations.CascadeType.MERGE, org.hibernate.annotations.CascadeType.REFRESH }) - private D d; + private D d; - public java.util.Set getGCollection() { - return gCollection; - } + public java.util.Set getGCollection() { + return gCollection; + } - public void setGCollection( - java.util.Set parameter) { - this.gCollection = parameter; - } + public void setGCollection( + java.util.Set parameter) { + this.gCollection = parameter; + } - public C getC() { - return c; - } + public C getC() { + return c; + } - public void setC(C parameter) { - this.c = parameter; - } + public void setC(C parameter) { + this.c = parameter; + } public D getD() { return d; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/multicircle/nonjpa/sequence/C.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/multicircle/nonjpa/sequence/C.java index dcc65fcd4b..e3d20ba596 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/multicircle/nonjpa/sequence/C.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/multicircle/nonjpa/sequence/C.java @@ -13,7 +13,7 @@ import java.util.Set; */ @jakarta.persistence.Entity public class C extends AbstractEntity { - private static final long serialVersionUID = 1226955752L; + private static final long serialVersionUID = 1226955752L; @jakarta.persistence.OneToMany(mappedBy = "c") private Set bCollection = new java.util.HashSet(); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/multicircle/nonjpa/sequence/D.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/multicircle/nonjpa/sequence/D.java index acfa50ddb6..5d3c4aa483 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/multicircle/nonjpa/sequence/D.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/multicircle/nonjpa/sequence/D.java @@ -11,7 +11,7 @@ package org.hibernate.orm.test.annotations.cascade.multicircle.nonjpa.sequence; */ @jakarta.persistence.Entity public class D extends AbstractEntity { - private static final long serialVersionUID = 2417176961L; + private static final long serialVersionUID = 2417176961L; @jakarta.persistence.OneToMany(mappedBy = "d") private java.util.Set bCollection = new java.util.HashSet(); @@ -22,13 +22,13 @@ public class D extends AbstractEntity { @jakarta.persistence.ManyToOne(optional = false) private E e; - @jakarta.persistence.OneToMany(mappedBy = "d") + @jakarta.persistence.OneToMany(mappedBy = "d") @org.hibernate.annotations.Cascade({ org.hibernate.annotations.CascadeType.PERSIST, org.hibernate.annotations.CascadeType.MERGE, org.hibernate.annotations.CascadeType.REFRESH }) - private java.util.Set fCollection = new java.util.HashSet(); + private java.util.Set fCollection = new java.util.HashSet(); public java.util.Set getBCollection() { return bCollection; @@ -52,12 +52,12 @@ public class D extends AbstractEntity { this.e = e; } - public java.util.Set getFCollection() { - return fCollection; - } - public void setFCollection( + public java.util.Set getFCollection() { + return fCollection; + } + public void setFCollection( java.util.Set parameter) { - this.fCollection = parameter; - } + this.fCollection = parameter; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/multicircle/nonjpa/sequence/E.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/multicircle/nonjpa/sequence/E.java index 80761b4b92..94285b1e41 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/multicircle/nonjpa/sequence/E.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/multicircle/nonjpa/sequence/E.java @@ -11,7 +11,7 @@ package org.hibernate.orm.test.annotations.cascade.multicircle.nonjpa.sequence; */ @jakarta.persistence.Entity public class E extends AbstractEntity { - private static final long serialVersionUID = 1226955558L; + private static final long serialVersionUID = 1226955558L; @jakarta.persistence.OneToMany(mappedBy = "e") private java.util.Set dCollection = new java.util.HashSet(); @@ -26,10 +26,10 @@ public class E extends AbstractEntity { this.dCollection = dCollection; } - public F getF() { - return f; - } - public void setF(F parameter) { - this.f = parameter; - } + public F getF() { + return f; + } + public void setF(F parameter) { + this.f = parameter; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/multicircle/nonjpa/sequence/F.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/multicircle/nonjpa/sequence/F.java index f49655f08b..eb3de1c520 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/multicircle/nonjpa/sequence/F.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/multicircle/nonjpa/sequence/F.java @@ -11,18 +11,18 @@ package org.hibernate.orm.test.annotations.cascade.multicircle.nonjpa.sequence; */ @jakarta.persistence.Entity public class F extends AbstractEntity { - private static final long serialVersionUID = 1471534025L; + private static final long serialVersionUID = 1471534025L; - /** - * No documentation - */ - @jakarta.persistence.OneToMany(mappedBy = "f") + /** + * No documentation + */ + @jakarta.persistence.OneToMany(mappedBy = "f") @org.hibernate.annotations.Cascade({ org.hibernate.annotations.CascadeType.PERSIST, org.hibernate.annotations.CascadeType.MERGE, org.hibernate.annotations.CascadeType.REFRESH }) - private java.util.Set eCollection = new java.util.HashSet(); + private java.util.Set eCollection = new java.util.HashSet(); @jakarta.persistence.ManyToOne(optional = false) private D d; @@ -30,20 +30,20 @@ public class F extends AbstractEntity { @jakarta.persistence.ManyToOne(optional = false) private G g; - public java.util.Set getECollection() { - return eCollection; - } - public void setECollection( - java.util.Set parameter) { - this.eCollection = parameter; - } + public java.util.Set getECollection() { + return eCollection; + } + public void setECollection( + java.util.Set parameter) { + this.eCollection = parameter; + } - public D getD() { - return d; - } - public void setD(D parameter) { - this.d = parameter; - } + public D getD() { + return d; + } + public void setD(D parameter) { + this.d = parameter; + } public G getG() { return g; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/multicircle/nonjpa/sequence/G.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/multicircle/nonjpa/sequence/G.java index 23149ef541..2a412fa451 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/multicircle/nonjpa/sequence/G.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/multicircle/nonjpa/sequence/G.java @@ -11,13 +11,13 @@ package org.hibernate.orm.test.annotations.cascade.multicircle.nonjpa.sequence; */ @jakarta.persistence.Entity public class G extends AbstractEntity { - private static final long serialVersionUID = 325417437L; + private static final long serialVersionUID = 325417437L; @jakarta.persistence.ManyToOne(optional = false) private B b; - @jakarta.persistence.OneToMany(mappedBy = "g") - private java.util.Set fCollection = new java.util.HashSet(); + @jakarta.persistence.OneToMany(mappedBy = "g") + private java.util.Set fCollection = new java.util.HashSet(); public B getB() { return b; @@ -26,11 +26,11 @@ public class G extends AbstractEntity { this.b = parameter; } - public java.util.Set getFCollection() { - return fCollection; - } - public void setFCollection( - java.util.Set parameter) { - this.fCollection = parameter; - } + public java.util.Set getFCollection() { + return fCollection; + } + public void setFCollection( + java.util.Set parameter) { + this.fCollection = parameter; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cid/Flight.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cid/Flight.java index ee3b5d7ed8..6b47dd2308 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cid/Flight.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cid/Flight.java @@ -14,32 +14,32 @@ import java.util.List; @Table(name = "flight") public class Flight { - @Id - @Column(name = "id") - private Integer id; + @Id + @Column(name = "id") + private Integer id; - @OneToMany(mappedBy = "flight", cascade = CascadeType.ALL, fetch = FetchType.LAZY) - private List segments; + @OneToMany(mappedBy = "flight", cascade = CascadeType.ALL, fetch = FetchType.LAZY) + private List segments; - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public List getSegments() { - return segments; - } + public List getSegments() { + return segments; + } - public void setSegments(List segments) { - this.segments = segments; - } + public void setSegments(List segments) { + this.segments = segments; + } - public void addSegment(FlightSegment segment) { - segment.setFlight(this); - segments.add(segment); - } + public void addSegment(FlightSegment segment) { + segment.setFlight(this); + segments.add(segment); + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cid/FlightSegment.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cid/FlightSegment.java index 81c66bf915..98142e0f58 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cid/FlightSegment.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cid/FlightSegment.java @@ -13,41 +13,41 @@ import jakarta.persistence.*; @Table(name = "flight_segment") public class FlightSegment { - @Id - @ManyToOne(fetch = FetchType.LAZY) - @JoinColumn(name = "flight_id", nullable = false) - private Flight flight; + @Id + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "flight_id", nullable = false) + private Flight flight; - @Id - @Column(name = "segment_number") - private Integer segmentNumber; + @Id + @Column(name = "segment_number") + private Integer segmentNumber; - @OneToOne(mappedBy = "segment", cascade = CascadeType.ALL, fetch = FetchType.LAZY) - private FlightSegmentConfiguration configuration; + @OneToOne(mappedBy = "segment", cascade = CascadeType.ALL, fetch = FetchType.LAZY) + private FlightSegmentConfiguration configuration; - public Flight getFlight() { - return flight; - } + public Flight getFlight() { + return flight; + } - public void setFlight(Flight flight) { - this.flight = flight; - } + public void setFlight(Flight flight) { + this.flight = flight; + } - public Integer getSegmentNumber() { - return segmentNumber; - } + public Integer getSegmentNumber() { + return segmentNumber; + } - public void setSegmentNumber(Integer segmentNumber) { - this.segmentNumber = segmentNumber; - } + public void setSegmentNumber(Integer segmentNumber) { + this.segmentNumber = segmentNumber; + } - public FlightSegmentConfiguration getConfiguration() { - return configuration; - } + public FlightSegmentConfiguration getConfiguration() { + return configuration; + } - public void setConfiguration(FlightSegmentConfiguration configuration) { - configuration.setSegment(this); - this.configuration = configuration; - } + public void setConfiguration(FlightSegmentConfiguration configuration) { + configuration.setSegment(this); + this.configuration = configuration; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cid/FlightSegmentConfiguration.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cid/FlightSegmentConfiguration.java index 8af20835f9..74d05cd1f0 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cid/FlightSegmentConfiguration.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cid/FlightSegmentConfiguration.java @@ -13,18 +13,18 @@ import jakarta.persistence.*; @Table(name = "flight_segment_configuration") public class FlightSegmentConfiguration { - @Id - @OneToOne(fetch = FetchType.LAZY) - @JoinColumn(name = "flight_id", referencedColumnName = "flight_id", nullable = false) - @JoinColumn(name = "segment_number", referencedColumnName = "segment_number", nullable = false) - private FlightSegment segment; + @Id + @OneToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "flight_id", referencedColumnName = "flight_id", nullable = false) + @JoinColumn(name = "segment_number", referencedColumnName = "segment_number", nullable = false) + private FlightSegment segment; - public FlightSegment getSegment() { - return segment; - } + public FlightSegment getSegment() { + return segment; + } - public void setSegment(FlightSegment segment) { - this.segment = segment; - } + public void setSegment(FlightSegment segment) { + this.segment = segment; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cid/FlightSegmentConfigurationId.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cid/FlightSegmentConfigurationId.java index b3c29ea2db..ef5714749b 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cid/FlightSegmentConfigurationId.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cid/FlightSegmentConfigurationId.java @@ -12,41 +12,41 @@ import java.util.StringJoiner; public class FlightSegmentConfigurationId implements Serializable { - private FlightSegmentId segment; + private FlightSegmentId segment; - public FlightSegmentConfigurationId() { - } + public FlightSegmentConfigurationId() { + } - public FlightSegmentConfigurationId(FlightSegmentId segment) { - this.segment = segment; - } + public FlightSegmentConfigurationId(FlightSegmentId segment) { + this.segment = segment; + } - public FlightSegmentId getSegment() { - return segment; - } + public FlightSegmentId getSegment() { + return segment; + } - public void setSegment(FlightSegmentId segment) { - this.segment = segment; - } + public void setSegment(FlightSegmentId segment) { + this.segment = segment; + } - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - FlightSegmentConfigurationId that = (FlightSegmentConfigurationId) o; - return Objects.equals(segment, that.segment); - } + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + FlightSegmentConfigurationId that = (FlightSegmentConfigurationId) o; + return Objects.equals(segment, that.segment); + } - @Override - public int hashCode() { - return Objects.hash(segment); - } + @Override + public int hashCode() { + return Objects.hash(segment); + } - @Override - public String toString() { - return new StringJoiner(", ", FlightSegmentConfigurationId.class.getSimpleName() + "[", "]") - .add("segment=" + segment) - .toString(); - } + @Override + public String toString() { + return new StringJoiner(", ", FlightSegmentConfigurationId.class.getSimpleName() + "[", "]") + .add("segment=" + segment) + .toString(); + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cid/FlightSegmentId.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cid/FlightSegmentId.java index e3f1046bd7..02e05b935c 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cid/FlightSegmentId.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cid/FlightSegmentId.java @@ -12,52 +12,52 @@ import java.util.StringJoiner; public class FlightSegmentId implements Serializable { - private Integer flight; - private Integer segmentNumber; + private Integer flight; + private Integer segmentNumber; - public FlightSegmentId() { - } + public FlightSegmentId() { + } - public FlightSegmentId(Integer flight, Integer segmentNumber) { - this.flight = flight; - this.segmentNumber = segmentNumber; - } + public FlightSegmentId(Integer flight, Integer segmentNumber) { + this.flight = flight; + this.segmentNumber = segmentNumber; + } - public Integer getFlight() { - return flight; - } + public Integer getFlight() { + return flight; + } - public void setFlight(Integer flight) { - this.flight = flight; - } + public void setFlight(Integer flight) { + this.flight = flight; + } - public Integer getSegmentNumber() { - return segmentNumber; - } + public Integer getSegmentNumber() { + return segmentNumber; + } - public void setSegmentNumber(Integer segmentNumber) { - this.segmentNumber = segmentNumber; - } + public void setSegmentNumber(Integer segmentNumber) { + this.segmentNumber = segmentNumber; + } - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - FlightSegmentId that = (FlightSegmentId) o; - return Objects.equals(flight, that.flight) && Objects.equals(segmentNumber, that.segmentNumber); - } + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + FlightSegmentId that = (FlightSegmentId) o; + return Objects.equals(flight, that.flight) && Objects.equals(segmentNumber, that.segmentNumber); + } - @Override - public int hashCode() { - return Objects.hash(flight, segmentNumber); - } + @Override + public int hashCode() { + return Objects.hash(flight, segmentNumber); + } - @Override - public String toString() { - return new StringJoiner(", ", FlightSegmentId.class.getSimpleName() + "[", "]") - .add("flight=" + flight) - .add("segmentNumber=" + segmentNumber) - .toString(); - } + @Override + public String toString() { + return new StringJoiner(", ", FlightSegmentId.class.getSimpleName() + "[", "]") + .add("flight=" + flight) + .add("segmentNumber=" + segmentNumber) + .toString(); + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cid/Freight.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cid/Freight.java index 354ceeee53..1713ad2850 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cid/Freight.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cid/Freight.java @@ -12,29 +12,29 @@ import jakarta.persistence.*; @Table(name = "freight") public class Freight { - @Id - @Column(name = "freight_number") - private Integer freightNumber; + @Id + @Column(name = "freight_number") + private Integer freightNumber; - @ManyToOne(fetch = FetchType.LAZY) - @JoinColumn(name = "flight_id", referencedColumnName = "flight_id") - @JoinColumn(name = "segment_number", referencedColumnName = "segment_number") - private FlightSegment flightSegment; + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "flight_id", referencedColumnName = "flight_id") + @JoinColumn(name = "segment_number", referencedColumnName = "segment_number") + private FlightSegment flightSegment; - public Integer getFreightNumber() { - return freightNumber; - } + public Integer getFreightNumber() { + return freightNumber; + } - public void setFreightNumber(Integer freightNumber) { - this.freightNumber = freightNumber; - } + public void setFreightNumber(Integer freightNumber) { + this.freightNumber = freightNumber; + } - public FlightSegment getFlightSegment() { - return flightSegment; - } + public FlightSegment getFlightSegment() { + return flightSegment; + } - public void setFlightSegment(FlightSegment flightSegment) { - this.flightSegment = flightSegment; - } + public void setFlightSegment(FlightSegment flightSegment) { + this.flightSegment = flightSegment; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cid/HierarchicalCompositeIdLazyTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cid/HierarchicalCompositeIdLazyTest.java index 1b4cc505b8..c44c8e0538 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cid/HierarchicalCompositeIdLazyTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cid/HierarchicalCompositeIdLazyTest.java @@ -17,180 +17,180 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; @Jpa( - annotatedClasses = { - Flight.class, - FlightSegment.class, - FlightSegmentConfiguration.class, - Freight.class - } + annotatedClasses = { + Flight.class, + FlightSegment.class, + FlightSegmentConfiguration.class, + Freight.class + } ) public class HierarchicalCompositeIdLazyTest { - @Test - void testFetchFlightSegmentFromFlight(EntityManagerFactoryScope scope) { - scope.inTransaction( - entityManager -> { - FlightSegment flightSegment = new FlightSegment(); - flightSegment.setSegmentNumber(1); + @Test + void testFetchFlightSegmentFromFlight(EntityManagerFactoryScope scope) { + scope.inTransaction( + entityManager -> { + FlightSegment flightSegment = new FlightSegment(); + flightSegment.setSegmentNumber(1); - Flight flight = new Flight(); - flight.setId(1); - flight.setSegments(new ArrayList<>()); - flight.addSegment(flightSegment); + Flight flight = new Flight(); + flight.setId(1); + flight.setSegments(new ArrayList<>()); + flight.addSegment(flightSegment); - entityManager.persist(flight); - entityManager.flush(); - entityManager.clear(); - } - ); + entityManager.persist(flight); + entityManager.flush(); + entityManager.clear(); + } + ); - scope.inTransaction( - entityManager -> { - Flight flight = entityManager.find(Flight.class, 1); - assertNotNull(flight); - assertEquals(1, flight.getSegments().get(0).getSegmentNumber()); - } - ); - } + scope.inTransaction( + entityManager -> { + Flight flight = entityManager.find(Flight.class, 1); + assertNotNull(flight); + assertEquals(1, flight.getSegments().get(0).getSegmentNumber()); + } + ); + } - @Test - void testFetchFlightFromFlightSegment(EntityManagerFactoryScope scope) { - scope.inTransaction( - entityManager -> { - FlightSegment flightSegment = new FlightSegment(); - flightSegment.setSegmentNumber(1); + @Test + void testFetchFlightFromFlightSegment(EntityManagerFactoryScope scope) { + scope.inTransaction( + entityManager -> { + FlightSegment flightSegment = new FlightSegment(); + flightSegment.setSegmentNumber(1); - Flight flight = new Flight(); - flight.setId(1); - flight.setSegments(new ArrayList<>()); - flight.addSegment(flightSegment); + Flight flight = new Flight(); + flight.setId(1); + flight.setSegments(new ArrayList<>()); + flight.addSegment(flightSegment); - entityManager.persist(flight); - entityManager.flush(); - entityManager.clear(); - } - ); + entityManager.persist(flight); + entityManager.flush(); + entityManager.clear(); + } + ); - scope.inTransaction( - entityManager -> { - FlightSegment segment = entityManager.find(FlightSegment.class, new FlightSegmentId(1, 1)); - assertNotNull(segment); - assertEquals(1, segment.getFlight().getId()); - } - ); - } + scope.inTransaction( + entityManager -> { + FlightSegment segment = entityManager.find(FlightSegment.class, new FlightSegmentId(1, 1)); + assertNotNull(segment); + assertEquals(1, segment.getFlight().getId()); + } + ); + } - @Test - void testFetchFlightFromFlightSegmentConfiguration(EntityManagerFactoryScope scope) { - scope.inTransaction( - entityManager -> { - FlightSegmentConfiguration flightSegmentConfiguration = new FlightSegmentConfiguration(); + @Test + void testFetchFlightFromFlightSegmentConfiguration(EntityManagerFactoryScope scope) { + scope.inTransaction( + entityManager -> { + FlightSegmentConfiguration flightSegmentConfiguration = new FlightSegmentConfiguration(); - FlightSegment flightSegment = new FlightSegment(); - flightSegment.setSegmentNumber(1); - flightSegment.setConfiguration(flightSegmentConfiguration); + FlightSegment flightSegment = new FlightSegment(); + flightSegment.setSegmentNumber(1); + flightSegment.setConfiguration(flightSegmentConfiguration); - Flight flight = new Flight(); - flight.setId(1); - flight.setSegments(new ArrayList<>()); - flight.addSegment(flightSegment); + Flight flight = new Flight(); + flight.setId(1); + flight.setSegments(new ArrayList<>()); + flight.addSegment(flightSegment); - entityManager.persist(flight); - entityManager.flush(); - entityManager.clear(); - } - ); + entityManager.persist(flight); + entityManager.flush(); + entityManager.clear(); + } + ); - scope.inTransaction( - entityManager -> { - FlightSegmentConfigurationId id = new FlightSegmentConfigurationId(new FlightSegmentId(1, 1)); - FlightSegmentConfiguration configuration = entityManager.find(FlightSegmentConfiguration.class, id); - assertNotNull(configuration); - assertEquals(1, configuration.getSegment().getFlight().getId()); - assertNotNull(configuration.getSegment().getConfiguration()); - } - ); - } + scope.inTransaction( + entityManager -> { + FlightSegmentConfigurationId id = new FlightSegmentConfigurationId(new FlightSegmentId(1, 1)); + FlightSegmentConfiguration configuration = entityManager.find(FlightSegmentConfiguration.class, id); + assertNotNull(configuration); + assertEquals(1, configuration.getSegment().getFlight().getId()); + assertNotNull(configuration.getSegment().getConfiguration()); + } + ); + } - @Test - void testFetchFlightFromFlightSegmentConfigurationViaQuery(EntityManagerFactoryScope scope) { - scope.inTransaction( - entityManager -> { - FlightSegmentConfiguration flightSegmentConfiguration = new FlightSegmentConfiguration(); + @Test + void testFetchFlightFromFlightSegmentConfigurationViaQuery(EntityManagerFactoryScope scope) { + scope.inTransaction( + entityManager -> { + FlightSegmentConfiguration flightSegmentConfiguration = new FlightSegmentConfiguration(); - FlightSegment flightSegment = new FlightSegment(); - flightSegment.setSegmentNumber(1); - flightSegment.setConfiguration(flightSegmentConfiguration); + FlightSegment flightSegment = new FlightSegment(); + flightSegment.setSegmentNumber(1); + flightSegment.setConfiguration(flightSegmentConfiguration); - Flight flight = new Flight(); - flight.setId(1); - flight.setSegments(new ArrayList<>()); - flight.addSegment(flightSegment); + Flight flight = new Flight(); + flight.setId(1); + flight.setSegments(new ArrayList<>()); + flight.addSegment(flightSegment); - entityManager.persist(flight); - entityManager.flush(); - entityManager.clear(); - } - ); + entityManager.persist(flight); + entityManager.flush(); + entityManager.clear(); + } + ); - scope.inTransaction( - entityManager -> { - FlightSegmentConfigurationId id = new FlightSegmentConfigurationId(new FlightSegmentId(1, 1)); - FlightSegmentConfiguration configuration = entityManager - .createQuery("from FlightSegmentConfiguration where id = :id", FlightSegmentConfiguration.class) - .setParameter("id", id) - .getSingleResult(); - assertNotNull(configuration); - assertEquals(1, configuration.getSegment().getFlight().getId()); - assertNotNull(configuration.getSegment().getConfiguration()); - } - ); - } + scope.inTransaction( + entityManager -> { + FlightSegmentConfigurationId id = new FlightSegmentConfigurationId(new FlightSegmentId(1, 1)); + FlightSegmentConfiguration configuration = entityManager + .createQuery("from FlightSegmentConfiguration where id = :id", FlightSegmentConfiguration.class) + .setParameter("id", id) + .getSingleResult(); + assertNotNull(configuration); + assertEquals(1, configuration.getSegment().getFlight().getId()); + assertNotNull(configuration.getSegment().getConfiguration()); + } + ); + } - @Test - void testFetchFlightFromFreight(EntityManagerFactoryScope scope) { - scope.inTransaction( - entityManager -> { - FlightSegment flightSegment = new FlightSegment(); - flightSegment.setSegmentNumber(1); + @Test + void testFetchFlightFromFreight(EntityManagerFactoryScope scope) { + scope.inTransaction( + entityManager -> { + FlightSegment flightSegment = new FlightSegment(); + flightSegment.setSegmentNumber(1); - Flight flight = new Flight(); - flight.setId(1); - flight.setSegments(new ArrayList<>()); - flight.addSegment(flightSegment); + Flight flight = new Flight(); + flight.setId(1); + flight.setSegments(new ArrayList<>()); + flight.addSegment(flightSegment); - entityManager.persist(flight); + entityManager.persist(flight); - Freight freight = new Freight(); - freight.setFreightNumber(1); - freight.setFlightSegment(flightSegment); + Freight freight = new Freight(); + freight.setFreightNumber(1); + freight.setFlightSegment(flightSegment); - entityManager.persist(freight); + entityManager.persist(freight); - entityManager.flush(); - entityManager.clear(); - } - ); + entityManager.flush(); + entityManager.clear(); + } + ); - scope.inTransaction( - entityManager -> { - Freight freight = entityManager.find(Freight.class, 1); - assertNotNull(freight); - assertEquals(1, freight.getFlightSegment().getFlight().getId()); - } - ); - } + scope.inTransaction( + entityManager -> { + Freight freight = entityManager.find(Freight.class, 1); + assertNotNull(freight); + assertEquals(1, freight.getFlightSegment().getFlight().getId()); + } + ); + } - @AfterEach - void cleanUp(EntityManagerFactoryScope scope) { - scope.inTransaction( - entityManager -> { - entityManager.createQuery("delete from Freight").executeUpdate(); - entityManager.createQuery("delete from FlightSegmentConfiguration").executeUpdate(); - entityManager.createQuery("delete from FlightSegment").executeUpdate(); - entityManager.createQuery("delete from Flight").executeUpdate(); - } - ); - } + @AfterEach + void cleanUp(EntityManagerFactoryScope scope) { + scope.inTransaction( + entityManager -> { + entityManager.createQuery("delete from Freight").executeUpdate(); + entityManager.createQuery("delete from FlightSegmentConfiguration").executeUpdate(); + entityManager.createQuery("delete from FlightSegment").executeUpdate(); + entityManager.createQuery("delete from Flight").executeUpdate(); + } + ); + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cid/HierarchicalCompositeIdMaxDepthTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cid/HierarchicalCompositeIdMaxDepthTest.java index 2d8d5bc01b..70c798175e 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cid/HierarchicalCompositeIdMaxDepthTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cid/HierarchicalCompositeIdMaxDepthTest.java @@ -19,181 +19,181 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; @Jpa( - annotatedClasses = { - Flight.class, - FlightSegment.class, - FlightSegmentConfiguration.class, - Freight.class - }, - properties = @Setting(name = AvailableSettings.MAX_FETCH_DEPTH, value = "0") + annotatedClasses = { + Flight.class, + FlightSegment.class, + FlightSegmentConfiguration.class, + Freight.class + }, + properties = @Setting(name = AvailableSettings.MAX_FETCH_DEPTH, value = "0") ) public class HierarchicalCompositeIdMaxDepthTest { - @Test - void testFetchFlightSegmentFromFlight(EntityManagerFactoryScope scope) { - scope.inTransaction( - entityManager -> { - FlightSegment flightSegment = new FlightSegment(); - flightSegment.setSegmentNumber(1); + @Test + void testFetchFlightSegmentFromFlight(EntityManagerFactoryScope scope) { + scope.inTransaction( + entityManager -> { + FlightSegment flightSegment = new FlightSegment(); + flightSegment.setSegmentNumber(1); - Flight flight = new Flight(); - flight.setId(1); - flight.setSegments(new ArrayList<>()); - flight.addSegment(flightSegment); + Flight flight = new Flight(); + flight.setId(1); + flight.setSegments(new ArrayList<>()); + flight.addSegment(flightSegment); - entityManager.persist(flight); - entityManager.flush(); - entityManager.clear(); - } - ); + entityManager.persist(flight); + entityManager.flush(); + entityManager.clear(); + } + ); - scope.inTransaction( - entityManager -> { - Flight flight = entityManager.find(Flight.class, 1); - assertNotNull(flight); - assertEquals(1, flight.getSegments().get(0).getSegmentNumber()); - } - ); - } + scope.inTransaction( + entityManager -> { + Flight flight = entityManager.find(Flight.class, 1); + assertNotNull(flight); + assertEquals(1, flight.getSegments().get(0).getSegmentNumber()); + } + ); + } - @Test - void testFetchFlightFromFlightSegment(EntityManagerFactoryScope scope) { - scope.inTransaction( - entityManager -> { - FlightSegment flightSegment = new FlightSegment(); - flightSegment.setSegmentNumber(1); + @Test + void testFetchFlightFromFlightSegment(EntityManagerFactoryScope scope) { + scope.inTransaction( + entityManager -> { + FlightSegment flightSegment = new FlightSegment(); + flightSegment.setSegmentNumber(1); - Flight flight = new Flight(); - flight.setId(1); - flight.setSegments(new ArrayList<>()); - flight.addSegment(flightSegment); + Flight flight = new Flight(); + flight.setId(1); + flight.setSegments(new ArrayList<>()); + flight.addSegment(flightSegment); - entityManager.persist(flight); - entityManager.flush(); - entityManager.clear(); - } - ); + entityManager.persist(flight); + entityManager.flush(); + entityManager.clear(); + } + ); - scope.inTransaction( - entityManager -> { - FlightSegment segment = entityManager.find(FlightSegment.class, new FlightSegmentId(1, 1)); - assertNotNull(segment); - assertEquals(1, segment.getFlight().getId()); - } - ); - } + scope.inTransaction( + entityManager -> { + FlightSegment segment = entityManager.find(FlightSegment.class, new FlightSegmentId(1, 1)); + assertNotNull(segment); + assertEquals(1, segment.getFlight().getId()); + } + ); + } - @Test - void testFetchFlightFromFlightSegmentConfiguration(EntityManagerFactoryScope scope) { - scope.inTransaction( - entityManager -> { - FlightSegmentConfiguration flightSegmentConfiguration = new FlightSegmentConfiguration(); + @Test + void testFetchFlightFromFlightSegmentConfiguration(EntityManagerFactoryScope scope) { + scope.inTransaction( + entityManager -> { + FlightSegmentConfiguration flightSegmentConfiguration = new FlightSegmentConfiguration(); - FlightSegment flightSegment = new FlightSegment(); - flightSegment.setSegmentNumber(1); - flightSegment.setConfiguration(flightSegmentConfiguration); + FlightSegment flightSegment = new FlightSegment(); + flightSegment.setSegmentNumber(1); + flightSegment.setConfiguration(flightSegmentConfiguration); - Flight flight = new Flight(); - flight.setId(1); - flight.setSegments(new ArrayList<>()); - flight.addSegment(flightSegment); + Flight flight = new Flight(); + flight.setId(1); + flight.setSegments(new ArrayList<>()); + flight.addSegment(flightSegment); - entityManager.persist(flight); - entityManager.flush(); - entityManager.clear(); - } - ); + entityManager.persist(flight); + entityManager.flush(); + entityManager.clear(); + } + ); - scope.inTransaction( - entityManager -> { - FlightSegmentConfigurationId id = new FlightSegmentConfigurationId(new FlightSegmentId(1, 1)); - FlightSegmentConfiguration configuration = entityManager.find(FlightSegmentConfiguration.class, id); - assertNotNull(configuration); - assertEquals(1, configuration.getSegment().getFlight().getId()); - assertNotNull(configuration.getSegment().getConfiguration()); - } - ); - } + scope.inTransaction( + entityManager -> { + FlightSegmentConfigurationId id = new FlightSegmentConfigurationId(new FlightSegmentId(1, 1)); + FlightSegmentConfiguration configuration = entityManager.find(FlightSegmentConfiguration.class, id); + assertNotNull(configuration); + assertEquals(1, configuration.getSegment().getFlight().getId()); + assertNotNull(configuration.getSegment().getConfiguration()); + } + ); + } - @Test - void testFetchFlightFromFlightSegmentConfigurationViaQuery(EntityManagerFactoryScope scope) { - scope.inTransaction( - entityManager -> { - FlightSegmentConfiguration flightSegmentConfiguration = new FlightSegmentConfiguration(); + @Test + void testFetchFlightFromFlightSegmentConfigurationViaQuery(EntityManagerFactoryScope scope) { + scope.inTransaction( + entityManager -> { + FlightSegmentConfiguration flightSegmentConfiguration = new FlightSegmentConfiguration(); - FlightSegment flightSegment = new FlightSegment(); - flightSegment.setSegmentNumber(1); - flightSegment.setConfiguration(flightSegmentConfiguration); + FlightSegment flightSegment = new FlightSegment(); + flightSegment.setSegmentNumber(1); + flightSegment.setConfiguration(flightSegmentConfiguration); - Flight flight = new Flight(); - flight.setId(1); - flight.setSegments(new ArrayList<>()); - flight.addSegment(flightSegment); + Flight flight = new Flight(); + flight.setId(1); + flight.setSegments(new ArrayList<>()); + flight.addSegment(flightSegment); - entityManager.persist(flight); - entityManager.flush(); - entityManager.clear(); - } - ); + entityManager.persist(flight); + entityManager.flush(); + entityManager.clear(); + } + ); - scope.inTransaction( - entityManager -> { - FlightSegmentConfigurationId id = new FlightSegmentConfigurationId(new FlightSegmentId(1, 1)); - FlightSegmentConfiguration configuration = entityManager - .createQuery("from FlightSegmentConfiguration where id = :id", FlightSegmentConfiguration.class) - .setParameter("id", id) - .getSingleResult(); - assertNotNull(configuration); - assertEquals(1, configuration.getSegment().getFlight().getId()); - assertNotNull(configuration.getSegment().getConfiguration()); - } - ); - } + scope.inTransaction( + entityManager -> { + FlightSegmentConfigurationId id = new FlightSegmentConfigurationId(new FlightSegmentId(1, 1)); + FlightSegmentConfiguration configuration = entityManager + .createQuery("from FlightSegmentConfiguration where id = :id", FlightSegmentConfiguration.class) + .setParameter("id", id) + .getSingleResult(); + assertNotNull(configuration); + assertEquals(1, configuration.getSegment().getFlight().getId()); + assertNotNull(configuration.getSegment().getConfiguration()); + } + ); + } - @Test - void testFetchFlightFromFreight(EntityManagerFactoryScope scope) { - scope.inTransaction( - entityManager -> { - FlightSegment flightSegment = new FlightSegment(); - flightSegment.setSegmentNumber(1); + @Test + void testFetchFlightFromFreight(EntityManagerFactoryScope scope) { + scope.inTransaction( + entityManager -> { + FlightSegment flightSegment = new FlightSegment(); + flightSegment.setSegmentNumber(1); - Flight flight = new Flight(); - flight.setId(1); - flight.setSegments(new ArrayList<>()); - flight.addSegment(flightSegment); + Flight flight = new Flight(); + flight.setId(1); + flight.setSegments(new ArrayList<>()); + flight.addSegment(flightSegment); - entityManager.persist(flight); + entityManager.persist(flight); - Freight freight = new Freight(); - freight.setFreightNumber(1); - freight.setFlightSegment(flightSegment); + Freight freight = new Freight(); + freight.setFreightNumber(1); + freight.setFlightSegment(flightSegment); - entityManager.persist(freight); + entityManager.persist(freight); - entityManager.flush(); - entityManager.clear(); - } - ); + entityManager.flush(); + entityManager.clear(); + } + ); - scope.inTransaction( - entityManager -> { - Freight freight = entityManager.find(Freight.class, 1); - assertNotNull(freight); - assertEquals(1, freight.getFlightSegment().getFlight().getId()); - } - ); - } + scope.inTransaction( + entityManager -> { + Freight freight = entityManager.find(Freight.class, 1); + assertNotNull(freight); + assertEquals(1, freight.getFlightSegment().getFlight().getId()); + } + ); + } - @AfterEach - void cleanUp(EntityManagerFactoryScope scope) { - scope.inTransaction( - entityManager -> { - entityManager.createQuery("delete from Freight").executeUpdate(); - entityManager.createQuery("delete from FlightSegmentConfiguration").executeUpdate(); - entityManager.createQuery("delete from FlightSegment").executeUpdate(); - entityManager.createQuery("delete from Flight").executeUpdate(); - } - ); - } + @AfterEach + void cleanUp(EntityManagerFactoryScope scope) { + scope.inTransaction( + entityManager -> { + entityManager.createQuery("delete from Freight").executeUpdate(); + entityManager.createQuery("delete from FlightSegmentConfiguration").executeUpdate(); + entityManager.createQuery("delete from FlightSegment").executeUpdate(); + entityManager.createQuery("delete from Flight").executeUpdate(); + } + ); + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cid/Order.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cid/Order.java index 13819cc479..f009dd5628 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cid/Order.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cid/Order.java @@ -17,6 +17,6 @@ import jakarta.persistence.Table; @Table(name = "OrderTableFoobar") public class Order { @Id - @GeneratedValue - public Integer id; + @GeneratedValue + public Integer id; } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cid/OrderLine.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cid/OrderLine.java index 010dc57977..8db8295301 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cid/OrderLine.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cid/OrderLine.java @@ -15,8 +15,8 @@ import jakarta.persistence.IdClass; @Entity @IdClass(OrderLinePk.class) public class OrderLine { - @Id - public Order order; - @Id - public Product product; + @Id + public Order order; + @Id + public Product product; } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cid/OrderLinePk.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cid/OrderLinePk.java index 92b0c720b8..38b4d80e28 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cid/OrderLinePk.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cid/OrderLinePk.java @@ -14,9 +14,9 @@ import jakarta.persistence.ManyToOne; */ public class OrderLinePk implements Serializable { @ManyToOne - @JoinColumn(name = "foo", nullable = false) - public Order order; + @JoinColumn(name = "foo", nullable = false) + public Order order; @ManyToOne - @JoinColumn(name = "bar", nullable = false) - public Product product; + @JoinColumn(name = "bar", nullable = false) + public Product product; } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cid/Product.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cid/Product.java index d03185b778..4a7b32c6aa 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cid/Product.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cid/Product.java @@ -14,5 +14,5 @@ import jakarta.persistence.Id; @Entity public class Product { @Id - public String name; + public String name; } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cid/TvMagazin.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cid/TvMagazin.java index 218853234b..fe0d874d59 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cid/TvMagazin.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cid/TvMagazin.java @@ -26,6 +26,6 @@ public class TvMagazin { @EmbeddedId public TvMagazinPk id; @Temporal(TemporalType.TIME) - @Column(name="`time`") + @Column(name="`time`") Date time; } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cid/TvProgram.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cid/TvProgram.java index 7a848fe20c..6cb762ec52 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cid/TvProgram.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cid/TvProgram.java @@ -33,7 +33,7 @@ public class TvProgram { public TvMagazinPk id; @Temporal( TemporalType.TIME ) - @Column(name="`time`") + @Column(name="`time`") Date time; @Column( name = "TXT", table = "TV_PROGRAM_EXT" ) diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cid/TvProgramIdClass.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cid/TvProgramIdClass.java index acf2a9b84b..14488c0350 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cid/TvProgramIdClass.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cid/TvProgramIdClass.java @@ -32,7 +32,7 @@ public class TvProgramIdClass { public Presenter presenter; @Temporal( TemporalType.TIME ) - @Column(name="`time`") + @Column(name="`time`") Date time; @Column( name = "TXT", table = "TV_PROGRAM_IDCLASS" ) diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collate/MySQLCollateTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collate/MySQLCollateTest.java index c184c04204..d8071064ab 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collate/MySQLCollateTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collate/MySQLCollateTest.java @@ -27,21 +27,21 @@ import org.junit.jupiter.api.Test; @SkipForDialect(dialectClass = TiDBDialect.class) public class MySQLCollateTest { - @Test void test(SessionFactoryScope scope) { - scope.inTransaction(session -> session.persist(new Message("Hello, world!"))); - } + @Test void test(SessionFactoryScope scope) { + scope.inTransaction(session -> session.persist(new Message("Hello, world!"))); + } - @Entity(name = "msgs") - static class Message { - @Id @GeneratedValue - Long id; - @Basic(optional = false) - @Collate("utf8mb4_spanish2_ci") - @Column(length = 200) - String text; + @Entity(name = "msgs") + static class Message { + @Id @GeneratedValue + Long id; + @Basic(optional = false) + @Collate("utf8mb4_spanish2_ci") + @Column(length = 200) + String text; - public Message(String text) { - this.text = text; - } - } + public Message(String text) { + this.text = text; + } + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collate/PostgresCollateTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collate/PostgresCollateTest.java index 6c7805412e..23ce64d372 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collate/PostgresCollateTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collate/PostgresCollateTest.java @@ -24,21 +24,21 @@ import org.junit.jupiter.api.Test; @RequiresDialect(PostgreSQLDialect.class) public class PostgresCollateTest { - @Test void test(SessionFactoryScope scope) { - scope.inTransaction(session -> session.persist(new Message("Hello, world!"))); - } + @Test void test(SessionFactoryScope scope) { + scope.inTransaction(session -> session.persist(new Message("Hello, world!"))); + } - @Entity(name = "msgs") - static class Message { - @Id @GeneratedValue - Long id; - @Basic(optional = false) - @Collate("en_US") - @Column(length = 200) - String text; + @Entity(name = "msgs") + static class Message { + @Id @GeneratedValue + Long id; + @Basic(optional = false) + @Collate("en_US") + @Column(length = 200) + String text; - public Message(String text) { - this.text = text; - } - } + public Message(String text) { + this.text = text; + } + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/Boy.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/Boy.java index e19ae7243c..e7fc3bd85b 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/Boy.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/Boy.java @@ -152,7 +152,7 @@ public class Boy { @ElementCollection @Enumerated(EnumType.STRING) - @Column(name = "`characters`") + @Column(name = "`characters`") public Set getCharacters() { return characters; } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/EmbeddableCollectionElementWithLazyManyToOneTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/EmbeddableCollectionElementWithLazyManyToOneTest.java index 8626980107..4e853375a7 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/EmbeddableCollectionElementWithLazyManyToOneTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/EmbeddableCollectionElementWithLazyManyToOneTest.java @@ -137,8 +137,8 @@ public class EmbeddableCollectionElementWithLazyManyToOneTest { session -> assertFalse( session.createQuery( "from Parent p join p.containedChildren c where c.child.id is not null", Parent.class ) - .getResultList() - .isEmpty() ) + .getResultList() + .isEmpty() ) ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/indexedCollection/Sale.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/indexedCollection/Sale.java index 2e107fbbb9..17aecd07fd 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/indexedCollection/Sale.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/indexedCollection/Sale.java @@ -30,10 +30,10 @@ import jakarta.persistence.JoinTable; public class Sale { @Id @GeneratedValue private Integer id; @ElementCollection - @JoinTable( - name = "contact", - joinColumns = @JoinColumn(name = "n_key_person")) - @CollectionId( column = @Column(name = "n_key_contact"), generator = "increment" ) + @JoinTable( + name = "contact", + joinColumns = @JoinColumn(name = "n_key_person")) + @CollectionId( column = @Column(name = "n_key_contact"), generator = "increment" ) @CollectionIdJdbcTypeCode( Types.BIGINT ) private List contacts = new ArrayList(); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/configuration/ConfigurationTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/configuration/ConfigurationTest.java index 5a0e7089a2..de9faab70a 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/configuration/ConfigurationTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/configuration/ConfigurationTest.java @@ -17,7 +17,7 @@ import org.junit.Test; * @author Emmanuel Bernard */ public class ConfigurationTest { - @Test + @Test public void testMixPackageAndResourceOrdering() throws Exception { try (BootstrapServiceRegistry serviceRegistry = new BootstrapServiceRegistryBuilder().build()) { Configuration config = new Configuration( serviceRegistry ); @@ -25,7 +25,7 @@ public class ConfigurationTest { config.addPackage( "org.hibernate.orm/test.annotations.configuration" ); } catch( Exception e ) { - Assert.fail( "Processing package first when ORM.xml is used should not fail" ); + Assert.fail( "Processing package first when ORM.xml is used should not fail" ); } } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/dataTypes/BasicOperationsTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/dataTypes/BasicOperationsTest.java index dcc061e6f9..ef34f34440 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/dataTypes/BasicOperationsTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/dataTypes/BasicOperationsTest.java @@ -128,10 +128,10 @@ public class BasicOperationsTest { String columnNamePattern = generateFinalNamePattern( meta, columnName ); ResultSet columnInfo = meta.getColumns( null, null, tableNamePattern, columnNamePattern ); - s.getJdbcCoordinator().getLogicalConnection().getResourceRegistry().register( columnInfo, columnInfo.getStatement() ); + s.getJdbcCoordinator().getLogicalConnection().getResourceRegistry().register( columnInfo, columnInfo.getStatement() ); assertTrue( columnInfo.next() ); int dataType = columnInfo.getInt( "DATA_TYPE" ); - s.getJdbcCoordinator().getLogicalConnection().getResourceRegistry().release( columnInfo, columnInfo.getStatement() ); + s.getJdbcCoordinator().getLogicalConnection().getResourceRegistry().release( columnInfo, columnInfo.getStatement() ); assertEquals( JdbcTypeNameMapper.getTypeName( expectedJdbcTypeCode ), JdbcTypeNameMapper.getTypeName( dataType ), diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/derivedidentities/bidirectional/CompositeIdDerivedIdWithIdClassTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/derivedidentities/bidirectional/CompositeIdDerivedIdWithIdClassTest.java index 20299b9cb0..c506ead111 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/derivedidentities/bidirectional/CompositeIdDerivedIdWithIdClassTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/derivedidentities/bidirectional/CompositeIdDerivedIdWithIdClassTest.java @@ -74,7 +74,7 @@ public class CompositeIdDerivedIdWithIdClassTest { // assertion for HHH-11274 - checking for exception final Object identifier = new PersistenceUnitUtilImpl( scope.getSessionFactory() ).getIdentifier( transientCart.getLineItems() - .get( 0 ) ); + .get( 0 ) ); // merge ID with transient many-to-one scope.inTransaction( diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/derivedidentities/bidirectional/DerivedIdentityWithBidirectionalAssociationTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/derivedidentities/bidirectional/DerivedIdentityWithBidirectionalAssociationTest.java index c32ab4b921..30ae93508c 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/derivedidentities/bidirectional/DerivedIdentityWithBidirectionalAssociationTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/derivedidentities/bidirectional/DerivedIdentityWithBidirectionalAssociationTest.java @@ -57,6 +57,6 @@ public class DerivedIdentityWithBidirectionalAssociationTest { private T getDerivedClassById(Employee e, Session s, Class clazz) { return clazz.cast( s.createQuery( "from " + clazz.getName() + " d where d.emp.empId = :empId" ) - .setParameter( "empId", e.empId ).uniqueResult() ); + .setParameter( "empId", e.empId ).uniqueResult() ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/derivedidentities/e1/b/specjmapid/Customer.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/derivedidentities/e1/b/specjmapid/Customer.java index 9bc70db07c..a4134f81e5 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/derivedidentities/e1/b/specjmapid/Customer.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/derivedidentities/e1/b/specjmapid/Customer.java @@ -182,7 +182,7 @@ public class Customer implements Serializable { } public CustomerInventory addInventory(Item item, int quantity, - BigDecimal totalValue) { + BigDecimal totalValue) { CustomerInventory inventory = new CustomerInventory( this, item, diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/derivedidentities/e1/b/specjmapid/IdMapManyToOneSpecjTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/derivedidentities/e1/b/specjmapid/IdMapManyToOneSpecjTest.java index 04e0f995e2..2bfd30095c 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/derivedidentities/e1/b/specjmapid/IdMapManyToOneSpecjTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/derivedidentities/e1/b/specjmapid/IdMapManyToOneSpecjTest.java @@ -106,7 +106,7 @@ public class IdMapManyToOneSpecjTest extends BaseNonConfigCoreFunctionalTestCase Customer customer2 = new Customer( - "foo2", "bar2", "contact12", "1002", new BigDecimal( 10002 ), new BigDecimal( 10002 ), new BigDecimal( 1000 )); + "foo2", "bar2", "contact12", "1002", new BigDecimal( 10002 ), new BigDecimal( 10002 ), new BigDecimal( 1000 )); customer2.setId(2); s.persist(customer2); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/derivedidentities/e1/b/specjmapid/lazy/CompositeKeyDeleteTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/derivedidentities/e1/b/specjmapid/lazy/CompositeKeyDeleteTest.java index c1b947d937..30cd2ffa66 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/derivedidentities/e1/b/specjmapid/lazy/CompositeKeyDeleteTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/derivedidentities/e1/b/specjmapid/lazy/CompositeKeyDeleteTest.java @@ -19,91 +19,91 @@ import org.junit.Test; public class CompositeKeyDeleteTest extends BaseCoreFunctionalTestCase { - @Override - protected String getBaseForMappings() { - return ""; - } - - @Override - public String[] getMappings() { - return new String[] { "org/hibernate/orm/test/annotations/derivedidentities/e1/b/specjmapid/lazy/order_orm.xml" }; - } - - public CompositeKeyDeleteTest() { - System.setProperty( "hibernate.enable_specj_proprietary_syntax", "true" ); - } - /** - * This test checks to make sure the non null column is not updated with a - * null value when a CustomerInventory is removed. - */ - @Test - public void testRemove() { - Session s = openSession(); - Transaction tx = s.beginTransaction(); - - CustomerTwo c1 = new CustomerTwo( - "foo", "bar", "contact1", "100", new BigDecimal( 1000 ), new BigDecimal( 1000 ), new BigDecimal( 1000 ) - ); - - s.persist( c1 ); - s.flush(); - s.clear(); - - Item boat = new Item(); - boat.setId( "1" ); - boat.setName( "cruiser" ); - boat.setPrice( new BigDecimal( 500 ) ); - boat.setDescription( "a boat" ); - boat.setCategory( 42 ); - - s.persist( boat ); - - - Item house = new Item(); - house.setId( "2" ); - house.setName( "blada" ); - house.setPrice( new BigDecimal( 5000 ) ); - house.setDescription( "a house" ); - house.setCategory( 74 ); - - s.persist( house ); - s.flush(); - s.clear(); - - c1.addInventory( boat, 10, new BigDecimal( 5000 ) ); - - c1.addInventory( house, 100, new BigDecimal( 50000 ) ); - s.merge( c1 ); - Integer id = c1.getId(); - tx.commit(); - s.close(); - - s = openSession(); - tx = s.beginTransaction(); - - CustomerTwo c12 = ( CustomerTwo) s.createQuery( "select c from CustomerTwo c" ).uniqueResult(); - Assert.assertNotNull(c12); - List list = c12.getInventories(); - Assert.assertNotNull(list); - Assert.assertEquals(2, list.size()); - CustomerInventoryTwo ci = list.get(1); - list.remove(ci); - s.remove(ci); - s.flush(); - - tx.commit();//fail - s.close(); - - } - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - CustomerTwo.class, - CustomerInventoryTwo.class, - CustomerInventoryTwoPK.class, - Item.class - - }; - } +@Override +protected String getBaseForMappings() { + return ""; +} + +@Override +public String[] getMappings() { + return new String[] { "org/hibernate/orm/test/annotations/derivedidentities/e1/b/specjmapid/lazy/order_orm.xml" }; +} + +public CompositeKeyDeleteTest() { + System.setProperty( "hibernate.enable_specj_proprietary_syntax", "true" ); +} +/** + * This test checks to make sure the non null column is not updated with a + * null value when a CustomerInventory is removed. + */ +@Test +public void testRemove() { + Session s = openSession(); + Transaction tx = s.beginTransaction(); + + CustomerTwo c1 = new CustomerTwo( + "foo", "bar", "contact1", "100", new BigDecimal( 1000 ), new BigDecimal( 1000 ), new BigDecimal( 1000 ) + ); + + s.persist( c1 ); + s.flush(); + s.clear(); + + Item boat = new Item(); + boat.setId( "1" ); + boat.setName( "cruiser" ); + boat.setPrice( new BigDecimal( 500 ) ); + boat.setDescription( "a boat" ); + boat.setCategory( 42 ); + + s.persist( boat ); + + + Item house = new Item(); + house.setId( "2" ); + house.setName( "blada" ); + house.setPrice( new BigDecimal( 5000 ) ); + house.setDescription( "a house" ); + house.setCategory( 74 ); + + s.persist( house ); + s.flush(); + s.clear(); + + c1.addInventory( boat, 10, new BigDecimal( 5000 ) ); + + c1.addInventory( house, 100, new BigDecimal( 50000 ) ); + s.merge( c1 ); + Integer id = c1.getId(); + tx.commit(); + s.close(); + + s = openSession(); + tx = s.beginTransaction(); + + CustomerTwo c12 = ( CustomerTwo) s.createQuery( "select c from CustomerTwo c" ).uniqueResult(); + Assert.assertNotNull(c12); + List list = c12.getInventories(); + Assert.assertNotNull(list); + Assert.assertEquals(2, list.size()); + CustomerInventoryTwo ci = list.get(1); + list.remove(ci); + s.remove(ci); + s.flush(); + + tx.commit();//fail + s.close(); + +} + +@Override +protected Class[] getAnnotatedClasses() { + return new Class[] { + CustomerTwo.class, + CustomerInventoryTwo.class, + CustomerInventoryTwoPK.class, + Item.class + + }; +} } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/derivedidentities/e1/b/specjmapid/lazy/CustomerInventoryTwo.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/derivedidentities/e1/b/specjmapid/lazy/CustomerInventoryTwo.java index 26a98137ef..a96047069e 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/derivedidentities/e1/b/specjmapid/lazy/CustomerInventoryTwo.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/derivedidentities/e1/b/specjmapid/lazy/CustomerInventoryTwo.java @@ -33,98 +33,98 @@ import org.hibernate.orm.test.annotations.derivedidentities.e1.b.specjmapid.Item @Table(name = "O_CUSTINVENTORY") @IdClass(CustomerInventoryTwoPK.class) public class CustomerInventoryTwo implements Serializable, - Comparator { + Comparator { - @Id - @TableGenerator(name = "inventory", table = "U_SEQUENCES", pkColumnName = "S_ID", valueColumnName = "S_NEXTNUM", pkColumnValue = "inventory", allocationSize = 1000) - @GeneratedValue(strategy = GenerationType.TABLE, generator = "inventory") - @Column(name = "CI_ID") - private Integer id; +@Id +@TableGenerator(name = "inventory", table = "U_SEQUENCES", pkColumnName = "S_ID", valueColumnName = "S_NEXTNUM", pkColumnValue = "inventory", allocationSize = 1000) +@GeneratedValue(strategy = GenerationType.TABLE, generator = "inventory") +@Column(name = "CI_ID") +private Integer id; - @Id - @Column(name = "CI_CUSTOMERID", insertable = false, updatable = false) - private int custId; +@Id +@Column(name = "CI_CUSTOMERID", insertable = false, updatable = false) +private int custId; - @ManyToOne(cascade = CascadeType.MERGE) - @JoinColumn(name = "CI_CUSTOMERID", nullable = false) - private CustomerTwo customer; +@ManyToOne(cascade = CascadeType.MERGE) +@JoinColumn(name = "CI_CUSTOMERID", nullable = false) +private CustomerTwo customer; - @ManyToOne(cascade = CascadeType.MERGE) - @JoinColumn(name = "CI_ITEMID") - private Item vehicle; +@ManyToOne(cascade = CascadeType.MERGE) +@JoinColumn(name = "CI_ITEMID") +private Item vehicle; - @Column(name = "CI_VALUE") - private BigDecimal totalCost; +@Column(name = "CI_VALUE") +private BigDecimal totalCost; - @Column(name = "CI_QUANTITY") - private int quantity; +@Column(name = "CI_QUANTITY") +private int quantity; - @Version - @Column(name = "CI_VERSION") - private int version; +@Version +@Column(name = "CI_VERSION") +private int version; - protected CustomerInventoryTwo() { - } +protected CustomerInventoryTwo() { +} - CustomerInventoryTwo(CustomerTwo customer, Item vehicle, int quantity, - BigDecimal totalValue) { - this.customer = customer; - this.vehicle = vehicle; - this.quantity = quantity; - this.totalCost = totalValue; - } +CustomerInventoryTwo(CustomerTwo customer, Item vehicle, int quantity, + BigDecimal totalValue) { + this.customer = customer; + this.vehicle = vehicle; + this.quantity = quantity; + this.totalCost = totalValue; +} - public Item getVehicle() { - return vehicle; - } +public Item getVehicle() { + return vehicle; +} - public BigDecimal getTotalCost() { - return totalCost; - } +public BigDecimal getTotalCost() { + return totalCost; +} - public int getQuantity() { - return quantity; - } +public int getQuantity() { + return quantity; +} - public Integer getId() { - return id; - } +public Integer getId() { + return id; +} - public CustomerTwo getCustomer() { - return customer; - } +public CustomerTwo getCustomer() { + return customer; +} - public int getCustId() { - return custId; - } +public int getCustId() { + return custId; +} - public int getVersion() { - return version; - } +public int getVersion() { + return version; +} - public int compare(CustomerInventoryTwo cdb1, CustomerInventoryTwo cdb2) { - return cdb1.id.compareTo(cdb2.id); - } +public int compare(CustomerInventoryTwo cdb1, CustomerInventoryTwo cdb2) { + return cdb1.id.compareTo(cdb2.id); +} - @Override - public boolean equals(Object obj) { - if (obj == this) { - return true; - } - if (obj == null || !(obj instanceof CustomerInventoryTwo)) { - return false; - } - if (this.id == ((CustomerInventoryTwo) obj).id) { - return true; - } - if (this.id != null && ((CustomerInventoryTwo) obj).id == null) { - return false; - } - if (this.id == null && ((CustomerInventoryTwo) obj).id != null) { - return false; - } +@Override +public boolean equals(Object obj) { + if (obj == this) { + return true; + } + if (obj == null || !(obj instanceof CustomerInventoryTwo)) { + return false; + } + if (this.id == ((CustomerInventoryTwo) obj).id) { + return true; + } + if (this.id != null && ((CustomerInventoryTwo) obj).id == null) { + return false; + } + if (this.id == null && ((CustomerInventoryTwo) obj).id != null) { + return false; + } - return this.id.equals(((CustomerInventoryTwo) obj).id); - } + return this.id.equals(((CustomerInventoryTwo) obj).id); +} } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/derivedidentities/e1/b/specjmapid/lazy/CustomerInventoryTwoPK.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/derivedidentities/e1/b/specjmapid/lazy/CustomerInventoryTwoPK.java index 040fc5e287..2c5ca6d49b 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/derivedidentities/e1/b/specjmapid/lazy/CustomerInventoryTwoPK.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/derivedidentities/e1/b/specjmapid/lazy/CustomerInventoryTwoPK.java @@ -10,40 +10,40 @@ import java.io.Serializable; public class CustomerInventoryTwoPK implements Serializable { - private Integer id; - private int custId; +private Integer id; +private int custId; - public CustomerInventoryTwoPK() { - } +public CustomerInventoryTwoPK() { +} - public CustomerInventoryTwoPK(Integer id, int custId) { - this.id = id; - this.custId = custId; - } +public CustomerInventoryTwoPK(Integer id, int custId) { + this.id = id; + this.custId = custId; +} - public boolean equals(Object other) { - if ( other == this ) { - return true; - } - if ( other == null || getClass() != other.getClass() ) { - return false; - } - CustomerInventoryTwoPK cip = ( CustomerInventoryTwoPK ) other; - return ( custId == cip.custId && ( id == cip.id || - ( id != null && id.equals( cip.id ) ) ) ); - } +public boolean equals(Object other) { + if ( other == this ) { + return true; + } + if ( other == null || getClass() != other.getClass() ) { + return false; + } + CustomerInventoryTwoPK cip = ( CustomerInventoryTwoPK ) other; + return ( custId == cip.custId && ( id == cip.id || + ( id != null && id.equals( cip.id ) ) ) ); +} - public int hashCode() { - return ( id == null ? 0 : id.hashCode() ) ^ custId; - } +public int hashCode() { + return ( id == null ? 0 : id.hashCode() ) ^ custId; +} - public Integer getId() { - return id; - } +public Integer getId() { + return id; +} - public int getCustId() { - return custId; - } +public int getCustId() { + return custId; +} } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/derivedidentities/e1/b/specjmapid/lazy/CustomerTwo.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/derivedidentities/e1/b/specjmapid/lazy/CustomerTwo.java index c769f2fa3c..fd15dd1a4f 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/derivedidentities/e1/b/specjmapid/lazy/CustomerTwo.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/derivedidentities/e1/b/specjmapid/lazy/CustomerTwo.java @@ -187,7 +187,7 @@ public class CustomerTwo implements Serializable{ } public CustomerInventoryTwo addInventory(Item item, int quantity, - BigDecimal totalValue) { + BigDecimal totalValue) { CustomerInventoryTwo inventory = new CustomerInventoryTwo( this, item, diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/derivedidentities/e1/b2/Item.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/derivedidentities/e1/b2/Item.java index 8603bf665e..d545a03c35 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/derivedidentities/e1/b2/Item.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/derivedidentities/e1/b2/Item.java @@ -17,108 +17,108 @@ import jakarta.persistence.Version; - @NamedQueries( { - @NamedQuery(name = "Item.findByCategory", - query = "SELECT i FROM Item i WHERE i.category=:category ORDER BY i.id")}) - @SuppressWarnings("serial") - @Entity - @Table(name = "O_ITEM") - public class Item implements Serializable - { +@NamedQueries( { + @NamedQuery(name = "Item.findByCategory", + query = "SELECT i FROM Item i WHERE i.category=:category ORDER BY i.id")}) +@SuppressWarnings("serial") +@Entity +@Table(name = "O_ITEM") +public class Item implements Serializable +{ - public static final String QUERY_BY_CATEGORY = "Item.findByCategory"; + public static final String QUERY_BY_CATEGORY = "Item.findByCategory"; - @Id - @Column(name = "I_ID") - private String id; + @Id + @Column(name = "I_ID") + private String id; - @Column(name = "I_NAME") - private String name; + @Column(name = "I_NAME") + private String name; - @Column(name = "I_PRICE") - private BigDecimal price; + @Column(name = "I_PRICE") + private BigDecimal price; - @Column(name = "I_DESC") - private String description; + @Column(name = "I_DESC") + private String description; - @Column(name = "I_DISCOUNT") - private BigDecimal discount; + @Column(name = "I_DISCOUNT") + private BigDecimal discount; - @Column(name = "I_CATEGORY") - private int category; + @Column(name = "I_CATEGORY") + private int category; - @Version - @Column(name = "I_VERSION") - int version; + @Version + @Column(name = "I_VERSION") + int version; - public String getId() { - return id; - } + public String getId() { + return id; + } - public void setId(String i) { - id = i; - } + public void setId(String i) { + id = i; + } - public int getCategory() { - return category; - } + public int getCategory() { + return category; + } - public void setCategory(int category) { - this.category = category; - } + public void setCategory(int category) { + this.category = category; + } - public String getDescription() { - return description; - } + public String getDescription() { + return description; + } - public void setDescription(String description) { - this.description = description; - } + public void setDescription(String description) { + this.description = description; + } - public BigDecimal getDiscount() { - return discount; - } + public BigDecimal getDiscount() { + return discount; + } - public void setDiscount(BigDecimal discount) { - if (discount.doubleValue() < 0 || discount.doubleValue() > 100.0) - throw new IllegalArgumentException(this + " discount " + discount - + " is invalid. Must be between 0.0 and 100.0"); - this.discount = discount; - } + public void setDiscount(BigDecimal discount) { + if (discount.doubleValue() < 0 || discount.doubleValue() > 100.0) + throw new IllegalArgumentException(this + " discount " + discount + + " is invalid. Must be between 0.0 and 100.0"); + this.discount = discount; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - public BigDecimal getPrice() { - return price; - } + public BigDecimal getPrice() { + return price; + } - public void setPrice(BigDecimal price) { - this.price = price; - } + public void setPrice(BigDecimal price) { + this.price = price; + } - public int getVersion() { - return version; - } + public int getVersion() { + return version; + } - @Override - public boolean equals(Object other) { - if (other == null || other.getClass() != this.getClass()) { - return false; - } - if (other == this) { - return true; - } - return id.equals(((Item) other).id); - } + @Override + public boolean equals(Object other) { + if (other == null || other.getClass() != this.getClass()) { + return false; + } + if (other == this) { + return true; + } + return id.equals(((Item) other).id); + } - @Override - public int hashCode() { - return id.hashCode(); - } + @Override + public int hashCode() { + return id.hashCode(); + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/derivedidentities/e2/b/Dependent.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/derivedidentities/e2/b/Dependent.java index ff13ab7467..703622b7be 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/derivedidentities/e2/b/Dependent.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/derivedidentities/e2/b/Dependent.java @@ -22,7 +22,7 @@ public class Dependent { @MapsId("empPK") - @ManyToOne - @JoinColumns( { @JoinColumn(nullable = false), @JoinColumn(nullable = false) }) - Employee emp; + @ManyToOne + @JoinColumns( { @JoinColumn(nullable = false), @JoinColumn(nullable = false) }) + Employee emp; } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/derivedidentities/e4/b/MedicalHistory.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/derivedidentities/e4/b/MedicalHistory.java index 91f689abae..aa1f94674c 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/derivedidentities/e4/b/MedicalHistory.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/derivedidentities/e4/b/MedicalHistory.java @@ -25,7 +25,7 @@ public class MedicalHistory { @MapsId @JoinColumn(name = "FK") - @OneToOne(cascade= CascadeType.PERSIST) + @OneToOne(cascade= CascadeType.PERSIST) Person patient; @Temporal(TemporalType.DATE) diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/duplicatedgenerator/DuplicateTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/duplicatedgenerator/DuplicateTest.java index 0373150312..fc14562fca 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/duplicatedgenerator/DuplicateTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/duplicatedgenerator/DuplicateTest.java @@ -21,7 +21,7 @@ import org.junit.Test; * @author Emmanuel Bernard */ public class DuplicateTest { - @Test + @Test public void testDuplicateEntityName() { Configuration cfg = new Configuration(); cfg.setProperty( Environment.HBM2DDL_AUTO, "create-drop" ); @@ -35,7 +35,7 @@ public class DuplicateTest { cfg.addResource( "org/hibernate/orm/test/annotations/duplicatedgenerator/orm.xml" ); serviceRegistry = ServiceRegistryBuilder.buildServiceRegistry( cfg.getProperties() ); sf = cfg.buildSessionFactory( serviceRegistry ); - Assert.fail( "Should not be able to map the same entity name twice" ); + Assert.fail( "Should not be able to map the same entity name twice" ); } catch (DuplicateMappingException ae) { //success diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/embeddables/Investment.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/embeddables/Investment.java index a051413c70..d1a1c94bdb 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/embeddables/Investment.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/embeddables/Investment.java @@ -17,7 +17,7 @@ public class Investment { private DollarValue amount; private String description; - @Column(name = "`date`") + @Column(name = "`date`") private MyDate date; public DollarValue getAmount() { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/embeddables/collection/AbstractEmbeddableWithManyToManyTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/embeddables/collection/AbstractEmbeddableWithManyToManyTest.java index 024688d640..8312beef5f 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/embeddables/collection/AbstractEmbeddableWithManyToManyTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/embeddables/collection/AbstractEmbeddableWithManyToManyTest.java @@ -25,7 +25,7 @@ public abstract class AbstractEmbeddableWithManyToManyTest { @Test public void test() { try (BootstrapServiceRegistry bsr = new BootstrapServiceRegistryBuilder().build(); - StandardServiceRegistry ssr = ServiceRegistryUtil.serviceRegistryBuilder( bsr ).build()) { + StandardServiceRegistry ssr = ServiceRegistryUtil.serviceRegistryBuilder( bsr ).build()) { MetadataSources metadataSources = new MetadataSources( ssr ); addResources( metadataSources ); addAnnotatedClasses(metadataSources); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/entity/Java5FeaturesTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/entity/Java5FeaturesTest.java index 3f341aec28..1aaa458b0f 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/entity/Java5FeaturesTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/entity/Java5FeaturesTest.java @@ -71,7 +71,7 @@ public class Java5FeaturesTest extends BaseCoreFunctionalTestCase { assertEquals( Starred.OK, bid.getNote() ); assertEquals( Starred.GOOD, bid.getEditorsNote() ); bid = (Bid)s.createQuery( "select b from Bid b where b.note = :note" + - " and b.editorsNote = :editorNote " + + " and b.editorsNote = :editorNote " + " and b.id = :id") .setParameter( "id", bid.getId() ) .setParameter( "note", Starred.OK ) diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/entitynonentity/EntityNonEntityTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/entitynonentity/EntityNonEntityTest.java index ded4f9d977..1480095a1a 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/entitynonentity/EntityNonEntityTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/entitynonentity/EntityNonEntityTest.java @@ -52,7 +52,7 @@ public class EntityNonEntityTest extends BaseCoreFunctionalTestCase { @JiraKey( value = "HHH-9856" ) public void testGetAndFindNonEntityThrowsIllegalArgumentException() { try { - sessionFactory().getMetamodel().locateEntityPersister(Cellular.class); + sessionFactory().getMetamodel().locateEntityPersister(Cellular.class); sessionFactory().getRuntimeMetamodels().getMappingMetamodel().getEntityDescriptor( Cellular.class ); } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/fetchprofile/FetchProfileTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/fetchprofile/FetchProfileTest.java index 98ed738f83..c04fdd033f 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/fetchprofile/FetchProfileTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/fetchprofile/FetchProfileTest.java @@ -40,13 +40,13 @@ public class FetchProfileTest extends BaseUnitTestCase { private ServiceRegistry serviceRegistry; @Before - public void setUp() { + public void setUp() { serviceRegistry = ServiceRegistryBuilder.buildServiceRegistry( Environment.getProperties() ); } @After - public void tearDown() { - if (serviceRegistry != null) ServiceRegistryBuilder.destroy(serviceRegistry); + public void tearDown() { + if (serviceRegistry != null) ServiceRegistryBuilder.destroy(serviceRegistry); } @Test @@ -83,7 +83,7 @@ public class FetchProfileTest extends BaseUnitTestCase { fail(); } catch ( MappingException e ) { - log.trace("success"); + log.trace("success"); } finally { ServiceRegistry metaServiceRegistry = metadataSources.getServiceRegistry(); @@ -105,7 +105,7 @@ public class FetchProfileTest extends BaseUnitTestCase { fail(); } catch ( MappingException e ) { - log.trace("success"); + log.trace("success"); } finally { ServiceRegistry metaServiceRegistry = metadataSources.getServiceRegistry(); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/fkcircularity/FkCircularityTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/fkcircularity/FkCircularityTest.java index 1996a3e275..04449c62a1 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/fkcircularity/FkCircularityTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/fkcircularity/FkCircularityTest.java @@ -21,7 +21,7 @@ import org.junit.jupiter.api.Test; */ public class FkCircularityTest { - @Test + @Test public void testJoinedSublcassesInPK() { MetadataSources metadataSources = new MetadataSources( ServiceRegistryUtil.serviceRegistry() ) .addAnnotatedClass(A.class) @@ -39,7 +39,7 @@ public class FkCircularityTest { } } - @Test + @Test public void testDeepJoinedSuclassesHierachy() { MetadataSources metadataSources = new MetadataSources( ServiceRegistryUtil.serviceRegistry() ) .addAnnotatedClass(ClassA.class) diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/id/entities/PlanetCheatSheet.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/id/entities/PlanetCheatSheet.java index fa102b276e..2a1ea40ec2 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/id/entities/PlanetCheatSheet.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/id/entities/PlanetCheatSheet.java @@ -73,18 +73,18 @@ public class PlanetCheatSheet { */ public String toString() { - final String TAB = " "; + final String TAB = " "; - String retValue = ""; + String retValue = ""; - retValue = "PlanetCheatSheet ( " - + super.toString() + TAB - + "planet = " + this.planet + TAB - + "mass = " + this.mass + TAB - + "radius = " + this.radius + TAB - + "numberOfInhabitants = " + this.numberOfInhabitants + TAB - + " )"; + retValue = "PlanetCheatSheet ( " + + super.toString() + TAB + + "planet = " + this.planet + TAB + + "mass = " + this.mass + TAB + + "radius = " + this.radius + TAB + + "numberOfInhabitants = " + this.numberOfInhabitants + TAB + + " )"; - return retValue; + return retValue; } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/id/entities/PointyTooth.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/id/entities/PointyTooth.java index aa8630c310..2d4084687e 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/id/entities/PointyTooth.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/id/entities/PointyTooth.java @@ -32,7 +32,7 @@ public class PointyTooth implements Serializable { private BigDecimal id; @ManyToOne - @JoinColumn(name = "bunny_id") + @JoinColumn(name = "bunny_id") Bunny bunny; public void setBunny(Bunny bunny) { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/id/generationmappings/NewGeneratorMappingsTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/id/generationmappings/NewGeneratorMappingsTest.java index b4bd300bf2..1f3e922084 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/id/generationmappings/NewGeneratorMappingsTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/id/generationmappings/NewGeneratorMappingsTest.java @@ -58,7 +58,7 @@ public class NewGeneratorMappingsTest { @Test public void testMinimalSequenceEntity(SessionFactoryScope scope) { - final EntityPersister persister = scope.getSessionFactory() + final EntityPersister persister = scope.getSessionFactory() .getRuntimeMetamodels() .getMappingMetamodel() .getEntityDescriptor(MinimalSequenceEntity.class.getName()); @@ -76,7 +76,7 @@ public class NewGeneratorMappingsTest { @Test public void testCompleteSequenceEntity(SessionFactoryScope scope) { - final EntityPersister persister = scope.getSessionFactory() + final EntityPersister persister = scope.getSessionFactory() .getRuntimeMetamodels() .getMappingMetamodel() .getEntityDescriptor(CompleteSequenceEntity.class.getName()); @@ -90,7 +90,7 @@ public class NewGeneratorMappingsTest { @Test public void testAutoEntity(SessionFactoryScope scope) { - final EntityPersister persister = scope.getSessionFactory().getRuntimeMetamodels().getMappingMetamodel().getEntityDescriptor(AutoEntity.class.getName()); + final EntityPersister persister = scope.getSessionFactory().getRuntimeMetamodels().getMappingMetamodel().getEntityDescriptor(AutoEntity.class.getName()); IdentifierGenerator generator = persister.getIdentifierGenerator(); assertTrue( SequenceStyleGenerator.class.isInstance( generator ) ); SequenceStyleGenerator seqGenerator = (SequenceStyleGenerator) generator; @@ -101,7 +101,7 @@ public class NewGeneratorMappingsTest { @Test public void testTablePerClassAutoEntity(SessionFactoryScope scope) { - final EntityPersister persister = scope.getSessionFactory().getRuntimeMetamodels().getMappingMetamodel().getEntityDescriptor(AbstractTPCAutoEntity.class.getName()); + final EntityPersister persister = scope.getSessionFactory().getRuntimeMetamodels().getMappingMetamodel().getEntityDescriptor(AbstractTPCAutoEntity.class.getName()); IdentifierGenerator generator = persister.getIdentifierGenerator(); assertTrue( SequenceStyleGenerator.class.isInstance( generator ) ); SequenceStyleGenerator seqGenerator = (SequenceStyleGenerator) generator; @@ -113,7 +113,7 @@ public class NewGeneratorMappingsTest { @Test public void testMinimalTableEntity(SessionFactoryScope scope) { - final EntityPersister persister = scope.getSessionFactory().getRuntimeMetamodels().getMappingMetamodel().getEntityDescriptor(MinimalTableEntity.class.getName()); + final EntityPersister persister = scope.getSessionFactory().getRuntimeMetamodels().getMappingMetamodel().getEntityDescriptor(MinimalTableEntity.class.getName()); IdentifierGenerator generator = persister.getIdentifierGenerator(); assertTrue( TableGenerator.class.isInstance( generator ) ); TableGenerator tabGenerator = (TableGenerator) generator; @@ -132,7 +132,7 @@ public class NewGeneratorMappingsTest { @JiraKey(value = "HHH-6790") public void testSequencePerEntity(SessionFactoryScope scope) { // Checking first entity. - EntityPersister persister = scope.getSessionFactory().getRuntimeMetamodels().getMappingMetamodel().getEntityDescriptor( + EntityPersister persister = scope.getSessionFactory().getRuntimeMetamodels().getMappingMetamodel().getEntityDescriptor( DedicatedSequenceEntity1.class.getName()); IdentifierGenerator generator = persister.getIdentifierGenerator(); assertTrue( SequenceStyleGenerator.class.isInstance( generator ) ); @@ -143,7 +143,7 @@ public class NewGeneratorMappingsTest { ); // Checking second entity. - persister = scope.getSessionFactory().getRuntimeMetamodels().getMappingMetamodel().getEntityDescriptor(DedicatedSequenceEntity2.class.getName()); + persister = scope.getSessionFactory().getRuntimeMetamodels().getMappingMetamodel().getEntityDescriptor(DedicatedSequenceEntity2.class.getName()); generator = persister.getIdentifierGenerator(); assertTrue( SequenceStyleGenerator.class.isInstance( generator ) ); seqGenerator = (SequenceStyleGenerator) generator; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/id/sequences/HibernateSequenceTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/id/sequences/HibernateSequenceTest.java index 98c0ec7270..5d4d7ec1a2 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/id/sequences/HibernateSequenceTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/id/sequences/HibernateSequenceTest.java @@ -41,7 +41,7 @@ public class HibernateSequenceTest { @Test public void testHibernateSequenceSchema(SessionFactoryScope scope) { - EntityPersister persister = scope.getSessionFactory().getRuntimeMetamodels().getMappingMetamodel().getEntityDescriptor(HibernateSequenceEntity.class.getName()); + EntityPersister persister = scope.getSessionFactory().getRuntimeMetamodels().getMappingMetamodel().getEntityDescriptor(HibernateSequenceEntity.class.getName()); IdentifierGenerator generator = persister.getIdentifierGenerator(); assertTrue( SequenceStyleGenerator.class.isInstance( generator ) ); SequenceStyleGenerator seqGenerator = (SequenceStyleGenerator) generator; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/id/sequences/entities/PlanetCheatSheet.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/id/sequences/entities/PlanetCheatSheet.java index bf7450219a..727456ed5f 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/id/sequences/entities/PlanetCheatSheet.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/id/sequences/entities/PlanetCheatSheet.java @@ -73,18 +73,18 @@ public class PlanetCheatSheet { */ public String toString() { - final String TAB = " "; + final String TAB = " "; - String retValue = ""; + String retValue = ""; - retValue = "PlanetCheatSheet ( " - + super.toString() + TAB - + "planet = " + this.planet + TAB - + "mass = " + this.mass + TAB - + "radius = " + this.radius + TAB - + "numberOfInhabitants = " + this.numberOfInhabitants + TAB - + " )"; + retValue = "PlanetCheatSheet ( " + + super.toString() + TAB + + "planet = " + this.planet + TAB + + "mass = " + this.mass + TAB + + "radius = " + this.radius + TAB + + "numberOfInhabitants = " + this.numberOfInhabitants + TAB + + " )"; - return retValue; + return retValue; } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/id/sequences/entities/PointyTooth.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/id/sequences/entities/PointyTooth.java index 1624f91a62..14cbbbe03b 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/id/sequences/entities/PointyTooth.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/id/sequences/entities/PointyTooth.java @@ -32,7 +32,7 @@ public class PointyTooth implements Serializable { private BigDecimal id; @ManyToOne - @JoinColumn(name = "bunny_id") + @JoinColumn(name = "bunny_id") Bunny bunny; public void setBunny(Bunny bunny) { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/idclassgeneratedvalue/Multiple.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/idclassgeneratedvalue/Multiple.java index 2d9fa18664..839e2be712 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/idclassgeneratedvalue/Multiple.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/idclassgeneratedvalue/Multiple.java @@ -25,55 +25,55 @@ import org.hibernate.annotations.GenericGenerator; @SuppressWarnings("serial") public class Multiple implements Serializable { - @Id - @GenericGenerator(name = "increment", strategy = "increment") - @GeneratedValue(generator = "increment") - private Long id1; +@Id +@GenericGenerator(name = "increment", strategy = "increment") +@GeneratedValue(generator = "increment") +private Long id1; - @Id - @GeneratedValue(generator = "MULTIPLE_SEQ", strategy = GenerationType.SEQUENCE) - @SequenceGenerator( name = "MULTIPLE_SEQ", sequenceName = "MULTIPLE_SEQ") - private Long id2; +@Id +@GeneratedValue(generator = "MULTIPLE_SEQ", strategy = GenerationType.SEQUENCE) +@SequenceGenerator( name = "MULTIPLE_SEQ", sequenceName = "MULTIPLE_SEQ") +private Long id2; - @Id - private Long id3; - private int quantity; +@Id +private Long id3; +private int quantity; - public Multiple() - { +public Multiple() +{ - } +} - public Multiple(Long id3, int quantity) - { - this.id3 = id3; - this.quantity = quantity; - } +public Multiple(Long id3, int quantity) +{ + this.id3 = id3; + this.quantity = quantity; +} - public Long getId1() - { - return id1; - } +public Long getId1() +{ + return id1; +} - public Long getId2() - { - return id2; - } +public Long getId2() +{ + return id2; +} - public Long getId3() - { - return id3; - } +public Long getId3() +{ + return id3; +} - public int getQuantity() - { - return quantity; - } +public int getQuantity() +{ + return quantity; +} - public void setQuantity(int quantity) - { - this.quantity = quantity; - } +public void setQuantity(int quantity) +{ + this.quantity = quantity; +} } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/idclassgeneratedvalue/MultiplePK.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/idclassgeneratedvalue/MultiplePK.java index cdaf4b225a..405f039bd9 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/idclassgeneratedvalue/MultiplePK.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/idclassgeneratedvalue/MultiplePK.java @@ -14,67 +14,67 @@ import java.io.Serializable; */ public class MultiplePK implements Serializable { - private final Long id1; - private final Long id2; - private final Long id3; +private final Long id1; +private final Long id2; +private final Long id3; // AnnotationSourceProcessor (incorrectly) requires this to be transient; see HHH-4819 and HHH-4820 - private final transient int cachedHashCode; +private final transient int cachedHashCode; - private MultiplePK() - { - id1 = null; - id2 = null; - id3 = null; - cachedHashCode = super.hashCode(); - } - - public MultiplePK(Long id1, Long id2, Long id3) - { - this.id1 = id1; - this.id2 = id2; - this.id3 = id3; - this.cachedHashCode = calculateHashCode(); - } - - - private int calculateHashCode() { - int result = id1.hashCode(); - result = 31 * result + id2.hashCode(); - return result; - } - - public Long getId1() { - return id1; - } - - public Long getId2() { - return id2; - } - - public Long getId3() { - return id3; - } - - @Override - public boolean equals(Object o) - { - if ( this == o ) { - return true; - } - if ( o == null || getClass() != o.getClass() ) - { - return false; - } - - MultiplePK multiplePK = (MultiplePK) o; - - return id1.equals( multiplePK.id1 ) - && id2.equals( multiplePK.id2 ) - && id3.equals( multiplePK.id3); - } - - @Override - public int hashCode() { - return cachedHashCode; - } +private MultiplePK() +{ + id1 = null; + id2 = null; + id3 = null; + cachedHashCode = super.hashCode(); +} + +public MultiplePK(Long id1, Long id2, Long id3) +{ + this.id1 = id1; + this.id2 = id2; + this.id3 = id3; + this.cachedHashCode = calculateHashCode(); +} + + +private int calculateHashCode() { + int result = id1.hashCode(); + result = 31 * result + id2.hashCode(); + return result; +} + +public Long getId1() { + return id1; +} + +public Long getId2() { + return id2; +} + +public Long getId3() { + return id3; +} + +@Override +public boolean equals(Object o) +{ + if ( this == o ) { + return true; + } + if ( o == null || getClass() != o.getClass() ) + { + return false; + } + + MultiplePK multiplePK = (MultiplePK) o; + + return id1.equals( multiplePK.id1 ) + && id2.equals( multiplePK.id2 ) + && id3.equals( multiplePK.id3); +} + +@Override +public int hashCode() { + return cachedHashCode; +} } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/idmanytoone/Course.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/idmanytoone/Course.java index f8e96b9688..beb67ef594 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/idmanytoone/Course.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/idmanytoone/Course.java @@ -21,39 +21,39 @@ import jakarta.persistence.Table; @Table(name = "idmanytoone_course") public class Course implements Serializable { - @Id - @GeneratedValue - private int id; + @Id + @GeneratedValue + private int id; - private String name; + private String name; - @OneToMany(mappedBy = "course") - private Set students; + @OneToMany(mappedBy = "course") + private Set students; - public Course() { - } + public Course() { + } - public int getId() { - return id; - } + public int getId() { + return id; + } - public void setId(int id) { - this.id = id; - } + public void setId(int id) { + this.id = id; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - public Set getStudents() { - return students; - } + public Set getStudents() { + return students; + } - public void setStudents(Set students) { - this.students = students; - } + public void setStudents(Set students) { + this.students = students; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/idmanytoone/CourseStudent.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/idmanytoone/CourseStudent.java index 3bcf585880..35978f70ab 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/idmanytoone/CourseStudent.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/idmanytoone/CourseStudent.java @@ -22,43 +22,43 @@ import jakarta.persistence.Table; @Table(name = "idmanytoone_course_student") public class CourseStudent implements Serializable { - @Id - @ManyToOne(fetch = FetchType.LAZY) - @JoinColumn(name = "course_id") - private Course course; + @Id + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "course_id") + private Course course; - @Id - @ManyToOne(fetch = FetchType.LAZY) - @JoinColumn(name = "student_id") - private Student student; + @Id + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "student_id") + private Student student; @Column(name = "`value`") - private String value; + private String value; - public CourseStudent() { - } + public CourseStudent() { + } - public Course getCourse() { - return course; - } + public Course getCourse() { + return course; + } - public void setCourse(Course course) { - this.course = course; - } + public void setCourse(Course course) { + this.course = course; + } - public Student getStudent() { - return student; - } + public Student getStudent() { + return student; + } - public void setStudent(Student student) { - this.student = student; - } + public void setStudent(Student student) { + this.student = student; + } - public String getValue() { - return value; - } + public String getValue() { + return value; + } - public void setValue(String value) { - this.value = value; - } + public void setValue(String value) { + this.value = value; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/idmanytoone/Customer.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/idmanytoone/Customer.java index eb61fc5369..0033e110bd 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/idmanytoone/Customer.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/idmanytoone/Customer.java @@ -22,11 +22,11 @@ import jakarta.persistence.Table; @Entity @Table(name = "Bs") public class Customer implements Serializable { - @Id @GeneratedValue + @Id @GeneratedValue public Integer id; - @OneToMany(mappedBy = "customer") - public Set stores; + @OneToMany(mappedBy = "customer") + public Set stores; - private static final long serialVersionUID = 3818501706063039923L; + private static final long serialVersionUID = 3818501706063039923L; } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/idmanytoone/IdManyToOneTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/idmanytoone/IdManyToOneTest.java index a22119d175..09a0a47abb 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/idmanytoone/IdManyToOneTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/idmanytoone/IdManyToOneTest.java @@ -52,9 +52,9 @@ public class IdManyToOneTest extends BaseCoreFunctionalTestCase { //TODO test Customers / ShoppingBaskets / BasketItems testIdClassManyToOneWithReferenceColumn } - @Test + @Test @JiraKey( value = "HHH-7767" ) - public void testCriteriaRestrictionOnIdManyToOne() { + public void testCriteriaRestrictionOnIdManyToOne() { inTransaction( s -> { s.createQuery( "from Course c join c.students cs join cs.student s where s.name = 'Foo'", Object[].class ).list(); @@ -78,7 +78,7 @@ public class IdManyToOneTest extends BaseCoreFunctionalTestCase { // criteria2.add( Restrictions.eq( "s.name", "Foo" ) ); // criteria2.list(); } ); - } + } @Override protected Class[] getAnnotatedClasses() { @@ -90,9 +90,9 @@ public class IdManyToOneTest extends BaseCoreFunctionalTestCase { CardField.class, Card.class, Project.class, - Course.class, - Student.class, - CourseStudent.class, + Course.class, + Student.class, + CourseStudent.class, //tested only through deployment //ANN-590 testIdClassManyToOneWithReferenceColumn diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/idmanytoone/Store.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/idmanytoone/Store.java index 8393da7ae3..ef208b90fd 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/idmanytoone/Store.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/idmanytoone/Store.java @@ -19,12 +19,12 @@ import jakarta.persistence.Table; @Entity @Table(name = "`As`") public class Store implements Serializable { - @Id @GeneratedValue + @Id @GeneratedValue public Integer id; - @OneToMany(mappedBy = "store") - public Set customers; + @OneToMany(mappedBy = "store") + public Set customers; - private static final long serialVersionUID = 1748046699322502790L; + private static final long serialVersionUID = 1748046699322502790L; } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/idmanytoone/StoreCustomer.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/idmanytoone/StoreCustomer.java index 240227f012..9fc842e43e 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/idmanytoone/StoreCustomer.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/idmanytoone/StoreCustomer.java @@ -22,21 +22,21 @@ import jakarta.persistence.Table; public class StoreCustomer implements Serializable { StoreCustomer() {} @Id - @ManyToOne(optional = false) - @JoinColumn(name = "idA") - public Store store; - - @Id @ManyToOne(optional = false) - @JoinColumn(name = "idB") - public Customer customer; + @JoinColumn(name = "idA") + public Store store; + + @Id + @ManyToOne(optional = false) + @JoinColumn(name = "idB") + public Customer customer; - public StoreCustomer(Store store, Customer customer) { + public StoreCustomer(Store store, Customer customer) { this.store = store; this.customer = customer; - } + } - private static final long serialVersionUID = -8295955012787627232L; + private static final long serialVersionUID = -8295955012787627232L; } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/idmanytoone/StoreCustomerPK.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/idmanytoone/StoreCustomerPK.java index f126e49ec7..2fd960d700 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/idmanytoone/StoreCustomerPK.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/idmanytoone/StoreCustomerPK.java @@ -16,21 +16,21 @@ import jakarta.persistence.ManyToOne; public class StoreCustomerPK implements Serializable { StoreCustomerPK() {} @Id - @ManyToOne(optional = false) - @JoinColumn(name = "idA") - public Store store; - - @Id @ManyToOne(optional = false) - @JoinColumn(name = "idB") - public Customer customer; + @JoinColumn(name = "idA") + public Store store; + + @Id + @ManyToOne(optional = false) + @JoinColumn(name = "idB") + public Customer customer; - public StoreCustomerPK(Store store, Customer customer) { + public StoreCustomerPK(Store store, Customer customer) { this.store = store; this.customer = customer; - } + } - private static final long serialVersionUID = -1102111921432271459L; + private static final long serialVersionUID = -1102111921432271459L; } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/idmanytoone/Student.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/idmanytoone/Student.java index d42a5af4e3..05048ffef7 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/idmanytoone/Student.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/idmanytoone/Student.java @@ -21,39 +21,39 @@ import jakarta.persistence.Table; @Table(name = "idmanytoone_student") public class Student implements Serializable { - @Id - @GeneratedValue - private int id; + @Id + @GeneratedValue + private int id; - private String name; + private String name; - @OneToMany(mappedBy = "student") - private Set courses; + @OneToMany(mappedBy = "student") + private Set courses; - public Student() { - } + public Student() { + } - public int getId() { - return id; - } + public int getId() { + return id; + } - public void setId(int id) { - this.id = id; - } + public void setId(int id) { + this.id = id; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - public Set getCourses() { - return courses; - } + public Set getCourses() { + return courses; + } - public void setCourses(Set courses) { - this.courses = courses; - } + public void setCourses(Set courses) { + this.courses = courses; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/idmanytoone/alphabetical/Service.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/idmanytoone/alphabetical/Service.java index 049ee61809..e80698e63c 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/idmanytoone/alphabetical/Service.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/idmanytoone/alphabetical/Service.java @@ -12,6 +12,6 @@ import jakarta.persistence.Id; @Entity public class Service { - @Id - private BigInteger idpk; + @Id + private BigInteger idpk; } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/immutable/ImmutableTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/immutable/ImmutableTest.java index fdf4f01118..f241d83571 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/immutable/ImmutableTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/immutable/ImmutableTest.java @@ -123,7 +123,7 @@ public class ImmutableTest extends BaseCoreFunctionalTestCase { fail(); } catch (PersistenceException e) { assertTrue(e.getMessage().contains("changed an immutable collection instance")); - log.debug("success"); + log.debug("success"); } s.close(); @@ -239,7 +239,7 @@ public class ImmutableTest extends BaseCoreFunctionalTestCase { } @Override - protected Class[] getAnnotatedClasses() { + protected Class[] getAnnotatedClasses() { return new Class[] { Country.class, State.class, Photo.class }; } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/index/jpa/AbstractJPAIndexTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/index/jpa/AbstractJPAIndexTest.java index 214ce40dc2..ecae357776 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/index/jpa/AbstractJPAIndexTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/index/jpa/AbstractJPAIndexTest.java @@ -51,7 +51,7 @@ public abstract class AbstractJPAIndexTest extends BaseNonConfigCoreFunctionalTe @Test public void testTableIndex() { PersistentClass entity = metadata().getEntityBinding( Car.class.getName() ); - Iterator itr = entity.getTable().getUniqueKeys().values().iterator(); + Iterator itr = entity.getTable().getUniqueKeys().values().iterator(); assertTrue( itr.hasNext() ); UniqueKey uk = (UniqueKey) itr.next(); assertFalse( itr.hasNext() ); @@ -70,7 +70,7 @@ public abstract class AbstractJPAIndexTest extends BaseNonConfigCoreFunctionalTe assertFalse( itr.hasNext() ); assertEquals( "Car_idx", index.getName() ); assertEquals( 1, index.getColumnSpan() ); - column = index.getColumns().iterator().next(); + column = index.getColumns().iterator().next(); assertEquals( "since", column.getName() ); assertSame( entity.getTable(), index.getTable() ); } @@ -86,7 +86,7 @@ public abstract class AbstractJPAIndexTest extends BaseNonConfigCoreFunctionalTe assertFalse( itr.hasNext() ); assertTrue( "index name is not generated", StringHelper.isNotEmpty( index.getName() ) ); assertEquals( 2, index.getColumnSpan() ); - Iterator columnIterator = index.getColumns().iterator(); + Iterator columnIterator = index.getColumns().iterator(); Column column = columnIterator.next(); assertEquals( "dealer_name", column.getName() ); column = columnIterator.next(); @@ -108,7 +108,7 @@ public abstract class AbstractJPAIndexTest extends BaseNonConfigCoreFunctionalTe assertFalse( itr.hasNext() ); assertTrue( "index name is not generated", StringHelper.isNotEmpty( index.getName() ) ); assertEquals( 1, index.getColumnSpan() ); - Iterator columnIterator = index.getColumns().iterator(); + Iterator columnIterator = index.getColumns().iterator(); Column column = columnIterator.next(); assertEquals( "name", column.getName() ); assertSame( collectionTable, index.getTable() ); @@ -128,7 +128,7 @@ public abstract class AbstractJPAIndexTest extends BaseNonConfigCoreFunctionalTe assertFalse( itr.hasNext() ); assertTrue( "index name is not generated", StringHelper.isNotEmpty( index.getName() ) ); assertEquals( 1, index.getColumnSpan() ); - Iterator columnIterator = index.getColumns().iterator(); + Iterator columnIterator = index.getColumns().iterator(); Column column = columnIterator.next(); assertEquals( "importers_id", column.getName() ); assertSame( collectionTable, index.getTable() ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/indexcoll/ExchangeOffice.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/indexcoll/ExchangeOffice.java index be2c19dfe8..14bd5fe5f5 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/indexcoll/ExchangeOffice.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/indexcoll/ExchangeOffice.java @@ -35,8 +35,8 @@ public class ExchangeOffice { } @jakarta.persistence.OneToMany(mappedBy = "parent") - @jakarta.persistence.MapKey(name="key") - private Map exchangeRates = new java.util.HashMap(); + @jakarta.persistence.MapKey(name="key") + private Map exchangeRates = new java.util.HashMap(); public Map getExchangeRates() { return exchangeRates; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/indexcoll/ExchangeRate.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/indexcoll/ExchangeRate.java index b61cc2cc3e..ec72ab9122 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/indexcoll/ExchangeRate.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/indexcoll/ExchangeRate.java @@ -44,7 +44,7 @@ public class ExchangeRate { } @Embedded - private ExchangeRateKey key = new ExchangeRateKey(); + private ExchangeRateKey key = new ExchangeRateKey(); public ExchangeRateKey getKey() { return key; @@ -55,7 +55,7 @@ public class ExchangeRate { } @jakarta.persistence.ManyToOne(fetch = FetchType.LAZY ) - private ExchangeOffice parent = null; + private ExchangeOffice parent = null; public ExchangeOffice getParent() { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/indexcoll/ExchangeRateKey.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/indexcoll/ExchangeRateKey.java index ea9388831e..fb90a22939 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/indexcoll/ExchangeRateKey.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/indexcoll/ExchangeRateKey.java @@ -14,48 +14,48 @@ import jakarta.persistence.FetchType; public class ExchangeRateKey { - public ExchangeRateKey() { - super(); - } + public ExchangeRateKey() { + super(); + } - public ExchangeRateKey( long date, Currency currency1, Currency currency2) { - super(); - this.date = date; - this.currency1 = currency1; - this.currency2 = currency2; - } + public ExchangeRateKey( long date, Currency currency1, Currency currency2) { + super(); + this.date = date; + this.currency1 = currency1; + this.currency2 = currency2; + } - @Column(name="`date`", nullable = false) - protected long date; + @Column(name="`date`", nullable = false) + protected long date; - @jakarta.persistence.ManyToOne(fetch = FetchType.LAZY, optional = false) - protected Currency currency1; + @jakarta.persistence.ManyToOne(fetch = FetchType.LAZY, optional = false) + protected Currency currency1; - @jakarta.persistence.ManyToOne(fetch = FetchType.LAZY, optional = false) - protected Currency currency2; + @jakarta.persistence.ManyToOne(fetch = FetchType.LAZY, optional = false) + protected Currency currency2; - @Override - public boolean equals (Object obj) { - if (this == obj) return true; + @Override + public boolean equals (Object obj) { + if (this == obj) return true; - if (!(obj instanceof ExchangeRateKey)) return false; + if (!(obj instanceof ExchangeRateKey)) return false; - ExchangeRateKey q = (ExchangeRateKey) obj; - return q.date == date && q.currency1 == this.currency1 && q.currency2 == this.currency2; + ExchangeRateKey q = (ExchangeRateKey) obj; + return q.date == date && q.currency1 == this.currency1 && q.currency2 == this.currency2; - } + } - @Override - public int hashCode() { - int hashcode = 0; - hashcode += date; - hashcode += (currency1 != null ? currency1.hashCode() : 0); - hashcode += (currency2 != null ? currency2.hashCode() : 0); - return hashcode; - } + @Override + public int hashCode() { + int hashcode = 0; + hashcode += date; + hashcode += (currency1 != null ? currency1.hashCode() : 0); + hashcode += (currency2 != null ? currency2.hashCode() : 0); + return hashcode; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/indexcoll/IndexedCollectionTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/indexcoll/IndexedCollectionTest.java index c01a7516fe..f179945927 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/indexcoll/IndexedCollectionTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/indexcoll/IndexedCollectionTest.java @@ -88,7 +88,7 @@ public class IndexedCollectionTest { private boolean isDefaultColumnPresent(SessionFactoryScope scope, String collectionOwner, String propertyName, String suffix) { final Collection collection = scope.getMetadataImplementor().getCollectionBinding( collectionOwner + "." + propertyName ); - final Iterator columnIterator = collection.getCollectionTable().getColumns().iterator(); + final Iterator columnIterator = collection.getCollectionTable().getColumns().iterator(); boolean hasDefault = false; while ( columnIterator.hasNext() ) { Column column = columnIterator.next(); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/indexcoll/eager/EagerIndexedCollectionTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/indexcoll/eager/EagerIndexedCollectionTest.java index 8b1a6efe34..d6b39b4704 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/indexcoll/eager/EagerIndexedCollectionTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/indexcoll/eager/EagerIndexedCollectionTest.java @@ -43,7 +43,7 @@ public class EagerIndexedCollectionTest extends BaseNonConfigCoreFunctionalTestC private boolean isDefaultColumnPresent(String collectionOwner, String propertyName, String suffix) { final Collection collection = metadata().getCollectionBinding( collectionOwner + "." + propertyName ); - final Iterator columnIterator = collection.getCollectionTable().getColumns().iterator(); + final Iterator columnIterator = collection.getCollectionTable().getColumns().iterator(); boolean hasDefault = false; while ( columnIterator.hasNext() ) { Column column = columnIterator.next(); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/inheritance/joined/PoolAddress.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/inheritance/joined/PoolAddress.java index 588fea5696..688befdf46 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/inheritance/joined/PoolAddress.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/inheritance/joined/PoolAddress.java @@ -11,14 +11,14 @@ import jakarta.persistence.Embeddable; @Embeddable public class PoolAddress { - @Column(table = "POOL_ADDRESS") - private String address; + @Column(table = "POOL_ADDRESS") + private String address; - public String getAddress() { - return address; - } + public String getAddress() { + return address; + } - public void setAddress(String address) { - this.address = address; - } + public void setAddress(String address) { + this.address = address; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/loader/Player.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/loader/Player.java index c4e7a6d9b7..15c10b0518 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/loader/Player.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/loader/Player.java @@ -21,8 +21,8 @@ public class Player { private Team team; private String name; - @Id - @GeneratedValue + @Id + @GeneratedValue public Long getId() { return id; } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/lob/ImageTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/lob/ImageTest.java index 8d9de213ef..e8378497d3 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/lob/ImageTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/lob/ImageTest.java @@ -150,7 +150,7 @@ public class ImageTest extends BaseCoreFunctionalTestCase { } @Override - public Class[] getAnnotatedClasses() { + public Class[] getAnnotatedClasses() { return new Class[] { ImageHolder.class }; } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/JobInfo.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/JobInfo.java index 14bc57741b..6bdff51faa 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/JobInfo.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/JobInfo.java @@ -11,7 +11,7 @@ import jakarta.persistence.ManyToOne; @Embeddable public class JobInfo { - String jobDescription; +String jobDescription; ProgramManager pm; // Bidirectional public String getJobDescription() { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/ManyToManyInverseJoinColumnSortedSetTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/ManyToManyInverseJoinColumnSortedSetTest.java index da8b51acb6..301c921a9e 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/ManyToManyInverseJoinColumnSortedSetTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/ManyToManyInverseJoinColumnSortedSetTest.java @@ -76,7 +76,7 @@ public class ManyToManyInverseJoinColumnSortedSetTest extends BaseCoreFunctional } @Override - protected Class[] getAnnotatedClasses() { + protected Class[] getAnnotatedClasses() { return new Class[]{ ContainingEntity.class, ContainedEntity.class diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/ManyToManyTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/ManyToManyTest.java index 49a330a755..1754e9ac02 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/ManyToManyTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/ManyToManyTest.java @@ -756,7 +756,7 @@ public class ManyToManyTest extends BaseCoreFunctionalTestCase { } @Override - protected Class[] getAnnotatedClasses() { + protected Class[] getAnnotatedClasses() { return new Class[]{ Friend.class, Employer.class, diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/defaults/ManyToManyImplicitNamingTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/defaults/ManyToManyImplicitNamingTest.java index 4edb70b928..22f2622443 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/defaults/ManyToManyImplicitNamingTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/defaults/ManyToManyImplicitNamingTest.java @@ -202,7 +202,7 @@ public class ManyToManyImplicitNamingTest extends BaseNonConfigCoreFunctionalTes } boolean hasOwnerFK = false; boolean hasInverseFK = false; - for (Iterator it = ownerCollection.getCollectionTable().getForeignKeys().values().iterator(); it.hasNext(); ) { + for (Iterator it = ownerCollection.getCollectionTable().getForeignKeys().values().iterator(); it.hasNext(); ) { final ForeignKey fk = (ForeignKey) it.next(); assertSame( ownerCollection.getCollectionTable(), fk.getTable() ); if ( fk.getColumnSpan() > 1 ) { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytoonewithformula/ManyToOneWithFormulaTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytoonewithformula/ManyToOneWithFormulaTest.java index 2870f9cae5..c77fb422a9 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytoonewithformula/ManyToOneWithFormulaTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytoonewithformula/ManyToOneWithFormulaTest.java @@ -184,14 +184,14 @@ public class ManyToOneWithFormulaTest { session.getTransaction().markRollbackOnly(); } ); - } + } - @Test + @Test @DomainModel( annotatedClasses = ProductSqlServer.class ) @SessionFactory @RequiresDialect( SQLServerDialect.class ) - public void testManyToOneFromNonPkToNonPkSqlServer(SessionFactoryScope scope) { - // also tests usage of the stand-alone @JoinFormula annotation + public void testManyToOneFromNonPkToNonPkSqlServer(SessionFactoryScope scope) { + // also tests usage of the stand-alone @JoinFormula annotation // (i.e. not wrapped within @JoinColumnsOrFormulas) scope.inTransaction( (session) -> { @@ -221,6 +221,6 @@ public class ManyToOneWithFormulaTest { session.getTransaction().markRollbackOnly(); } ); - } + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytoonewithformula/Product.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytoonewithformula/Product.java index 0f815fe8ac..7562d5d138 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytoonewithformula/Product.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytoonewithformula/Product.java @@ -28,24 +28,24 @@ public class Product implements Serializable private static final long serialVersionUID = 6956478993159505828L; @Id - public Integer id; + public Integer id; - @Column(name="product_idnf", length=18, nullable=false, unique=true, - columnDefinition="char(18)") - public String productIdnf; + @Column(name="product_idnf", length=18, nullable=false, unique=true, + columnDefinition="char(18)") + public String productIdnf; - @Column(name="description", nullable=false) - public String description; + @Column(name="description", nullable=false) + public String description; - @ManyToOne + @ManyToOne @JoinFormula(value="{fn substring(product_idnf, 1, 3)}", - referencedColumnName="product_idnf") + referencedColumnName="product_idnf") @Fetch(FetchMode.JOIN) - private Product productFamily; + private Product productFamily; - public Product getProductFamily() - { - return productFamily; - } + public Product getProductFamily() + { + return productFamily; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytoonewithformula/ProductSqlServer.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytoonewithformula/ProductSqlServer.java index ffd6fde799..b1cc586a3e 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytoonewithformula/ProductSqlServer.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytoonewithformula/ProductSqlServer.java @@ -28,24 +28,24 @@ public class ProductSqlServer implements Serializable private static final long serialVersionUID = 6956478993159505828L; @Id - public Integer id; + public Integer id; - @Column(name="product_idnf", length=18, nullable=false, unique=true, - columnDefinition="char(18)") - public String productIdnf; + @Column(name="product_idnf", length=18, nullable=false, unique=true, + columnDefinition="char(18)") + public String productIdnf; - @Column(name="description", nullable=false) - public String description; + @Column(name="description", nullable=false) + public String description; - @ManyToOne + @ManyToOne @JoinFormula(value="{fn substring(product_idnf, 1, 3)}", - referencedColumnName="product_idnf") + referencedColumnName="product_idnf") @Fetch(FetchMode.JOIN) - private ProductSqlServer productFamily; + private ProductSqlServer productFamily; - public ProductSqlServer getProductFamily() - { - return productFamily; - } + public ProductSqlServer getProductFamily() + { + return productFamily; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/mapsid/DefaultedMapsIdTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/mapsid/DefaultedMapsIdTest.java index 5bc687c498..e51b9167a1 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/mapsid/DefaultedMapsIdTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/mapsid/DefaultedMapsIdTest.java @@ -32,99 +32,99 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; @DomainModel(annotatedClasses = {DefaultedMapsIdTest.Loan.class, DefaultedMapsIdTest.Extension.class}) public class DefaultedMapsIdTest { - @Test void test(SessionFactoryScope scope) { - ExtensionId eid = scope.fromTransaction( s -> { - Loan loan = new Loan(); - loan.id = 999L; - Extension extension = new Extension(); - extension.exLoanId = loan.id; - extension.loan = loan; - extension.exNo = 1; - extension.exExtensionDays = 30; - loan.extensions.add(extension); - extension = new Extension(); - extension.exLoanId = loan.id; - extension.loan = loan; - extension.exNo = 2; - extension.exExtensionDays = 14; - loan.extensions.add(extension); - s.persist(loan); - return new ExtensionId(extension.exLoanId, extension.exNo ); - }); - scope.inSession( s -> { - List extensions = s.createQuery("from Extension", Extension.class).getResultList(); - assertEquals(2, extensions.size()); - } ); - scope.inSession( s -> { - Extension extension = s.find(Extension.class, eid); - assertEquals(14, extension.exExtensionDays); - assertEquals(2, extension.exNo); - assertEquals(999L, extension.exLoanId); - assertNotNull( extension.loan ); - }); - scope.inSession( s -> { - Loan loan = s.find(Loan.class, eid.exLoanId); - Extension extension = loan.extensions.get(0); - assertEquals(1, extension.exNo); - assertEquals(30, extension.exExtensionDays); - assertEquals(999L, extension.exLoanId); - assertEquals(loan, extension.loan); - }); - } + @Test void test(SessionFactoryScope scope) { + ExtensionId eid = scope.fromTransaction( s -> { + Loan loan = new Loan(); + loan.id = 999L; + Extension extension = new Extension(); + extension.exLoanId = loan.id; + extension.loan = loan; + extension.exNo = 1; + extension.exExtensionDays = 30; + loan.extensions.add(extension); + extension = new Extension(); + extension.exLoanId = loan.id; + extension.loan = loan; + extension.exNo = 2; + extension.exExtensionDays = 14; + loan.extensions.add(extension); + s.persist(loan); + return new ExtensionId(extension.exLoanId, extension.exNo ); + }); + scope.inSession( s -> { + List extensions = s.createQuery("from Extension", Extension.class).getResultList(); + assertEquals(2, extensions.size()); + } ); + scope.inSession( s -> { + Extension extension = s.find(Extension.class, eid); + assertEquals(14, extension.exExtensionDays); + assertEquals(2, extension.exNo); + assertEquals(999L, extension.exLoanId); + assertNotNull( extension.loan ); + }); + scope.inSession( s -> { + Loan loan = s.find(Loan.class, eid.exLoanId); + Extension extension = loan.extensions.get(0); + assertEquals(1, extension.exNo); + assertEquals(30, extension.exExtensionDays); + assertEquals(999L, extension.exLoanId); + assertEquals(loan, extension.loan); + }); + } - @Entity(name = "Loan") - static class Loan { - @Id - @Column(name = "LOAN_ID") - private Long id; + @Entity(name = "Loan") + static class Loan { + @Id + @Column(name = "LOAN_ID") + private Long id; - private BigDecimal amount = BigDecimal.ZERO; + private BigDecimal amount = BigDecimal.ZERO; - @OneToMany(cascade = CascadeType.ALL, mappedBy = "loan") - private List extensions = new ArrayList<>(); - } + @OneToMany(cascade = CascadeType.ALL, mappedBy = "loan") + private List extensions = new ArrayList<>(); + } - static class ExtensionId { - private Long exLoanId; - private int exNo; + static class ExtensionId { + private Long exLoanId; + private int exNo; - public ExtensionId(Long exLoanId, int exNo) { - this.exLoanId = exLoanId; - this.exNo = exNo; - } + public ExtensionId(Long exLoanId, int exNo) { + this.exLoanId = exLoanId; + this.exNo = exNo; + } - public ExtensionId() { - } + public ExtensionId() { + } - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof ExtensionId)) return false; - ExtensionId that = (ExtensionId) o; - return exNo == that.exNo && Objects.equals(exLoanId, that.exLoanId); - } + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (!(o instanceof ExtensionId)) return false; + ExtensionId that = (ExtensionId) o; + return exNo == that.exNo && Objects.equals(exLoanId, that.exLoanId); + } - @Override - public int hashCode() { - return Objects.hash(exLoanId, exNo); - } - } + @Override + public int hashCode() { + return Objects.hash(exLoanId, exNo); + } + } - @Entity(name = "Extension") - @IdClass(ExtensionId.class) - static class Extension { - @Id - private Long exLoanId; + @Entity(name = "Extension") + @IdClass(ExtensionId.class) + static class Extension { + @Id + private Long exLoanId; - @Id - @Column(name = "EX_NO") - private int exNo; + @Id + @Column(name = "EX_NO") + private int exNo; - @Column(name = "EX_EXTENSION_DAYS") - private int exExtensionDays; + @Column(name = "EX_EXTENSION_DAYS") + private int exExtensionDays; - @ManyToOne - @MapsId("exLoanId") - private Loan loan; - } + @ManyToOne + @MapsId("exLoanId") + private Loan loan; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/mapsid/MapsEmbeddedIdTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/mapsid/MapsEmbeddedIdTest.java index ea6d4f35f9..821f383678 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/mapsid/MapsEmbeddedIdTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/mapsid/MapsEmbeddedIdTest.java @@ -33,100 +33,100 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; @DomainModel(annotatedClasses = {MapsEmbeddedIdTest.Loan.class, MapsEmbeddedIdTest.ExtensionId.class, MapsEmbeddedIdTest.Extension.class}) public class MapsEmbeddedIdTest { - @Test void test(SessionFactoryScope scope) { - ExtensionId eid = scope.fromTransaction( s -> { - Loan loan = new Loan(); - loan.id = 999L; - ExtensionId exid = new ExtensionId(loan.id, 1); - Extension extension = new Extension(); - extension.id = exid; - extension.loan = loan; - extension.exExtensionDays = 30; - loan.extensions.add(extension); - exid = new ExtensionId(loan.id, 2); - extension = new Extension(); - extension.id = exid; - extension.loan = loan; - extension.exExtensionDays = 14; - loan.extensions.add(extension); - s.persist(loan); - return exid; - }); - scope.inSession( s -> { - List extensions = s.createQuery("from Extension", Extension.class).getResultList(); - assertEquals(2, extensions.size()); - } ); - scope.inSession( s -> { - Extension extension = s.find(Extension.class, eid); - assertEquals(14, extension.exExtensionDays); - assertEquals(2, extension.id.exNo); - assertEquals(999L, extension.id.exLoanId); - assertNotNull( extension.loan ); - }); - scope.inSession( s -> { - Loan loan = s.find(Loan.class, eid.exLoanId); - Extension extension = loan.extensions.get(0); - assertEquals(1, extension.id.exNo); - assertEquals(30, extension.exExtensionDays); - assertEquals(999L, extension.id.exLoanId); - assertEquals(loan, extension.loan); - }); - } + @Test void test(SessionFactoryScope scope) { + ExtensionId eid = scope.fromTransaction( s -> { + Loan loan = new Loan(); + loan.id = 999L; + ExtensionId exid = new ExtensionId(loan.id, 1); + Extension extension = new Extension(); + extension.id = exid; + extension.loan = loan; + extension.exExtensionDays = 30; + loan.extensions.add(extension); + exid = new ExtensionId(loan.id, 2); + extension = new Extension(); + extension.id = exid; + extension.loan = loan; + extension.exExtensionDays = 14; + loan.extensions.add(extension); + s.persist(loan); + return exid; + }); + scope.inSession( s -> { + List extensions = s.createQuery("from Extension", Extension.class).getResultList(); + assertEquals(2, extensions.size()); + } ); + scope.inSession( s -> { + Extension extension = s.find(Extension.class, eid); + assertEquals(14, extension.exExtensionDays); + assertEquals(2, extension.id.exNo); + assertEquals(999L, extension.id.exLoanId); + assertNotNull( extension.loan ); + }); + scope.inSession( s -> { + Loan loan = s.find(Loan.class, eid.exLoanId); + Extension extension = loan.extensions.get(0); + assertEquals(1, extension.id.exNo); + assertEquals(30, extension.exExtensionDays); + assertEquals(999L, extension.id.exLoanId); + assertEquals(loan, extension.loan); + }); + } - @Entity(name = "Loan") - static class Loan { - @Id - @Column(name = "LOAN_ID") - private Long id; + @Entity(name = "Loan") + static class Loan { + @Id + @Column(name = "LOAN_ID") + private Long id; - private BigDecimal amount = BigDecimal.ZERO; + private BigDecimal amount = BigDecimal.ZERO; - @OneToMany(cascade = CascadeType.ALL, mappedBy = "loan") - private List extensions = new ArrayList<>(); - } + @OneToMany(cascade = CascadeType.ALL, mappedBy = "loan") + private List extensions = new ArrayList<>(); + } - @Embeddable - public static class ExtensionId { + @Embeddable + public static class ExtensionId { - private Long exLoanId; + private Long exLoanId; - @Column(name="EX_NO") - private int exNo; + @Column(name="EX_NO") + private int exNo; - public ExtensionId(Long exLoanId, int exNo) { - this.exLoanId = exLoanId; - this.exNo = exNo; - } + public ExtensionId(Long exLoanId, int exNo) { + this.exLoanId = exLoanId; + this.exNo = exNo; + } - public ExtensionId() { - } + public ExtensionId() { + } - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof ExtensionId)) return false; - ExtensionId that = (ExtensionId) o; - return exNo == that.exNo && Objects.equals(exLoanId, that.exLoanId); - } + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (!(o instanceof ExtensionId)) return false; + ExtensionId that = (ExtensionId) o; + return exNo == that.exNo && Objects.equals(exLoanId, that.exLoanId); + } - @Override - public int hashCode() { - return Objects.hash(exLoanId, exNo); - } - } + @Override + public int hashCode() { + return Objects.hash(exLoanId, exNo); + } + } - @Entity(name = "Extension") - static class Extension { + @Entity(name = "Extension") + static class Extension { - @EmbeddedId - private ExtensionId id; + @EmbeddedId + private ExtensionId id; - @Column(name = "EX_EXTENSION_DAYS") - private int exExtensionDays; + @Column(name = "EX_EXTENSION_DAYS") + private int exExtensionDays; - @ManyToOne - @MapsId("exLoanId") - @JoinColumn(name = "EX_LOAN_ID") - private Loan loan; - } + @ManyToOne + @MapsId("exLoanId") + @JoinColumn(name = "EX_LOAN_ID") + private Loan loan; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/mapsid/MapsEmbeddedIdWithOverrideTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/mapsid/MapsEmbeddedIdWithOverrideTest.java index 9f4364f8a4..612836d8f1 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/mapsid/MapsEmbeddedIdWithOverrideTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/mapsid/MapsEmbeddedIdWithOverrideTest.java @@ -34,100 +34,100 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; @DomainModel(annotatedClasses = {MapsEmbeddedIdWithOverrideTest.Loan.class, MapsEmbeddedIdWithOverrideTest.ExtensionId.class, MapsEmbeddedIdWithOverrideTest.Extension.class}) public class MapsEmbeddedIdWithOverrideTest { - @Test void test(SessionFactoryScope scope) { - ExtensionId eid = scope.fromTransaction( s -> { - Loan loan = new Loan(); - loan.id = 999L; - ExtensionId exid = new ExtensionId(loan.id, 1); - Extension extension = new Extension(); - extension.id = exid; - extension.loan = loan; - extension.exExtensionDays = 30; - loan.extensions.add(extension); - exid = new ExtensionId(loan.id, 2); - extension = new Extension(); - extension.id = exid; - extension.loan = loan; - extension.exExtensionDays = 14; - loan.extensions.add(extension); - s.persist(loan); - return exid; - }); - scope.inSession( s -> { - List extensions = s.createQuery("from Extension", Extension.class).getResultList(); - assertEquals(2, extensions.size()); - } ); - scope.inSession( s -> { - Extension extension = s.find(Extension.class, eid); - assertEquals(14, extension.exExtensionDays); - assertEquals(2, extension.id.exNo); - assertEquals(999L, extension.id.exLoanId); - assertNotNull( extension.loan ); - }); - scope.inSession( s -> { - Loan loan = s.find(Loan.class, eid.exLoanId); - Extension extension = loan.extensions.get(0); - assertEquals(1, extension.id.exNo); - assertEquals(30, extension.exExtensionDays); - assertEquals(999L, extension.id.exLoanId); - assertEquals(loan, extension.loan); - }); - } + @Test void test(SessionFactoryScope scope) { + ExtensionId eid = scope.fromTransaction( s -> { + Loan loan = new Loan(); + loan.id = 999L; + ExtensionId exid = new ExtensionId(loan.id, 1); + Extension extension = new Extension(); + extension.id = exid; + extension.loan = loan; + extension.exExtensionDays = 30; + loan.extensions.add(extension); + exid = new ExtensionId(loan.id, 2); + extension = new Extension(); + extension.id = exid; + extension.loan = loan; + extension.exExtensionDays = 14; + loan.extensions.add(extension); + s.persist(loan); + return exid; + }); + scope.inSession( s -> { + List extensions = s.createQuery("from Extension", Extension.class).getResultList(); + assertEquals(2, extensions.size()); + } ); + scope.inSession( s -> { + Extension extension = s.find(Extension.class, eid); + assertEquals(14, extension.exExtensionDays); + assertEquals(2, extension.id.exNo); + assertEquals(999L, extension.id.exLoanId); + assertNotNull( extension.loan ); + }); + scope.inSession( s -> { + Loan loan = s.find(Loan.class, eid.exLoanId); + Extension extension = loan.extensions.get(0); + assertEquals(1, extension.id.exNo); + assertEquals(30, extension.exExtensionDays); + assertEquals(999L, extension.id.exLoanId); + assertEquals(loan, extension.loan); + }); + } - @Entity(name = "Loan") - static class Loan { - @Id - @Column(name = "LOAN_ID") - private Long id; + @Entity(name = "Loan") + static class Loan { + @Id + @Column(name = "LOAN_ID") + private Long id; - private BigDecimal amount = BigDecimal.ZERO; + private BigDecimal amount = BigDecimal.ZERO; - @OneToMany(cascade = CascadeType.ALL, mappedBy = "loan") - private List extensions = new ArrayList<>(); - } + @OneToMany(cascade = CascadeType.ALL, mappedBy = "loan") + private List extensions = new ArrayList<>(); + } - @Embeddable - public static class ExtensionId { + @Embeddable + public static class ExtensionId { - private Long exLoanId; + private Long exLoanId; - private int exNo; + private int exNo; - public ExtensionId(Long exLoanId, int exNo) { - this.exLoanId = exLoanId; - this.exNo = exNo; - } + public ExtensionId(Long exLoanId, int exNo) { + this.exLoanId = exLoanId; + this.exNo = exNo; + } - public ExtensionId() { - } + public ExtensionId() { + } - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof ExtensionId)) return false; - ExtensionId that = (ExtensionId) o; - return exNo == that.exNo && Objects.equals(exLoanId, that.exLoanId); - } + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (!(o instanceof ExtensionId)) return false; + ExtensionId that = (ExtensionId) o; + return exNo == that.exNo && Objects.equals(exLoanId, that.exLoanId); + } - @Override - public int hashCode() { - return Objects.hash(exLoanId, exNo); - } - } + @Override + public int hashCode() { + return Objects.hash(exLoanId, exNo); + } + } - @Entity(name = "Extension") - static class Extension { + @Entity(name = "Extension") + static class Extension { - @EmbeddedId - @AttributeOverride(name = "exNo", column = @Column(name="EX_NO")) - private ExtensionId id; + @EmbeddedId + @AttributeOverride(name = "exNo", column = @Column(name="EX_NO")) + private ExtensionId id; - @Column(name = "EX_EXTENSION_DAYS") - private int exExtensionDays; + @Column(name = "EX_EXTENSION_DAYS") + private int exExtensionDays; - @ManyToOne - @MapsId("exLoanId") - @JoinColumn(name = "EX_LOAN_ID") - private Loan loan; - } + @ManyToOne + @MapsId("exLoanId") + @JoinColumn(name = "EX_LOAN_ID") + private Loan loan; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/mapsid/MapsIdTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/mapsid/MapsIdTest.java index 8dac224130..0e834b0c2c 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/mapsid/MapsIdTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/mapsid/MapsIdTest.java @@ -32,100 +32,100 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; @DomainModel(annotatedClasses = {MapsIdTest.Loan.class, MapsIdTest.Extension.class}) public class MapsIdTest { - @Test void test(SessionFactoryScope scope) { - ExtensionId eid = scope.fromTransaction( s -> { - Loan loan = new Loan(); - loan.id = 999L; - Extension extension = new Extension(); - extension.exLoanId = loan.id; - extension.loan = loan; - extension.exNo = 1; - extension.exExtensionDays = 30; - loan.extensions.add(extension); - extension = new Extension(); - extension.exLoanId = loan.id; - extension.loan = loan; - extension.exNo = 2; - extension.exExtensionDays = 14; - loan.extensions.add(extension); - s.persist(loan); - return new ExtensionId(extension.exLoanId, extension.exNo ); - }); - scope.inSession( s -> { - List extensions = s.createQuery("from Extension", Extension.class).getResultList(); - assertEquals(2, extensions.size()); - } ); - scope.inSession( s -> { - Extension extension = s.find(Extension.class, eid); - assertEquals(14, extension.exExtensionDays); - assertEquals(2, extension.exNo); - assertEquals(999L, extension.exLoanId); - assertNotNull( extension.loan ); - }); - scope.inSession( s -> { - Loan loan = s.find(Loan.class, eid.exLoanId); - Extension extension = loan.extensions.get(0); - assertEquals(1, extension.exNo); - assertEquals(30, extension.exExtensionDays); - assertEquals(999L, extension.exLoanId); - assertEquals(loan, extension.loan); - }); - } + @Test void test(SessionFactoryScope scope) { + ExtensionId eid = scope.fromTransaction( s -> { + Loan loan = new Loan(); + loan.id = 999L; + Extension extension = new Extension(); + extension.exLoanId = loan.id; + extension.loan = loan; + extension.exNo = 1; + extension.exExtensionDays = 30; + loan.extensions.add(extension); + extension = new Extension(); + extension.exLoanId = loan.id; + extension.loan = loan; + extension.exNo = 2; + extension.exExtensionDays = 14; + loan.extensions.add(extension); + s.persist(loan); + return new ExtensionId(extension.exLoanId, extension.exNo ); + }); + scope.inSession( s -> { + List extensions = s.createQuery("from Extension", Extension.class).getResultList(); + assertEquals(2, extensions.size()); + } ); + scope.inSession( s -> { + Extension extension = s.find(Extension.class, eid); + assertEquals(14, extension.exExtensionDays); + assertEquals(2, extension.exNo); + assertEquals(999L, extension.exLoanId); + assertNotNull( extension.loan ); + }); + scope.inSession( s -> { + Loan loan = s.find(Loan.class, eid.exLoanId); + Extension extension = loan.extensions.get(0); + assertEquals(1, extension.exNo); + assertEquals(30, extension.exExtensionDays); + assertEquals(999L, extension.exLoanId); + assertEquals(loan, extension.loan); + }); + } - @Entity(name = "Loan") - static class Loan { - @Id - @Column(name = "LOAN_ID") - private Long id; + @Entity(name = "Loan") + static class Loan { + @Id + @Column(name = "LOAN_ID") + private Long id; - private BigDecimal amount = BigDecimal.ZERO; + private BigDecimal amount = BigDecimal.ZERO; - @OneToMany(cascade = CascadeType.ALL, mappedBy = "loan") - private List extensions = new ArrayList<>(); - } + @OneToMany(cascade = CascadeType.ALL, mappedBy = "loan") + private List extensions = new ArrayList<>(); + } - static class ExtensionId { - private Long exLoanId; - private int exNo; + static class ExtensionId { + private Long exLoanId; + private int exNo; - public ExtensionId(Long exLoanId, int exNo) { - this.exLoanId = exLoanId; - this.exNo = exNo; - } + public ExtensionId(Long exLoanId, int exNo) { + this.exLoanId = exLoanId; + this.exNo = exNo; + } - public ExtensionId() { - } + public ExtensionId() { + } - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof ExtensionId)) return false; - ExtensionId that = (ExtensionId) o; - return exNo == that.exNo && Objects.equals(exLoanId, that.exLoanId); - } + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (!(o instanceof ExtensionId)) return false; + ExtensionId that = (ExtensionId) o; + return exNo == that.exNo && Objects.equals(exLoanId, that.exLoanId); + } - @Override - public int hashCode() { - return Objects.hash(exLoanId, exNo); - } - } + @Override + public int hashCode() { + return Objects.hash(exLoanId, exNo); + } + } - @Entity(name = "Extension") - @IdClass(ExtensionId.class) - static class Extension { - @Id - private Long exLoanId; + @Entity(name = "Extension") + @IdClass(ExtensionId.class) + static class Extension { + @Id + private Long exLoanId; - @Id - @Column(name = "EX_NO") - private int exNo; + @Id + @Column(name = "EX_NO") + private int exNo; - @Column(name = "EX_EXTENSION_DAYS") - private int exExtensionDays; + @Column(name = "EX_EXTENSION_DAYS") + private int exExtensionDays; - @ManyToOne - @MapsId("exLoanId") - @JoinColumn(name = "EX_LOAN_ID") - private Loan loan; - } + @ManyToOne + @MapsId("exLoanId") + @JoinColumn(name = "EX_LOAN_ID") + private Loan loan; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/mapsid/NoIdClassMapsIdTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/mapsid/NoIdClassMapsIdTest.java index 5c9707a860..7c76f573d5 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/mapsid/NoIdClassMapsIdTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/mapsid/NoIdClassMapsIdTest.java @@ -30,74 +30,74 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; @DomainModel(annotatedClasses = {NoIdClassMapsIdTest.Loan.class, NoIdClassMapsIdTest.Extension.class}) public class NoIdClassMapsIdTest { - @Test void test(SessionFactoryScope scope) { - Extension eid = scope.fromTransaction( s -> { - Loan loan = new Loan(); - loan.id = 999L; - Extension extension = new Extension(); - extension.exLoanId = loan.id; - extension.loan = loan; - extension.exNo = 1; - extension.exExtensionDays = 30; - loan.extensions.add(extension); - extension = new Extension(); - extension.exLoanId = loan.id; - extension.loan = loan; - extension.exNo = 2; - extension.exExtensionDays = 14; - loan.extensions.add(extension); - s.persist(loan); - return extension; - }); - scope.inSession( s -> { - List extensions = s.createQuery("from Extension", Extension.class).getResultList(); - assertEquals(2, extensions.size()); - } ); - scope.inSession( s -> { - Extension extension = s.find(Extension.class, eid); - assertEquals(14, extension.exExtensionDays); - assertEquals(2, extension.exNo); - assertEquals(999L, extension.exLoanId); - assertNotNull( extension.loan ); - }); - scope.inSession( s -> { - Loan loan = s.find(Loan.class, eid.exLoanId); - Extension extension = loan.extensions.get(0); - assertEquals(1, extension.exNo); - assertEquals(30, extension.exExtensionDays); - assertEquals(999L, extension.exLoanId); - assertEquals(loan, extension.loan); - }); - } + @Test void test(SessionFactoryScope scope) { + Extension eid = scope.fromTransaction( s -> { + Loan loan = new Loan(); + loan.id = 999L; + Extension extension = new Extension(); + extension.exLoanId = loan.id; + extension.loan = loan; + extension.exNo = 1; + extension.exExtensionDays = 30; + loan.extensions.add(extension); + extension = new Extension(); + extension.exLoanId = loan.id; + extension.loan = loan; + extension.exNo = 2; + extension.exExtensionDays = 14; + loan.extensions.add(extension); + s.persist(loan); + return extension; + }); + scope.inSession( s -> { + List extensions = s.createQuery("from Extension", Extension.class).getResultList(); + assertEquals(2, extensions.size()); + } ); + scope.inSession( s -> { + Extension extension = s.find(Extension.class, eid); + assertEquals(14, extension.exExtensionDays); + assertEquals(2, extension.exNo); + assertEquals(999L, extension.exLoanId); + assertNotNull( extension.loan ); + }); + scope.inSession( s -> { + Loan loan = s.find(Loan.class, eid.exLoanId); + Extension extension = loan.extensions.get(0); + assertEquals(1, extension.exNo); + assertEquals(30, extension.exExtensionDays); + assertEquals(999L, extension.exLoanId); + assertEquals(loan, extension.loan); + }); + } - @Entity(name = "Loan") - static class Loan { - @Id - @Column(name = "LOAN_ID") - private Long id; + @Entity(name = "Loan") + static class Loan { + @Id + @Column(name = "LOAN_ID") + private Long id; - private BigDecimal amount = BigDecimal.ZERO; + private BigDecimal amount = BigDecimal.ZERO; - @OneToMany(cascade = CascadeType.ALL, mappedBy = "loan") - private List extensions = new ArrayList<>(); - } + @OneToMany(cascade = CascadeType.ALL, mappedBy = "loan") + private List extensions = new ArrayList<>(); + } - @Entity(name = "Extension") - static class Extension { - @Id - private Long exLoanId; + @Entity(name = "Extension") + static class Extension { + @Id + private Long exLoanId; - @Id - @Column(name = "EX_NO") - private int exNo; + @Id + @Column(name = "EX_NO") + private int exNo; - @Column(name = "EX_EXTENSION_DAYS") - private int exExtensionDays; + @Column(name = "EX_EXTENSION_DAYS") + private int exExtensionDays; - @ManyToOne - @MapsId("exLoanId") - @JoinColumn(name = "EX_LOAN_ID") - private Loan loan; - } + @ManyToOne + @MapsId("exLoanId") + @JoinColumn(name = "EX_LOAN_ID") + private Loan loan; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/mapsid/NoMapsIdTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/mapsid/NoMapsIdTest.java index 47868a4c6b..e366531506 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/mapsid/NoMapsIdTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/mapsid/NoMapsIdTest.java @@ -31,96 +31,96 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; @DomainModel(annotatedClasses = {NoMapsIdTest.Loan.class, NoMapsIdTest.Extension.class}) public class NoMapsIdTest { - @Test void test(SessionFactoryScope scope) { - ExtensionId eid = scope.fromTransaction( s -> { - Loan loan = new Loan(); - loan.id = 999L; - Extension extension = new Extension(); - extension.loan = loan; - extension.exNo = 1; - extension.exExtensionDays = 30; - loan.extensions.add(extension); - extension = new Extension(); - extension.loan = loan; - extension.exNo = 2; - extension.exExtensionDays = 14; - loan.extensions.add(extension); - s.persist(loan); - return new ExtensionId(extension.loan.id, extension.exNo ); - }); - scope.inSession( s -> { - List extensions = s.createQuery("from Extension", Extension.class).getResultList(); - assertEquals(2, extensions.size()); - } ); - scope.inSession( s -> { - Extension extension = s.find(Extension.class, eid); - assertEquals(14, extension.exExtensionDays); - assertEquals(2, extension.exNo); - assertEquals(999L, extension.loan.id); - assertNotNull( extension.loan ); - }); - scope.inSession( s -> { - Loan loan = s.find(Loan.class, eid.loan); - Extension extension = loan.extensions.get(0); - assertEquals(1, extension.exNo); - assertEquals(30, extension.exExtensionDays); - assertEquals(999L, extension.loan.id); - assertEquals(loan, extension.loan); - }); - } + @Test void test(SessionFactoryScope scope) { + ExtensionId eid = scope.fromTransaction( s -> { + Loan loan = new Loan(); + loan.id = 999L; + Extension extension = new Extension(); + extension.loan = loan; + extension.exNo = 1; + extension.exExtensionDays = 30; + loan.extensions.add(extension); + extension = new Extension(); + extension.loan = loan; + extension.exNo = 2; + extension.exExtensionDays = 14; + loan.extensions.add(extension); + s.persist(loan); + return new ExtensionId(extension.loan.id, extension.exNo ); + }); + scope.inSession( s -> { + List extensions = s.createQuery("from Extension", Extension.class).getResultList(); + assertEquals(2, extensions.size()); + } ); + scope.inSession( s -> { + Extension extension = s.find(Extension.class, eid); + assertEquals(14, extension.exExtensionDays); + assertEquals(2, extension.exNo); + assertEquals(999L, extension.loan.id); + assertNotNull( extension.loan ); + }); + scope.inSession( s -> { + Loan loan = s.find(Loan.class, eid.loan); + Extension extension = loan.extensions.get(0); + assertEquals(1, extension.exNo); + assertEquals(30, extension.exExtensionDays); + assertEquals(999L, extension.loan.id); + assertEquals(loan, extension.loan); + }); + } - @Entity(name = "Loan") - static class Loan { - @Id - @Column(name = "LOAN_ID") - private Long id; + @Entity(name = "Loan") + static class Loan { + @Id + @Column(name = "LOAN_ID") + private Long id; - private BigDecimal amount = BigDecimal.ZERO; + private BigDecimal amount = BigDecimal.ZERO; - @OneToMany(cascade = CascadeType.ALL, mappedBy = "loan") - private List extensions = new ArrayList<>(); - } + @OneToMany(cascade = CascadeType.ALL, mappedBy = "loan") + private List extensions = new ArrayList<>(); + } - static class ExtensionId { - private Long loan; - private int exNo; + static class ExtensionId { + private Long loan; + private int exNo; - public ExtensionId(Long loan, int exNo) { - this.loan = loan; - this.exNo = exNo; - } + public ExtensionId(Long loan, int exNo) { + this.loan = loan; + this.exNo = exNo; + } - public ExtensionId() { - } + public ExtensionId() { + } - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof ExtensionId)) return false; - ExtensionId that = (ExtensionId) o; - return exNo == that.exNo && Objects.equals(loan, that.loan); - } + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (!(o instanceof ExtensionId)) return false; + ExtensionId that = (ExtensionId) o; + return exNo == that.exNo && Objects.equals(loan, that.loan); + } - @Override - public int hashCode() { - return Objects.hash(loan, exNo); - } - } + @Override + public int hashCode() { + return Objects.hash(loan, exNo); + } + } - @Entity(name = "Extension") - @IdClass(ExtensionId.class) - static class Extension { + @Entity(name = "Extension") + @IdClass(ExtensionId.class) + static class Extension { - @Id - @Column(name = "EX_NO") - private int exNo; + @Id + @Column(name = "EX_NO") + private int exNo; - @Column(name = "EX_EXTENSION_DAYS") - private int exExtensionDays; + @Column(name = "EX_EXTENSION_DAYS") + private int exExtensionDays; - @ManyToOne - @Id - @JoinColumn(name = "EX_LOAN_ID") - private Loan loan; - } + @ManyToOne + @Id + @JoinColumn(name = "EX_LOAN_ID") + private Loan loan; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/namingstrategy/AddressEntry.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/namingstrategy/AddressEntry.java index ccfebe9e22..c21f0c9515 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/namingstrategy/AddressEntry.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/namingstrategy/AddressEntry.java @@ -17,7 +17,7 @@ public class AddressEntry implements java.io.Serializable { public AddressEntry() { } - public AddressEntry( String street, String city, String state, String zip) { + public AddressEntry( String street, String city, String state, String zip) { this.street = street; this.city = city; this.state = state; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/namingstrategy/LongKeyNamingStrategyTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/namingstrategy/LongKeyNamingStrategyTest.java index 3876506aba..3a799398fd 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/namingstrategy/LongKeyNamingStrategyTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/namingstrategy/LongKeyNamingStrategyTest.java @@ -41,17 +41,17 @@ public class LongKeyNamingStrategyTest extends BaseUnitTestCase { private ServiceRegistry serviceRegistry; @Before - public void setUp() { + public void setUp() { serviceRegistry = ServiceRegistryBuilder.buildServiceRegistry( Environment.getProperties() ); } @After - public void tearDown() { - if ( serviceRegistry != null ) { + public void tearDown() { + if ( serviceRegistry != null ) { ServiceRegistryBuilder.destroy( serviceRegistry ); } } - @Test + @Test public void testWithCustomNamingStrategy() throws Exception { Metadata metadata = new MetadataSources( serviceRegistry ) .addAnnotatedClass(Address.class) @@ -64,10 +64,10 @@ public class LongKeyNamingStrategyTest extends BaseUnitTestCase { (org.hibernate.mapping.ForeignKey) metadata.getEntityBinding(Address.class.getName()).getTable().getForeignKeys().values().iterator().next(); assertEquals( "FK_way_longer_than_the_30_char", foreignKey.getName() ); - UniqueKey uniqueKey = metadata.getEntityBinding(Address.class.getName()).getTable().getUniqueKeys().values().iterator().next(); + UniqueKey uniqueKey = metadata.getEntityBinding(Address.class.getName()).getTable().getUniqueKeys().values().iterator().next(); assertEquals( "UK_way_longer_than_the_30_char", uniqueKey.getName() ); - org.hibernate.mapping.Index index = metadata.getEntityBinding(Address.class.getName()).getTable().getIndexes().values().iterator().next(); + org.hibernate.mapping.Index index = metadata.getEntityBinding(Address.class.getName()).getTable().getIndexes().values().iterator().next(); assertEquals( "IDX_way_longer_than_the_30_cha", index.getName() ); } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/namingstrategy/NamingStrategyTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/namingstrategy/NamingStrategyTest.java index dc861998b8..20a9f36b5c 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/namingstrategy/NamingStrategyTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/namingstrategy/NamingStrategyTest.java @@ -37,18 +37,18 @@ public class NamingStrategyTest extends BaseUnitTestCase { private ServiceRegistry serviceRegistry; @Before - public void setUp() { + public void setUp() { serviceRegistry = ServiceRegistryBuilder.buildServiceRegistry( Environment.getProperties() ); } @After - public void tearDown() { - if ( serviceRegistry != null ) { + public void tearDown() { + if ( serviceRegistry != null ) { ServiceRegistryBuilder.destroy( serviceRegistry ); } } - @Test + @Test public void testWithCustomNamingStrategy() throws Exception { new MetadataSources( serviceRegistry ) .addAnnotatedClass(Address.class) @@ -74,12 +74,12 @@ public class NamingStrategyTest extends BaseUnitTestCase { PersistentClass entityBinding = metadata.getEntityBinding( A.class.getName() ); assertEquals("NAME", - ((Selectable) entityBinding.getProperty( "name" ).getSelectables().get( 0 ) ).getText()); + ((Selectable) entityBinding.getProperty( "name" ).getSelectables().get( 0 ) ).getText()); assertEquals("VALUE", - ((Selectable) entityBinding.getProperty( "value" ).getSelectables().get( 0 ) ).getText()); + ((Selectable) entityBinding.getProperty( "value" ).getSelectables().get( 0 ) ).getText()); } - @Test + @Test public void testWithJpaCompliantNamingStrategy() throws Exception { Metadata metadata = new MetadataSources( serviceRegistry ) .addAnnotatedClass( A.class ) @@ -96,7 +96,7 @@ public class NamingStrategyTest extends BaseUnitTestCase { ); } - @Test + @Test public void testWithoutCustomNamingStrategy() throws Exception { new MetadataSources( serviceRegistry ) .addAnnotatedClass( Address.class ) diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/namingstrategy/charset/AbstractCharsetNamingStrategyTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/namingstrategy/charset/AbstractCharsetNamingStrategyTest.java index 53a4ebb98e..a99dc44283 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/namingstrategy/charset/AbstractCharsetNamingStrategyTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/namingstrategy/charset/AbstractCharsetNamingStrategyTest.java @@ -41,7 +41,7 @@ public abstract class AbstractCharsetNamingStrategyTest extends BaseUnitTestCase protected ServiceRegistry serviceRegistry; @Before - public void setUp() { + public void setUp() { Map properties = PropertiesHelper.map( Environment.getProperties() ); properties.put( AvailableSettings.HBM2DDL_CHARSET_NAME, charsetName() ); serviceRegistry = ServiceRegistryBuilder.buildServiceRegistry( properties ); @@ -50,12 +50,12 @@ public abstract class AbstractCharsetNamingStrategyTest extends BaseUnitTestCase protected abstract String charsetName(); @After - public void tearDown() { - if ( serviceRegistry != null ) { + public void tearDown() { + if ( serviceRegistry != null ) { ServiceRegistryBuilder.destroy( serviceRegistry ); } } - @Test + @Test public void testWithCustomNamingStrategy() throws Exception { Metadata metadata = new MetadataSources( serviceRegistry ) .addAnnotatedClass(Address.class) @@ -64,14 +64,14 @@ public abstract class AbstractCharsetNamingStrategyTest extends BaseUnitTestCase .applyImplicitNamingStrategy( new LongIdentifierNamingStrategy() ) .build(); - UniqueKey uniqueKey = metadata.getEntityBinding(Address.class.getName()).getTable().getUniqueKeys().values().iterator().next(); + UniqueKey uniqueKey = metadata.getEntityBinding(Address.class.getName()).getTable().getUniqueKeys().values().iterator().next(); assertEquals( expectedUniqueKeyName(), uniqueKey.getName() ); org.hibernate.mapping.ForeignKey foreignKey = (org.hibernate.mapping.ForeignKey) metadata.getEntityBinding(Address.class.getName()).getTable().getForeignKeys().values().iterator().next(); assertEquals( expectedForeignKeyName(), foreignKey.getName() ); - org.hibernate.mapping.Index index = metadata.getEntityBinding(Address.class.getName()).getTable().getIndexes().values().iterator().next(); + org.hibernate.mapping.Index index = metadata.getEntityBinding(Address.class.getName()).getTable().getIndexes().values().iterator().next(); assertEquals( expectedIndexName(), index.getName() ); } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/naturalid/NaturalIdOnManyToOne.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/naturalid/NaturalIdOnManyToOne.java index 0e577c2d60..71dbbe87c7 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/naturalid/NaturalIdOnManyToOne.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/naturalid/NaturalIdOnManyToOne.java @@ -23,13 +23,13 @@ import org.hibernate.annotations.NaturalIdCache; */ class NaturalIdOnManyToOne { - @Id - @GeneratedValue - int id; + @Id + @GeneratedValue + int id; - @NaturalId - @ManyToOne - Citizen citizen; + @NaturalId + @ManyToOne + Citizen citizen; public int getId() { return id; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/naturalid/cid/A.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/naturalid/cid/A.java index 696b439492..b1af4bda13 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/naturalid/cid/A.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/naturalid/cid/A.java @@ -16,22 +16,22 @@ import org.hibernate.annotations.NaturalId; */ @Entity public class A { - @EmbeddedId - private AId accountId; - @NaturalId(mutable = false) - private String shortCode; + @EmbeddedId + private AId accountId; + @NaturalId(mutable = false) + private String shortCode; - protected A() { - } + protected A() { + } - public A(AId accountId, String shortCode) { - this.accountId = accountId; - this.shortCode = shortCode; - } - public String getShortCode() { - return shortCode; - } - public AId getAccountId() { - return accountId; - } + public A(AId accountId, String shortCode) { + this.accountId = accountId; + this.shortCode = shortCode; + } + public String getShortCode() { + return shortCode; + } + public AId getAccountId() { + return accountId; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/naturalid/cid/AId.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/naturalid/cid/AId.java index c017edcbf3..ed6fc156c7 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/naturalid/cid/AId.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/naturalid/cid/AId.java @@ -14,33 +14,33 @@ import jakarta.persistence.Embeddable; @Embeddable public class AId implements java.io.Serializable { - private final int id; + private final int id; - protected AId() { - this.id = 0; - } + protected AId() { + this.id = 0; + } - public AId(int id) { - this.id = id; - } - public int intValue() { - return id; - } - @Override - public int hashCode() { - return id; - } - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - AId other = (AId) obj; - if (other != null && id != other.id) - return false; - return true; - } + public AId(int id) { + this.id = id; + } + public int intValue() { + return id; + } + @Override + public int hashCode() { + return id; + } + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + AId other = (AId) obj; + if (other != null && id != other.id) + return false; + return true; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetomany/A.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetomany/A.java index ec4fdab0ac..05548642b6 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetomany/A.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetomany/A.java @@ -31,8 +31,8 @@ public class A { @NotNull String name; - @OneToMany( cascade = CascadeType.ALL) - @Cascade(org.hibernate.annotations.CascadeType.ALL) + @OneToMany( cascade = CascadeType.ALL) + @Cascade(org.hibernate.annotations.CascadeType.ALL) @OrderBy("name") java.util.List bs = new ArrayList(); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetomany/B.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetomany/B.java index bc29b23e20..4be5b62168 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetomany/B.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetomany/B.java @@ -32,8 +32,8 @@ public class B { @NotNull String name; - @OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL) - @Cascade(org.hibernate.annotations.CascadeType.ALL) + @OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL) + @Cascade(org.hibernate.annotations.CascadeType.ALL) @OrderBy("name") java.util.List cs = new ArrayList(); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetomany/OneToManyTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetomany/OneToManyTest.java index 3c273aded2..64957209f0 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetomany/OneToManyTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetomany/OneToManyTest.java @@ -531,7 +531,7 @@ public class OneToManyTest extends BaseNonConfigCoreFunctionalTestCase { public void testJoinColumnConfiguredInXml() { PersistentClass pc = metadata().getEntityBinding( Model.class.getName() ); Table table = pc.getRootTable(); - Iterator iter = table.getColumns().iterator(); + Iterator iter = table.getColumns().iterator(); boolean joinColumnFound = false; while(iter.hasNext()) { Column column = (Column) iter.next(); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetomany/OrderByTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetomany/OrderByTest.java index 2478929880..aa6faf6eae 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetomany/OrderByTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetomany/OrderByTest.java @@ -288,7 +288,7 @@ public class OrderByTest extends BaseCoreFunctionalTestCase { @Test @JiraKey(value = "HHH-5732") public void testInverseIndex() { - final CollectionPersister transactionsPersister = sessionFactory().getRuntimeMetamodels() + final CollectionPersister transactionsPersister = sessionFactory().getRuntimeMetamodels() .getMappingMetamodel() .getCollectionDescriptor( BankAccount.class.getName() + ".transactions" ); assertTrue( transactionsPersister.isInverse() ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetoone/SerialNumber.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetoone/SerialNumber.java index 0a3a8a7a0c..b06df639fa 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetoone/SerialNumber.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetoone/SerialNumber.java @@ -42,7 +42,7 @@ public class SerialNumber { this.id = id; } - @Column(name="`value`") + @Column(name="`value`") public String getValue() { return value; } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/query/AllTables.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/query/AllTables.java index b4218de5d4..cbf3cdb912 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/query/AllTables.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/query/AllTables.java @@ -23,7 +23,7 @@ import org.hibernate.annotations.Formula; @FieldResult(name = "tableName", column = "t_name"), @FieldResult(name = "daysOld", column = "t_time") })) - public class AllTables { +public class AllTables { @Id @Column(name = "table_name", nullable = false) @@ -48,4 +48,4 @@ import org.hibernate.annotations.Formula; public void setDaysOld(String daysOld) { this.daysOld = daysOld; } - } +} diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/query/Attrvalue.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/query/Attrvalue.java index 1567647f61..5d5ccb4d41 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/query/Attrvalue.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/query/Attrvalue.java @@ -13,12 +13,12 @@ import jakarta.persistence.Id; @Entity public class Attrvalue { - @Id - @GeneratedValue - private Long id; + @Id + @GeneratedValue + private Long id; @Column(name = "val") - private String value; + private String value; public Long getId() { return id; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/query/Employee.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/query/Employee.java index 9e41123d42..267d942b3e 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/query/Employee.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/query/Employee.java @@ -13,15 +13,15 @@ import jakarta.persistence.ManyToOne; @Entity public class Employee { - @Id - @GeneratedValue - private Long id; + @Id + @GeneratedValue + private Long id; - @ManyToOne - private Employeegroup employeegroup; + @ManyToOne + private Employeegroup employeegroup; - @ManyToOne - private Attrset attrset; + @ManyToOne + private Attrset attrset; public Long getId() { return id; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/query/Employeegroup.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/query/Employeegroup.java index c365e5af10..79b54f4a03 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/query/Employeegroup.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/query/Employeegroup.java @@ -18,15 +18,15 @@ import jakarta.persistence.OneToMany; @Entity public class Employeegroup { - @Id - @GeneratedValue - private Long id; + @Id + @GeneratedValue + private Long id; - @OneToMany(cascade = CascadeType.ALL, mappedBy = "employeegroup") - private List employees = new ArrayList(); + @OneToMany(cascade = CascadeType.ALL, mappedBy = "employeegroup") + private List employees = new ArrayList(); - @ManyToOne - private Attrset attrset; + @ManyToOne + private Attrset attrset; public Long getId() { return id; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/query/QueryAndSQLTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/query/QueryAndSQLTest.java index 5a41949266..f4c6215f28 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/query/QueryAndSQLTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/query/QueryAndSQLTest.java @@ -91,7 +91,7 @@ public class QueryAndSQLTest { @Test public void testNativeQueryWithFormulaAttribute(SessionFactoryScope scope) { - final String dateFunctionRendered = scope.getSessionFactory().getJdbcServices().getDialect() + final String dateFunctionRendered = scope.getSessionFactory().getJdbcServices().getDialect() .currentDate(); String sql = String.format( @@ -125,7 +125,7 @@ public class QueryAndSQLTest { public void testNativeQueryWithFormulaAttributeWithoutAlias(SessionFactoryScope scope) { scope.inTransaction( session -> { - String sql = "select table_name , " + scope.getSessionFactory().getJdbcServices().getDialect() + String sql = "select table_name , " + scope.getSessionFactory().getJdbcServices().getDialect() .currentDate() + " as days_old from ALL_TABLES where table_name = 'AUDIT_ACTIONS' "; session.createNativeQuery( sql ).addEntity( "t", AllTables.class ).list(); } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/refcolnames/basics/BasicsRefColNamesTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/refcolnames/basics/BasicsRefColNamesTest.java index 2d417d8d0b..f091943dc2 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/refcolnames/basics/BasicsRefColNamesTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/refcolnames/basics/BasicsRefColNamesTest.java @@ -15,28 +15,28 @@ import org.junit.jupiter.api.Test; @DomainModel(annotatedClasses = {Region.class, Town.class}) @SessionFactory public class BasicsRefColNamesTest { - @Test - public void test(SessionFactoryScope scope) { - Region region = new Region(); - PostalCode postalCode = new PostalCode(); - postalCode.countryCode = "ES"; - postalCode.zipCode = 69; - region.countryCode = postalCode.countryCode; - region.zipCode = postalCode.zipCode; - Town town = new Town(); - TownCode townCode = new TownCode(); - townCode.town = "Barcelona"; - townCode.countryCode = "ES"; - townCode.zipCode = 69; - town.region = region; - town.townCode = townCode; - scope.inTransaction(s -> { - s.persist(region); - s.persist(town); - }); - scope.inTransaction(s -> { - Town t = s.createQuery("from Town join fetch region", Town.class).getSingleResult(); - Assertions.assertNotNull(t); - }); - } + @Test + public void test(SessionFactoryScope scope) { + Region region = new Region(); + PostalCode postalCode = new PostalCode(); + postalCode.countryCode = "ES"; + postalCode.zipCode = 69; + region.countryCode = postalCode.countryCode; + region.zipCode = postalCode.zipCode; + Town town = new Town(); + TownCode townCode = new TownCode(); + townCode.town = "Barcelona"; + townCode.countryCode = "ES"; + townCode.zipCode = 69; + town.region = region; + town.townCode = townCode; + scope.inTransaction(s -> { + s.persist(region); + s.persist(town); + }); + scope.inTransaction(s -> { + Town t = s.createQuery("from Town join fetch region", Town.class).getSingleResult(); + Assertions.assertNotNull(t); + }); + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/refcolnames/basics/PostalCode.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/refcolnames/basics/PostalCode.java index e72bfc0734..e748a60f9e 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/refcolnames/basics/PostalCode.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/refcolnames/basics/PostalCode.java @@ -12,8 +12,8 @@ import jakarta.persistence.MappedSuperclass; @Embeddable @MappedSuperclass class PostalCode { - @Column(name="country_code", nullable = false) - String countryCode; - @Column(name="zip_code", nullable = false) - int zipCode; + @Column(name="country_code", nullable = false) + String countryCode; + @Column(name="zip_code", nullable = false) + int zipCode; } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/refcolnames/basics/Region.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/refcolnames/basics/Region.java index e991eea22d..299ff34d07 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/refcolnames/basics/Region.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/refcolnames/basics/Region.java @@ -16,19 +16,19 @@ import org.hibernate.annotations.NaturalId; @Entity class Region { - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - @Column(name = "id", nullable = false) - int id; + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name = "id", nullable = false) + int id; - String name; + String name; - @NaturalId - @Column(name = "country_code", nullable = false) - String countryCode; + @NaturalId + @Column(name = "country_code", nullable = false) + String countryCode; - @NaturalId - @Column(name = "zip_code", nullable = false) - int zipCode; + @NaturalId + @Column(name = "zip_code", nullable = false) + int zipCode; } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/refcolnames/basics/Town.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/refcolnames/basics/Town.java index 342d7cc46c..9796ffe4fe 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/refcolnames/basics/Town.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/refcolnames/basics/Town.java @@ -19,19 +19,19 @@ import org.hibernate.annotations.NaturalId; @Entity class Town { - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - @Column(name = "id", nullable = false) - Integer id; + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name = "id", nullable = false) + Integer id; - String name; + String name; - @NaturalId - @Embedded - TownCode townCode; + @NaturalId + @Embedded + TownCode townCode; - @ManyToOne - @JoinColumn(name = "country_code", referencedColumnName = "country_code", nullable = false, insertable = false, updatable = false) - @JoinColumn(name = "zip_code", referencedColumnName = "zip_code", nullable = false, insertable = false, updatable = false) - Region region; + @ManyToOne + @JoinColumn(name = "country_code", referencedColumnName = "country_code", nullable = false, insertable = false, updatable = false) + @JoinColumn(name = "zip_code", referencedColumnName = "zip_code", nullable = false, insertable = false, updatable = false) + Region region; } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/refcolnames/basics/TownCode.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/refcolnames/basics/TownCode.java index 3044800950..63e9ceeae6 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/refcolnames/basics/TownCode.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/refcolnames/basics/TownCode.java @@ -10,5 +10,5 @@ import jakarta.persistence.Embeddable; @Embeddable class TownCode extends PostalCode { - String town; + String town; } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/refcolnames/embedded/EmbeddedRefColNamesTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/refcolnames/embedded/EmbeddedRefColNamesTest.java index d9fdffb438..e30fd92b60 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/refcolnames/embedded/EmbeddedRefColNamesTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/refcolnames/embedded/EmbeddedRefColNamesTest.java @@ -15,27 +15,27 @@ import org.junit.jupiter.api.Test; @DomainModel(annotatedClasses = {Region.class, Town.class}) @SessionFactory public class EmbeddedRefColNamesTest { - @Test - public void test(SessionFactoryScope scope) { - Region region = new Region(); - PostalCode postalCode = new PostalCode(); - postalCode.countryCode = "ES"; - postalCode.zipCode = 69; - region.postalCode = postalCode; - Town town = new Town(); - TownCode townCode = new TownCode(); - townCode.town = "Barcelona"; - townCode.countryCode = "ES"; - townCode.zipCode = 69; - town.region = region; - town.townCode = townCode; - scope.inTransaction(s -> { - s.persist(region); - s.persist(town); - }); - scope.inTransaction(s -> { - Town t = s.createQuery("from Town join fetch region", Town.class).getSingleResult(); - Assertions.assertNotNull(t); - }); - } + @Test + public void test(SessionFactoryScope scope) { + Region region = new Region(); + PostalCode postalCode = new PostalCode(); + postalCode.countryCode = "ES"; + postalCode.zipCode = 69; + region.postalCode = postalCode; + Town town = new Town(); + TownCode townCode = new TownCode(); + townCode.town = "Barcelona"; + townCode.countryCode = "ES"; + townCode.zipCode = 69; + town.region = region; + town.townCode = townCode; + scope.inTransaction(s -> { + s.persist(region); + s.persist(town); + }); + scope.inTransaction(s -> { + Town t = s.createQuery("from Town join fetch region", Town.class).getSingleResult(); + Assertions.assertNotNull(t); + }); + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/refcolnames/embedded/PostalCode.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/refcolnames/embedded/PostalCode.java index 1b309bd072..4f2c4a5f60 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/refcolnames/embedded/PostalCode.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/refcolnames/embedded/PostalCode.java @@ -12,8 +12,8 @@ import jakarta.persistence.MappedSuperclass; @Embeddable @MappedSuperclass class PostalCode { - @Column(name="country_code", nullable = false) - String countryCode; - @Column(name="zip_code", nullable = false) - int zipCode; + @Column(name="country_code", nullable = false) + String countryCode; + @Column(name="zip_code", nullable = false) + int zipCode; } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/refcolnames/embedded/Region.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/refcolnames/embedded/Region.java index 0a8ecdf237..35b46abdc8 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/refcolnames/embedded/Region.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/refcolnames/embedded/Region.java @@ -17,15 +17,15 @@ import org.hibernate.annotations.NaturalId; @Entity class Region { - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - @Column(name = "id", nullable = false) - int id; + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name = "id", nullable = false) + int id; - String name; + String name; - @NaturalId - @Embedded - PostalCode postalCode; + @NaturalId + @Embedded + PostalCode postalCode; } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/refcolnames/embedded/Town.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/refcolnames/embedded/Town.java index 269180f757..7a159c478a 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/refcolnames/embedded/Town.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/refcolnames/embedded/Town.java @@ -19,19 +19,19 @@ import org.hibernate.annotations.NaturalId; @Entity class Town { - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - @Column(name = "id", nullable = false) - Integer id; + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name = "id", nullable = false) + Integer id; - String name; + String name; - @NaturalId - @Embedded - TownCode townCode; + @NaturalId + @Embedded + TownCode townCode; - @ManyToOne - @JoinColumn(name = "country_code", referencedColumnName = "country_code", nullable = false, insertable = false, updatable = false) - @JoinColumn(name = "zip_code", referencedColumnName = "zip_code", nullable = false, insertable = false, updatable = false) - Region region; + @ManyToOne + @JoinColumn(name = "country_code", referencedColumnName = "country_code", nullable = false, insertable = false, updatable = false) + @JoinColumn(name = "zip_code", referencedColumnName = "zip_code", nullable = false, insertable = false, updatable = false) + Region region; } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/refcolnames/embedded/TownCode.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/refcolnames/embedded/TownCode.java index 4a03e635b2..47009f9424 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/refcolnames/embedded/TownCode.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/refcolnames/embedded/TownCode.java @@ -10,5 +10,5 @@ import jakarta.persistence.Embeddable; @Embeddable class TownCode extends PostalCode { - String town; + String town; } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/refcolnames/embeddedid/EmbeddedIdRefColNamesTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/refcolnames/embeddedid/EmbeddedIdRefColNamesTest.java index faea0d5017..9bac5cdce7 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/refcolnames/embeddedid/EmbeddedIdRefColNamesTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/refcolnames/embeddedid/EmbeddedIdRefColNamesTest.java @@ -15,27 +15,27 @@ import org.junit.jupiter.api.Test; @DomainModel(annotatedClasses = {Region.class, Town.class}) @SessionFactory public class EmbeddedIdRefColNamesTest { - @Test - public void test(SessionFactoryScope scope) { - Region region = new Region(); - PostalCode postalCode = new PostalCode(); - postalCode.countryCode = "ES"; - postalCode.zipCode = 69; - region.postalCode = postalCode; - Town town = new Town(); - TownCode townCode = new TownCode(); - townCode.town = "Barcelona"; - townCode.countryCode = "ES"; - townCode.zipCode = 69; - town.region = region; - town.townCode = townCode; - scope.inTransaction(s -> { - s.persist(region); - s.persist(town); - }); - scope.inTransaction(s -> { - Town t = s.createQuery("from Town join fetch region", Town.class).getSingleResult(); - Assertions.assertNotNull(t); - }); - } + @Test + public void test(SessionFactoryScope scope) { + Region region = new Region(); + PostalCode postalCode = new PostalCode(); + postalCode.countryCode = "ES"; + postalCode.zipCode = 69; + region.postalCode = postalCode; + Town town = new Town(); + TownCode townCode = new TownCode(); + townCode.town = "Barcelona"; + townCode.countryCode = "ES"; + townCode.zipCode = 69; + town.region = region; + town.townCode = townCode; + scope.inTransaction(s -> { + s.persist(region); + s.persist(town); + }); + scope.inTransaction(s -> { + Town t = s.createQuery("from Town join fetch region", Town.class).getSingleResult(); + Assertions.assertNotNull(t); + }); + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/refcolnames/embeddedid/PostalCode.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/refcolnames/embeddedid/PostalCode.java index 8edb878b7f..b079a6b3d0 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/refcolnames/embeddedid/PostalCode.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/refcolnames/embeddedid/PostalCode.java @@ -12,8 +12,8 @@ import jakarta.persistence.MappedSuperclass; @Embeddable @MappedSuperclass class PostalCode { - @Column(name="country_code") - String countryCode; - @Column(name="zip_code") - int zipCode; + @Column(name="country_code") + String countryCode; + @Column(name="zip_code") + int zipCode; } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/refcolnames/embeddedid/Region.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/refcolnames/embeddedid/Region.java index 95c75bf1e5..c7b4b951ff 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/refcolnames/embeddedid/Region.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/refcolnames/embeddedid/Region.java @@ -13,8 +13,8 @@ import jakarta.persistence.Entity; @Entity class Region { - @EmbeddedId - @AttributeOverride(name = "countryCode", column=@Column(name="region_country_code")) - @AttributeOverride(name = "zipCode", column=@Column(name="region_zip_code")) - PostalCode postalCode; + @EmbeddedId + @AttributeOverride(name = "countryCode", column=@Column(name="region_country_code")) + @AttributeOverride(name = "zipCode", column=@Column(name="region_zip_code")) + PostalCode postalCode; } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/refcolnames/embeddedid/Town.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/refcolnames/embeddedid/Town.java index f69bb028b7..b1826ccb10 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/refcolnames/embeddedid/Town.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/refcolnames/embeddedid/Town.java @@ -15,13 +15,13 @@ import jakarta.persistence.ManyToOne; @Entity class Town { - @EmbeddedId - @AttributeOverride(name = "countryCode", column=@Column(name="town_country_code")) - @AttributeOverride(name = "zipCode", column=@Column(name="town_zip_code")) - TownCode townCode; + @EmbeddedId + @AttributeOverride(name = "countryCode", column=@Column(name="town_country_code")) + @AttributeOverride(name = "zipCode", column=@Column(name="town_zip_code")) + TownCode townCode; - @ManyToOne - @JoinColumn(name = "town_zip_code", referencedColumnName = "region_zip_code", insertable = false, updatable = false) - @JoinColumn(name = "town_country_code", referencedColumnName = "region_country_code", insertable = false, updatable = false) - Region region; + @ManyToOne + @JoinColumn(name = "town_zip_code", referencedColumnName = "region_zip_code", insertable = false, updatable = false) + @JoinColumn(name = "town_country_code", referencedColumnName = "region_country_code", insertable = false, updatable = false) + Region region; } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/refcolnames/embeddedid/TownCode.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/refcolnames/embeddedid/TownCode.java index 6732479733..9cc08b83d6 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/refcolnames/embeddedid/TownCode.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/refcolnames/embeddedid/TownCode.java @@ -10,5 +10,5 @@ import jakarta.persistence.Embeddable; @Embeddable class TownCode extends PostalCode { - String town; + String town; } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/refcolnames/misc/Misc0Test.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/refcolnames/misc/Misc0Test.java index 3b961ca5e2..9b93ff267a 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/refcolnames/misc/Misc0Test.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/refcolnames/misc/Misc0Test.java @@ -24,36 +24,36 @@ import java.io.Serializable; @SessionFactory @JiraKey(value = "HHH-15355") public class Misc0Test { - @Test - public void test(SessionFactoryScope scope) { - scope.inTransaction(s->{ - EntityA a = new EntityA(); - EntityB b = new EntityB(); - a.flag = 1; - a.entityB = b; - b.entityA = a; - s.persist(a); - s.persist(b); + @Test + public void test(SessionFactoryScope scope) { + scope.inTransaction(s->{ + EntityA a = new EntityA(); + EntityB b = new EntityB(); + a.flag = 1; + a.entityB = b; + b.entityA = a; + s.persist(a); + s.persist(b); - s.createQuery("from B join entityA", EntityB.class).getSingleResult(); - }); - } + s.createQuery("from B join entityA", EntityB.class).getSingleResult(); + }); + } - @Entity(name = "A") - public static class EntityA implements Serializable { - @Id long entityBKey; - @Id int flag; - @OneToOne(mappedBy = "entityA") - public EntityB entityB; - } + @Entity(name = "A") + public static class EntityA implements Serializable { + @Id long entityBKey; + @Id int flag; + @OneToOne(mappedBy = "entityA") + public EntityB entityB; + } - @Entity(name = "B") - public static class EntityB implements Serializable { - @Id long entityBKey; - @OneToOne + @Entity(name = "B") + public static class EntityB implements Serializable { + @Id long entityBKey; + @OneToOne - @JoinColumnOrFormula(column = @JoinColumn(name = "entityBKey", referencedColumnName = "entityBKey", insertable = false, updatable = false)) - @JoinColumnOrFormula(formula = @JoinFormula(value = "1", referencedColumnName = "flag")) - public EntityA entityA; - } + @JoinColumnOrFormula(column = @JoinColumn(name = "entityBKey", referencedColumnName = "entityBKey", insertable = false, updatable = false)) + @JoinColumnOrFormula(formula = @JoinFormula(value = "1", referencedColumnName = "flag")) + public EntityA entityA; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/refcolnames/misc/Misc1Test.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/refcolnames/misc/Misc1Test.java index 3b6c0bd375..9b83a3841e 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/refcolnames/misc/Misc1Test.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/refcolnames/misc/Misc1Test.java @@ -22,35 +22,35 @@ import java.io.Serializable; @SessionFactory @JiraKey(value = "HHH-15355") public class Misc1Test { - @Test - public void test(SessionFactoryScope scope) { - scope.inTransaction(s->{ - EntityA a = new EntityA(); - EntityB b = new EntityB(); - a.entityB = b; - b.entityA = a; - s.persist(a); - s.persist(b); + @Test + public void test(SessionFactoryScope scope) { + scope.inTransaction(s->{ + EntityA a = new EntityA(); + EntityB b = new EntityB(); + a.entityB = b; + b.entityA = a; + s.persist(a); + s.persist(b); - s.createQuery("from B join entityA", EntityB.class).getSingleResult(); - }); - } + s.createQuery("from B join entityA", EntityB.class).getSingleResult(); + }); + } - @Entity(name = "A") - public static class EntityA implements Serializable { - @Id long entityBKey; - @Id boolean flag; - @OneToOne(mappedBy = "entityA") - public EntityB entityB; - } + @Entity(name = "A") + public static class EntityA implements Serializable { + @Id long entityBKey; + @Id boolean flag; + @OneToOne(mappedBy = "entityA") + public EntityB entityB; + } - @Entity(name = "B") - public static class EntityB implements Serializable { - @Id long entityBKey; - @Id boolean flag; - @OneToOne - @JoinColumn(name = "entityBKey", referencedColumnName = "entityBKey", insertable = false, updatable = false) - @JoinColumn(name = "flag", referencedColumnName = "flag", insertable = false, updatable = false) - public EntityA entityA; - } + @Entity(name = "B") + public static class EntityB implements Serializable { + @Id long entityBKey; + @Id boolean flag; + @OneToOne + @JoinColumn(name = "entityBKey", referencedColumnName = "entityBKey", insertable = false, updatable = false) + @JoinColumn(name = "flag", referencedColumnName = "flag", insertable = false, updatable = false) + public EntityA entityA; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/refcolnames/misc/Misc2Test.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/refcolnames/misc/Misc2Test.java index 6df996ede7..03bb9bee02 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/refcolnames/misc/Misc2Test.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/refcolnames/misc/Misc2Test.java @@ -29,131 +29,131 @@ import static org.junit.jupiter.api.Assertions.assertEquals; @SessionFactory @JiraKey(value = "HHH-15277") public class Misc2Test { - @Test - public void test(SessionFactoryScope scope) { - scope.inTransaction(s-> { - String aid = "boo"; + @Test + public void test(SessionFactoryScope scope) { + scope.inTransaction(s-> { + String aid = "boo"; - A a = new A(aid, "baa"); - B b = new B("some2", "thing2"); - s.persist(a); - a.b_R1 = b; - b.a_R1 = a; - s.persist(b); + A a = new A(aid, "baa"); + B b = new B("some2", "thing2"); + s.persist(a); + a.b_R1 = b; + b.a_R1 = a; + s.persist(b); - A result = s.createQuery("SELECT a FROM A a WHERE a.id.aOne = :param", A.class) - .setParameter("param", aid).getSingleResult(); - assertEquals( result.id.aOne, aid ); - }); - } + A result = s.createQuery("SELECT a FROM A a WHERE a.id.aOne = :param", A.class) + .setParameter("param", aid).getSingleResult(); + assertEquals( result.id.aOne, aid ); + }); + } - @Entity(name = "A") - @Table(name = "a_table") - public static class A { + @Entity(name = "A") + @Table(name = "a_table") + public static class A { - @EmbeddedId - private AId id; + @EmbeddedId + private AId id; - // primary side of relationship - @OneToOne(mappedBy = "a_R1", fetch = FetchType.LAZY, targetEntity = B.class) - private B b_R1; + // primary side of relationship + @OneToOne(mappedBy = "a_R1", fetch = FetchType.LAZY, targetEntity = B.class) + private B b_R1; - public A(String aOne, String aTwo) { - this.id = new AId(aOne, aTwo); - } + public A(String aOne, String aTwo) { + this.id = new AId(aOne, aTwo); + } - } + } - @Embeddable - public static class AId implements Serializable { + @Embeddable + public static class AId implements Serializable { - @Column(name = "a_one", nullable = false) - private String aOne; + @Column(name = "a_one", nullable = false) + private String aOne; - @Column(name = "a_two", nullable = false) - private String aTwo; + @Column(name = "a_two", nullable = false) + private String aTwo; - private AId() {} + private AId() {} - public AId(String aOne, String aTwo) { - this.aOne = aOne; - this.aTwo = aTwo; - } + public AId(String aOne, String aTwo) { + this.aOne = aOne; + this.aTwo = aTwo; + } - @Override - public int hashCode() { - return Objects.hash(aOne, aTwo); - } + @Override + public int hashCode() { + return Objects.hash(aOne, aTwo); + } - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - AId other = (AId) obj; - return Objects.equals(aOne, other.aOne) && Objects.equals(aTwo, other.aTwo); - } - } + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + AId other = (AId) obj; + return Objects.equals(aOne, other.aOne) && Objects.equals(aTwo, other.aTwo); + } + } - @Entity(name = "B") - @Table(name = "b_table") - public static class B { + @Entity(name = "B") + @Table(name = "b_table") + public static class B { - @EmbeddedId - private BId id; - // secondary side of relationship - @OneToOne(targetEntity = A.class, fetch = FetchType.LAZY) - @JoinColumn(name = "b_a_two", referencedColumnName = "a_two") - @JoinColumn(name = "b_a_one", referencedColumnName = "a_one") - private A a_R1; + @EmbeddedId + private BId id; + // secondary side of relationship + @OneToOne(targetEntity = A.class, fetch = FetchType.LAZY) + @JoinColumn(name = "b_a_two", referencedColumnName = "a_two") + @JoinColumn(name = "b_a_one", referencedColumnName = "a_one") + private A a_R1; - public B(String bOne, String bTwo) { - this.id = new BId(bOne, bTwo); - } + public B(String bOne, String bTwo) { + this.id = new BId(bOne, bTwo); + } - } + } - @Embeddable - public static class BId implements Serializable { + @Embeddable + public static class BId implements Serializable { - @Column(name = "b_one", nullable = false) - private String bOne = new String(""); + @Column(name = "b_one", nullable = false) + private String bOne = new String(""); - @Column(name = "b_two", nullable = false) - private String bTwo = new String(""); + @Column(name = "b_two", nullable = false) + private String bTwo = new String(""); - private BId() {} + private BId() {} - public BId(String bOne, String bTwo) { - this.bOne = bOne; - this.bTwo = bTwo; - } + public BId(String bOne, String bTwo) { + this.bOne = bOne; + this.bTwo = bTwo; + } - @Override - public int hashCode() { - return Objects.hash(bOne, bTwo); - } + @Override + public int hashCode() { + return Objects.hash(bOne, bTwo); + } - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - BId other = (BId) obj; - return Objects.equals(bOne, other.bOne) && Objects.equals(bTwo, other.bTwo); - } + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + BId other = (BId) obj; + return Objects.equals(bOne, other.bOne) && Objects.equals(bTwo, other.bTwo); + } - } + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/refcolnames/misc/Misc3Test.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/refcolnames/misc/Misc3Test.java index 35233c1f4f..ac0b3e4334 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/refcolnames/misc/Misc3Test.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/refcolnames/misc/Misc3Test.java @@ -28,56 +28,56 @@ import org.junit.jupiter.api.Test; @JiraKey(value = "HHH-14687") public class Misc3Test { - @Test - void test(SessionFactoryScope scope) { - scope.inTransaction(x -> {}); - } + @Test + void test(SessionFactoryScope scope) { + scope.inTransaction(x -> {}); + } - @Entity - @Table(name = "A") - public static final class A { - @Id - @GeneratedValue - private Long id; - @Basic - private String name; - } + @Entity + @Table(name = "A") + public static final class A { + @Id + @GeneratedValue + private Long id; + @Basic + private String name; + } - @Entity - @Table(name = "B", uniqueConstraints = {@UniqueConstraint(columnNames = {"a_id", "uniqueName"})}) - public static final class B { - @Id - @GeneratedValue - private Long id; + @Entity + @Table(name = "B", uniqueConstraints = {@UniqueConstraint(columnNames = {"a_id", "uniqueName"})}) + public static final class B { + @Id + @GeneratedValue + private Long id; - @Basic - private String uniqueName; - @ManyToOne - @JoinColumn(name="a_id", referencedColumnName="id") - private A a; - } + @Basic + private String uniqueName; + @ManyToOne + @JoinColumn(name="a_id", referencedColumnName="id") + private A a; + } - @Entity - @Table(name = "C", uniqueConstraints = {@UniqueConstraint(columnNames = {"a_id", "uniqueName"})}) - public static final class C { - @Id - @GeneratedValue - private Long id; + @Entity + @Table(name = "C", uniqueConstraints = {@UniqueConstraint(columnNames = {"a_id", "uniqueName"})}) + public static final class C { + @Id + @GeneratedValue + private Long id; - @Basic - private String uniqueName; + @Basic + private String uniqueName; - @ManyToOne - @JoinColumn(name="a_id", referencedColumnName="id") - private A a; - @ManyToOne - @JoinColumns( - value = { - @JoinColumn(name = "uniqueName", referencedColumnName = "uniqueName", insertable = false, updatable = false), - @JoinColumn(name = "a_id", referencedColumnName = "a_id", insertable = false, updatable = false) - }, - foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT) - ) - private B b; - } + @ManyToOne + @JoinColumn(name="a_id", referencedColumnName="id") + private A a; + @ManyToOne + @JoinColumns( + value = { + @JoinColumn(name = "uniqueName", referencedColumnName = "uniqueName", insertable = false, updatable = false), + @JoinColumn(name = "a_id", referencedColumnName = "a_id", insertable = false, updatable = false) + }, + foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT) + ) + private B b; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/refcolnames/misc/Misc4Test.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/refcolnames/misc/Misc4Test.java index 628eef6bcf..2f764eeab6 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/refcolnames/misc/Misc4Test.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/refcolnames/misc/Misc4Test.java @@ -32,272 +32,272 @@ import java.util.Objects; @JiraKey(value = "HHH-13054") public class Misc4Test { - @Test - void test(SessionFactoryScope scope) { - scope.inTransaction(x -> {}); - } + @Test + void test(SessionFactoryScope scope) { + scope.inTransaction(x -> {}); + } - @Entity - @Table(name = "A", schema = "", catalog = "") - @IdClass(APK.class) - public static class A { + @Entity + @Table(name = "A", schema = "", catalog = "") + @IdClass(APK.class) + public static class A { - private String a1; - private String a2; - private String a3; - private String a4; - private String a5; - private String a6; - private List bObj; + private String a1; + private String a2; + private String a3; + private String a4; + private String a5; + private String a6; + private List bObj; - @Id - @Column(name = "A1", nullable = false, length = 15) - public String getA1() { - return a1; - } + @Id + @Column(name = "A1", nullable = false, length = 15) + public String getA1() { + return a1; + } - public void setA1(String a1) { - this.a1 = a1; - } + public void setA1(String a1) { + this.a1 = a1; + } - @Basic - @Column(name = "A2", nullable = false, length = 15) - public String getA2() { - return a2; - } + @Basic + @Column(name = "A2", nullable = false, length = 15) + public String getA2() { + return a2; + } - public void setA2(String a2) { - this.a2 = a2; - } + public void setA2(String a2) { + this.a2 = a2; + } - @Basic - @Column(name = "A3", nullable = false, length = 15) - public String getA3() { - return a3; - } + @Basic + @Column(name = "A3", nullable = false, length = 15) + public String getA3() { + return a3; + } - public void setA3(String a3) { - this.a3 = a3; - } + public void setA3(String a3) { + this.a3 = a3; + } - @Id - @Column(name = "A4", nullable = false, length = 15) - public String getA4() { - return a4; - } + @Id + @Column(name = "A4", nullable = false, length = 15) + public String getA4() { + return a4; + } - public void setA4(String a4) { - this.a4 = a4; - } + public void setA4(String a4) { + this.a4 = a4; + } - @Id - @Column(name = "A5", nullable = false, length = 15) - public String getA5() { - return a5; - } + @Id + @Column(name = "A5", nullable = false, length = 15) + public String getA5() { + return a5; + } - public void setA5(String a5) { - this.a5 = a5; - } + public void setA5(String a5) { + this.a5 = a5; + } - @Id - @Column(name = "A6", nullable = false, length = 15) - public String getA6() { - return a6; - } + @Id + @Column(name = "A6", nullable = false, length = 15) + public String getA6() { + return a6; + } - public void setA6(String a6) { - this.a6 = a6; - } + public void setA6(String a6) { + this.a6 = a6; + } - @OneToMany(mappedBy = "aObj") - public List getB() { - return bObj; - } + @OneToMany(mappedBy = "aObj") + public List getB() { + return bObj; + } - public void setB(List bObj) { - this.bObj = bObj; - } - } + public void setB(List bObj) { + this.bObj = bObj; + } + } - public static class APK implements Serializable { + public static class APK implements Serializable { - private String a1; - private String a4; - private String a5; - private String a6; + private String a1; + private String a4; + private String a5; + private String a6; - @Column(name = "A1", nullable = false, length = 15) - @Id - public String getA1() { - return a1; - } + @Column(name = "A1", nullable = false, length = 15) + @Id + public String getA1() { + return a1; + } - public void setA1(String a1) { - this.a1 = a1; - } + public void setA1(String a1) { + this.a1 = a1; + } - @Column(name = "A4", nullable = false, length = 15) - @Id - public String getA4() { - return a4; - } + @Column(name = "A4", nullable = false, length = 15) + @Id + public String getA4() { + return a4; + } - public void setA4(String a4) { - this.a4 = a4; - } + public void setA4(String a4) { + this.a4 = a4; + } - @Column(name = "A5", nullable = false, length = 15) - @Id - public String getA5() { - return a5; - } + @Column(name = "A5", nullable = false, length = 15) + @Id + public String getA5() { + return a5; + } - public void setA5(String a5) { - this.a5 = a5; - } + public void setA5(String a5) { + this.a5 = a5; + } - public String getA6() { - return a6; - } + public String getA6() { + return a6; + } - public void setA6(String a6) { - this.a6 = a6; - } + public void setA6(String a6) { + this.a6 = a6; + } - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - APK apk = (APK) o; - return Objects.equals(a1, apk.a1) && - Objects.equals(a4, apk.a4) && - Objects.equals(a5, apk.a5) && - Objects.equals(a6, apk.a6); - } + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + APK apk = (APK) o; + return Objects.equals(a1, apk.a1) && + Objects.equals(a4, apk.a4) && + Objects.equals(a5, apk.a5) && + Objects.equals(a6, apk.a6); + } - @Override - public int hashCode() { + @Override + public int hashCode() { - return Objects.hash(a1, a4, a5, a6); - } - } + return Objects.hash(a1, a4, a5, a6); + } + } - @Entity - @Table(name = "B", schema = "", catalog = "") - @IdClass(BPK.class) - public static class B { + @Entity + @Table(name = "B", schema = "", catalog = "") + @IdClass(BPK.class) + public static class B { - private int a1; - private String a2; - private String a3; - private String b1; - private String b2; - private A aObj; + private int a1; + private String a2; + private String a3; + private String b1; + private String b2; + private A aObj; - @Id - @Column(name = "A1", nullable = false, length = 15) - public int getA1() { - return a1; - } + @Id + @Column(name = "A1", nullable = false, length = 15) + public int getA1() { + return a1; + } - public void setA1(int a1) { - this.a1 = a1; - } + public void setA1(int a1) { + this.a1 = a1; + } - @Id - @Column(name = "A2", nullable = false, length = 15) - public String getA2() { - return a2; - } + @Id + @Column(name = "A2", nullable = false, length = 15) + public String getA2() { + return a2; + } - public void setA2(String a2) { - this.a2 = a2; - } + public void setA2(String a2) { + this.a2 = a2; + } - @Id - @Column(name = "A3", nullable = false, length = 15) - public String getA3() { - return a3; - } + @Id + @Column(name = "A3", nullable = false, length = 15) + public String getA3() { + return a3; + } - public void setA3(String a3) { - this.a3 = a3; - } + public void setA3(String a3) { + this.a3 = a3; + } - @Basic - @Column(name = "B1", nullable = false, length = 15) - public String getB1() { - return b1; - } + @Basic + @Column(name = "B1", nullable = false, length = 15) + public String getB1() { + return b1; + } - public void setB1(String b1) { - this.b1 = b1; - } + public void setB1(String b1) { + this.b1 = b1; + } - @Basic - @Column(name = "B2", nullable = false, length = 15) - public String getB2() { - return b2; - } + @Basic + @Column(name = "B2", nullable = false, length = 15) + public String getB2() { + return b2; + } - public void setB2(String b2) { - this.b2 = b2; - } + public void setB2(String b2) { + this.b2 = b2; + } - @ManyToOne(targetEntity = A.class) - @Fetch(FetchMode.SELECT) - @JoinColumn(name ="A1", referencedColumnName = "A1" , insertable = false, updatable = false) - public A getaObj() { - return aObj; - } + @ManyToOne(targetEntity = A.class) + @Fetch(FetchMode.SELECT) + @JoinColumn(name ="A1", referencedColumnName = "A1" , insertable = false, updatable = false) + public A getaObj() { + return aObj; + } - public void setaObj(A aObj) { - this.aObj = aObj; - } - } + public void setaObj(A aObj) { + this.aObj = aObj; + } + } - public static class BPK implements Serializable { + public static class BPK implements Serializable { - private int a1; - private String a2; - private String a3; + private int a1; + private String a2; + private String a3; - @Column(name = "A1", nullable = false, length = 15) - @Id - public int getA1() { - return a1; - } + @Column(name = "A1", nullable = false, length = 15) + @Id + public int getA1() { + return a1; + } - public void setA1(int a1) { - this.a1 = a1; - } + public void setA1(int a1) { + this.a1 = a1; + } - @Column(name = "A2", nullable = false, length = 15) - @Id - public String getA2() { - return a2; - } + @Column(name = "A2", nullable = false, length = 15) + @Id + public String getA2() { + return a2; + } - public void setA2(String a2) { - this.a2 = a2; - } + public void setA2(String a2) { + this.a2 = a2; + } - @Column(name = "A3", nullable = false, length = 15) - @Id - public String getA3() { - return a3; - } + @Column(name = "A3", nullable = false, length = 15) + @Id + public String getA3() { + return a3; + } - public void setA3(String a3) { - this.a3 = a3; - } - } + public void setA3(String a3) { + this.a3 = a3; + } + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/refcolnames/mixed/MixedRefColNamesTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/refcolnames/mixed/MixedRefColNamesTest.java index 57a8ecc0bd..81452c07e0 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/refcolnames/mixed/MixedRefColNamesTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/refcolnames/mixed/MixedRefColNamesTest.java @@ -15,28 +15,28 @@ import org.junit.jupiter.api.Test; @DomainModel(annotatedClasses = {Region.class, Town.class}) @SessionFactory public class MixedRefColNamesTest { - @Test - public void test(SessionFactoryScope scope) { - Region region = new Region(); - PostalCode postalCode = new PostalCode(); - postalCode.countryCode = "ES"; - postalCode.zipCode = 69; - region.postalCode = postalCode; - Town town = new Town(); - TownCode townCode = new TownCode(); - townCode.town = "Barcelona"; - townCode.countryCode = "ES"; - townCode.zipCode = 69; - town.region = region; - town.townCode = townCode; - scope.inTransaction(s -> { - s.persist(region); - town.regionId = region.id; - s.persist(town); - }); - scope.inTransaction(s -> { - Town t = s.createQuery("from Town join fetch region", Town.class).getSingleResult(); - Assertions.assertNotNull(t); - }); - } + @Test + public void test(SessionFactoryScope scope) { + Region region = new Region(); + PostalCode postalCode = new PostalCode(); + postalCode.countryCode = "ES"; + postalCode.zipCode = 69; + region.postalCode = postalCode; + Town town = new Town(); + TownCode townCode = new TownCode(); + townCode.town = "Barcelona"; + townCode.countryCode = "ES"; + townCode.zipCode = 69; + town.region = region; + town.townCode = townCode; + scope.inTransaction(s -> { + s.persist(region); + town.regionId = region.id; + s.persist(town); + }); + scope.inTransaction(s -> { + Town t = s.createQuery("from Town join fetch region", Town.class).getSingleResult(); + Assertions.assertNotNull(t); + }); + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/refcolnames/mixed/PostalCode.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/refcolnames/mixed/PostalCode.java index bd16e988fe..f32b008238 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/refcolnames/mixed/PostalCode.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/refcolnames/mixed/PostalCode.java @@ -12,8 +12,8 @@ import jakarta.persistence.MappedSuperclass; @Embeddable @MappedSuperclass class PostalCode { - @Column(name="country_code", nullable = false) - String countryCode; - @Column(name="zip_code", nullable = false) - int zipCode; + @Column(name="country_code", nullable = false) + String countryCode; + @Column(name="zip_code", nullable = false) + int zipCode; } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/refcolnames/mixed/Region.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/refcolnames/mixed/Region.java index cf16e40a55..8fd32f225c 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/refcolnames/mixed/Region.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/refcolnames/mixed/Region.java @@ -17,15 +17,15 @@ import org.hibernate.annotations.NaturalId; @Entity class Region { - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - @Column(name = "id", nullable = false) - int id; + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name = "id", nullable = false) + int id; - String name; + String name; - @NaturalId - @Embedded - PostalCode postalCode; + @NaturalId + @Embedded + PostalCode postalCode; } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/refcolnames/mixed/Town.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/refcolnames/mixed/Town.java index 4ba17af642..3f09ee356c 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/refcolnames/mixed/Town.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/refcolnames/mixed/Town.java @@ -19,23 +19,23 @@ import org.hibernate.annotations.NaturalId; @Entity class Town { - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - @Column(name = "id", nullable = false) - Integer id; + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name = "id", nullable = false) + Integer id; - String name; + String name; - @NaturalId - @Embedded - TownCode townCode; + @NaturalId + @Embedded + TownCode townCode; - @Column(name = "region_id", nullable = false) - int regionId; + @Column(name = "region_id", nullable = false) + int regionId; - @ManyToOne - @JoinColumn(name = "region_id", referencedColumnName = "id", nullable = false, insertable = false, updatable = false) - @JoinColumn(name = "country_code", referencedColumnName = "country_code", nullable = false, insertable = false, updatable = false) - @JoinColumn(name = "zip_code", referencedColumnName = "zip_code", nullable = false, insertable = false, updatable = false) - Region region; + @ManyToOne + @JoinColumn(name = "region_id", referencedColumnName = "id", nullable = false, insertable = false, updatable = false) + @JoinColumn(name = "country_code", referencedColumnName = "country_code", nullable = false, insertable = false, updatable = false) + @JoinColumn(name = "zip_code", referencedColumnName = "zip_code", nullable = false, insertable = false, updatable = false) + Region region; } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/refcolnames/mixed/TownCode.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/refcolnames/mixed/TownCode.java index 3e322fea7b..fd262b9e73 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/refcolnames/mixed/TownCode.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/refcolnames/mixed/TownCode.java @@ -10,5 +10,5 @@ import jakarta.persistence.Embeddable; @Embeddable class TownCode extends PostalCode { - String town; + String town; } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/referencedcolumnname/WarehouseItem.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/referencedcolumnname/WarehouseItem.java index f7ec1d2b4e..5820ef5b52 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/referencedcolumnname/WarehouseItem.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/referencedcolumnname/WarehouseItem.java @@ -58,7 +58,7 @@ public class WarehouseItem { this.vendor = vendor; } - @ManyToOne + @ManyToOne @JoinColumn(name="vendor_id", referencedColumnName="vendor_id", insertable=false, updatable=false) @JoinColumn(name="item_id", referencedColumnName="item_id", insertable=false, updatable=false) public ItemCost getDefaultCost() { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/reflection/LogListener.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/reflection/LogListener.java index 9840faaccc..d5784fc4d2 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/reflection/LogListener.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/reflection/LogListener.java @@ -21,10 +21,10 @@ public class LogListener { @PrePersist @PostPersist public void log(Object entity) { - log.debug("Logging entity " + entity.getClass().getName() + " with hashCode: " + entity.hashCode()); + log.debug("Logging entity " + entity.getClass().getName() + " with hashCode: " + entity.hashCode()); } public void noLog(Object entity) { - log.debug("NoLogging entity " + entity.getClass().getName() + " with hashCode: " + entity.hashCode()); + log.debug("NoLogging entity " + entity.getClass().getName() + " with hashCode: " + entity.hashCode()); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/reflection/OrganizationConverter.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/reflection/OrganizationConverter.java index c4d6237ac6..1c2eeb3213 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/reflection/OrganizationConverter.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/reflection/OrganizationConverter.java @@ -13,15 +13,15 @@ import jakarta.persistence.AttributeConverter; */ public class OrganizationConverter implements AttributeConverter { - @Override - public String convertToDatabaseColumn(Organization organization) { - return "ORG-" + organization.getOrganizationId(); - } + @Override + public String convertToDatabaseColumn(Organization organization) { + return "ORG-" + organization.getOrganizationId(); + } - @Override - public Organization convertToEntityAttribute(String organizationId) { - Organization organization = new Organization(); - organization.setOrganizationId(organizationId.replace("ORG-", "")); - return organization; - } + @Override + public Organization convertToEntityAttribute(String organizationId) { + Organization organization = new Organization(); + organization.setOrganizationId(organizationId.replace("ORG-", "")); + return organization; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/reflection/OtherLogListener.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/reflection/OtherLogListener.java index 1a2a5001f8..7e4f811930 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/reflection/OtherLogListener.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/reflection/OtherLogListener.java @@ -20,10 +20,10 @@ public class OtherLogListener { @PrePersist @PostPersist public void log(Object entity) { - log.debug("Logging entity " + entity.getClass().getName() + " with hashCode: " + entity.hashCode()); + log.debug("Logging entity " + entity.getClass().getName() + " with hashCode: " + entity.hashCode()); } public void noLog(Object entity) { - log.debug("NoLogging entity " + entity.getClass().getName() + " with hashCode: " + entity.hashCode()); + log.debug("NoLogging entity " + entity.getClass().getName() + " with hashCode: " + entity.hashCode()); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/subselect/Bid.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/subselect/Bid.java index 4487b48546..6544e165bb 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/subselect/Bid.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/subselect/Bid.java @@ -20,7 +20,7 @@ public class Bid { private double amount; @Id - public int getId() { + public int getId() { return id; } public void setId(int id) { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/subselect/Item.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/subselect/Item.java index fc87de39bf..51bb4d8192 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/subselect/Item.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/subselect/Item.java @@ -18,7 +18,7 @@ public class Item { private String name; @Id - public long getId() { + public long getId() { return id; } public void setId(long id) { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/target/SizeImpl.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/target/SizeImpl.java index 67596b020f..1d92a34d72 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/target/SizeImpl.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/target/SizeImpl.java @@ -13,7 +13,7 @@ import jakarta.persistence.Embeddable; */ @Embeddable public class SizeImpl implements Size { - @Column(name = "name", nullable = false) + @Column(name = "name", nullable = false) private String name; public String getName() { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/type/dynamicparameterized/MyGenericType.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/type/dynamicparameterized/MyGenericType.java index 452e587b4e..e211e7c1ce 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/type/dynamicparameterized/MyGenericType.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/type/dynamicparameterized/MyGenericType.java @@ -31,7 +31,7 @@ public class MyGenericType implements UserType, DynamicParameterizedType @Override public void setParameterValues(Properties params) { parameterType = (ParameterType) params.get(PARAMETER_TYPE); - } + } @Override public void nullSafeSet(PreparedStatement st, Object value, int index, SharedSessionContractImplementor session) diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/uniqueconstraint/Building.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/uniqueconstraint/Building.java index 4da1fd1552..8b840b17a4 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/uniqueconstraint/Building.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/uniqueconstraint/Building.java @@ -15,24 +15,24 @@ import jakarta.persistence.MappedSuperclass; @MappedSuperclass public class Building { - public Long height; + public Long height; - private Room room; + private Room room; - public Long getHeight() { - return height; - } + public Long getHeight() { + return height; + } - public void setHeight(Long height) { - this.height = height; - } + public void setHeight(Long height) { + this.height = height; + } - @ManyToOne(optional = false) - public Room getRoom() { - return room; - } + @ManyToOne(optional = false) + public Room getRoom() { + return room; + } - public void setRoom(Room room) { - this.room = room; - } + public void setRoom(Room room) { + this.room = room; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/uniqueconstraint/House.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/uniqueconstraint/House.java index 270e02b8d9..1e970cbdac 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/uniqueconstraint/House.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/uniqueconstraint/House.java @@ -20,24 +20,24 @@ import jakarta.validation.constraints.NotNull; @Table(uniqueConstraints = {@UniqueConstraint(name = "uniqueWithInherited", columnNames = {"room_id", "cost"} )}) public class House extends Building { @Column(nullable = false) - public Long id; + public Long id; @NotNull - public Integer cost; + public Integer cost; - @Id - public Long getId() { - return id; - } + @Id + public Long getId() { + return id; + } - public void setId(Long id) { - this.id = id; - } + public void setId(Long id) { + this.id = id; + } - public Integer getCost() { - return cost; - } + public Integer getCost() { + return cost; + } - public void setCost(Integer cost) { - this.cost = cost; - } + public void setCost(Integer cost) { + this.cost = cost; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/uniqueconstraint/Room.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/uniqueconstraint/Room.java index 67764dbd42..1a22b4873d 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/uniqueconstraint/Room.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/uniqueconstraint/Room.java @@ -15,25 +15,25 @@ import jakarta.persistence.Id; */ @Entity public class Room { - private Long id; + private Long id; - private String name; + private String name; - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - @Id + @Id @Column(nullable = false) - public Long getId() { - return id; - } + public Long getId() { + return id; + } - public void setId(Long id) { - this.id = id; - } + public void setId(Long id) { + this.id = id; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/uniqueconstraint/UniqueConstraintTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/uniqueconstraint/UniqueConstraintTest.java index e60cf21597..a301708133 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/uniqueconstraint/UniqueConstraintTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/uniqueconstraint/UniqueConstraintTest.java @@ -28,43 +28,43 @@ import static org.junit.Assert.fail; @DomainModel( annotatedClasses = { Room.class, Building.class, House.class } ) @SessionFactory @SkipForDialect( dialectClass = SybaseDialect.class, - matchSubTypes = true, - reason = "Sybase does not properly support unique constraints on nullable columns" ) + matchSubTypes = true, + reason = "Sybase does not properly support unique constraints on nullable columns" ) public class UniqueConstraintTest { @Test public void testUniquenessConstraintWithSuperclassProperty(SessionFactoryScope scope) { - scope.inTransaction( (s) -> { - Room livingRoom = new Room(); - livingRoom.setId(1l); - livingRoom.setName("livingRoom"); - s.persist(livingRoom); - s.flush(); - House house = new House(); - house.setId(1l); - house.setCost(100); - house.setHeight(1000l); - house.setRoom(livingRoom); - s.persist(house); - s.flush(); - House house2 = new House(); - house2.setId(2l); - house2.setCost(100); - house2.setHeight(1001l); - house2.setRoom(livingRoom); - s.persist(house2); - try { - s.flush(); - fail( "Database constraint non-existent" ); - } - catch (PersistenceException e) { - assertTyping( JDBCException.class, e ); - //success - } - finally { - s.getTransaction().markRollbackOnly(); - } - } ); - } + scope.inTransaction( (s) -> { + Room livingRoom = new Room(); + livingRoom.setId(1l); + livingRoom.setName("livingRoom"); + s.persist(livingRoom); + s.flush(); + House house = new House(); + house.setId(1l); + house.setCost(100); + house.setHeight(1000l); + house.setRoom(livingRoom); + s.persist(house); + s.flush(); + House house2 = new House(); + house2.setId(2l); + house2.setCost(100); + house2.setHeight(1001l); + house2.setRoom(livingRoom); + s.persist(house2); + try { + s.flush(); + fail( "Database constraint non-existent" ); + } + catch (PersistenceException e) { + assertTyping( JDBCException.class, e ); + //success + } + finally { + s.getTransaction().markRollbackOnly(); + } + } ); + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/uniqueconstraint/UniqueConstraintUnitTests.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/uniqueconstraint/UniqueConstraintUnitTests.java index 4d5509e1c1..86069aef99 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/uniqueconstraint/UniqueConstraintUnitTests.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/uniqueconstraint/UniqueConstraintUnitTests.java @@ -62,7 +62,7 @@ public class UniqueConstraintUnitTests extends BaseUnitTestCase { } assertTrue( "Could not find the expected tables.", tableA != null && tableB != null ); - assertFalse( + assertFalse( tableA.getUniqueKeys().values().iterator().next().getName().equals( tableB.getUniqueKeys().values().iterator().next().getName() ) diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/xml/hbm/Z.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/xml/hbm/Z.java index cfc97fac35..79a3bc6083 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/xml/hbm/Z.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/xml/hbm/Z.java @@ -11,11 +11,11 @@ package org.hibernate.orm.test.annotations.xml.hbm; * @author Emmanuel Bernard */ public interface Z extends java.io.Serializable { - public Integer getZId(); +public Integer getZId(); - public void setZId(Integer zId); +public void setZId(Integer zId); - public B getB(); +public B getB(); - public void setB(B b); +public void setB(B b); } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/any/annotations/ImplicitPropertyList.java b/hibernate-core/src/test/java/org/hibernate/orm/test/any/annotations/ImplicitPropertyList.java index 1f46faa2b5..6d55a32fd7 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/any/annotations/ImplicitPropertyList.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/any/annotations/ImplicitPropertyList.java @@ -46,19 +46,19 @@ public class ImplicitPropertyList { @ManyToAny @Column(name = "property_type") @AnyKeyJavaClass( Integer.class ) - @Cascade( CascadeType.ALL ) - @JoinTable(name = "list_properties", + @Cascade( CascadeType.ALL ) + @JoinTable(name = "list_properties", joinColumns = @JoinColumn(name = "obj_id"), inverseJoinColumns = @JoinColumn(name = "property_id") ) - @OrderColumn(name = "prop_index") - public List getGeneralProperties() { - return generalProperties; - } + @OrderColumn(name = "prop_index") + public List getGeneralProperties() { + return generalProperties; + } - public void setGeneralProperties(List generalProperties) { - this.generalProperties = generalProperties; - } + public void setGeneralProperties(List generalProperties) { + this.generalProperties = generalProperties; + } @Id @GeneratedValue @@ -78,7 +78,7 @@ public class ImplicitPropertyList { this.name = name; } - @Any + @Any @Column(name = "property_type") @JoinColumn(name = "property_id") @AnyKeyJavaClass( Integer.class ) @@ -88,8 +88,8 @@ public class ImplicitPropertyList { @AnyDiscriminatorValue( discriminator = "L", entity = LongProperty.class) @Cascade( CascadeType.ALL ) public T getSomeProperty() { - return someProperty; - } + return someProperty; + } public void setSomeProperty(T someProperty) { this.someProperty = someProperty; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/any/annotations/LongProperty.java b/hibernate-core/src/test/java/org/hibernate/orm/test/any/annotations/LongProperty.java index a6528d7353..08dc8e7ab7 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/any/annotations/LongProperty.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/any/annotations/LongProperty.java @@ -14,50 +14,50 @@ import jakarta.persistence.Column; @Entity @Table(name = "long_property") public class LongProperty implements Property { - private Integer id; + private Integer id; - private String name; - private Long value; + private String name; + private Long value; - public LongProperty() { - super(); - } + public LongProperty() { + super(); + } - public LongProperty(String name, Long value) { - super(); - this.name = name; - this.value = value; - } + public LongProperty(String name, Long value) { + super(); + this.name = name; + this.value = value; + } - public String asString() { - return Long.toString(value); - } + public String asString() { + return Long.toString(value); + } - public String getName() { - return name; - } + public String getName() { + return name; + } - @Id - @GeneratedValue - public Integer getId() { - return id; - } + @Id + @GeneratedValue + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - @Column(name = "`value`") - public Long getValue() { - return value; - } + @Column(name = "`value`") + public Long getValue() { + return value; + } - public void setValue(Long value) { - this.value = value; - } + public void setValue(Long value) { + this.value = value; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/any/annotations/PropertyList.java b/hibernate-core/src/test/java/org/hibernate/orm/test/any/annotations/PropertyList.java index e186da590c..7c878a3ba0 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/any/annotations/PropertyList.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/any/annotations/PropertyList.java @@ -51,19 +51,19 @@ public class PropertyList { @AnyDiscriminatorValue( discriminator = "I", entity = IntegerProperty.class) @AnyDiscriminatorValue( discriminator = "S", entity = StringProperty.class) @AnyDiscriminatorValue( discriminator = "L", entity = LongProperty.class) - @Cascade( { CascadeType.ALL }) - @JoinTable(name = "list_properties", + @Cascade( { CascadeType.ALL }) + @JoinTable(name = "list_properties", joinColumns = @JoinColumn(name = "obj_id"), inverseJoinColumns = @JoinColumn(name = "property_id") ) - @OrderColumn(name = "prop_index") - public List getGeneralProperties() { - return generalProperties; - } + @OrderColumn(name = "prop_index") + public List getGeneralProperties() { + return generalProperties; + } - public void setGeneralProperties(List generalProperties) { - this.generalProperties = generalProperties; - } + public void setGeneralProperties(List generalProperties) { + this.generalProperties = generalProperties; + } @Id @GeneratedValue @@ -83,7 +83,7 @@ public class PropertyList { this.name = name; } - @Any + @Any @Column(name = "property_type") @JoinColumn(name = "property_id") @AnyKeyJavaClass( Integer.class ) @@ -93,8 +93,8 @@ public class PropertyList { @AnyDiscriminatorValue( discriminator = "L", entity = LongProperty.class) @Cascade( CascadeType.ALL ) public T getSomeProperty() { - return someProperty; - } + return someProperty; + } public void setSomeProperty(T someProperty) { this.someProperty = someProperty; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/associations/FieldWithUnderscoreTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/associations/FieldWithUnderscoreTest.java index 6c67a4315b..8521f8977e 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/associations/FieldWithUnderscoreTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/associations/FieldWithUnderscoreTest.java @@ -19,19 +19,19 @@ import org.junit.jupiter.api.Test; @DomainModel(annotatedClasses = {FieldWithUnderscoreTest.A.class, FieldWithUnderscoreTest.B.class}) public class FieldWithUnderscoreTest { - @Test void test(SessionFactoryScope scope) { - scope.inSession(s -> s.createSelectionQuery("from B join _a", B.class).getResultList()); - scope.inSession(s -> s.createSelectionQuery("from B left join fetch _a", B.class).getResultList()); - } + @Test void test(SessionFactoryScope scope) { + scope.inSession(s -> s.createSelectionQuery("from B join _a", B.class).getResultList()); + scope.inSession(s -> s.createSelectionQuery("from B left join fetch _a", B.class).getResultList()); + } - @Entity(name = "A") - static class A { - @Id Long _id; + @Entity(name = "A") + static class A { + @Id Long _id; - } - @Entity(name = "B") - static class B { - @Id Long _id; - @ManyToOne(fetch = FetchType.LAZY) A _a; - } + } + @Entity(name = "B") + static class B { + @Id Long _id; + @ManyToOne(fetch = FetchType.LAZY) A _a; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/associations/ManyToOneJoinTableTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/associations/ManyToOneJoinTableTest.java index 9671f47730..745220c80a 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/associations/ManyToOneJoinTableTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/associations/ManyToOneJoinTableTest.java @@ -19,36 +19,36 @@ import org.junit.jupiter.api.Test; @SessionFactory @DomainModel(annotatedClasses = - {ManyToOneJoinTableTest.Book.class, ManyToOneJoinTableTest.Publisher.class, ManyToOneJoinTableTest.Company.class}) + {ManyToOneJoinTableTest.Book.class, ManyToOneJoinTableTest.Publisher.class, ManyToOneJoinTableTest.Company.class}) public class ManyToOneJoinTableTest { - @Test void test(SessionFactoryScope scope) { - scope.inSession( s -> s.createSelectionQuery( "from Book join publisher", Object[].class ).getResultList() ); - scope.inSession( s -> s.createSelectionQuery( "from Book join publisher join company", Object[].class ).getResultList() ); - } + @Test void test(SessionFactoryScope scope) { + scope.inSession( s -> s.createSelectionQuery( "from Book join publisher", Object[].class ).getResultList() ); + scope.inSession( s -> s.createSelectionQuery( "from Book join publisher join company", Object[].class ).getResultList() ); + } - @Entity(name="Book") - static class Book { - @Id - @GeneratedValue - long id; - @ManyToOne - @JoinTable // no explicit table name! - Publisher publisher; - } - @Entity(name="Publisher") - static class Publisher { - @Id - @GeneratedValue - long id; - @OneToOne - @JoinTable // no explicit table name! - Company company; - } - @Entity(name="Company") - static class Company { - @Id - @GeneratedValue - long id; - } + @Entity(name="Book") + static class Book { + @Id + @GeneratedValue + long id; + @ManyToOne + @JoinTable // no explicit table name! + Publisher publisher; + } + @Entity(name="Publisher") + static class Publisher { + @Id + @GeneratedValue + long id; + @OneToOne + @JoinTable // no explicit table name! + Company company; + } + @Entity(name="Company") + static class Company { + @Id + @GeneratedValue + long id; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/associations/any/AnyTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/associations/any/AnyTest.java index a980a7a8d6..cc2089f683 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/associations/any/AnyTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/associations/any/AnyTest.java @@ -18,84 +18,84 @@ import static org.junit.Assert.assertEquals; */ public class AnyTest extends BaseCoreFunctionalTestCase { - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - IntegerProperty.class, - StringProperty.class, - PropertyHolder.class, - PropertyHolder2.class, - }; - } + @Override + protected Class[] getAnnotatedClasses() { + return new Class[] { + IntegerProperty.class, + StringProperty.class, + PropertyHolder.class, + PropertyHolder2.class, + }; + } - @Override - protected String[] getAnnotatedPackages() { - return new String[] { - getClass().getPackage().getName() - }; - } + @Override + protected String[] getAnnotatedPackages() { + return new String[] { + getClass().getPackage().getName() + }; + } - @Test - public void test() { + @Test + public void test() { - doInHibernate(this::sessionFactory, session -> { - //tag::associations-any-persist-example[] - IntegerProperty ageProperty = new IntegerProperty(); - ageProperty.setId(1L); - ageProperty.setName("age"); - ageProperty.setValue(23); + doInHibernate(this::sessionFactory, session -> { + //tag::associations-any-persist-example[] + IntegerProperty ageProperty = new IntegerProperty(); + ageProperty.setId(1L); + ageProperty.setName("age"); + ageProperty.setValue(23); - session.persist(ageProperty); + session.persist(ageProperty); - StringProperty nameProperty = new StringProperty(); - nameProperty.setId(1L); - nameProperty.setName("name"); - nameProperty.setValue("John Doe"); + StringProperty nameProperty = new StringProperty(); + nameProperty.setId(1L); + nameProperty.setName("name"); + nameProperty.setValue("John Doe"); - session.persist(nameProperty); + session.persist(nameProperty); - PropertyHolder namePropertyHolder = new PropertyHolder(); - namePropertyHolder.setId(1L); - namePropertyHolder.setProperty(nameProperty); + PropertyHolder namePropertyHolder = new PropertyHolder(); + namePropertyHolder.setId(1L); + namePropertyHolder.setProperty(nameProperty); - session.persist(namePropertyHolder); - //end::associations-any-persist-example[] - }); + session.persist(namePropertyHolder); + //end::associations-any-persist-example[] + }); - doInHibernate(this::sessionFactory, session -> { - //tag::associations-any-query-example[] - PropertyHolder propertyHolder = session.get(PropertyHolder.class, 1L); + doInHibernate(this::sessionFactory, session -> { + //tag::associations-any-query-example[] + PropertyHolder propertyHolder = session.get(PropertyHolder.class, 1L); - assertEquals("name", propertyHolder.getProperty().getName()); - assertEquals("John Doe", propertyHolder.getProperty().getValue()); - //end::associations-any-query-example[] - }); - } + assertEquals("name", propertyHolder.getProperty().getName()); + assertEquals("John Doe", propertyHolder.getProperty().getValue()); + //end::associations-any-query-example[] + }); + } - @Test - @Jira( "https://hibernate.atlassian.net/browse/HHH-16938" ) - public void testMetaAnnotated() { - doInHibernate( this::sessionFactory, session -> { - final StringProperty nameProperty = new StringProperty(); - nameProperty.setId( 2L ); - nameProperty.setName( "name2" ); - nameProperty.setValue( "Mario Rossi" ); - session.persist( nameProperty ); - final PropertyHolder2 namePropertyHolder = new PropertyHolder2(); - namePropertyHolder.setId( 2L ); - namePropertyHolder.setProperty( nameProperty ); - session.persist( namePropertyHolder ); - } ); - doInHibernate( this::sessionFactory, session -> { - final PropertyHolder2 propertyHolder = session.get( PropertyHolder2.class, 2L ); - assertEquals( "name2", propertyHolder.getProperty().getName() ); - assertEquals( "Mario Rossi", propertyHolder.getProperty().getValue() ); - final String propertyType = (String) session.createNativeQuery( - "select property_type from property_holder2", - String.class - ).getSingleResult(); - assertEquals( "S", propertyType ); - } ); - } + @Test + @Jira( "https://hibernate.atlassian.net/browse/HHH-16938" ) + public void testMetaAnnotated() { + doInHibernate( this::sessionFactory, session -> { + final StringProperty nameProperty = new StringProperty(); + nameProperty.setId( 2L ); + nameProperty.setName( "name2" ); + nameProperty.setValue( "Mario Rossi" ); + session.persist( nameProperty ); + final PropertyHolder2 namePropertyHolder = new PropertyHolder2(); + namePropertyHolder.setId( 2L ); + namePropertyHolder.setProperty( nameProperty ); + session.persist( namePropertyHolder ); + } ); + doInHibernate( this::sessionFactory, session -> { + final PropertyHolder2 propertyHolder = session.get( PropertyHolder2.class, 2L ); + assertEquals( "name2", propertyHolder.getProperty().getName() ); + assertEquals( "Mario Rossi", propertyHolder.getProperty().getValue() ); + final String propertyType = (String) session.createNativeQuery( + "select property_type from property_holder2", + String.class + ).getSingleResult(); + assertEquals( "S", propertyType ); + } ); + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/associations/any/IntegerProperty.java b/hibernate-core/src/test/java/org/hibernate/orm/test/associations/any/IntegerProperty.java index 0adef5c63d..0f75bf6f48 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/associations/any/IntegerProperty.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/associations/any/IntegerProperty.java @@ -17,43 +17,43 @@ import jakarta.persistence.Table; @Table(name="integer_property") public class IntegerProperty implements Property { - @Id - private Long id; + @Id + private Long id; - @Column(name = "`name`") - private String name; + @Column(name = "`name`") + private String name; - @Column(name = "`value`") - private Integer value; + @Column(name = "`value`") + private Integer value; - @Override - public String getName() { - return name; - } + @Override + public String getName() { + return name; + } - @Override - public Integer getValue() { - return value; - } + @Override + public Integer getValue() { + return value; + } - //Getters and setters omitted for brevity + //Getters and setters omitted for brevity //end::associations-any-property-example[] - public Long getId() { - return id; - } + public Long getId() { + return id; + } - public void setId(Long id) { - this.id = id; - } + public void setId(Long id) { + this.id = id; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - public void setValue(Integer value) { - this.value = value; - } + public void setValue(Integer value) { + this.value = value; + } //tag::associations-any-property-example[] } //end::associations-any-property-example[] diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/associations/any/ManyToAnyTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/associations/any/ManyToAnyTest.java index c2bad8c302..f5858abcc3 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/associations/any/ManyToAnyTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/associations/any/ManyToAnyTest.java @@ -18,63 +18,63 @@ import static org.junit.Assert.assertNotNull; */ public class ManyToAnyTest extends BaseCoreFunctionalTestCase { - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - IntegerProperty.class, - StringProperty.class, - PropertyRepository.class - }; - } + @Override + protected Class[] getAnnotatedClasses() { + return new Class[] { + IntegerProperty.class, + StringProperty.class, + PropertyRepository.class + }; + } - @Override - protected String[] getAnnotatedPackages() { - return new String[] { - getClass().getPackage().getName() - }; - } + @Override + protected String[] getAnnotatedPackages() { + return new String[] { + getClass().getPackage().getName() + }; + } - @Test - public void test() { + @Test + public void test() { - doInHibernate(this::sessionFactory, session -> { - //tag::associations-many-to-any-persist-example[] - IntegerProperty ageProperty = new IntegerProperty(); - ageProperty.setId(1L); - ageProperty.setName("age"); - ageProperty.setValue(23); + doInHibernate(this::sessionFactory, session -> { + //tag::associations-many-to-any-persist-example[] + IntegerProperty ageProperty = new IntegerProperty(); + ageProperty.setId(1L); + ageProperty.setName("age"); + ageProperty.setValue(23); - session.persist(ageProperty); + session.persist(ageProperty); - StringProperty nameProperty = new StringProperty(); - nameProperty.setId(1L); - nameProperty.setName("name"); - nameProperty.setValue("John Doe"); + StringProperty nameProperty = new StringProperty(); + nameProperty.setId(1L); + nameProperty.setName("name"); + nameProperty.setValue("John Doe"); - session.persist(nameProperty); + session.persist(nameProperty); - PropertyRepository propertyRepository = new PropertyRepository(); - propertyRepository.setId(1L); + PropertyRepository propertyRepository = new PropertyRepository(); + propertyRepository.setId(1L); - propertyRepository.getProperties().add(ageProperty); - propertyRepository.getProperties().add(nameProperty); + propertyRepository.getProperties().add(ageProperty); + propertyRepository.getProperties().add(nameProperty); - session.persist(propertyRepository); - //end::associations-many-to-any-persist-example[] - }); + session.persist(propertyRepository); + //end::associations-many-to-any-persist-example[] + }); - doInHibernate(this::sessionFactory, session -> { - //tag::associations-many-to-any-query-example[] - PropertyRepository propertyRepository = session.get(PropertyRepository.class, 1L); + doInHibernate(this::sessionFactory, session -> { + //tag::associations-many-to-any-query-example[] + PropertyRepository propertyRepository = session.get(PropertyRepository.class, 1L); - assertEquals(2, propertyRepository.getProperties().size()); + assertEquals(2, propertyRepository.getProperties().size()); - for(Property property : propertyRepository.getProperties()) { - assertNotNull(property.getValue()); - } - //end::associations-many-to-any-query-example[] - }); - } + for(Property property : propertyRepository.getProperties()) { + assertNotNull(property.getValue()); + } + //end::associations-many-to-any-query-example[] + }); + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/associations/any/Property.java b/hibernate-core/src/test/java/org/hibernate/orm/test/associations/any/Property.java index 0ce013e981..a0737a198d 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/associations/any/Property.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/associations/any/Property.java @@ -9,8 +9,8 @@ package org.hibernate.orm.test.associations.any; //tag::associations-any-property-example[] public interface Property { - String getName(); + String getName(); - T getValue(); + T getValue(); } //end::associations-any-property-example[] diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/associations/any/PropertyHolder.java b/hibernate-core/src/test/java/org/hibernate/orm/test/associations/any/PropertyHolder.java index 2aa5a9920b..a38490aed5 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/associations/any/PropertyHolder.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/associations/any/PropertyHolder.java @@ -23,36 +23,36 @@ import jakarta.persistence.Table; @Table(name = "property_holder") public class PropertyHolder { - @Id - private Long id; + @Id + private Long id; - @Any - @AnyDiscriminator(DiscriminatorType.STRING) - @AnyDiscriminatorValue(discriminator = "S", entity = StringProperty.class) - @AnyDiscriminatorValue(discriminator = "I", entity = IntegerProperty.class) - @AnyKeyJavaClass(Long.class) - @Column(name = "property_type") - @JoinColumn(name = "property_id") - private Property property; + @Any + @AnyDiscriminator(DiscriminatorType.STRING) + @AnyDiscriminatorValue(discriminator = "S", entity = StringProperty.class) + @AnyDiscriminatorValue(discriminator = "I", entity = IntegerProperty.class) + @AnyKeyJavaClass(Long.class) + @Column(name = "property_type") + @JoinColumn(name = "property_id") + private Property property; - //Getters and setters are omitted for brevity + //Getters and setters are omitted for brevity //end::associations-any-example[] - public Long getId() { - return id; - } + public Long getId() { + return id; + } - public void setId(Long id) { - this.id = id; - } + public void setId(Long id) { + this.id = id; + } - public Property getProperty() { - return property; - } + public Property getProperty() { + return property; + } - public void setProperty(Property property) { - this.property = property; - } + public void setProperty(Property property) { + this.property = property; + } //tag::associations-any-example[] } //end::associations-any-example[] diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/associations/any/PropertyHolder2.java b/hibernate-core/src/test/java/org/hibernate/orm/test/associations/any/PropertyHolder2.java index e036460a56..496013a49a 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/associations/any/PropertyHolder2.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/associations/any/PropertyHolder2.java @@ -19,33 +19,33 @@ import jakarta.persistence.Table; @Table(name = "property_holder2") public class PropertyHolder2 { - @Id - private Long id; + @Id + private Long id; - @Any - @PropertyDiscriminationDef - @Column(name = "property_type") - @JoinColumn(name = "property_id") - private Property property; + @Any + @PropertyDiscriminationDef + @Column(name = "property_type") + @JoinColumn(name = "property_id") + private Property property; - //Getters and setters are omitted for brevity + //Getters and setters are omitted for brevity //end::associations-any-def-example[] - public Long getId() { - return id; - } + public Long getId() { + return id; + } - public void setId(Long id) { - this.id = id; - } + public void setId(Long id) { + this.id = id; + } - public Property getProperty() { - return property; - } + public Property getProperty() { + return property; + } - public void setProperty(Property property) { - this.property = property; - } + public void setProperty(Property property) { + this.property = property; + } //tag::associations-any-def-example[] } //end::associations-any-def-example[] diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/associations/any/PropertyRepository.java b/hibernate-core/src/test/java/org/hibernate/orm/test/associations/any/PropertyRepository.java index 1362e9c9c2..c6cb96c977 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/associations/any/PropertyRepository.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/associations/any/PropertyRepository.java @@ -29,37 +29,37 @@ import static org.hibernate.annotations.CascadeType.ALL; @Table(name = "property_repository") public class PropertyRepository { - @Id - private Long id; + @Id + private Long id; - @ManyToAny - @AnyDiscriminator(DiscriminatorType.STRING) - @Column(name = "property_type") - @AnyKeyJavaClass(Long.class) - @AnyDiscriminatorValue(discriminator = "S", entity = StringProperty.class) - @AnyDiscriminatorValue(discriminator = "I", entity = IntegerProperty.class) - @Cascade(ALL) - @JoinTable(name = "repository_properties", - joinColumns = @JoinColumn(name = "repository_id"), - inverseJoinColumns = @JoinColumn(name = "property_id") - ) - private List> properties = new ArrayList<>(); + @ManyToAny + @AnyDiscriminator(DiscriminatorType.STRING) + @Column(name = "property_type") + @AnyKeyJavaClass(Long.class) + @AnyDiscriminatorValue(discriminator = "S", entity = StringProperty.class) + @AnyDiscriminatorValue(discriminator = "I", entity = IntegerProperty.class) + @Cascade(ALL) + @JoinTable(name = "repository_properties", + joinColumns = @JoinColumn(name = "repository_id"), + inverseJoinColumns = @JoinColumn(name = "property_id") +) + private List> properties = new ArrayList<>(); - //Getters and setters are omitted for brevity + //Getters and setters are omitted for brevity //end::associations-many-to-any-example[] - public Long getId() { - return id; - } + public Long getId() { + return id; + } - public void setId(Long id) { - this.id = id; - } + public void setId(Long id) { + this.id = id; + } - public List> getProperties() { - return properties; - } + public List> getProperties() { + return properties; + } - //tag::associations-many-to-any-example[] + //tag::associations-many-to-any-example[] } //end::associations-many-to-any-example[] diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/associations/any/StringProperty.java b/hibernate-core/src/test/java/org/hibernate/orm/test/associations/any/StringProperty.java index 424b1a089d..5eb93cacee 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/associations/any/StringProperty.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/associations/any/StringProperty.java @@ -17,43 +17,43 @@ import jakarta.persistence.Table; @Table(name="string_property") public class StringProperty implements Property { - @Id - private Long id; + @Id + private Long id; - @Column(name = "`name`") - private String name; + @Column(name = "`name`") + private String name; - @Column(name = "`value`") - private String value; + @Column(name = "`value`") + private String value; - @Override - public String getName() { - return name; - } + @Override + public String getName() { + return name; + } - @Override - public String getValue() { - return value; - } + @Override + public String getValue() { + return value; + } - //Getters and setters omitted for brevity + //Getters and setters omitted for brevity //end::associations-any-property-example[] - public Long getId() { - return id; - } + public Long getId() { + return id; + } - public void setId(Long id) { - this.id = id; - } + public void setId(Long id) { + this.id = id; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - public void setValue(String value) { - this.value = value; - } + public void setValue(String value) { + this.value = value; + } //tag::associations-any-property-example[] } //end::associations-any-property-example[] diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/batchfetch/A.java b/hibernate-core/src/test/java/org/hibernate/orm/test/batchfetch/A.java index 67bda0bf06..be2146e394 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/batchfetch/A.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/batchfetch/A.java @@ -13,42 +13,42 @@ import jakarta.persistence.OneToOne; @Entity public class A { - @Id - private Integer id; +@Id +private Integer id; - private String otherProperty; +private String otherProperty; - @OneToOne(fetch = FetchType.LAZY) - private B b; +@OneToOne(fetch = FetchType.LAZY) +private B b; - public A() { - } - - public A(Integer id) { - this.id = id; - } - - public Integer getId() { - return id; - } - - public void setId(Integer id) { - this.id = id; - } - - public String getOtherProperty() { - return otherProperty; - } - - public void setOtherProperty(String otherProperty) { - this.otherProperty = otherProperty; - } - - public B getB() { - return b; - } - - public void setB(B b) { - this.b = b; - } +public A() { +} + +public A(Integer id) { + this.id = id; +} + +public Integer getId() { + return id; +} + +public void setId(Integer id) { + this.id = id; +} + +public String getOtherProperty() { + return otherProperty; +} + +public void setOtherProperty(String otherProperty) { + this.otherProperty = otherProperty; +} + +public B getB() { + return b; +} + +public void setB(B b) { + this.b = b; +} } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/batchfetch/B.java b/hibernate-core/src/test/java/org/hibernate/orm/test/batchfetch/B.java index 60368d0309..29fd0e07bf 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/batchfetch/B.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/batchfetch/B.java @@ -17,43 +17,43 @@ import jakarta.persistence.IdClass; @BatchSize(size = 1000) public class B { - @Id - private Integer idPart1; +@Id +private Integer idPart1; - @Id - private Integer idPart2; +@Id +private Integer idPart2; - private String otherProperty; +private String otherProperty; - public B() { - } - - public B(Integer idPart1, Integer idPart2) { - this.idPart1 = idPart1; - this.idPart2 = idPart2; - } - - public Integer getIdPart1() { - return idPart1; - } - - public void setIdPart1(Integer idPart1) { - this.idPart1 = idPart1; - } - - public Integer getIdPart2() { - return idPart2; - } - - public void setIdPart2(Integer idPart2) { - this.idPart2 = idPart2; - } - - public String getOtherProperty() { - return otherProperty; - } - - public void setOtherProperty(String otherProperty) { - this.otherProperty = otherProperty; - } +public B() { +} + +public B(Integer idPart1, Integer idPart2) { + this.idPart1 = idPart1; + this.idPart2 = idPart2; +} + +public Integer getIdPart1() { + return idPart1; +} + +public void setIdPart1(Integer idPart1) { + this.idPart1 = idPart1; +} + +public Integer getIdPart2() { + return idPart2; +} + +public void setIdPart2(Integer idPart2) { + this.idPart2 = idPart2; +} + +public String getOtherProperty() { + return otherProperty; +} + +public void setOtherProperty(String otherProperty) { + this.otherProperty = otherProperty; +} } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/batchfetch/BId.java b/hibernate-core/src/test/java/org/hibernate/orm/test/batchfetch/BId.java index 6bd424bea5..6d0b5f2129 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/batchfetch/BId.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/batchfetch/BId.java @@ -9,38 +9,38 @@ package org.hibernate.orm.test.batchfetch; import java.io.Serializable; public class BId - implements Serializable { - private static final long serialVersionUID = 1L; + implements Serializable { +private static final long serialVersionUID = 1L; - private Integer idPart1; - private Integer idPart2; +private Integer idPart1; +private Integer idPart2; - public BId() { - } - - public BId(Integer idPart1, Integer idPart2) { - this.idPart1 = idPart1; - this.idPart2 = idPart2; - } - - public Integer getIdPart1() { - return idPart1; - } - - public void setIdPart1(Integer idPart1) { - this.idPart1 = idPart1; - } - - public Integer getIdPart2() { - return idPart2; - } - - public void setIdPart2(Integer idPart2) { - this.idPart2 = idPart2; - } - - @Override - public String toString() { - return "BId (" + idPart1 + ", " + idPart2 + ")"; - } +public BId() { +} + +public BId(Integer idPart1, Integer idPart2) { + this.idPart1 = idPart1; + this.idPart2 = idPart2; +} + +public Integer getIdPart1() { + return idPart1; +} + +public void setIdPart1(Integer idPart1) { + this.idPart1 = idPart1; +} + +public Integer getIdPart2() { + return idPart2; +} + +public void setIdPart2(Integer idPart2) { + this.idPart2 = idPart2; +} + +@Override +public String toString() { + return "BId (" + idPart1 + ", " + idPart2 + ")"; +} } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/batchfetch/BatchFetchStrategyLoadingTests.java b/hibernate-core/src/test/java/org/hibernate/orm/test/batchfetch/BatchFetchStrategyLoadingTests.java index 4db62fb10d..78c3c74e0a 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/batchfetch/BatchFetchStrategyLoadingTests.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/batchfetch/BatchFetchStrategyLoadingTests.java @@ -94,9 +94,9 @@ public class BatchFetchStrategyLoadingTests { @Entity( name = "Thing1" ) @Table( name = "Thing1" ) public static class Thing1 { - @Id - private Integer id; - @Basic + @Id + private Integer id; + @Basic private String name; @ManyToOne @JoinColumn( name = "thing2_fk" ) @@ -137,9 +137,9 @@ public class BatchFetchStrategyLoadingTests { @Table( name = "Thing2" ) @BatchSize( size = 64 ) public static class Thing2 { - @Id - private Integer id; - @Basic + @Id + private Integer id; + @Basic private String name; protected Thing2() { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/boot/database/qualfiedTableNaming/QualifiedTableNamingTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/boot/database/qualfiedTableNaming/QualifiedTableNamingTest.java index 45552e3c0c..3d9dfab129 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/boot/database/qualfiedTableNaming/QualifiedTableNamingTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/boot/database/qualfiedTableNaming/QualifiedTableNamingTest.java @@ -73,7 +73,7 @@ public class QualifiedTableNamingTest extends BaseNonConfigCoreFunctionalTestCas assertNotNull( expectedName ); - SingleTableEntityPersister persister = (SingleTableEntityPersister) sessionFactory().getRuntimeMetamodels() + SingleTableEntityPersister persister = (SingleTableEntityPersister) sessionFactory().getRuntimeMetamodels() .getMappingMetamodel() .getEntityDescriptor( Box.class.getName()); assertEquals( expectedName, persister.getTableName() ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/boot/database/qualfiedTableNaming/XmlDefinedNamespaceTests.java b/hibernate-core/src/test/java/org/hibernate/orm/test/boot/database/qualfiedTableNaming/XmlDefinedNamespaceTests.java index bf754c3c52..87f721566c 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/boot/database/qualfiedTableNaming/XmlDefinedNamespaceTests.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/boot/database/qualfiedTableNaming/XmlDefinedNamespaceTests.java @@ -89,21 +89,21 @@ public class XmlDefinedNamespaceTests { domainModel, serviceRegistry, new TargetDescriptor() { - @Override - public EnumSet getTargetTypes() { - return EnumSet.of( TargetType.SCRIPT ); - } + @Override + public EnumSet getTargetTypes() { + return EnumSet.of( TargetType.SCRIPT ); + } - @Override - public ScriptTargetOutput getScriptTargetOutput() { - return new ScriptTargetOutputToWriter( writer ) { - @Override - public void accept(String command) { - super.accept( command ); - } - }; - } - } + @Override + public ScriptTargetOutput getScriptTargetOutput() { + return new ScriptTargetOutputToWriter( writer ) { + @Override + public void accept(String command) { + super.accept( command ); + } + }; + } + } ); return writer.toString(); } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/BootstrapTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/BootstrapTest.java index 755b88563e..adb336cf86 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/BootstrapTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/BootstrapTest.java @@ -73,692 +73,692 @@ import jakarta.persistence.spi.PersistenceUnitTransactionType; */ public class BootstrapTest { - @Test - public void test_bootstrap_bootstrap_native_registry_BootstrapServiceRegistry_example() { - - ClassLoader customClassLoader = Thread.currentThread().getContextClassLoader(); - Integrator customIntegrator = new BeanValidationIntegrator(); - - //tag::example-bootstrap-native-BootstrapServiceRegistry[] - BootstrapServiceRegistryBuilder bootstrapRegistryBuilder = - new BootstrapServiceRegistryBuilder(); - // add a custom ClassLoader - bootstrapRegistryBuilder.applyClassLoader(customClassLoader); - // manually add an Integrator - bootstrapRegistryBuilder.applyIntegrator(customIntegrator); - - BootstrapServiceRegistry bootstrapRegistry = bootstrapRegistryBuilder.build(); - //end::example-bootstrap-native-BootstrapServiceRegistry[] - } - - @Test - public void test_bootstrap_bootstrap_native_registry_StandardServiceRegistryBuilder_example_1() { - //tag::example-bootstrap-native-StandardServiceRegistryBuilder[] - // An example using an implicitly built BootstrapServiceRegistry - StandardServiceRegistryBuilder standardRegistryBuilder = - new StandardServiceRegistryBuilder(); - //end::example-bootstrap-native-StandardServiceRegistryBuilder[] - } - - @Test - public void test_bootstrap_bootstrap_native_registry_StandardServiceRegistryBuilder_example_2() { - //tag::example-bootstrap-native-StandardServiceRegistryBuilder[] - - // An example using an explicitly built BootstrapServiceRegistry - BootstrapServiceRegistry bootstrapRegistry = - new BootstrapServiceRegistryBuilder().build(); - - StandardServiceRegistryBuilder standardRegistryBuilder = - new StandardServiceRegistryBuilder(bootstrapRegistry); - //end::example-bootstrap-native-StandardServiceRegistryBuilder[] - } - - @Test - @Disabled - public void testMetadataSources() { - //tag::example-bootstrap-native-MetadataSources[] - ServiceRegistry standardRegistry = - new StandardServiceRegistryBuilder().build(); - - MetadataSources sources = new MetadataSources(standardRegistry); - - // add a class using JPA/Hibernate annotations for mapping - sources.addAnnotatedClass(MyEntity.class); - - // add the name of a class using JPA/Hibernate annotations for mapping. - // differs from above in that accessing the Class is deferred which is - // important if using runtime bytecode-enhancement - sources.addAnnotatedClassName("org.hibernate.example.Customer"); - - // Read package-level metadata. - sources.addPackage("hibernate.example"); - - // Adds the named JPA orm.xml resource as a source: which performs the - // classpath lookup and parses the XML - sources.addResource("org/hibernate/example/Product.orm.xml"); - //end::example-bootstrap-native-MetadataSources[] - } - - @Test - @Disabled - public void testMetadataSourcesChaining() { - //tag::example-bootstrap-native-MetadataSources-chained[] - ServiceRegistry standardRegistry = - new StandardServiceRegistryBuilder().build(); - - MetadataSources sources = new MetadataSources(standardRegistry) - .addAnnotatedClass(MyEntity.class) - .addAnnotatedClassName("org.hibernate.example.Customer") - .addPackage("hibernate.example") - .addResource("org/hibernate/example/Product.orm.xml"); - //end::example-bootstrap-native-MetadataSources-chained[] - } - - @Test - public void testBuildMetadataNoBuilder() { - ServiceRegistry standardRegistry = new StandardServiceRegistryBuilder().build(); - MetadataSources sources = new MetadataSources(standardRegistry).addAnnotatedClass(MyEntity.class); - - //tag::example-bootstrap-native-Metadata-no-builder[] - Metadata metadata = sources.buildMetadata(); - //end::example-bootstrap-native-Metadata-no-builder[] - } - - @Test - public void testBuildMetadataUsingBuilder() { - ServiceRegistry standardRegistry = new StandardServiceRegistryBuilder().build(); - MetadataSources sources = new MetadataSources(standardRegistry).addAnnotatedClass(MyEntity.class); - - //tag::example-bootstrap-native-Metadata-using-builder[] - Metadata metadata = sources.getMetadataBuilder() - // configure second-level caching - .applyAccessType( AccessType.READ_WRITE ) - // default catalog - .applyImplicitCatalogName( "my_catalog" ) - // default schema - .applyImplicitSchemaName( "my_schema" ) - .build(); - //end::example-bootstrap-native-Metadata-using-builder[] - } - - @Test - public void testBuildSessionFactoryNoBuilder() { - ServiceRegistry standardRegistry = new StandardServiceRegistryBuilder().build(); - Metadata metadata = new MetadataSources(standardRegistry) - .addAnnotatedClass(MyEntity.class) - .buildMetadata(); - - //tag::example-bootstrap-native-SessionFactory-no-builder[] - final SessionFactory sessionFactory = metadata.buildSessionFactory(); - //end::example-bootstrap-native-SessionFactory-no-builder[] - - sessionFactory.close(); - } - - @Test - public void testBuildSessionFactoryUsingBuilder() { - ServiceRegistry standardRegistry = new StandardServiceRegistryBuilder().build(); - Metadata metadata = new MetadataSources(standardRegistry) - .addAnnotatedClass(MyEntity.class) - .buildMetadata(); - - //tag::example-bootstrap-native-SessionFactory-using-builder[] - final SessionFactory sessionFactory = metadata.getSessionFactoryBuilder() - .applyStatisticsSupport( true ) - .build(); - //end::example-bootstrap-native-SessionFactory-using-builder[] - - sessionFactory.close(); - } - - @Test - public void testNativeBuilders() { - //tag::example-bootstrap-native-MetadataBuilder[] - ServiceRegistry standardRegistry = - new StandardServiceRegistryBuilder().build(); - - MetadataSources sources = new MetadataSources(standardRegistry); - // ... - //end::example-bootstrap-native-MetadataBuilder[] - - sources.addAnnotatedClass(MyEntity.class); - - //tag::example-bootstrap-native-MetadataBuilder[] - final MetadataBuilder metadataBuilder = sources.getMetadataBuilder(); - - // configure second-level caching - metadataBuilder.applyAccessType( AccessType.READ_WRITE ); - - // default catalog - metadataBuilder.applyImplicitCatalogName( "my_catalog" ); - - // default schema - metadataBuilder.applyImplicitSchemaName( "my_schema" ); - //end::example-bootstrap-native-MetadataBuilder[] - - //tag::example-bootstrap-native-Metadata[] - Metadata metadata = metadataBuilder.build(); - // or Metadata metadata = sources.buildMetadata() - //end::example-bootstrap-native-Metadata[] - - //tag::example-bootstrap-native-SessionFactoryBuilder[] - SessionFactoryBuilder sessionFactoryBuilder - = metadata.getSessionFactoryBuilder(); - - // collect statistics - sessionFactoryBuilder.applyStatisticsSupport( true ); - //end::example-bootstrap-native-SessionFactoryBuilder[] - } - - @Test - public void test_bootstrap_bootstrap_native_registry_MetadataSources_example() { - - try { - //tag::bootstrap-bootstrap-native-registry-MetadataSources-example[] - ServiceRegistry standardRegistry = - new StandardServiceRegistryBuilder().build(); - - MetadataSources sources = new MetadataSources(standardRegistry); - - // alternatively, we can build the MetadataSources without passing - // a service registry, in which case it will build a default - // BootstrapServiceRegistry to use. But the approach shown - // above is preferred - // MetadataSources sources = new MetadataSources(); - - // add a class using JPA/Hibernate annotations for mapping - sources.addAnnotatedClass(MyEntity.class); - - // add the name of a class using JPA/Hibernate annotations for mapping. - // differs from above in that accessing the Class is deferred which is - // important if using runtime bytecode-enhancement - sources.addAnnotatedClassName("org.hibernate.example.Customer"); - - // Read package-level metadata. - sources.addPackage("hibernate.example"); - - // Read package-level metadata. - sources.addPackage(MyEntity.class.getPackage()); - - // Adds the named hbm.xml resource as a source: which performs the - // classpath lookup and parses the XML - sources.addResource("org/hibernate/example/Order.hbm.xml"); - - // Adds the named JPA orm.xml resource as a source: which performs the - // classpath lookup and parses the XML - sources.addResource("org/hibernate/example/Product.orm.xml"); - - // Read all mapping documents from a directory tree. - // Assumes that any file named *.hbm.xml is a mapping document. - sources.addDirectory(new File(".")); - - // Read mappings from a particular XML file - sources.addFile(new File("./mapping.xml")); - - // Read all mappings from a jar file. - // Assumes that any file named *.hbm.xml is a mapping document. - sources.addJar(new File("./entities.jar")); - //end::bootstrap-bootstrap-native-registry-MetadataSources-example[] - } - catch (Exception ignore) { - - } - } - - - @Test - public void test_bootstrap_bootstrap_native_metadata_source_example() { - try { - { - //tag::bootstrap-native-metadata-source-example[] - ServiceRegistry standardRegistry = - new StandardServiceRegistryBuilder().build(); - - MetadataSources sources = new MetadataSources(standardRegistry) - .addAnnotatedClass(MyEntity.class) - .addAnnotatedClassName("org.hibernate.example.Customer") - .addResource("org/hibernate/example/Order.hbm.xml") - .addResource("org/hibernate/example/Product.orm.xml"); - //end::bootstrap-native-metadata-source-example[] - } - - { - AttributeConverter myAttributeConverter = new AttributeConverter() { - @Override - public Object convertToDatabaseColumn(Object attribute) { - return null; - } - - @Override - public Object convertToEntityAttribute(Object dbData) { - return null; - } - } ; - //tag::bootstrap-native-metadata-builder-example[] - ServiceRegistry standardRegistry = - new StandardServiceRegistryBuilder().build(); - - MetadataSources sources = new MetadataSources(standardRegistry); - - MetadataBuilder metadataBuilder = sources.getMetadataBuilder(); - - // Use the JPA-compliant implicit naming strategy - metadataBuilder.applyImplicitNamingStrategy( - ImplicitNamingStrategyJpaCompliantImpl.INSTANCE); - - // specify the schema name to use for tables, etc when none is explicitly specified - metadataBuilder.applyImplicitSchemaName("my_default_schema"); - - // specify a custom Attribute Converter - metadataBuilder.applyAttributeConverter(myAttributeConverter); - - Metadata metadata = metadataBuilder.build(); - //end::bootstrap-native-metadata-builder-example[] - } - } - catch (Exception ignore) { - - } - } - - @Test - public void test_bootstrap_bootstrap_native_SessionFactory_example() { - try { - { - //tag::bootstrap-native-SessionFactory-example[] - StandardServiceRegistry standardRegistry = new StandardServiceRegistryBuilder() - .configure("org/hibernate/example/hibernate.cfg.xml") - .build(); - - Metadata metadata = new MetadataSources(standardRegistry) - .addAnnotatedClass(MyEntity.class) - .addAnnotatedClassName("org.hibernate.example.Customer") - .addResource("org/hibernate/example/Order.hbm.xml") - .addResource("org/hibernate/example/Product.orm.xml") - .getMetadataBuilder() - .applyImplicitNamingStrategy(ImplicitNamingStrategyJpaCompliantImpl.INSTANCE) - .build(); - - SessionFactory sessionFactory = metadata.getSessionFactoryBuilder() - .applyBeanManager(getBeanManager()) - .build(); - //end::bootstrap-native-SessionFactory-example[] - } - { - //tag::bootstrap-native-SessionFactoryBuilder-example[] - StandardServiceRegistry standardRegistry = new StandardServiceRegistryBuilder() - .configure("org/hibernate/example/hibernate.cfg.xml") - .build(); - - Metadata metadata = new MetadataSources(standardRegistry) - .addAnnotatedClass(MyEntity.class) - .addAnnotatedClassName("org.hibernate.example.Customer") - .addResource("org/hibernate/example/Order.hbm.xml") - .addResource("org/hibernate/example/Product.orm.xml") - .getMetadataBuilder() - .applyImplicitNamingStrategy(ImplicitNamingStrategyJpaCompliantImpl.INSTANCE) - .build(); - - SessionFactoryBuilder sessionFactoryBuilder = metadata.getSessionFactoryBuilder(); - - // Supply a SessionFactory-level Interceptor - sessionFactoryBuilder.applyInterceptor(new CustomSessionFactoryInterceptor()); - - // Add a custom observer - sessionFactoryBuilder.addSessionFactoryObservers(new CustomSessionFactoryObserver()); - - // Apply a CDI BeanManager (for JPA event listeners) - sessionFactoryBuilder.applyBeanManager(getBeanManager()); - - SessionFactory sessionFactory = sessionFactoryBuilder.build(); - //end::bootstrap-native-SessionFactoryBuilder-example[] - } - } - catch (Exception ignore) { - - } - } - - @Test - public void test_bootstrap_bootstrap_jpa_compliant_EntityManagerFactory_example() { - try { - //tag::bootstrap-jpa-compliant-EntityManagerFactory-example[] - // Create an EMF for our CRM persistence-unit. - EntityManagerFactory emf = Persistence.createEntityManagerFactory("CRM"); - //end::bootstrap-jpa-compliant-EntityManagerFactory-example[] - } catch (Exception ignore) {} - } - - @Test - public void test_bootstrap_bootstrap_native_EntityManagerFactory_example() { - - try { - //tag::bootstrap-native-EntityManagerFactory-example[] - String persistenceUnitName = "CRM"; - List entityClassNames = new ArrayList<>(); - Properties properties = new Properties(); - - PersistenceUnitInfoImpl persistenceUnitInfo = new PersistenceUnitInfoImpl( - persistenceUnitName, - entityClassNames, - properties - ); - - Map integrationSettings = ServiceRegistryUtil.createBaseSettings(); - integrationSettings.put( - AvailableSettings.INTERCEPTOR, - new CustomSessionFactoryInterceptor() - ); - - EntityManagerFactoryBuilderImpl entityManagerFactoryBuilder = - new EntityManagerFactoryBuilderImpl( - new PersistenceUnitInfoDescriptor(persistenceUnitInfo), - integrationSettings - ); - - EntityManagerFactory emf = entityManagerFactoryBuilder.build(); - //end::bootstrap-native-EntityManagerFactory-example[] - } - catch (Exception ignore) { - } - } - - @Test - @JiraKey("HHH-17154") - public void build_EntityManagerFactory_with_NewTempClassLoader() { - new EntityManagerFactoryBuilderImpl( - new PersistenceUnitInfoDescriptor( - new PersistenceUnitInfoImpl( "", new ArrayList<>(), new Properties() ) { - @Override - public ClassLoader getNewTempClassLoader() { - return Thread.currentThread().getContextClassLoader(); - } - } - ), + @Test + public void test_bootstrap_bootstrap_native_registry_BootstrapServiceRegistry_example() { + + ClassLoader customClassLoader = Thread.currentThread().getContextClassLoader(); + Integrator customIntegrator = new BeanValidationIntegrator(); + + //tag::example-bootstrap-native-BootstrapServiceRegistry[] + BootstrapServiceRegistryBuilder bootstrapRegistryBuilder = + new BootstrapServiceRegistryBuilder(); + // add a custom ClassLoader + bootstrapRegistryBuilder.applyClassLoader(customClassLoader); + // manually add an Integrator + bootstrapRegistryBuilder.applyIntegrator(customIntegrator); + + BootstrapServiceRegistry bootstrapRegistry = bootstrapRegistryBuilder.build(); + //end::example-bootstrap-native-BootstrapServiceRegistry[] + } + + @Test + public void test_bootstrap_bootstrap_native_registry_StandardServiceRegistryBuilder_example_1() { + //tag::example-bootstrap-native-StandardServiceRegistryBuilder[] + // An example using an implicitly built BootstrapServiceRegistry + StandardServiceRegistryBuilder standardRegistryBuilder = + new StandardServiceRegistryBuilder(); + //end::example-bootstrap-native-StandardServiceRegistryBuilder[] + } + + @Test + public void test_bootstrap_bootstrap_native_registry_StandardServiceRegistryBuilder_example_2() { + //tag::example-bootstrap-native-StandardServiceRegistryBuilder[] + + // An example using an explicitly built BootstrapServiceRegistry + BootstrapServiceRegistry bootstrapRegistry = + new BootstrapServiceRegistryBuilder().build(); + + StandardServiceRegistryBuilder standardRegistryBuilder = + new StandardServiceRegistryBuilder(bootstrapRegistry); + //end::example-bootstrap-native-StandardServiceRegistryBuilder[] + } + + @Test + @Disabled + public void testMetadataSources() { + //tag::example-bootstrap-native-MetadataSources[] + ServiceRegistry standardRegistry = + new StandardServiceRegistryBuilder().build(); + + MetadataSources sources = new MetadataSources(standardRegistry); + + // add a class using JPA/Hibernate annotations for mapping + sources.addAnnotatedClass(MyEntity.class); + + // add the name of a class using JPA/Hibernate annotations for mapping. + // differs from above in that accessing the Class is deferred which is + // important if using runtime bytecode-enhancement + sources.addAnnotatedClassName("org.hibernate.example.Customer"); + + // Read package-level metadata. + sources.addPackage("hibernate.example"); + + // Adds the named JPA orm.xml resource as a source: which performs the + // classpath lookup and parses the XML + sources.addResource("org/hibernate/example/Product.orm.xml"); + //end::example-bootstrap-native-MetadataSources[] + } + + @Test + @Disabled + public void testMetadataSourcesChaining() { + //tag::example-bootstrap-native-MetadataSources-chained[] + ServiceRegistry standardRegistry = + new StandardServiceRegistryBuilder().build(); + + MetadataSources sources = new MetadataSources(standardRegistry) + .addAnnotatedClass(MyEntity.class) + .addAnnotatedClassName("org.hibernate.example.Customer") + .addPackage("hibernate.example") + .addResource("org/hibernate/example/Product.orm.xml"); + //end::example-bootstrap-native-MetadataSources-chained[] + } + + @Test + public void testBuildMetadataNoBuilder() { + ServiceRegistry standardRegistry = new StandardServiceRegistryBuilder().build(); + MetadataSources sources = new MetadataSources(standardRegistry).addAnnotatedClass(MyEntity.class); + + //tag::example-bootstrap-native-Metadata-no-builder[] + Metadata metadata = sources.buildMetadata(); + //end::example-bootstrap-native-Metadata-no-builder[] + } + + @Test + public void testBuildMetadataUsingBuilder() { + ServiceRegistry standardRegistry = new StandardServiceRegistryBuilder().build(); + MetadataSources sources = new MetadataSources(standardRegistry).addAnnotatedClass(MyEntity.class); + + //tag::example-bootstrap-native-Metadata-using-builder[] + Metadata metadata = sources.getMetadataBuilder() + // configure second-level caching + .applyAccessType( AccessType.READ_WRITE ) + // default catalog + .applyImplicitCatalogName( "my_catalog" ) + // default schema + .applyImplicitSchemaName( "my_schema" ) + .build(); + //end::example-bootstrap-native-Metadata-using-builder[] + } + + @Test + public void testBuildSessionFactoryNoBuilder() { + ServiceRegistry standardRegistry = new StandardServiceRegistryBuilder().build(); + Metadata metadata = new MetadataSources(standardRegistry) + .addAnnotatedClass(MyEntity.class) + .buildMetadata(); + + //tag::example-bootstrap-native-SessionFactory-no-builder[] + final SessionFactory sessionFactory = metadata.buildSessionFactory(); + //end::example-bootstrap-native-SessionFactory-no-builder[] + + sessionFactory.close(); + } + + @Test + public void testBuildSessionFactoryUsingBuilder() { + ServiceRegistry standardRegistry = new StandardServiceRegistryBuilder().build(); + Metadata metadata = new MetadataSources(standardRegistry) + .addAnnotatedClass(MyEntity.class) + .buildMetadata(); + + //tag::example-bootstrap-native-SessionFactory-using-builder[] + final SessionFactory sessionFactory = metadata.getSessionFactoryBuilder() + .applyStatisticsSupport( true ) + .build(); + //end::example-bootstrap-native-SessionFactory-using-builder[] + + sessionFactory.close(); + } + + @Test + public void testNativeBuilders() { + //tag::example-bootstrap-native-MetadataBuilder[] + ServiceRegistry standardRegistry = + new StandardServiceRegistryBuilder().build(); + + MetadataSources sources = new MetadataSources(standardRegistry); + // ... + //end::example-bootstrap-native-MetadataBuilder[] + + sources.addAnnotatedClass(MyEntity.class); + + //tag::example-bootstrap-native-MetadataBuilder[] + final MetadataBuilder metadataBuilder = sources.getMetadataBuilder(); + + // configure second-level caching + metadataBuilder.applyAccessType( AccessType.READ_WRITE ); + + // default catalog + metadataBuilder.applyImplicitCatalogName( "my_catalog" ); + + // default schema + metadataBuilder.applyImplicitSchemaName( "my_schema" ); + //end::example-bootstrap-native-MetadataBuilder[] + + //tag::example-bootstrap-native-Metadata[] + Metadata metadata = metadataBuilder.build(); + // or Metadata metadata = sources.buildMetadata() + //end::example-bootstrap-native-Metadata[] + + //tag::example-bootstrap-native-SessionFactoryBuilder[] + SessionFactoryBuilder sessionFactoryBuilder + = metadata.getSessionFactoryBuilder(); + + // collect statistics + sessionFactoryBuilder.applyStatisticsSupport( true ); + //end::example-bootstrap-native-SessionFactoryBuilder[] + } + + @Test + public void test_bootstrap_bootstrap_native_registry_MetadataSources_example() { + + try { + //tag::bootstrap-bootstrap-native-registry-MetadataSources-example[] + ServiceRegistry standardRegistry = + new StandardServiceRegistryBuilder().build(); + + MetadataSources sources = new MetadataSources(standardRegistry); + + // alternatively, we can build the MetadataSources without passing + // a service registry, in which case it will build a default + // BootstrapServiceRegistry to use. But the approach shown + // above is preferred + // MetadataSources sources = new MetadataSources(); + + // add a class using JPA/Hibernate annotations for mapping + sources.addAnnotatedClass(MyEntity.class); + + // add the name of a class using JPA/Hibernate annotations for mapping. + // differs from above in that accessing the Class is deferred which is + // important if using runtime bytecode-enhancement + sources.addAnnotatedClassName("org.hibernate.example.Customer"); + + // Read package-level metadata. + sources.addPackage("hibernate.example"); + + // Read package-level metadata. + sources.addPackage(MyEntity.class.getPackage()); + + // Adds the named hbm.xml resource as a source: which performs the + // classpath lookup and parses the XML + sources.addResource("org/hibernate/example/Order.hbm.xml"); + + // Adds the named JPA orm.xml resource as a source: which performs the + // classpath lookup and parses the XML + sources.addResource("org/hibernate/example/Product.orm.xml"); + + // Read all mapping documents from a directory tree. + // Assumes that any file named *.hbm.xml is a mapping document. + sources.addDirectory(new File(".")); + + // Read mappings from a particular XML file + sources.addFile(new File("./mapping.xml")); + + // Read all mappings from a jar file. + // Assumes that any file named *.hbm.xml is a mapping document. + sources.addJar(new File("./entities.jar")); + //end::bootstrap-bootstrap-native-registry-MetadataSources-example[] + } + catch (Exception ignore) { + + } + } + + + @Test + public void test_bootstrap_bootstrap_native_metadata_source_example() { + try { + { + //tag::bootstrap-native-metadata-source-example[] + ServiceRegistry standardRegistry = + new StandardServiceRegistryBuilder().build(); + + MetadataSources sources = new MetadataSources(standardRegistry) + .addAnnotatedClass(MyEntity.class) + .addAnnotatedClassName("org.hibernate.example.Customer") + .addResource("org/hibernate/example/Order.hbm.xml") + .addResource("org/hibernate/example/Product.orm.xml"); + //end::bootstrap-native-metadata-source-example[] + } + + { + AttributeConverter myAttributeConverter = new AttributeConverter() { + @Override + public Object convertToDatabaseColumn(Object attribute) { + return null; + } + + @Override + public Object convertToEntityAttribute(Object dbData) { + return null; + } + } ; + //tag::bootstrap-native-metadata-builder-example[] + ServiceRegistry standardRegistry = + new StandardServiceRegistryBuilder().build(); + + MetadataSources sources = new MetadataSources(standardRegistry); + + MetadataBuilder metadataBuilder = sources.getMetadataBuilder(); + + // Use the JPA-compliant implicit naming strategy + metadataBuilder.applyImplicitNamingStrategy( + ImplicitNamingStrategyJpaCompliantImpl.INSTANCE); + + // specify the schema name to use for tables, etc when none is explicitly specified + metadataBuilder.applyImplicitSchemaName("my_default_schema"); + + // specify a custom Attribute Converter + metadataBuilder.applyAttributeConverter(myAttributeConverter); + + Metadata metadata = metadataBuilder.build(); + //end::bootstrap-native-metadata-builder-example[] + } + } + catch (Exception ignore) { + + } + } + + @Test + public void test_bootstrap_bootstrap_native_SessionFactory_example() { + try { + { + //tag::bootstrap-native-SessionFactory-example[] + StandardServiceRegistry standardRegistry = new StandardServiceRegistryBuilder() + .configure("org/hibernate/example/hibernate.cfg.xml") + .build(); + + Metadata metadata = new MetadataSources(standardRegistry) + .addAnnotatedClass(MyEntity.class) + .addAnnotatedClassName("org.hibernate.example.Customer") + .addResource("org/hibernate/example/Order.hbm.xml") + .addResource("org/hibernate/example/Product.orm.xml") + .getMetadataBuilder() + .applyImplicitNamingStrategy(ImplicitNamingStrategyJpaCompliantImpl.INSTANCE) + .build(); + + SessionFactory sessionFactory = metadata.getSessionFactoryBuilder() + .applyBeanManager(getBeanManager()) + .build(); + //end::bootstrap-native-SessionFactory-example[] + } + { + //tag::bootstrap-native-SessionFactoryBuilder-example[] + StandardServiceRegistry standardRegistry = new StandardServiceRegistryBuilder() + .configure("org/hibernate/example/hibernate.cfg.xml") + .build(); + + Metadata metadata = new MetadataSources(standardRegistry) + .addAnnotatedClass(MyEntity.class) + .addAnnotatedClassName("org.hibernate.example.Customer") + .addResource("org/hibernate/example/Order.hbm.xml") + .addResource("org/hibernate/example/Product.orm.xml") + .getMetadataBuilder() + .applyImplicitNamingStrategy(ImplicitNamingStrategyJpaCompliantImpl.INSTANCE) + .build(); + + SessionFactoryBuilder sessionFactoryBuilder = metadata.getSessionFactoryBuilder(); + + // Supply a SessionFactory-level Interceptor + sessionFactoryBuilder.applyInterceptor(new CustomSessionFactoryInterceptor()); + + // Add a custom observer + sessionFactoryBuilder.addSessionFactoryObservers(new CustomSessionFactoryObserver()); + + // Apply a CDI BeanManager (for JPA event listeners) + sessionFactoryBuilder.applyBeanManager(getBeanManager()); + + SessionFactory sessionFactory = sessionFactoryBuilder.build(); + //end::bootstrap-native-SessionFactoryBuilder-example[] + } + } + catch (Exception ignore) { + + } + } + + @Test + public void test_bootstrap_bootstrap_jpa_compliant_EntityManagerFactory_example() { + try { + //tag::bootstrap-jpa-compliant-EntityManagerFactory-example[] + // Create an EMF for our CRM persistence-unit. + EntityManagerFactory emf = Persistence.createEntityManagerFactory("CRM"); + //end::bootstrap-jpa-compliant-EntityManagerFactory-example[] + } catch (Exception ignore) {} + } + + @Test + public void test_bootstrap_bootstrap_native_EntityManagerFactory_example() { + + try { + //tag::bootstrap-native-EntityManagerFactory-example[] + String persistenceUnitName = "CRM"; + List entityClassNames = new ArrayList<>(); + Properties properties = new Properties(); + + PersistenceUnitInfoImpl persistenceUnitInfo = new PersistenceUnitInfoImpl( + persistenceUnitName, + entityClassNames, + properties + ); + + Map integrationSettings = ServiceRegistryUtil.createBaseSettings(); + integrationSettings.put( + AvailableSettings.INTERCEPTOR, + new CustomSessionFactoryInterceptor() + ); + + EntityManagerFactoryBuilderImpl entityManagerFactoryBuilder = + new EntityManagerFactoryBuilderImpl( + new PersistenceUnitInfoDescriptor(persistenceUnitInfo), + integrationSettings + ); + + EntityManagerFactory emf = entityManagerFactoryBuilder.build(); + //end::bootstrap-native-EntityManagerFactory-example[] + } + catch (Exception ignore) { + } + } + + @Test + @JiraKey("HHH-17154") + public void build_EntityManagerFactory_with_NewTempClassLoader() { + new EntityManagerFactoryBuilderImpl( + new PersistenceUnitInfoDescriptor( + new PersistenceUnitInfoImpl( "", new ArrayList<>(), new Properties() ) { + @Override + public ClassLoader getNewTempClassLoader() { + return Thread.currentThread().getContextClassLoader(); + } + } + ), ServiceRegistryUtil.createBaseSettings() - ).cancel(); - } + ).cancel(); + } - public Object getBeanManager() { - return null; - } - - @Entity - public static class MyEntity { - @Id - private Long id; - } - - //tag::bootstrap-event-listener-registration-example[] - public class MyIntegrator implements Integrator { - - @Override - public void integrate( - Metadata metadata, - BootstrapContext bootstrapContext, - SessionFactoryImplementor sessionFactory) { - - // As you might expect, an EventListenerRegistry is the thing with which event - // listeners are registered - // It is a service so we look it up using the service registry - final EventListenerRegistry eventListenerRegistry = - bootstrapContext.getServiceRegistry().getService(EventListenerRegistry.class); + public Object getBeanManager() { + return null; + } + + @Entity + public static class MyEntity { + @Id + private Long id; + } + + //tag::bootstrap-event-listener-registration-example[] + public class MyIntegrator implements Integrator { + + @Override + public void integrate( + Metadata metadata, + BootstrapContext bootstrapContext, + SessionFactoryImplementor sessionFactory) { + + // As you might expect, an EventListenerRegistry is the thing with which event + // listeners are registered + // It is a service so we look it up using the service registry + final EventListenerRegistry eventListenerRegistry = + bootstrapContext.getServiceRegistry().getService(EventListenerRegistry.class); - // If you wish to have custom determination and handling of "duplicate" listeners, - // you would have to add an implementation of the - // org.hibernate.event.service.spi.DuplicationStrategy contract like this - eventListenerRegistry.addDuplicationStrategy(new CustomDuplicationStrategy()); + // If you wish to have custom determination and handling of "duplicate" listeners, + // you would have to add an implementation of the + // org.hibernate.event.service.spi.DuplicationStrategy contract like this + eventListenerRegistry.addDuplicationStrategy(new CustomDuplicationStrategy()); - // EventListenerRegistry defines 3 ways to register listeners: + // EventListenerRegistry defines 3 ways to register listeners: - // 1) This form overrides any existing registrations with - eventListenerRegistry.setListeners(EventType.AUTO_FLUSH, - DefaultAutoFlushEventListener.class); + // 1) This form overrides any existing registrations with + eventListenerRegistry.setListeners(EventType.AUTO_FLUSH, + DefaultAutoFlushEventListener.class); - // 2) This form adds the specified listener(s) to the beginning of the listener chain - eventListenerRegistry.prependListeners(EventType.PERSIST, - DefaultPersistEventListener.class); + // 2) This form adds the specified listener(s) to the beginning of the listener chain + eventListenerRegistry.prependListeners(EventType.PERSIST, + DefaultPersistEventListener.class); - // 3) This form adds the specified listener(s) to the end of the listener chain - eventListenerRegistry.appendListeners(EventType.MERGE, - DefaultMergeEventListener.class); - } - - @Override - public void disintegrate( - SessionFactoryImplementor sessionFactory, - SessionFactoryServiceRegistry serviceRegistry) { - - } - } - //end::bootstrap-event-listener-registration-example[] - - public class CustomDuplicationStrategy implements DuplicationStrategy { - - @Override - public boolean areMatch(Object listener, Object original) { - return false; - } - - @Override - public Action getAction() { - return null; - } - } - - public class CustomSessionFactoryInterceptor implements Interceptor {} - - public class CustomSessionFactoryObserver implements SessionFactoryObserver { - - @Override - public void sessionFactoryCreated(SessionFactory factory) { - - } - - @Override - public void sessionFactoryClosed(SessionFactory factory) { - - } - } - - //tag::bootstrap-jpa-compliant-PersistenceUnit-example[] - @PersistenceUnit - private EntityManagerFactory emf; - //end::bootstrap-jpa-compliant-PersistenceUnit-example[] - - //tag::bootstrap-jpa-compliant-PersistenceUnit-configurable-example[] - @PersistenceUnit(unitName="CRM") - private EntityManagerFactory entityManagerFactory; - //end::bootstrap-jpa-compliant-PersistenceUnit-configurable-example[] - - //tag::bootstrap-jpa-compliant-PersistenceContext-example[] - @PersistenceContext - private EntityManager em; - //end::bootstrap-jpa-compliant-PersistenceContext-example[] - - //tag::bootstrap-jpa-compliant-PersistenceContext-configurable-example[] - @PersistenceContext( - unitName = "CRM", - properties = { - @PersistenceProperty( - name="org.hibernate.flushMode", - value= "MANUAL" - ) - } - ) - private EntityManager entityManager; - //end::bootstrap-jpa-compliant-PersistenceContext-configurable-example[] - - //tag::bootstrap-native-PersistenceUnitInfoImpl-example[] - public class PersistenceUnitInfoImpl implements PersistenceUnitInfo { - - private final String persistenceUnitName; - - private PersistenceUnitTransactionType transactionType = - PersistenceUnitTransactionType.RESOURCE_LOCAL; - - private final List managedClassNames; - - private final Properties properties; - - private DataSource jtaDataSource; - - private DataSource nonJtaDataSource; - - public PersistenceUnitInfoImpl( - String persistenceUnitName, - List managedClassNames, - Properties properties) { - this.persistenceUnitName = persistenceUnitName; - this.managedClassNames = managedClassNames; - this.properties = properties; - } - - @Override - public String getPersistenceUnitName() { - return persistenceUnitName; - } - - @Override - public String getPersistenceProviderClassName() { - return HibernatePersistenceProvider.class.getName(); - } - - @Override - public String getScopeAnnotationName() { - return null; - } - - @Override - public List getQualifierAnnotationNames() { - return List.of(); - } - - @Override - public jakarta.persistence.spi.PersistenceUnitTransactionType getTransactionType() { - return transactionType; - } - - @Override - public DataSource getJtaDataSource() { - return jtaDataSource; - } - - public PersistenceUnitInfoImpl setJtaDataSource(DataSource jtaDataSource) { - this.jtaDataSource = jtaDataSource; - this.nonJtaDataSource = null; - transactionType = PersistenceUnitTransactionType.JTA; - return this; - } - - @Override - public DataSource getNonJtaDataSource() { - return nonJtaDataSource; - } - - public PersistenceUnitInfoImpl setNonJtaDataSource(DataSource nonJtaDataSource) { - this.nonJtaDataSource = nonJtaDataSource; - this.jtaDataSource = null; - transactionType = PersistenceUnitTransactionType.RESOURCE_LOCAL; - return this; - } - - @Override - public List getMappingFileNames() { - return null; - } - - @Override - public List getJarFileUrls() { - return Collections.emptyList(); - } - - @Override - public URL getPersistenceUnitRootUrl() { - return null; - } - - @Override - public List getManagedClassNames() { - return managedClassNames; - } - - @Override - public boolean excludeUnlistedClasses() { - return false; - } - - @Override - public SharedCacheMode getSharedCacheMode() { - return SharedCacheMode.UNSPECIFIED; - } - - @Override - public ValidationMode getValidationMode() { - return ValidationMode.AUTO; - } - - public Properties getProperties() { - return properties; - } - - @Override - public String getPersistenceXMLSchemaVersion() { - return "2.1"; - } - - @Override - public ClassLoader getClassLoader() { - return Thread.currentThread().getContextClassLoader(); - } - - @Override - public void addTransformer(ClassTransformer transformer) { - - } - - @Override - public ClassLoader getNewTempClassLoader() { - return null; - } - } - //end::bootstrap-native-PersistenceUnitInfoImpl-example[] - - @Test - public void test_basic_custom_type_register_BasicType_example() { - try { - //tag::basic-custom-type-register-BasicType-example[] - ServiceRegistry standardRegistry = - new StandardServiceRegistryBuilder().build(); - - MetadataSources sources = new MetadataSources( standardRegistry ); - - MetadataBuilder metadataBuilder = sources.getMetadataBuilder(); - - metadataBuilder.applyBasicType( BitSetType.INSTANCE ); - //end::basic-custom-type-register-BasicType-example[] - } - catch (Exception ignore) { - - } - } - - @Test - public void test_basic_custom_type_register_UserType_example() { - try { - //tag::basic-custom-type-register-UserType-example[] - ServiceRegistry standardRegistry = - new StandardServiceRegistryBuilder().build(); - - MetadataSources sources = new MetadataSources(standardRegistry); - - MetadataBuilder metadataBuilder = sources.getMetadataBuilder(); - - metadataBuilder.applyBasicType(new BitSetUserType(), "bitset"); - //end::basic-custom-type-register-UserType-example[] - } - catch (Exception ignore) { - - } - } + // 3) This form adds the specified listener(s) to the end of the listener chain + eventListenerRegistry.appendListeners(EventType.MERGE, + DefaultMergeEventListener.class); + } + + @Override + public void disintegrate( + SessionFactoryImplementor sessionFactory, + SessionFactoryServiceRegistry serviceRegistry) { + + } + } + //end::bootstrap-event-listener-registration-example[] + + public class CustomDuplicationStrategy implements DuplicationStrategy { + + @Override + public boolean areMatch(Object listener, Object original) { + return false; + } + + @Override + public Action getAction() { + return null; + } + } + + public class CustomSessionFactoryInterceptor implements Interceptor {} + + public class CustomSessionFactoryObserver implements SessionFactoryObserver { + + @Override + public void sessionFactoryCreated(SessionFactory factory) { + + } + + @Override + public void sessionFactoryClosed(SessionFactory factory) { + + } + } + + //tag::bootstrap-jpa-compliant-PersistenceUnit-example[] + @PersistenceUnit + private EntityManagerFactory emf; + //end::bootstrap-jpa-compliant-PersistenceUnit-example[] + + //tag::bootstrap-jpa-compliant-PersistenceUnit-configurable-example[] + @PersistenceUnit(unitName="CRM") + private EntityManagerFactory entityManagerFactory; + //end::bootstrap-jpa-compliant-PersistenceUnit-configurable-example[] + + //tag::bootstrap-jpa-compliant-PersistenceContext-example[] + @PersistenceContext + private EntityManager em; + //end::bootstrap-jpa-compliant-PersistenceContext-example[] + + //tag::bootstrap-jpa-compliant-PersistenceContext-configurable-example[] + @PersistenceContext( + unitName = "CRM", + properties = { + @PersistenceProperty( + name="org.hibernate.flushMode", + value= "MANUAL" + ) + } +) + private EntityManager entityManager; + //end::bootstrap-jpa-compliant-PersistenceContext-configurable-example[] + + //tag::bootstrap-native-PersistenceUnitInfoImpl-example[] + public class PersistenceUnitInfoImpl implements PersistenceUnitInfo { + + private final String persistenceUnitName; + + private PersistenceUnitTransactionType transactionType = + PersistenceUnitTransactionType.RESOURCE_LOCAL; + + private final List managedClassNames; + + private final Properties properties; + + private DataSource jtaDataSource; + + private DataSource nonJtaDataSource; + + public PersistenceUnitInfoImpl( + String persistenceUnitName, + List managedClassNames, + Properties properties) { + this.persistenceUnitName = persistenceUnitName; + this.managedClassNames = managedClassNames; + this.properties = properties; + } + + @Override + public String getPersistenceUnitName() { + return persistenceUnitName; + } + + @Override + public String getPersistenceProviderClassName() { + return HibernatePersistenceProvider.class.getName(); + } + + @Override + public String getScopeAnnotationName() { + return null; + } + + @Override + public List getQualifierAnnotationNames() { + return List.of(); + } + + @Override + public jakarta.persistence.spi.PersistenceUnitTransactionType getTransactionType() { + return transactionType; + } + + @Override + public DataSource getJtaDataSource() { + return jtaDataSource; + } + + public PersistenceUnitInfoImpl setJtaDataSource(DataSource jtaDataSource) { + this.jtaDataSource = jtaDataSource; + this.nonJtaDataSource = null; + transactionType = PersistenceUnitTransactionType.JTA; + return this; + } + + @Override + public DataSource getNonJtaDataSource() { + return nonJtaDataSource; + } + + public PersistenceUnitInfoImpl setNonJtaDataSource(DataSource nonJtaDataSource) { + this.nonJtaDataSource = nonJtaDataSource; + this.jtaDataSource = null; + transactionType = PersistenceUnitTransactionType.RESOURCE_LOCAL; + return this; + } + + @Override + public List getMappingFileNames() { + return null; + } + + @Override + public List getJarFileUrls() { + return Collections.emptyList(); + } + + @Override + public URL getPersistenceUnitRootUrl() { + return null; + } + + @Override + public List getManagedClassNames() { + return managedClassNames; + } + + @Override + public boolean excludeUnlistedClasses() { + return false; + } + + @Override + public SharedCacheMode getSharedCacheMode() { + return SharedCacheMode.UNSPECIFIED; + } + + @Override + public ValidationMode getValidationMode() { + return ValidationMode.AUTO; + } + + public Properties getProperties() { + return properties; + } + + @Override + public String getPersistenceXMLSchemaVersion() { + return "2.1"; + } + + @Override + public ClassLoader getClassLoader() { + return Thread.currentThread().getContextClassLoader(); + } + + @Override + public void addTransformer(ClassTransformer transformer) { + + } + + @Override + public ClassLoader getNewTempClassLoader() { + return null; + } + } + //end::bootstrap-native-PersistenceUnitInfoImpl-example[] + + @Test + public void test_basic_custom_type_register_BasicType_example() { + try { + //tag::basic-custom-type-register-BasicType-example[] + ServiceRegistry standardRegistry = + new StandardServiceRegistryBuilder().build(); + + MetadataSources sources = new MetadataSources( standardRegistry ); + + MetadataBuilder metadataBuilder = sources.getMetadataBuilder(); + + metadataBuilder.applyBasicType( BitSetType.INSTANCE ); + //end::basic-custom-type-register-BasicType-example[] + } + catch (Exception ignore) { + + } + } + + @Test + public void test_basic_custom_type_register_UserType_example() { + try { + //tag::basic-custom-type-register-UserType-example[] + ServiceRegistry standardRegistry = + new StandardServiceRegistryBuilder().build(); + + MetadataSources sources = new MetadataSources(standardRegistry); + + MetadataBuilder metadataBuilder = sources.getMetadataBuilder(); + + metadataBuilder.applyBasicType(new BitSetUserType(), "bitset"); + //end::basic-custom-type-register-UserType-example[] + } + catch (Exception ignore) { + + } + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/binding/annotations/access/jpa/AccessMappingTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/binding/annotations/access/jpa/AccessMappingTest.java index b1cfb5fbe8..b1941b8499 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/binding/annotations/access/jpa/AccessMappingTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/binding/annotations/access/jpa/AccessMappingTest.java @@ -48,11 +48,11 @@ public class AccessMappingTest { } } - @Test - public void testInconsistentAnnotationPlacement() { - Configuration cfg = new Configuration(); - cfg.addAnnotatedClass( Course1.class ); - cfg.addAnnotatedClass( Student.class ); + @Test + public void testInconsistentAnnotationPlacement() { + Configuration cfg = new Configuration(); + cfg.addAnnotatedClass( Course1.class ); + cfg.addAnnotatedClass( Student.class ); SessionFactory sf = null; try { sf = cfg.buildSessionFactory( serviceRegistry ); @@ -76,7 +76,7 @@ public class AccessMappingTest { cfg.addAnnotatedClass( Student.class ); SessionFactoryImplementor factory = (SessionFactoryImplementor) cfg.buildSessionFactory( serviceRegistry ); try { - final EntityPersister entityPersister = factory.getRuntimeMetamodels() + final EntityPersister entityPersister = factory.getRuntimeMetamodels() .getMappingMetamodel() .getEntityDescriptor(classUnderTest.getName()); final BasicEntityIdentifierMappingImpl identifierMapping = (BasicEntityIdentifierMappingImpl) entityPersister.getIdentifierMapping(); @@ -99,7 +99,7 @@ public class AccessMappingTest { cfg.addAnnotatedClass( Student.class ); SessionFactoryImplementor factory = (SessionFactoryImplementor) cfg.buildSessionFactory( serviceRegistry ); try { - final EntityPersister entityPersister = factory.getRuntimeMetamodels() + final EntityPersister entityPersister = factory.getRuntimeMetamodels() .getMappingMetamodel() .getEntityDescriptor(classUnderTest.getName()); final BasicEntityIdentifierMappingImpl identifierMapping = (BasicEntityIdentifierMappingImpl) entityPersister.getIdentifierMapping(); @@ -122,7 +122,7 @@ public class AccessMappingTest { cfg.addAnnotatedClass( Student.class ); SessionFactoryImplementor factory = (SessionFactoryImplementor) cfg.buildSessionFactory( serviceRegistry ); try { - final EntityPersister entityPersister = factory.getRuntimeMetamodels() + final EntityPersister entityPersister = factory.getRuntimeMetamodels() .getMappingMetamodel() .getEntityDescriptor(classUnderTest.getName()); final BasicEntityIdentifierMappingImpl identifierMapping = (BasicEntityIdentifierMappingImpl) entityPersister.getIdentifierMapping(); @@ -165,7 +165,7 @@ public class AccessMappingTest { cfg.addAnnotatedClass( Student.class ); SessionFactoryImplementor factory = (SessionFactoryImplementor) cfg.buildSessionFactory( serviceRegistry ); try { - final EntityPersister entityPersister = factory.getRuntimeMetamodels() + final EntityPersister entityPersister = factory.getRuntimeMetamodels() .getMappingMetamodel() .getEntityDescriptor(classUnderTest.getName()); final BasicEntityIdentifierMappingImpl identifierMapping = (BasicEntityIdentifierMappingImpl) entityPersister.getIdentifierMapping(); @@ -193,7 +193,7 @@ public class AccessMappingTest { cfg.addAnnotatedClass( Student.class ); SessionFactoryImplementor factory = (SessionFactoryImplementor) cfg.buildSessionFactory( serviceRegistry ); try { - final EntityPersister entityPersister = factory.getRuntimeMetamodels() + final EntityPersister entityPersister = factory.getRuntimeMetamodels() .getMappingMetamodel() .getEntityDescriptor(classUnderTest.getName()); final BasicEntityIdentifierMappingImpl identifierMapping = (BasicEntityIdentifierMappingImpl) entityPersister.getIdentifierMapping(); @@ -222,7 +222,7 @@ public class AccessMappingTest { cfg.addAnnotatedClass( Being.class ); SessionFactoryImplementor factory = (SessionFactoryImplementor) cfg.buildSessionFactory( serviceRegistry ); try { - final EntityPersister entityPersister = factory.getRuntimeMetamodels() + final EntityPersister entityPersister = factory.getRuntimeMetamodels() .getMappingMetamodel() .getEntityDescriptor(classUnderTest.getName()); final BasicEntityIdentifierMappingImpl identifierMapping = (BasicEntityIdentifierMappingImpl) entityPersister.getIdentifierMapping(); @@ -245,7 +245,7 @@ public class AccessMappingTest { SessionFactoryImplementor factory = (SessionFactoryImplementor) cfg.buildSessionFactory( serviceRegistry ); try { - EntityPersister entityPersister = factory.getRuntimeMetamodels() + EntityPersister entityPersister = factory.getRuntimeMetamodels() .getMappingMetamodel() .getEntityDescriptor(Animal.class.getName()); final BasicEntityIdentifierMappingImpl identifierMapping = (BasicEntityIdentifierMappingImpl) entityPersister.getIdentifierMapping(); @@ -255,7 +255,7 @@ public class AccessMappingTest { identifierMapping.getPropertyAccess().getGetter() instanceof GetterMethodImpl ); - entityPersister = factory.getRuntimeMetamodels() + entityPersister = factory.getRuntimeMetamodels() .getMappingMetamodel() .getEntityDescriptor(Horse.class.getName()); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/binding/annotations/embedded/AddressBis.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/binding/annotations/embedded/AddressBis.java index 94e447bdde..2de0dd8d7b 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/binding/annotations/embedded/AddressBis.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/binding/annotations/embedded/AddressBis.java @@ -12,6 +12,6 @@ import org.hibernate.annotations.Formula; @Embeddable public class AddressBis { - @Formula("2") - Integer formula; + @Formula("2") + Integer formula; } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/binding/annotations/embedded/EmbeddedTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/binding/annotations/embedded/EmbeddedTest.java index 1f5893d47c..b3c0e69412 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/binding/annotations/embedded/EmbeddedTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/binding/annotations/embedded/EmbeddedTest.java @@ -233,8 +233,8 @@ public class EmbeddedTest { scope.inTransaction( session -> { Query query = session.createQuery( "from Person p " + - "where ( p.bornIn.iso2 is null or p.bornIn.iso2 = :i ) and " + - "( p.bornIn.name is null or p.bornIn.name = :n )" + "where ( p.bornIn.iso2 is null or p.bornIn.iso2 = :i ) and " + + "( p.bornIn.name is null or p.bornIn.name = :n )" ); query.setParameter( "i", person.bornIn.getIso2() ); query.setParameter( "n", person.bornIn.getName() ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/binding/mixed/AnnotationEntity.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/binding/mixed/AnnotationEntity.java index 5105e367d4..01d13639c6 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/binding/mixed/AnnotationEntity.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/binding/mixed/AnnotationEntity.java @@ -11,21 +11,21 @@ import jakarta.persistence.*; @Entity public class AnnotationEntity { - @Id - @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "annotationentity_id_seq") - @SequenceGenerator( - name = "annotationentity_id_seq", - sequenceName = "annotationentity_id_seq" - ) - private Long _id; + @Id + @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "annotationentity_id_seq") + @SequenceGenerator( + name = "annotationentity_id_seq", + sequenceName = "annotationentity_id_seq" + ) + private Long _id; - /** - * Get the identifier. - * - * @return the id. - */ - public Long getId() - { - return _id; - } + /** + * Get the identifier. + * + * @return the id. + */ + public Long getId() + { + return _id; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/binding/mixed/HBMEntity.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/binding/mixed/HBMEntity.java index 70f534f4e2..ea86798eec 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/binding/mixed/HBMEntity.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/binding/mixed/HBMEntity.java @@ -8,22 +8,22 @@ package org.hibernate.orm.test.bootstrap.binding.mixed; public class HBMEntity { - private long _id; - private AnnotationEntity _association; + private long _id; + private AnnotationEntity _association; - public long getId() { - return _id; - } + public long getId() { + return _id; + } - public void setId(long id) { - _id = id; - } + public void setId(long id) { + _id = id; + } - public AnnotationEntity getAssociation() { - return _association; - } + public AnnotationEntity getAssociation() { + return _association; + } - public void setAssociation(AnnotationEntity association) { - _association = association; - } + public void setAssociation(AnnotationEntity association) { + _association = association; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/binding/mixed/HBMManyToOneAnnotationMissingPrimaryKeyTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/binding/mixed/HBMManyToOneAnnotationMissingPrimaryKeyTest.java index 676db5480d..93e11ab5e8 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/binding/mixed/HBMManyToOneAnnotationMissingPrimaryKeyTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/binding/mixed/HBMManyToOneAnnotationMissingPrimaryKeyTest.java @@ -17,31 +17,31 @@ import org.junit.Test; */ public class HBMManyToOneAnnotationMissingPrimaryKeyTest extends BaseNonConfigCoreFunctionalTestCase { - @Override - protected Class[] getAnnotatedClasses() { - return new Class[]{ - AnnotationEntity.class - }; - } + @Override + protected Class[] getAnnotatedClasses() { + return new Class[]{ + AnnotationEntity.class + }; + } - @Override - protected String[] getMappings() { - return new String[]{ - "HBMEntity.hbm.xml" - }; - } + @Override + protected String[] getMappings() { + return new String[]{ + "HBMEntity.hbm.xml" + }; + } - @Override - protected String getBaseForMappings() { - return "/org/hibernate/orm/test/bootstrap/binding/mixed/"; - } + @Override + protected String getBaseForMappings() { + return "/org/hibernate/orm/test/bootstrap/binding/mixed/"; + } - /** - * Test to trigger the NullPointerException in the ModelBinder. - * @throws Exception on error. - */ - @Test - public void hhh11502() throws Exception { - Assert.assertTrue(true); - } + /** + * Test to trigger the NullPointerException in the ModelBinder. + * @throws Exception on error. + */ + @Test + public void hhh11502() throws Exception { + Assert.assertTrue(true); + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/registry/classloading/ClassLoaderLeakDetector.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/registry/classloading/ClassLoaderLeakDetector.java index 895f43789a..844f6f433b 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/registry/classloading/ClassLoaderLeakDetector.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/registry/classloading/ClassLoaderLeakDetector.java @@ -30,7 +30,7 @@ public final class ClassLoaderLeakDetector { */ public static void assertNotLeakingAction(String fullClassnameOfRunnableAction) { Assert.assertTrue( "It seems the action might have leaked the classloader", - ClassLoaderLeakDetector.verifyActionNotLeakingClassloader( fullClassnameOfRunnableAction ) ); + ClassLoaderLeakDetector.verifyActionNotLeakingClassloader( fullClassnameOfRunnableAction ) ); } static boolean verifyActionNotLeakingClassloader(String fullClassnameOfRunnableAction) { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/registry/classloading/ClassLoaderServiceImplTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/registry/classloading/ClassLoaderServiceImplTest.java index 1023c49dcd..7ad90ceeaa 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/registry/classloading/ClassLoaderServiceImplTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/registry/classloading/ClassLoaderServiceImplTest.java @@ -45,21 +45,21 @@ public class ClassLoaderServiceImplTest { Thread.currentThread().setContextClassLoader( null ); ClassLoaderServiceImpl csi1 = new ClassLoaderServiceImpl( null, - TcclLookupPrecedence.BEFORE ); + TcclLookupPrecedence.BEFORE ); Class clazz1 = csi1.classForName( ClassLoaderServiceImplTest.class.getName() ); assertEquals( ClassLoaderServiceImplTest.class, clazz1 ); csi1.stop(); ClassLoaderServiceImpl csi2 = new ClassLoaderServiceImpl( null, - TcclLookupPrecedence.AFTER ); + TcclLookupPrecedence.AFTER ); Class clazz2 = csi2.classForName( ClassLoaderServiceImplTest.class.getName() ); assertEquals( ClassLoaderServiceImplTest.class, clazz2 ); csi2.stop(); ClassLoaderServiceImpl csi3 = new ClassLoaderServiceImpl( null, - TcclLookupPrecedence.NEVER ); + TcclLookupPrecedence.NEVER ); Class clazz3 = csi3.classForName( ClassLoaderServiceImplTest.class.getName() ); assertEquals( ClassLoaderServiceImplTest.class, clazz3 ); @@ -72,7 +72,7 @@ public class ClassLoaderServiceImplTest { Thread.currentThread().setContextClassLoader( icl ); ClassLoaderServiceImpl csi = new ClassLoaderServiceImpl( null, - TcclLookupPrecedence.BEFORE ); + TcclLookupPrecedence.BEFORE ); Class clazz = csi.classForName( ClassLoaderServiceImplTest.class.getName() ); assertEquals( ClassLoaderServiceImplTest.class, clazz ); @@ -86,7 +86,7 @@ public class ClassLoaderServiceImplTest { Thread.currentThread().setContextClassLoader( icl ); ClassLoaderServiceImpl csi = new ClassLoaderServiceImpl( null, - TcclLookupPrecedence.AFTER ); + TcclLookupPrecedence.AFTER ); Class clazz = csi.classForName( ClassLoaderServiceImplTest.class.getName() ); assertEquals( ClassLoaderServiceImplTest.class, clazz ); @@ -100,7 +100,7 @@ public class ClassLoaderServiceImplTest { Thread.currentThread().setContextClassLoader( icl ); ClassLoaderServiceImpl csi = new ClassLoaderServiceImpl( null, - TcclLookupPrecedence.AFTER ); + TcclLookupPrecedence.AFTER ); try { csi.classForName( "test.class.name" ); assertTrue( false ); @@ -117,7 +117,7 @@ public class ClassLoaderServiceImplTest { Thread.currentThread().setContextClassLoader( icl ); ClassLoaderServiceImpl csi = new ClassLoaderServiceImpl( null, - TcclLookupPrecedence.BEFORE ); + TcclLookupPrecedence.BEFORE ); try { csi.classForName( "test.class.not.found" ); assertTrue( false ); @@ -134,7 +134,7 @@ public class ClassLoaderServiceImplTest { Thread.currentThread().setContextClassLoader( icl ); ClassLoaderServiceImpl csi = new ClassLoaderServiceImpl( null, - TcclLookupPrecedence.NEVER ); + TcclLookupPrecedence.NEVER ); try { csi.classForName( "test.class.name" ); assertTrue( false ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/registry/classloading/HibernateClassLoaderLeaksTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/registry/classloading/HibernateClassLoaderLeaksTest.java index f7a371eb81..66d2bac327 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/registry/classloading/HibernateClassLoaderLeaksTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/registry/classloading/HibernateClassLoaderLeaksTest.java @@ -35,7 +35,7 @@ public class HibernateClassLoaderLeaksTest { public static void prepareForClassLoaderLeakTest() { final String property = System.getProperty( "log4j2.disableJmx" ); Assert.assertEquals( "To be able to test against leaks, the system property 'log4j2.disableJmx' must be set to true", - "true", property ); + "true", property ); //Attempt to workaround the mess of DriverManager leaks by clearing it before the test; //it will most certainly re-register all drivers again within the test running context, diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/scanning/JarVisitorTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/scanning/JarVisitorTest.java index 91590a7830..77dfbc634d 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/scanning/JarVisitorTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/scanning/JarVisitorTest.java @@ -284,17 +284,17 @@ public class JarVisitorTest extends PackagingTestCase { //setting URL to accept vfs based protocol URL.setURLStreamHandlerFactory(new URLStreamHandlerFactory() { - public URLStreamHandler createURLStreamHandler(String protocol) { - if("vfszip".equals(protocol) || "vfsfile".equals(protocol) ) - return new URLStreamHandler() { - protected URLConnection openConnection(URL u) - throws IOException { - return null; - } - }; - return null; - } - }); + public URLStreamHandler createURLStreamHandler(String protocol) { + if("vfszip".equals(protocol) || "vfsfile".equals(protocol) ) + return new URLStreamHandler() { + protected URLConnection openConnection(URL u) + throws IOException { + return null; + } + }; + return null; + } + }); URL jarUrl = defaultPar.toURL(); ArchiveDescriptor descriptor = StandardArchiveDescriptorFactory.INSTANCE.buildArchiveDescriptor( jarUrl ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/spi/metadatabuildercontributor/SqlFunctionMetadataBuilderContributor.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/spi/metadatabuildercontributor/SqlFunctionMetadataBuilderContributor.java index dee6cbcd71..7f01bab84d 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/spi/metadatabuildercontributor/SqlFunctionMetadataBuilderContributor.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/spi/metadatabuildercontributor/SqlFunctionMetadataBuilderContributor.java @@ -16,13 +16,13 @@ import org.hibernate.type.StandardBasicTypes; */ //tag::bootstrap-jpa-compliant-MetadataBuilderContributor-example[] public class SqlFunctionMetadataBuilderContributor - implements MetadataBuilderContributor { + implements MetadataBuilderContributor { - @Override - public void contribute(MetadataBuilder metadataBuilder) { - metadataBuilder.applySqlFunction( - "instr", new StandardSQLFunction( "instr", StandardBasicTypes.INTEGER ) - ); - } + @Override + public void contribute(MetadataBuilder metadataBuilder) { + metadataBuilder.applySqlFunction( + "instr", new StandardSQLFunction( "instr", StandardBasicTypes.INTEGER ) + ); + } } //end::bootstrap-jpa-compliant-MetadataBuilderContributor-example[] diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/ReflectionOptimizerTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/ReflectionOptimizerTest.java index 9a25bd9e1a..c2262c655f 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/ReflectionOptimizerTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/ReflectionOptimizerTest.java @@ -43,9 +43,9 @@ public class ReflectionOptimizerTest extends BaseUnitTestCase { public void testReflectionOptimization() { ReflectionOptimizer optimizer = provider.getReflectionOptimizer( Bean.class, - BeanReflectionHelper.getGetterNames(), - BeanReflectionHelper.getSetterNames(), - BeanReflectionHelper.getTypes() + BeanReflectionHelper.getGetterNames(), + BeanReflectionHelper.getSetterNames(), + BeanReflectionHelper.getTypes() ); assertNotNull( optimizer ); assertNotNull( optimizer.getInstantiationOptimizer() ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/access/MixedAccessTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/access/MixedAccessTest.java index c345979fc7..09420f579f 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/access/MixedAccessTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/access/MixedAccessTest.java @@ -45,156 +45,156 @@ import static org.junit.jupiter.api.Assertions.assertTrue; */ @JiraKey("HHH-10851" ) @DomainModel( - annotatedClasses = { - MixedAccessTest.TestEntity.class, MixedAccessTest.TestOtherEntity.class, - } + annotatedClasses = { + MixedAccessTest.TestEntity.class, MixedAccessTest.TestOtherEntity.class, + } ) @SessionFactory @BytecodeEnhanced @CustomEnhancementContext(MixedAccessTest.NoDirtyCheckingContext.class) public class MixedAccessTest { - private static final Pattern PARAM_PATTERN = Pattern.compile( "\\{\\\"(.*)\\\"\\:\\\"(.*)\\\"\\}" ); - private static final Function MAPPING_FUNCTION = e -> "\"" + e.getKey() + "\":\"" + e.getValue() + "\""; - private static final String ID = "foo", PARAM_KEY = "paramName", PARAM_VAL = "paramValue", PARAMS_AS_STR = "{\"" + PARAM_KEY + "\":\"" + PARAM_VAL + "\"}"; + private static final Pattern PARAM_PATTERN = Pattern.compile( "\\{\\\"(.*)\\\"\\:\\\"(.*)\\\"\\}" ); + private static final Function MAPPING_FUNCTION = e -> "\"" + e.getKey() + "\":\"" + e.getValue() + "\""; + private static final String ID = "foo", PARAM_KEY = "paramName", PARAM_VAL = "paramValue", PARAMS_AS_STR = "{\"" + PARAM_KEY + "\":\"" + PARAM_VAL + "\"}"; - @BeforeEach - public void prepare(SessionFactoryScope scope) { - scope.inTransaction( s -> { - TestEntity testEntity = new TestEntity( ID ); - testEntity.setParamsAsString( PARAMS_AS_STR ); - s.persist( testEntity ); + @BeforeEach + public void prepare(SessionFactoryScope scope) { + scope.inTransaction( s -> { + TestEntity testEntity = new TestEntity( ID ); + testEntity.setParamsAsString( PARAMS_AS_STR ); + s.persist( testEntity ); - TestOtherEntity testOtherEntity = new TestOtherEntity( ID ); - testOtherEntity.setParamsAsString( PARAMS_AS_STR ); - s.persist( testOtherEntity ); - } ); - } + TestOtherEntity testOtherEntity = new TestOtherEntity( ID ); + testOtherEntity.setParamsAsString( PARAMS_AS_STR ); + s.persist( testOtherEntity ); + } ); + } - @Test - public void test(SessionFactoryScope scope) { - scope.inTransaction( s -> { - TestEntity testEntity = s.get( TestEntity.class, ID ); - assertEquals( PARAMS_AS_STR, testEntity.getParamsAsString() ); + @Test + public void test(SessionFactoryScope scope) { + scope.inTransaction( s -> { + TestEntity testEntity = s.get( TestEntity.class, ID ); + assertEquals( PARAMS_AS_STR, testEntity.getParamsAsString() ); - TestOtherEntity testOtherEntity = s.get( TestOtherEntity.class, ID ); - assertEquals( PARAMS_AS_STR, testOtherEntity.getParamsAsString() ); + TestOtherEntity testOtherEntity = s.get( TestOtherEntity.class, ID ); + assertEquals( PARAMS_AS_STR, testOtherEntity.getParamsAsString() ); - // Clean parameters - testEntity.setParamsAsString( "{}" ); - testOtherEntity.setParamsAsString( "{}" ); - } ); - } + // Clean parameters + testEntity.setParamsAsString( "{}" ); + testOtherEntity.setParamsAsString( "{}" ); + } ); + } - @AfterEach - public void cleanup(SessionFactoryScope scope) { - scope.inTransaction( s -> { - TestEntity testEntity = s.get( TestEntity.class, ID ); - assertTrue( testEntity.getParams().isEmpty() ); + @AfterEach + public void cleanup(SessionFactoryScope scope) { + scope.inTransaction( s -> { + TestEntity testEntity = s.get( TestEntity.class, ID ); + assertTrue( testEntity.getParams().isEmpty() ); - TestOtherEntity testOtherEntity = s.get( TestOtherEntity.class, ID ); - assertTrue( testOtherEntity.getParams().isEmpty() ); - } ); - } + TestOtherEntity testOtherEntity = s.get( TestOtherEntity.class, ID ); + assertTrue( testOtherEntity.getParams().isEmpty() ); + } ); + } - // --- // + // --- // - @Entity - @Table( name = "TEST_ENTITY" ) - static class TestEntity { + @Entity + @Table( name = "TEST_ENTITY" ) + static class TestEntity { - @Id - String name; + @Id + String name; - @Transient - Map params = new LinkedHashMap<>(); + @Transient + Map params = new LinkedHashMap<>(); - TestEntity(String name) { - this(); - this.name = name; - } + TestEntity(String name) { + this(); + this.name = name; + } - TestEntity() { - } + TestEntity() { + } - Map getParams() { - return Collections.unmodifiableMap( params ); - } + Map getParams() { + return Collections.unmodifiableMap( params ); + } - void setParams(Map params) { - this.params.clear(); - this.params.putAll( params ); - } + void setParams(Map params) { + this.params.clear(); + this.params.putAll( params ); + } - @Column( name = "params", length = 4000 ) - @Access( AccessType.PROPERTY ) - String getParamsAsString() { - return "{" + params.entrySet().stream().map( MAPPING_FUNCTION ).collect( joining( "," ) ) + "}"; - } + @Column( name = "params", length = 4000 ) + @Access( AccessType.PROPERTY ) + String getParamsAsString() { + return "{" + params.entrySet().stream().map( MAPPING_FUNCTION ).collect( joining( "," ) ) + "}"; + } - @SuppressWarnings( "unchecked" ) - void setParamsAsString(String string) { - Matcher matcher = PARAM_PATTERN.matcher( string ); + @SuppressWarnings( "unchecked" ) + void setParamsAsString(String string) { + Matcher matcher = PARAM_PATTERN.matcher( string ); - params.clear(); - if ( matcher.matches() && matcher.groupCount() > 1 ) { - params.put( matcher.group( 1 ), matcher.group( 2 ) ); - } - } - } + params.clear(); + if ( matcher.matches() && matcher.groupCount() > 1 ) { + params.put( matcher.group( 1 ), matcher.group( 2 ) ); + } + } + } - @Entity - @Table( name = "OTHER_ENTITY" ) - @Access( AccessType.FIELD ) - static class TestOtherEntity { + @Entity + @Table( name = "OTHER_ENTITY" ) + @Access( AccessType.FIELD ) + static class TestOtherEntity { - @Id - String name; + @Id + String name; - @Transient - Map params = new LinkedHashMap<>(); + @Transient + Map params = new LinkedHashMap<>(); - TestOtherEntity(String name) { - this(); - this.name = name; - } + TestOtherEntity(String name) { + this(); + this.name = name; + } - TestOtherEntity() { - } + TestOtherEntity() { + } - Map getParams() { - return Collections.unmodifiableMap( params ); - } + Map getParams() { + return Collections.unmodifiableMap( params ); + } - void setParams(Map params) { - this.params.clear(); - this.params.putAll( params ); - } + void setParams(Map params) { + this.params.clear(); + this.params.putAll( params ); + } - @Column( name = "params", length = 4000 ) - @Access( AccessType.PROPERTY ) - String getParamsAsString() { - return "{" + params.entrySet().stream().map( MAPPING_FUNCTION ).collect( joining( "," ) ) + "}"; - } + @Column( name = "params", length = 4000 ) + @Access( AccessType.PROPERTY ) + String getParamsAsString() { + return "{" + params.entrySet().stream().map( MAPPING_FUNCTION ).collect( joining( "," ) ) + "}"; + } - @SuppressWarnings( "unchecked" ) - void setParamsAsString(String string) { - Matcher matcher = PARAM_PATTERN.matcher( string ); + @SuppressWarnings( "unchecked" ) + void setParamsAsString(String string) { + Matcher matcher = PARAM_PATTERN.matcher( string ); - params.clear(); - if ( matcher.matches() && matcher.groupCount() > 1 ) { - params.put( matcher.group( 1 ), matcher.group( 2 ) ); - } - } - } + params.clear(); + if ( matcher.matches() && matcher.groupCount() > 1 ) { + params.put( matcher.group( 1 ), matcher.group( 2 ) ); + } + } + } - // --- // + // --- // - public static class NoDirtyCheckingContext extends EnhancerTestContext { + public static class NoDirtyCheckingContext extends EnhancerTestContext { - @Override - public boolean doDirtyCheckingInline(UnloadedClass classDescriptor) { - return false; - } - } + @Override + public boolean doDirtyCheckingInline(UnloadedClass classDescriptor) { + return false; + } + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/association/ManyToManyAssociationListTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/association/ManyToManyAssociationListTest.java index eb025746a2..8e36b792c0 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/association/ManyToManyAssociationListTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/association/ManyToManyAssociationListTest.java @@ -25,68 +25,68 @@ import org.junit.jupiter.api.Test; */ @BytecodeEnhanced public class ManyToManyAssociationListTest { - @Test - public void testBidirectionalExisting() { - Group group = new Group(); - Group anotherGroup = new Group(); + @Test + public void testBidirectionalExisting() { + Group group = new Group(); + Group anotherGroup = new Group(); - User user = new User(); - anotherGroup.users.add( user ); + User user = new User(); + anotherGroup.users.add( user ); - user.setGroups( new ArrayList<>( Collections.singleton( group ) ) ); - user.setGroups( new ArrayList<>( Arrays.asList( group, anotherGroup ) ) ); + user.setGroups( new ArrayList<>( Collections.singleton( group ) ) ); + user.setGroups( new ArrayList<>( Arrays.asList( group, anotherGroup ) ) ); - assertEquals( 1, group.getUsers().size() ); - assertEquals( 1, anotherGroup.getUsers().size() ); - } + assertEquals( 1, group.getUsers().size() ); + assertEquals( 1, anotherGroup.getUsers().size() ); + } - // -- // + // -- // - @Entity - private static class Group { + @Entity + private static class Group { - @Id - Long id; + @Id + Long id; - @Column - String name; + @Column + String name; - @ManyToMany( mappedBy = "groups" ) - List users = new ArrayList<>(); + @ManyToMany( mappedBy = "groups" ) + List users = new ArrayList<>(); - List getUsers() { - return Collections.unmodifiableList( users ); - } + List getUsers() { + return Collections.unmodifiableList( users ); + } - void resetUsers() { - // this wouldn't trigger association management: users.clear(); - users = new ArrayList<>(); - } - } + void resetUsers() { + // this wouldn't trigger association management: users.clear(); + users = new ArrayList<>(); + } + } - @Entity - private static class User { + @Entity + private static class User { - @Id - Long id; + @Id + Long id; - String password; + String password; - @ManyToMany - List groups; + @ManyToMany + List groups; - void addGroup(Group group) { - List groups = this.groups == null ? new ArrayList<>() : this.groups; - groups.add( group ); - this.groups = groups; - } + void addGroup(Group group) { + List groups = this.groups == null ? new ArrayList<>() : this.groups; + groups.add( group ); + this.groups = groups; + } - List getGroups() { - return Collections.unmodifiableList( groups ); - } + List getGroups() { + return Collections.unmodifiableList( groups ); + } - void setGroups(List groups) { - this.groups = groups; - } - } + void setGroups(List groups) { + this.groups = groups; + } + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/association/ManyToManyAssociationTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/association/ManyToManyAssociationTest.java index 2fdc211cd9..308f83fb84 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/association/ManyToManyAssociationTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/association/ManyToManyAssociationTest.java @@ -25,95 +25,95 @@ import java.util.Set; @BytecodeEnhanced public class ManyToManyAssociationTest { - @Test - public void test() { - Group group = new Group(); - Group anotherGroup = new Group(); + @Test + public void test() { + Group group = new Group(); + Group anotherGroup = new Group(); - User user = new User(); - User anotherUser = new User(); + User user = new User(); + User anotherUser = new User(); - user.addGroup( group ); - user.addGroup( anotherGroup ); - anotherUser.addGroup( group ); + user.addGroup( group ); + user.addGroup( anotherGroup ); + anotherUser.addGroup( group ); - assertEquals( 2, group.getUsers().size() ); - assertEquals( 1, anotherGroup.getUsers().size() ); + assertEquals( 2, group.getUsers().size() ); + assertEquals( 1, anotherGroup.getUsers().size() ); - group.resetUsers(); + group.resetUsers(); - assertEquals( 1, user.getGroups().size() ); - assertEquals( 0, anotherUser.getGroups().size() ); + assertEquals( 1, user.getGroups().size() ); + assertEquals( 0, anotherUser.getGroups().size() ); - // Test remove - user.addGroup( group ); - anotherUser.addGroup( group ); + // Test remove + user.addGroup( group ); + anotherUser.addGroup( group ); - assertEquals( 2, group.getUsers().size() ); - assertEquals( 1, anotherGroup.getUsers().size() ); + assertEquals( 2, group.getUsers().size() ); + assertEquals( 1, anotherGroup.getUsers().size() ); - Set groups = new HashSet<>( user.getGroups() ); - groups.remove( group ); - user.setGroups( groups ); + Set groups = new HashSet<>( user.getGroups() ); + groups.remove( group ); + user.setGroups( groups ); - assertEquals( 1, group.getUsers().size() ); - assertEquals( 1, anotherGroup.getUsers().size() ); + assertEquals( 1, group.getUsers().size() ); + assertEquals( 1, anotherGroup.getUsers().size() ); - groups.remove( anotherGroup ); - user.setGroups( groups ); + groups.remove( anotherGroup ); + user.setGroups( groups ); - assertEquals( 1, group.getUsers().size() ); - // This happens (and is expected) because there was no snapshot taken before remove - assertEquals( 1, anotherGroup.getUsers().size() ); - } + assertEquals( 1, group.getUsers().size() ); + // This happens (and is expected) because there was no snapshot taken before remove + assertEquals( 1, anotherGroup.getUsers().size() ); + } - // -- // + // -- // - @Entity - private static class Group { + @Entity + private static class Group { - @Id - Long id; + @Id + Long id; - @Column - String name; + @Column + String name; - @ManyToMany( mappedBy = "groups" ) - Set users = new HashSet<>(); + @ManyToMany( mappedBy = "groups" ) + Set users = new HashSet<>(); - Set getUsers() { - return Collections.unmodifiableSet( users ); - } + Set getUsers() { + return Collections.unmodifiableSet( users ); + } - void resetUsers() { - // this wouldn't trigger association management: users.clear(); - users = new HashSet<>(); - } - } + void resetUsers() { + // this wouldn't trigger association management: users.clear(); + users = new HashSet<>(); + } + } - @Entity - private static class User { + @Entity + private static class User { - @Id - Long id; + @Id + Long id; - String password; + String password; - @ManyToMany - Set groups; + @ManyToMany + Set groups; - void addGroup(Group group) { - Set groups = this.groups == null ? new HashSet<>() : this.groups; - groups.add( group ); - this.groups = groups; - } + void addGroup(Group group) { + Set groups = this.groups == null ? new HashSet<>() : this.groups; + groups.add( group ); + this.groups = groups; + } - Set getGroups() { - return Collections.unmodifiableSet( groups ); - } + Set getGroups() { + return Collections.unmodifiableSet( groups ); + } - void setGroups(Set groups) { - this.groups = groups; - } - } + void setGroups(Set groups) { + this.groups = groups; + } + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/association/OneToManyAssociationTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/association/OneToManyAssociationTest.java index 1d558531a8..336b6e24fe 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/association/OneToManyAssociationTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/association/OneToManyAssociationTest.java @@ -30,99 +30,99 @@ import java.util.List; @BytecodeEnhanced public class OneToManyAssociationTest { - @Test - public void test() { - Customer customer = new Customer(); - assertTrue( customer.getInventories().isEmpty() ); + @Test + public void test() { + Customer customer = new Customer(); + assertTrue( customer.getInventories().isEmpty() ); - CustomerInventory customerInventory = new CustomerInventory(); - customerInventory.setCustomer( customer ); + CustomerInventory customerInventory = new CustomerInventory(); + customerInventory.setCustomer( customer ); - assertEquals( 1, customer.getInventories().size() ); - assertTrue( customer.getInventories().contains( customerInventory ) ); + assertEquals( 1, customer.getInventories().size() ); + assertTrue( customer.getInventories().contains( customerInventory ) ); - Customer anotherCustomer = new Customer(); - assertTrue( anotherCustomer.getInventories().isEmpty() ); - customerInventory.setCustomer( anotherCustomer ); + Customer anotherCustomer = new Customer(); + assertTrue( anotherCustomer.getInventories().isEmpty() ); + customerInventory.setCustomer( anotherCustomer ); - assertTrue( customer.getInventories().isEmpty() ); - assertEquals( 1, anotherCustomer.getInventories().size() ); - assertSame( customerInventory, anotherCustomer.getInventories().get( 0 ) ); + assertTrue( customer.getInventories().isEmpty() ); + assertEquals( 1, anotherCustomer.getInventories().size() ); + assertSame( customerInventory, anotherCustomer.getInventories().get( 0 ) ); - customer.addInventory( customerInventory ); + customer.addInventory( customerInventory ); - assertSame( customer, customerInventory.getCustomer() ); - assertTrue( anotherCustomer.getInventories().isEmpty() ); - assertEquals( 1, customer.getInventories().size() ); + assertSame( customer, customerInventory.getCustomer() ); + assertTrue( anotherCustomer.getInventories().isEmpty() ); + assertEquals( 1, customer.getInventories().size() ); - customer.addInventory( new CustomerInventory() ); - assertEquals( 2, customer.getInventories().size() ); + customer.addInventory( new CustomerInventory() ); + assertEquals( 2, customer.getInventories().size() ); - // Test remove - customer.removeInventory( customerInventory ); - assertEquals( 1, customer.getInventories().size() ); + // Test remove + customer.removeInventory( customerInventory ); + assertEquals( 1, customer.getInventories().size() ); - // This happens (and is expected) because there was no snapshot taken before remove - assertNotNull( customerInventory.getCustomer() ); - } + // This happens (and is expected) because there was no snapshot taken before remove + assertNotNull( customerInventory.getCustomer() ); + } - // --- // + // --- // - @Entity - private static class Customer { + @Entity + private static class Customer { - @Id - Long id; + @Id + Long id; - String name; + String name; - // HHH-13446 - Type not validated in bi-directional association mapping - @OneToMany(cascade = CascadeType.ALL, mappedBy = "custId", fetch = FetchType.EAGER) - List inventoryIdList = new ArrayList<>(); + // HHH-13446 - Type not validated in bi-directional association mapping + @OneToMany(cascade = CascadeType.ALL, mappedBy = "custId", fetch = FetchType.EAGER) + List inventoryIdList = new ArrayList<>(); - @OneToMany( mappedBy = "customer", cascade = CascadeType.ALL, fetch = FetchType.EAGER ) - List customerInventories = new ArrayList<>(); + @OneToMany( mappedBy = "customer", cascade = CascadeType.ALL, fetch = FetchType.EAGER ) + List customerInventories = new ArrayList<>(); - void addInventory(CustomerInventory inventory) { - List list = customerInventories; - list.add( inventory ); - customerInventories = list; - } + void addInventory(CustomerInventory inventory) { + List list = customerInventories; + list.add( inventory ); + customerInventories = list; + } - List getInventories() { - return Collections.unmodifiableList( customerInventories ); - } + List getInventories() { + return Collections.unmodifiableList( customerInventories ); + } - void removeInventory(CustomerInventory inventory) { - customerInventories.remove( inventory ); - } - } + void removeInventory(CustomerInventory inventory) { + customerInventories.remove( inventory ); + } + } - @Entity - private static class CustomerInventory { + @Entity + private static class CustomerInventory { - @Id - Long id; + @Id + Long id; - @Id - Long custId; + @Id + Long custId; - @ManyToOne( cascade = CascadeType.MERGE ) - Customer customer; + @ManyToOne( cascade = CascadeType.MERGE ) + Customer customer; - @ManyToOne( cascade = CascadeType.MERGE ) - String vehicle; + @ManyToOne( cascade = CascadeType.MERGE ) + String vehicle; - Customer getCustomer() { - return customer; - } + Customer getCustomer() { + return customer; + } - void setCustomer(Customer customer) { - this.customer = customer; - } + void setCustomer(Customer customer) { + this.customer = customer; + } - void setVehicle(String vehicle) { - this.vehicle = vehicle; - } - } + void setVehicle(String vehicle) { + this.vehicle = vehicle; + } + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/association/OneToOneAssociationTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/association/OneToOneAssociationTest.java index 4cd35d5e8c..fce462f676 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/association/OneToOneAssociationTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/association/OneToOneAssociationTest.java @@ -25,94 +25,94 @@ import org.hibernate.testing.util.uuid.SafeRandomUUIDGenerator; @BytecodeEnhanced public class OneToOneAssociationTest { - @Test - public void test() { - User user = new User(); - user.setLogin( SafeRandomUUIDGenerator.safeRandomUUIDAsString() ); + @Test + public void test() { + User user = new User(); + user.setLogin( SafeRandomUUIDGenerator.safeRandomUUIDAsString() ); - Customer customer = new Customer(); - customer.setUser( user ); + Customer customer = new Customer(); + customer.setUser( user ); - assertEquals( customer, user.getCustomer() ); + assertEquals( customer, user.getCustomer() ); - // check dirty tracking is set automatically with bi-directional association management - EnhancerTestUtils.checkDirtyTracking( user, "login", "customer" ); + // check dirty tracking is set automatically with bi-directional association management + EnhancerTestUtils.checkDirtyTracking( user, "login", "customer" ); - User anotherUser = new User(); - anotherUser.setLogin( SafeRandomUUIDGenerator.safeRandomUUIDAsString() ); + User anotherUser = new User(); + anotherUser.setLogin( SafeRandomUUIDGenerator.safeRandomUUIDAsString() ); - customer.setUser( anotherUser ); + customer.setUser( anotherUser ); - assertNull( user.getCustomer() ); - assertEquals( customer, anotherUser.getCustomer() ); + assertNull( user.getCustomer() ); + assertEquals( customer, anotherUser.getCustomer() ); - user.setCustomer( new Customer() ); + user.setCustomer( new Customer() ); - assertEquals( user, user.getCustomer().getUser() ); - } + assertEquals( user, user.getCustomer().getUser() ); + } - @Test - public void testSetNull() { - User user = new User(); - user.setLogin( SafeRandomUUIDGenerator.safeRandomUUIDAsString() ); + @Test + public void testSetNull() { + User user = new User(); + user.setLogin( SafeRandomUUIDGenerator.safeRandomUUIDAsString() ); - Customer customer = new Customer(); - customer.setUser( user ); + Customer customer = new Customer(); + customer.setUser( user ); - assertEquals( customer, user.getCustomer() ); + assertEquals( customer, user.getCustomer() ); - // check dirty tracking is set automatically with bi-directional association management - EnhancerTestUtils.checkDirtyTracking( user, "login", "customer" ); + // check dirty tracking is set automatically with bi-directional association management + EnhancerTestUtils.checkDirtyTracking( user, "login", "customer" ); - user.setCustomer( null ); + user.setCustomer( null ); - assertNull( user.getCustomer() ); - assertNull( customer.getUser() ); - } + assertNull( user.getCustomer() ); + assertNull( customer.getUser() ); + } - // --- // + // --- // - @Entity - private static class Customer { + @Entity + private static class Customer { - @Id - Long id; + @Id + Long id; - @OneToOne - User user; + @OneToOne + User user; - User getUser() { - return user; - } + User getUser() { + return user; + } - void setUser(User newUser) { - user = newUser; - } - } + void setUser(User newUser) { + user = newUser; + } + } - @Entity - private static class User { + @Entity + private static class User { - @Id - Long id; + @Id + Long id; - String login; + String login; - String password; + String password; - @OneToOne( mappedBy = "user" ) - Customer customer; + @OneToOne( mappedBy = "user" ) + Customer customer; - void setLogin(String login) { - this.login = login; - } + void setLogin(String login) { + this.login = login; + } - Customer getCustomer() { - return customer; - } + Customer getCustomer() { + return customer; + } - void setCustomer(Customer customer) { - this.customer = customer; - } - } + void setCustomer(Customer customer) { + this.customer = customer; + } + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/basic/BasicEnhancementTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/basic/BasicEnhancementTest.java index b2a20a03a3..5716157fe1 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/basic/BasicEnhancementTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/basic/BasicEnhancementTest.java @@ -37,146 +37,146 @@ import static org.junit.jupiter.api.Assertions.assertTrue; @BytecodeEnhanced public class BasicEnhancementTest { - @Test - public void basicManagedTest() { - SimpleEntity entity = new SimpleEntity(); + @Test + public void basicManagedTest() { + SimpleEntity entity = new SimpleEntity(); - // Call the new ManagedEntity methods - assertTyping( ManagedEntity.class, entity ); - ManagedEntity managedEntity = (ManagedEntity) entity; - assertSame( entity, managedEntity.$$_hibernate_getEntityInstance() ); + // Call the new ManagedEntity methods + assertTyping( ManagedEntity.class, entity ); + ManagedEntity managedEntity = (ManagedEntity) entity; + assertSame( entity, managedEntity.$$_hibernate_getEntityInstance() ); - assertNull( managedEntity.$$_hibernate_getEntityEntry() ); - managedEntity.$$_hibernate_setEntityEntry( EnhancerTestUtils.makeEntityEntry() ); - assertNotNull( managedEntity.$$_hibernate_getEntityEntry() ); - managedEntity.$$_hibernate_setEntityEntry( null ); - assertNull( managedEntity.$$_hibernate_getEntityEntry() ); + assertNull( managedEntity.$$_hibernate_getEntityEntry() ); + managedEntity.$$_hibernate_setEntityEntry( EnhancerTestUtils.makeEntityEntry() ); + assertNotNull( managedEntity.$$_hibernate_getEntityEntry() ); + managedEntity.$$_hibernate_setEntityEntry( null ); + assertNull( managedEntity.$$_hibernate_getEntityEntry() ); - managedEntity.$$_hibernate_setNextManagedEntity( managedEntity ); - managedEntity.$$_hibernate_setPreviousManagedEntity( managedEntity ); - assertSame( managedEntity, managedEntity.$$_hibernate_getNextManagedEntity() ); - assertSame( managedEntity, managedEntity.$$_hibernate_getPreviousManagedEntity() ); - } + managedEntity.$$_hibernate_setNextManagedEntity( managedEntity ); + managedEntity.$$_hibernate_setPreviousManagedEntity( managedEntity ); + assertSame( managedEntity, managedEntity.$$_hibernate_getNextManagedEntity() ); + assertSame( managedEntity, managedEntity.$$_hibernate_getPreviousManagedEntity() ); + } - @Test - @Jira("HHH-13439") - public void enhancementInfoTest() { - EnhancementInfo info = SimpleEntity.class.getAnnotation( EnhancementInfo.class ); - assertNotNull( info, "EnhancementInfo was not applied" ); + @Test + @Jira("HHH-13439") + public void enhancementInfoTest() { + EnhancementInfo info = SimpleEntity.class.getAnnotation( EnhancementInfo.class ); + assertNotNull( info, "EnhancementInfo was not applied" ); - assertEquals( Version.getVersionString(), info.version() ); - } + assertEquals( Version.getVersionString(), info.version() ); + } - @Test - public void basicInterceptableTest() { - SimpleEntity entity = new SimpleEntity(); + @Test + public void basicInterceptableTest() { + SimpleEntity entity = new SimpleEntity(); - assertTyping( PersistentAttributeInterceptable.class, entity ); - PersistentAttributeInterceptable interceptableEntity = (PersistentAttributeInterceptable) entity; + assertTyping( PersistentAttributeInterceptable.class, entity ); + PersistentAttributeInterceptable interceptableEntity = (PersistentAttributeInterceptable) entity; - assertNull( interceptableEntity.$$_hibernate_getInterceptor() ); - interceptableEntity.$$_hibernate_setInterceptor( new ObjectAttributeMarkerInterceptor() ); - assertNotNull( interceptableEntity.$$_hibernate_getInterceptor() ); + assertNull( interceptableEntity.$$_hibernate_getInterceptor() ); + interceptableEntity.$$_hibernate_setInterceptor( new ObjectAttributeMarkerInterceptor() ); + assertNotNull( interceptableEntity.$$_hibernate_getInterceptor() ); - assertNull( EnhancerTestUtils.getFieldByReflection( entity, "anUnspecifiedObject" ) ); - entity.setAnObject( new Object() ); + assertNull( EnhancerTestUtils.getFieldByReflection( entity, "anUnspecifiedObject" ) ); + entity.setAnObject( new Object() ); - assertSame( ObjectAttributeMarkerInterceptor.WRITE_MARKER, EnhancerTestUtils.getFieldByReflection( entity, "anUnspecifiedObject" ) ); - assertSame( ObjectAttributeMarkerInterceptor.READ_MARKER, entity.getAnObject() ); + assertSame( ObjectAttributeMarkerInterceptor.WRITE_MARKER, EnhancerTestUtils.getFieldByReflection( entity, "anUnspecifiedObject" ) ); + assertSame( ObjectAttributeMarkerInterceptor.READ_MARKER, entity.getAnObject() ); - entity.setAnObject( null ); - assertSame( ObjectAttributeMarkerInterceptor.WRITE_MARKER, EnhancerTestUtils.getFieldByReflection( entity, "anUnspecifiedObject" ) ); - } + entity.setAnObject( null ); + assertSame( ObjectAttributeMarkerInterceptor.WRITE_MARKER, EnhancerTestUtils.getFieldByReflection( entity, "anUnspecifiedObject" ) ); + } - @Test - public void basicExtendedEnhancementTest() { - // test uses ObjectAttributeMarkerInterceptor to ensure that field access is routed through enhanced methods + @Test + public void basicExtendedEnhancementTest() { + // test uses ObjectAttributeMarkerInterceptor to ensure that field access is routed through enhanced methods - SimpleEntity entity = new SimpleEntity(); - ( (PersistentAttributeInterceptable) entity ).$$_hibernate_setInterceptor( new ObjectAttributeMarkerInterceptor() ); + SimpleEntity entity = new SimpleEntity(); + ( (PersistentAttributeInterceptable) entity ).$$_hibernate_setInterceptor( new ObjectAttributeMarkerInterceptor() ); - Object decoy = new Object(); - entity.anUnspecifiedObject = decoy; + Object decoy = new Object(); + entity.anUnspecifiedObject = decoy; - Object gotByReflection = EnhancerTestUtils.getFieldByReflection( entity, "anUnspecifiedObject" ); - assertNotSame( decoy, gotByReflection ); - assertSame( ObjectAttributeMarkerInterceptor.WRITE_MARKER, gotByReflection ); + Object gotByReflection = EnhancerTestUtils.getFieldByReflection( entity, "anUnspecifiedObject" ); + assertNotSame( decoy, gotByReflection ); + assertSame( ObjectAttributeMarkerInterceptor.WRITE_MARKER, gotByReflection ); - Object entityObject = entity.anUnspecifiedObject; + Object entityObject = entity.anUnspecifiedObject; - assertNotSame( decoy, entityObject ); - assertSame( ObjectAttributeMarkerInterceptor.READ_MARKER, entityObject ); + assertNotSame( decoy, entityObject ); + assertSame( ObjectAttributeMarkerInterceptor.READ_MARKER, entityObject ); - // do some more calls on the various types, without the interceptor - ( (PersistentAttributeInterceptable) entity ).$$_hibernate_setInterceptor( null ); + // do some more calls on the various types, without the interceptor + ( (PersistentAttributeInterceptable) entity ).$$_hibernate_setInterceptor( null ); - entity.id = 1234567890L; - assertEquals( 1234567890L, (long) entity.getId() ); + entity.id = 1234567890L; + assertEquals( 1234567890L, (long) entity.getId() ); - entity.name = "Entity Name"; - assertSame( "Entity Name", entity.name ); + entity.name = "Entity Name"; + assertSame( "Entity Name", entity.name ); - entity.active = true; - assertTrue( entity.getActive() ); + entity.active = true; + assertTrue( entity.getActive() ); - entity.someStrings = Arrays.asList( "A", "B", "C", "D" ); - assertArrayEquals( new String[]{"A", "B", "C", "D"}, entity.someStrings.toArray() ); - } + entity.someStrings = Arrays.asList( "A", "B", "C", "D" ); + assertArrayEquals( new String[]{"A", "B", "C", "D"}, entity.someStrings.toArray() ); + } - // --- // + // --- // - @Entity - private static class SimpleEntity { + @Entity + private static class SimpleEntity { - Object anUnspecifiedObject; + Object anUnspecifiedObject; - @Id - Long id; + @Id + Long id; - String name; + String name; - Boolean active; + Boolean active; - List someStrings; + List someStrings; - Long getId() { - return id; - } + Long getId() { + return id; + } - void setId(Long id) { - this.id = id; - } + void setId(Long id) { + this.id = id; + } - String getName() { - return name; - } + String getName() { + return name; + } - void setName(String name) { - this.name = name; - } + void setName(String name) { + this.name = name; + } - public Boolean getActive() { - return active; - } + public Boolean getActive() { + return active; + } - public void setActive(Boolean active) { - this.active = active; - } + public void setActive(Boolean active) { + this.active = active; + } - Object getAnObject() { - return anUnspecifiedObject; - } + Object getAnObject() { + return anUnspecifiedObject; + } - void setAnObject(Object providedObject) { - this.anUnspecifiedObject = providedObject; - } + void setAnObject(Object providedObject) { + this.anUnspecifiedObject = providedObject; + } - List getSomeStrings() { - return Collections.unmodifiableList( someStrings ); - } + List getSomeStrings() { + return Collections.unmodifiableList( someStrings ); + } - void setSomeStrings(List someStrings) { - this.someStrings = someStrings; - } - } + void setSomeStrings(List someStrings) { + this.someStrings = someStrings; + } + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/basic/BasicSessionTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/basic/BasicSessionTest.java index cb05208536..90c9e91f0b 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/basic/BasicSessionTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/basic/BasicSessionTest.java @@ -28,112 +28,112 @@ import static org.junit.jupiter.api.Assertions.assertSame; * @author Luis Barreiro */ @DomainModel( - annotatedClasses = { - BasicSessionTest.MyEntity.class, - } + annotatedClasses = { + BasicSessionTest.MyEntity.class, + } ) @SessionFactory @BytecodeEnhanced public class BasicSessionTest { - @Test - public void test(SessionFactoryScope scope) { - scope.inTransaction( s -> { - s.persist( new MyEntity( 1L ) ); - s.persist( new MyEntity( 2L ) ); - } ); + @Test + public void test(SessionFactoryScope scope) { + scope.inTransaction( s -> { + s.persist( new MyEntity( 1L ) ); + s.persist( new MyEntity( 2L ) ); + } ); - MyEntity[] entities = new MyEntity[2]; + MyEntity[] entities = new MyEntity[2]; - scope.inTransaction( s -> { - entities[0] = s.get( MyEntity.class, 1L ); - entities[1] = s.get( MyEntity.class, 2L ); + scope.inTransaction( s -> { + entities[0] = s.get( MyEntity.class, 1L ); + entities[1] = s.get( MyEntity.class, 2L ); - assertNotNull( entities[0].$$_hibernate_getEntityInstance() ); - assertSame( entities[0], entities[0].$$_hibernate_getEntityInstance() ); - assertNotNull( entities[0].$$_hibernate_getEntityEntry() ); - assertNull( entities[0].$$_hibernate_getPreviousManagedEntity() ); - assertNotNull( entities[0].$$_hibernate_getNextManagedEntity() ); + assertNotNull( entities[0].$$_hibernate_getEntityInstance() ); + assertSame( entities[0], entities[0].$$_hibernate_getEntityInstance() ); + assertNotNull( entities[0].$$_hibernate_getEntityEntry() ); + assertNull( entities[0].$$_hibernate_getPreviousManagedEntity() ); + assertNotNull( entities[0].$$_hibernate_getNextManagedEntity() ); - assertNotNull( entities[1].$$_hibernate_getEntityInstance() ); - assertSame( entities[1], entities[1].$$_hibernate_getEntityInstance() ); - assertNotNull( entities[1].$$_hibernate_getEntityEntry() ); - assertNotNull( entities[1].$$_hibernate_getPreviousManagedEntity() ); - assertNull( entities[1].$$_hibernate_getNextManagedEntity() ); + assertNotNull( entities[1].$$_hibernate_getEntityInstance() ); + assertSame( entities[1], entities[1].$$_hibernate_getEntityInstance() ); + assertNotNull( entities[1].$$_hibernate_getEntityEntry() ); + assertNotNull( entities[1].$$_hibernate_getPreviousManagedEntity() ); + assertNull( entities[1].$$_hibernate_getNextManagedEntity() ); - s.createQuery( "delete MyEntity" ).executeUpdate(); - } ); + s.createQuery( "delete MyEntity" ).executeUpdate(); + } ); - assertNull( entities[0].$$_hibernate_getEntityEntry() ); - assertNull( entities[1].$$_hibernate_getEntityEntry() ); - } + assertNull( entities[0].$$_hibernate_getEntityEntry() ); + assertNull( entities[1].$$_hibernate_getEntityEntry() ); + } - // --- // + // --- // - @Entity( name = "MyEntity" ) - @Table( name = "MY_ENTITY" ) - static class MyEntity implements ManagedEntity { + @Entity( name = "MyEntity" ) + @Table( name = "MY_ENTITY" ) + static class MyEntity implements ManagedEntity { - @Id - Long id; + @Id + Long id; - @Transient - private transient EntityEntry entityEntry; - @Transient - private transient ManagedEntity previous; - @Transient - private transient ManagedEntity next; + @Transient + private transient EntityEntry entityEntry; + @Transient + private transient ManagedEntity previous; + @Transient + private transient ManagedEntity next; - MyEntity() { - } + MyEntity() { + } - MyEntity(Long id) { - this.id = id; - } + MyEntity(Long id) { + this.id = id; + } - @Override - public Object $$_hibernate_getEntityInstance() { - return this; - } + @Override + public Object $$_hibernate_getEntityInstance() { + return this; + } - @Override - public EntityEntry $$_hibernate_getEntityEntry() { - return entityEntry; - } + @Override + public EntityEntry $$_hibernate_getEntityEntry() { + return entityEntry; + } - @Override - public void $$_hibernate_setEntityEntry(EntityEntry entityEntry) { - this.entityEntry = entityEntry; - } + @Override + public void $$_hibernate_setEntityEntry(EntityEntry entityEntry) { + this.entityEntry = entityEntry; + } - @Override - public ManagedEntity $$_hibernate_getNextManagedEntity() { - return next; - } + @Override + public ManagedEntity $$_hibernate_getNextManagedEntity() { + return next; + } - @Override - public void $$_hibernate_setNextManagedEntity(ManagedEntity next) { - this.next = next; - } + @Override + public void $$_hibernate_setNextManagedEntity(ManagedEntity next) { + this.next = next; + } - @Override - public ManagedEntity $$_hibernate_getPreviousManagedEntity() { - return previous; - } + @Override + public ManagedEntity $$_hibernate_getPreviousManagedEntity() { + return previous; + } - @Override - public void $$_hibernate_setPreviousManagedEntity(ManagedEntity previous) { - this.previous = previous; - } + @Override + public void $$_hibernate_setPreviousManagedEntity(ManagedEntity previous) { + this.previous = previous; + } - @Override - public void $$_hibernate_setUseTracker(boolean useTracker) { + @Override + public void $$_hibernate_setUseTracker(boolean useTracker) { - } + } - @Override - public boolean $$_hibernate_useTracker() { - return false; - } - } + @Override + public boolean $$_hibernate_useTracker() { + return false; + } + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/basic/CrossEnhancementTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/basic/CrossEnhancementTest.java index aa977c1d0b..ee3b3b9140 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/basic/CrossEnhancementTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/basic/CrossEnhancementTest.java @@ -27,54 +27,54 @@ import java.io.Serializable; */ @JiraKey( "HHH-9529" ) @DomainModel( - annotatedClasses = { - CrossEnhancementTest.Parent.class, CrossEnhancementTest.Child.class, CrossEnhancementTest.ChildKey.class - } + annotatedClasses = { + CrossEnhancementTest.Parent.class, CrossEnhancementTest.Child.class, CrossEnhancementTest.ChildKey.class + } ) @SessionFactory @BytecodeEnhanced public class CrossEnhancementTest { - @Test - public void test(SessionFactoryScope scope) { + @Test + public void test(SessionFactoryScope scope) { // sessionFactory().close(); // buildSessionFactory(); scope.getSessionFactory().close(); - // TODO: I do not get this test ^ and not sure how to update it ... + // TODO: I do not get this test ^ and not sure how to update it ... } - // --- // + // --- // - @Entity - @Table( name = "PARENT" ) - static class Parent { - @Id - String id; - } + @Entity + @Table( name = "PARENT" ) + static class Parent { + @Id + String id; + } - @Embeddable - static class ChildKey implements Serializable { - String parent; - String type; - } + @Embeddable + static class ChildKey implements Serializable { + String parent; + String type; + } - @Entity - @Table( name = "CHILD" ) - static class Child { - @EmbeddedId - ChildKey id; + @Entity + @Table( name = "CHILD" ) + static class Child { + @EmbeddedId + ChildKey id; - @MapsId( "parent" ) - @ManyToOne - Parent parent; + @MapsId( "parent" ) + @ManyToOne + Parent parent; - public String getfieldOnChildKeyParent() { - // Note that there are two GETFIELD ops here, one on the field 'id' that should be enhanced and another - // on the field 'parent' that may be or not (depending if 'extended enhancement' is enabled) + public String getfieldOnChildKeyParent() { + // Note that there are two GETFIELD ops here, one on the field 'id' that should be enhanced and another + // on the field 'parent' that may be or not (depending if 'extended enhancement' is enabled) - // Either way, the field 'parent' on ChildKey should not be confused with the field 'parent' on Child + // Either way, the field 'parent' on ChildKey should not be confused with the field 'parent' on Child - return id.parent; - } - } + return id.parent; + } + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/basic/ExtendedAssociationManagementTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/basic/ExtendedAssociationManagementTest.java index f68fceda71..b74638480c 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/basic/ExtendedAssociationManagementTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/basic/ExtendedAssociationManagementTest.java @@ -27,58 +27,58 @@ import static org.junit.jupiter.api.Assertions.assertNull; @BytecodeEnhanced public class ExtendedAssociationManagementTest { - @Test - public void test() { - User user = new User(); - user.login = SafeRandomUUIDGenerator.safeRandomUUIDAsString(); + @Test + public void test() { + User user = new User(); + user.login = SafeRandomUUIDGenerator.safeRandomUUIDAsString(); - Customer customer = new Customer(); - customer.user = user; + Customer customer = new Customer(); + customer.user = user; - assertEquals( customer, getFieldByReflection( user, "customer" ) ); + assertEquals( customer, getFieldByReflection( user, "customer" ) ); - // check dirty tracking is set automatically with bi-directional association management - EnhancerTestUtils.checkDirtyTracking( user, "login", "customer" ); + // check dirty tracking is set automatically with bi-directional association management + EnhancerTestUtils.checkDirtyTracking( user, "login", "customer" ); - User anotherUser = new User(); - anotherUser.login = SafeRandomUUIDGenerator.safeRandomUUIDAsString(); + User anotherUser = new User(); + anotherUser.login = SafeRandomUUIDGenerator.safeRandomUUIDAsString(); - customer.user = anotherUser; + customer.user = anotherUser; - assertNull( user.customer ); - assertEquals( customer, getFieldByReflection( anotherUser, "customer" ) ); + assertNull( user.customer ); + assertEquals( customer, getFieldByReflection( anotherUser, "customer" ) ); - user.customer = new Customer(); - assertEquals( user, user.customer.user ); - } + user.customer = new Customer(); + assertEquals( user, user.customer.user ); + } - // --- // + // --- // - @Entity - private static class Customer { + @Entity + private static class Customer { - @Id - Long id; + @Id + Long id; - String firstName; + String firstName; - String lastName; + String lastName; - @OneToOne( fetch = FetchType.LAZY ) - User user; - } + @OneToOne( fetch = FetchType.LAZY ) + User user; + } - @Entity - private static class User { + @Entity + private static class User { - @Id - Long id; + @Id + Long id; - String login; + String login; - String password; + String password; - @OneToOne( mappedBy = "user", fetch = FetchType.LAZY ) - Customer customer; - } + @OneToOne( mappedBy = "user", fetch = FetchType.LAZY ) + Customer customer; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/basic/InheritedTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/basic/InheritedTest.java index b553ba15e2..a3e5423704 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/basic/InheritedTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/basic/InheritedTest.java @@ -36,130 +36,130 @@ import static org.junit.jupiter.api.Assumptions.assumeTrue; @CustomEnhancementContext( {EnhancerTestContext.class, InheritedTest.EagerEnhancementContext.class} ) public class InheritedTest { - @Test - public void test() { - Employee charles = new Employee( "Charles", "Engineer" ); - charles.setOca( 1002 ); + @Test + public void test() { + Employee charles = new Employee( "Charles", "Engineer" ); + charles.setOca( 1002 ); - // Check that both types of class attributes are being dirty tracked - checkDirtyTracking( charles, "title", "oca" ); - clearDirtyTracking( charles ); + // Check that both types of class attributes are being dirty tracked + checkDirtyTracking( charles, "title", "oca" ); + clearDirtyTracking( charles ); - // Let's give charles a promotion, this time using method references - charles.setOca( 99 ); - charles.setTitle( "Manager" ); + // Let's give charles a promotion, this time using method references + charles.setOca( 99 ); + charles.setTitle( "Manager" ); - checkDirtyTracking( charles, "title", "oca" ); + checkDirtyTracking( charles, "title", "oca" ); - Contractor bob = new Contractor( "Bob", 100 ); - bob.setOca( 1003 ); + Contractor bob = new Contractor( "Bob", 100 ); + bob.setOca( 1003 ); - // Check that both types of class attributes are being dirty tracked - checkDirtyTracking( bob, "rate", "oca" ); - clearDirtyTracking( bob ); + // Check that both types of class attributes are being dirty tracked + checkDirtyTracking( bob, "rate", "oca" ); + clearDirtyTracking( bob ); - // Let's give bob a rate increase, this time using method references - bob.setOca( 88 ); - bob.setRate( 200 ); + // Let's give bob a rate increase, this time using method references + bob.setOca( 88 ); + bob.setRate( 200 ); - checkDirtyTracking( bob, "rate", "oca" ); - } + checkDirtyTracking( bob, "rate", "oca" ); + } - // Adapted from BasicEnhancementTest#basicExtendedEnhancementTest - @Test - @JiraKey("HHH-14006") - public void extendedEnhancementTest() { - // This test only works if lazy loading bytecode enhancement is enabled, - // otherwise extended bytecode enhancement does not do anything we can check. - assumeTrue( PersistentAttributeInterceptable.class.isAssignableFrom( Employee.class ) ); + // Adapted from BasicEnhancementTest#basicExtendedEnhancementTest + @Test + @JiraKey("HHH-14006") + public void extendedEnhancementTest() { + // This test only works if lazy loading bytecode enhancement is enabled, + // otherwise extended bytecode enhancement does not do anything we can check. + assumeTrue( PersistentAttributeInterceptable.class.isAssignableFrom( Employee.class ) ); - Employee entity = new Employee(); - ( (PersistentAttributeInterceptable) entity ).$$_hibernate_setInterceptor( new ObjectAttributeMarkerInterceptor() ); + Employee entity = new Employee(); + ( (PersistentAttributeInterceptable) entity ).$$_hibernate_setInterceptor( new ObjectAttributeMarkerInterceptor() ); - Object decoy = new Object(); - // This accesses "anUnspecifiedObject" on a variable of type Employee, - // but "anUnspecifiedObject" is defined the superclass Person. - // Such "virtual" access used to break extended bytecode enhancement. - entity.anUnspecifiedObject = decoy; + Object decoy = new Object(); + // This accesses "anUnspecifiedObject" on a variable of type Employee, + // but "anUnspecifiedObject" is defined the superclass Person. + // Such "virtual" access used to break extended bytecode enhancement. + entity.anUnspecifiedObject = decoy; - Object gotByReflection = EnhancerTestUtils.getFieldByReflection( entity, "anUnspecifiedObject" ); - assertNotSame( decoy, gotByReflection ); - assertSame( ObjectAttributeMarkerInterceptor.WRITE_MARKER, gotByReflection ); + Object gotByReflection = EnhancerTestUtils.getFieldByReflection( entity, "anUnspecifiedObject" ); + assertNotSame( decoy, gotByReflection ); + assertSame( ObjectAttributeMarkerInterceptor.WRITE_MARKER, gotByReflection ); - Object gotByEnhancedDirectAccess = entity.anUnspecifiedObject; - assertNotSame( decoy, gotByEnhancedDirectAccess ); - assertSame( ObjectAttributeMarkerInterceptor.READ_MARKER, gotByEnhancedDirectAccess ); - } + Object gotByEnhancedDirectAccess = entity.anUnspecifiedObject; + assertNotSame( decoy, gotByEnhancedDirectAccess ); + assertSame( ObjectAttributeMarkerInterceptor.READ_MARKER, gotByEnhancedDirectAccess ); + } - // --- // + // --- // - @Entity - private static abstract class Person { + @Entity + private static abstract class Person { - Object anUnspecifiedObject; + Object anUnspecifiedObject; - @Id - String name; + @Id + String name; - @Version - long oca; + @Version + long oca; - Person() { - } + Person() { + } - Person(String name) { - this(); - this.name = name; - } + Person(String name) { + this(); + this.name = name; + } - void setOca(long l) { - this.oca = l; - } - } + void setOca(long l) { + this.oca = l; + } + } - @Entity - private static class Employee extends Person { + @Entity + private static class Employee extends Person { - String title; + String title; - Employee() { - } + Employee() { + } - Employee(String name, String title) { - super( name ); - this.title = title; - } + Employee(String name, String title) { + super( name ); + this.title = title; + } - void setTitle(String title) { - this.title = title; - } - } + void setTitle(String title) { + this.title = title; + } + } - @Entity - private static class Contractor extends Person { + @Entity + private static class Contractor extends Person { - Integer rate; + Integer rate; - Contractor() { - } + Contractor() { + } - Contractor(String name, Integer rate) { - super( name ); - this.rate = rate; - } + Contractor(String name, Integer rate) { + super( name ); + this.rate = rate; + } - void setRate(Integer rate) { - this.rate = rate; - } - } + void setRate(Integer rate) { + this.rate = rate; + } + } - // --- // + // --- // - public static class EagerEnhancementContext extends DefaultEnhancementContext { - @Override - public boolean hasLazyLoadableAttributes(UnloadedClass classDescriptor) { - // HHH-10981 - Without lazy loading, the generation of getters and setters has a different code path - return false; - } - } + public static class EagerEnhancementContext extends DefaultEnhancementContext { + @Override + public boolean hasLazyLoadableAttributes(UnloadedClass classDescriptor) { + // HHH-10981 - Without lazy loading, the generation of getters and setters has a different code path + return false; + } + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/basic/MappedSuperclassTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/basic/MappedSuperclassTest.java index 29492fab86..30bbc60b65 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/basic/MappedSuperclassTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/basic/MappedSuperclassTest.java @@ -36,98 +36,98 @@ import static org.junit.jupiter.api.Assumptions.assumeTrue; @CustomEnhancementContext( {EnhancerTestContext.class, MappedSuperclassTest.EagerEnhancementContext.class} ) public class MappedSuperclassTest { - @Test - public void test() { - Employee charles = new Employee( "Charles", "Engineer" ); - charles.setOca( 1002 ); + @Test + public void test() { + Employee charles = new Employee( "Charles", "Engineer" ); + charles.setOca( 1002 ); - // Check that both types of class attributes are being dirty tracked - checkDirtyTracking( charles, "title", "oca" ); - clearDirtyTracking( charles ); + // Check that both types of class attributes are being dirty tracked + checkDirtyTracking( charles, "title", "oca" ); + clearDirtyTracking( charles ); - // Let's give charles a promotion, this time using method references - charles.setOca( 99 ); - charles.setTitle( "Manager" ); + // Let's give charles a promotion, this time using method references + charles.setOca( 99 ); + charles.setTitle( "Manager" ); - checkDirtyTracking( charles, "title", "oca" ); - } + checkDirtyTracking( charles, "title", "oca" ); + } - // Adapted from BasicEnhancementTest#basicExtendedEnhancementTest - @Test - @JiraKey("HHH-14006") - public void extendedEnhancementTest() { - // This test only works if lazy loading bytecode enhancement is enabled, - // otherwise extended bytecode enhancement does not do anything we can check. - assumeTrue( PersistentAttributeInterceptable.class.isAssignableFrom( Employee.class ) ); + // Adapted from BasicEnhancementTest#basicExtendedEnhancementTest + @Test + @JiraKey("HHH-14006") + public void extendedEnhancementTest() { + // This test only works if lazy loading bytecode enhancement is enabled, + // otherwise extended bytecode enhancement does not do anything we can check. + assumeTrue( PersistentAttributeInterceptable.class.isAssignableFrom( Employee.class ) ); - Employee entity = new Employee(); - ( (PersistentAttributeInterceptable) entity ).$$_hibernate_setInterceptor( new ObjectAttributeMarkerInterceptor() ); + Employee entity = new Employee(); + ( (PersistentAttributeInterceptable) entity ).$$_hibernate_setInterceptor( new ObjectAttributeMarkerInterceptor() ); - Object decoy = new Object(); - // This accesses "name" on a variable of type Employee, - // but "anUnspecifiedObject" is defined the superclass Person. - // Such "virtual" access used to break extended bytecode enhancement. - entity.anUnspecifiedObject = decoy; + Object decoy = new Object(); + // This accesses "name" on a variable of type Employee, + // but "anUnspecifiedObject" is defined the superclass Person. + // Such "virtual" access used to break extended bytecode enhancement. + entity.anUnspecifiedObject = decoy; - Object gotByReflection = EnhancerTestUtils.getFieldByReflection( entity, "anUnspecifiedObject" ); - assertNotSame( decoy, gotByReflection ); - assertSame( ObjectAttributeMarkerInterceptor.WRITE_MARKER, gotByReflection ); + Object gotByReflection = EnhancerTestUtils.getFieldByReflection( entity, "anUnspecifiedObject" ); + assertNotSame( decoy, gotByReflection ); + assertSame( ObjectAttributeMarkerInterceptor.WRITE_MARKER, gotByReflection ); - Object gotByEnhancedDirectAccess = entity.anUnspecifiedObject; - assertNotSame( decoy, gotByEnhancedDirectAccess ); - assertSame( ObjectAttributeMarkerInterceptor.READ_MARKER, gotByEnhancedDirectAccess ); - } + Object gotByEnhancedDirectAccess = entity.anUnspecifiedObject; + assertNotSame( decoy, gotByEnhancedDirectAccess ); + assertSame( ObjectAttributeMarkerInterceptor.READ_MARKER, gotByEnhancedDirectAccess ); + } - // --- // + // --- // - @MappedSuperclass - private static class Person { + @MappedSuperclass + private static class Person { - Object anUnspecifiedObject; + Object anUnspecifiedObject; - @Id - String name; + @Id + String name; - @Version - Long oca; + @Version + Long oca; - Person(String name) { - this.name = name; - } + Person(String name) { + this.name = name; + } - Person() { - } + Person() { + } - void setOca(long l) { - this.oca = l; - } - } + void setOca(long l) { + this.oca = l; + } + } - @Entity - private static class Employee extends Person { + @Entity + private static class Employee extends Person { - String title; + String title; - Employee(String name, String title) { - super( name ); - this.title = title; - } + Employee(String name, String title) { + super( name ); + this.title = title; + } - Employee() { - } + Employee() { + } - void setTitle(String title) { - this.title = title; - } - } + void setTitle(String title) { + this.title = title; + } + } - // --- // + // --- // - public static class EagerEnhancementContext extends DefaultEnhancementContext { - @Override - public boolean hasLazyLoadableAttributes(UnloadedClass classDescriptor) { - // HHH-10981 - Without lazy loading, the generation of getters and setters has a different code path - return false; - } - } + public static class EagerEnhancementContext extends DefaultEnhancementContext { + @Override + public boolean hasLazyLoadableAttributes(UnloadedClass classDescriptor) { + // HHH-10981 - Without lazy loading, the generation of getters and setters has a different code path + return false; + } + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/callbacks/PostLoadLazyListenerTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/callbacks/PostLoadLazyListenerTest.java index 981e9b7b17..369bd7ecf1 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/callbacks/PostLoadLazyListenerTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/callbacks/PostLoadLazyListenerTest.java @@ -40,9 +40,9 @@ public class PostLoadLazyListenerTest { @AfterEach public void tearDown(SessionFactoryScope scope) { scope.inTransaction( session -> { - session.createQuery( "delete from Tag" ).executeUpdate(); - session.createQuery( "delete from Person" ).executeUpdate(); - } + session.createQuery( "delete from Tag" ).executeUpdate(); + session.createQuery( "delete from Person" ).executeUpdate(); + } ); } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/cascade/CascadeDeleteCollectionTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/cascade/CascadeDeleteCollectionTest.java index 2584191722..c06030e590 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/cascade/CascadeDeleteCollectionTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/cascade/CascadeDeleteCollectionTest.java @@ -41,213 +41,213 @@ import org.hibernate.bytecode.spi.BytecodeEnhancementMetadata; */ @JiraKey( "HHH-10252" ) @DomainModel( - annotatedClasses = { - CascadeDeleteCollectionTest.Parent.class, CascadeDeleteCollectionTest.Child.class - } + annotatedClasses = { + CascadeDeleteCollectionTest.Parent.class, CascadeDeleteCollectionTest.Child.class + } ) @SessionFactory @BytecodeEnhanced public class CascadeDeleteCollectionTest { - private Parent originalParent; + private Parent originalParent; - @BeforeEach - public void prepare(SessionFactoryScope scope) { - // Create a Parent with one Child - originalParent = scope.fromTransaction( s -> { - Parent p = new Parent(); - p.setName( "PARENT" ); - p.setLazy( "LAZY" ); - p.makeChild(); - s.persist( p ); - return p; - } - ); - } + @BeforeEach + public void prepare(SessionFactoryScope scope) { + // Create a Parent with one Child + originalParent = scope.fromTransaction( s -> { + Parent p = new Parent(); + p.setName( "PARENT" ); + p.setLazy( "LAZY" ); + p.makeChild(); + s.persist( p ); + return p; + } + ); + } - @Test - public void testManagedWithUninitializedAssociation(SessionFactoryScope scope) { - // Delete the Parent - scope.inTransaction( s -> { - Parent loadedParent = (Parent) s.createQuery( "SELECT p FROM Parent p WHERE name=:name" ) - .setParameter( "name", "PARENT" ) - .uniqueResult(); - checkInterceptor( scope, loadedParent, false ); - assertFalse( Hibernate.isInitialized( loadedParent.getChildren() ) ); - s.remove( loadedParent ); - } ); - // If the lazy relation is not fetch on cascade there is a constraint violation on commit - } + @Test + public void testManagedWithUninitializedAssociation(SessionFactoryScope scope) { + // Delete the Parent + scope.inTransaction( s -> { + Parent loadedParent = (Parent) s.createQuery( "SELECT p FROM Parent p WHERE name=:name" ) + .setParameter( "name", "PARENT" ) + .uniqueResult(); + checkInterceptor( scope, loadedParent, false ); + assertFalse( Hibernate.isInitialized( loadedParent.getChildren() ) ); + s.remove( loadedParent ); + } ); + // If the lazy relation is not fetch on cascade there is a constraint violation on commit + } - @Test - @JiraKey("HHH-13129") - public void testManagedWithInitializedAssociation(SessionFactoryScope scope) { - // Delete the Parent - scope.inTransaction( s -> { - Parent loadedParent = (Parent) s.createQuery( "SELECT p FROM Parent p WHERE name=:name" ) - .setParameter( "name", "PARENT" ) - .uniqueResult(); - checkInterceptor( scope, loadedParent, false ); - loadedParent.getChildren().size(); - assertTrue( Hibernate.isInitialized( loadedParent.getChildren() ) ); - s.remove( loadedParent ); - } ); - // If the lazy relation is not fetch on cascade there is a constraint violation on commit - } + @Test + @JiraKey("HHH-13129") + public void testManagedWithInitializedAssociation(SessionFactoryScope scope) { + // Delete the Parent + scope.inTransaction( s -> { + Parent loadedParent = (Parent) s.createQuery( "SELECT p FROM Parent p WHERE name=:name" ) + .setParameter( "name", "PARENT" ) + .uniqueResult(); + checkInterceptor( scope, loadedParent, false ); + loadedParent.getChildren().size(); + assertTrue( Hibernate.isInitialized( loadedParent.getChildren() ) ); + s.remove( loadedParent ); + } ); + // If the lazy relation is not fetch on cascade there is a constraint violation on commit + } - @Test - @JiraKey("HHH-13129") - public void testDetachedWithUninitializedAssociation(SessionFactoryScope scope) { - final Parent detachedParent = scope.fromTransaction( s -> { - return s.get( Parent.class, originalParent.getId() ); - } ); + @Test + @JiraKey("HHH-13129") + public void testDetachedWithUninitializedAssociation(SessionFactoryScope scope) { + final Parent detachedParent = scope.fromTransaction( s -> { + return s.get( Parent.class, originalParent.getId() ); + } ); - assertFalse( Hibernate.isInitialized( detachedParent.getChildren() ) ); + assertFalse( Hibernate.isInitialized( detachedParent.getChildren() ) ); - checkInterceptor( scope, detachedParent, false ); + checkInterceptor( scope, detachedParent, false ); - // Delete the detached Parent with uninitialized children - scope.inTransaction( s -> { - s.remove( detachedParent ); - } ); - // If the lazy relation is not fetch on cascade there is a constraint violation on commit - } + // Delete the detached Parent with uninitialized children + scope.inTransaction( s -> { + s.remove( detachedParent ); + } ); + // If the lazy relation is not fetch on cascade there is a constraint violation on commit + } - @Test - @JiraKey("HHH-13129") - public void testDetachedWithInitializedAssociation(SessionFactoryScope scope) { - final Parent detachedParent = scope.fromTransaction( s -> { - Parent parent = s.get( Parent.class, originalParent.getId() ); - // initialize collection before detaching - parent.getChildren().size(); - return parent; - } ); + @Test + @JiraKey("HHH-13129") + public void testDetachedWithInitializedAssociation(SessionFactoryScope scope) { + final Parent detachedParent = scope.fromTransaction( s -> { + Parent parent = s.get( Parent.class, originalParent.getId() ); + // initialize collection before detaching + parent.getChildren().size(); + return parent; + } ); - assertTrue( Hibernate.isInitialized( detachedParent.getChildren() ) ); + assertTrue( Hibernate.isInitialized( detachedParent.getChildren() ) ); - checkInterceptor( scope, detachedParent, false ); + checkInterceptor( scope, detachedParent, false ); - // Delete the detached Parent with initialized children - scope.inTransaction( s -> { - s.remove( detachedParent ); - } ); - // If the lazy relation is not fetch on cascade there is a constraint violation on commit - } + // Delete the detached Parent with initialized children + scope.inTransaction( s -> { + s.remove( detachedParent ); + } ); + // If the lazy relation is not fetch on cascade there is a constraint violation on commit + } - @Test - @JiraKey("HHH-13129") - public void testDetachedOriginal(SessionFactoryScope scope) { + @Test + @JiraKey("HHH-13129") + public void testDetachedOriginal(SessionFactoryScope scope) { - // originalParent#children should be initialized - assertTrue( Hibernate.isPropertyInitialized( originalParent, "children" ) ); + // originalParent#children should be initialized + assertTrue( Hibernate.isPropertyInitialized( originalParent, "children" ) ); - checkInterceptor( scope, originalParent, true ); + checkInterceptor( scope, originalParent, true ); - // Delete the Parent - scope.inTransaction( s -> { - s.remove( originalParent ); - } ); - // If the lazy relation is not fetch on cascade there is a constraint violation on commit - } + // Delete the Parent + scope.inTransaction( s -> { + s.remove( originalParent ); + } ); + // If the lazy relation is not fetch on cascade there is a constraint violation on commit + } - private void checkInterceptor(SessionFactoryScope scope, Parent parent, boolean isNullExpected) { - final BytecodeEnhancementMetadata bytecodeEnhancementMetadata = scope.getSessionFactory().getRuntimeMetamodels() - .getMappingMetamodel() - .getEntityDescriptor( Parent.class ) - .getBytecodeEnhancementMetadata(); - if ( isNullExpected ) { - // if a null Interceptor is expected, then there shouldn't be any uninitialized attributes - assertFalse( bytecodeEnhancementMetadata.hasUnFetchedAttributes( parent ) ); - assertNull( bytecodeEnhancementMetadata.extractInterceptor( parent ) ); - } - else { - assertNotNull( bytecodeEnhancementMetadata.extractInterceptor( parent ) ); - } - } + private void checkInterceptor(SessionFactoryScope scope, Parent parent, boolean isNullExpected) { + final BytecodeEnhancementMetadata bytecodeEnhancementMetadata = scope.getSessionFactory().getRuntimeMetamodels() + .getMappingMetamodel() + .getEntityDescriptor( Parent.class ) + .getBytecodeEnhancementMetadata(); + if ( isNullExpected ) { + // if a null Interceptor is expected, then there shouldn't be any uninitialized attributes + assertFalse( bytecodeEnhancementMetadata.hasUnFetchedAttributes( parent ) ); + assertNull( bytecodeEnhancementMetadata.extractInterceptor( parent ) ); + } + else { + assertNotNull( bytecodeEnhancementMetadata.extractInterceptor( parent ) ); + } + } - // --- // + // --- // - @Entity( name = "Parent" ) - @Table( name = "PARENT" ) - public static class Parent { + @Entity( name = "Parent" ) + @Table( name = "PARENT" ) + public static class Parent { - Long id; + Long id; - String name; + String name; - List children = new ArrayList<>(); + List children = new ArrayList<>(); - String lazy; + String lazy; - @Id - @GeneratedValue( strategy = GenerationType.AUTO ) - Long getId() { - return id; - } + @Id + @GeneratedValue( strategy = GenerationType.AUTO ) + Long getId() { + return id; + } - void setId(Long id) { - this.id = id; - } + void setId(Long id) { + this.id = id; + } - @OneToMany( mappedBy = "parent", cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REMOVE}, fetch = FetchType.LAZY ) - List getChildren() { - return children; - } + @OneToMany( mappedBy = "parent", cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REMOVE}, fetch = FetchType.LAZY ) + List getChildren() { + return children; + } - void setChildren(List children) { - this.children = children; - } + void setChildren(List children) { + this.children = children; + } - String getName() { - return name; - } + String getName() { + return name; + } - void setName(String name) { - this.name = name; - } + void setName(String name) { + this.name = name; + } - @Basic( fetch = FetchType.LAZY ) - String getLazy() { - return lazy; - } + @Basic( fetch = FetchType.LAZY ) + String getLazy() { + return lazy; + } - void setLazy(String lazy) { - this.lazy = lazy; - } + void setLazy(String lazy) { + this.lazy = lazy; + } - void makeChild() { - Child c = new Child(); - c.setParent( this ); - children.add( c ); - } - } + void makeChild() { + Child c = new Child(); + c.setParent( this ); + children.add( c ); + } + } - @Entity - @Table( name = "CHILD" ) - static class Child { + @Entity + @Table( name = "CHILD" ) + static class Child { - @Id - @GeneratedValue( strategy = GenerationType.AUTO ) - Long id; + @Id + @GeneratedValue( strategy = GenerationType.AUTO ) + Long id; - @ManyToOne( optional = false ) - @JoinColumn( name = "parent_id" ) - Parent parent; + @ManyToOne( optional = false ) + @JoinColumn( name = "parent_id" ) + Parent parent; - Long getId() { - return id; - } + Long getId() { + return id; + } - void setId(Long id) { - this.id = id; - } + void setId(Long id) { + this.id = id; + } - Parent getParent() { - return parent; - } + Parent getParent() { + return parent; + } - void setParent(Parent parent) { - this.parent = parent; - } - } + void setParent(Parent parent) { + this.parent = parent; + } + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/cascade/CascadeDeleteCollectionWithCollectionInDefaultFetchGroupFalseTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/cascade/CascadeDeleteCollectionWithCollectionInDefaultFetchGroupFalseTest.java index da447930c0..93f1cc0274 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/cascade/CascadeDeleteCollectionWithCollectionInDefaultFetchGroupFalseTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/cascade/CascadeDeleteCollectionWithCollectionInDefaultFetchGroupFalseTest.java @@ -48,218 +48,218 @@ import jakarta.persistence.Table; */ @JiraKey( "HHH-10252" ) @DomainModel( - annotatedClasses = { - CascadeDeleteCollectionWithCollectionInDefaultFetchGroupFalseTest.Parent.class, CascadeDeleteCollectionWithCollectionInDefaultFetchGroupFalseTest.Child.class - } + annotatedClasses = { + CascadeDeleteCollectionWithCollectionInDefaultFetchGroupFalseTest.Parent.class, CascadeDeleteCollectionWithCollectionInDefaultFetchGroupFalseTest.Child.class + } ) @SessionFactory( - // We want to test with this setting set to false explicitly, - // because another test already takes care of the default. - applyCollectionsInDefaultFetchGroup = false + // We want to test with this setting set to false explicitly, + // because another test already takes care of the default. + applyCollectionsInDefaultFetchGroup = false ) @BytecodeEnhanced public class CascadeDeleteCollectionWithCollectionInDefaultFetchGroupFalseTest { - private Parent originalParent; + private Parent originalParent; - @BeforeEach - public void prepare(SessionFactoryScope scope) { - // Create a Parent with one Child - originalParent = scope.fromTransaction( s -> { - Parent p = new Parent(); - p.setName( "PARENT" ); - p.setLazy( "LAZY" ); - p.makeChild(); - s.persist( p ); - return p; - } - ); - } + @BeforeEach + public void prepare(SessionFactoryScope scope) { + // Create a Parent with one Child + originalParent = scope.fromTransaction( s -> { + Parent p = new Parent(); + p.setName( "PARENT" ); + p.setLazy( "LAZY" ); + p.makeChild(); + s.persist( p ); + return p; + } + ); + } - @Test - public void testManagedWithUninitializedAssociation(SessionFactoryScope scope) { - // Delete the Parent - scope.inTransaction( s -> { - Parent loadedParent = (Parent) s.createQuery( "SELECT p FROM Parent p WHERE name=:name" ) - .setParameter( "name", "PARENT" ) - .uniqueResult(); - checkInterceptor( scope, loadedParent, false ); - assertFalse( Hibernate.isPropertyInitialized( loadedParent, "children" ) ); - s.remove( loadedParent ); - } ); - // If the lazy relation is not fetch on cascade there is a constraint violation on commit - } + @Test + public void testManagedWithUninitializedAssociation(SessionFactoryScope scope) { + // Delete the Parent + scope.inTransaction( s -> { + Parent loadedParent = (Parent) s.createQuery( "SELECT p FROM Parent p WHERE name=:name" ) + .setParameter( "name", "PARENT" ) + .uniqueResult(); + checkInterceptor( scope, loadedParent, false ); + assertFalse( Hibernate.isPropertyInitialized( loadedParent, "children" ) ); + s.remove( loadedParent ); + } ); + // If the lazy relation is not fetch on cascade there is a constraint violation on commit + } - @Test - @JiraKey("HHH-13129") - public void testManagedWithInitializedAssociation(SessionFactoryScope scope) { - // Delete the Parent - scope.inTransaction( s -> { - Parent loadedParent = (Parent) s.createQuery( "SELECT p FROM Parent p WHERE name=:name" ) - .setParameter( "name", "PARENT" ) - .uniqueResult(); - checkInterceptor( scope, loadedParent, false ); - loadedParent.getChildren(); - assertTrue( Hibernate.isPropertyInitialized( loadedParent, "children" ) ); - s.remove( loadedParent ); - } ); - // If the lazy relation is not fetch on cascade there is a constraint violation on commit - } + @Test + @JiraKey("HHH-13129") + public void testManagedWithInitializedAssociation(SessionFactoryScope scope) { + // Delete the Parent + scope.inTransaction( s -> { + Parent loadedParent = (Parent) s.createQuery( "SELECT p FROM Parent p WHERE name=:name" ) + .setParameter( "name", "PARENT" ) + .uniqueResult(); + checkInterceptor( scope, loadedParent, false ); + loadedParent.getChildren(); + assertTrue( Hibernate.isPropertyInitialized( loadedParent, "children" ) ); + s.remove( loadedParent ); + } ); + // If the lazy relation is not fetch on cascade there is a constraint violation on commit + } - @Test - @JiraKey("HHH-13129") - public void testDetachedWithUninitializedAssociation(SessionFactoryScope scope) { - final Parent detachedParent = scope.fromTransaction( s -> { - return s.get( Parent.class, originalParent.getId() ); - } ); + @Test + @JiraKey("HHH-13129") + public void testDetachedWithUninitializedAssociation(SessionFactoryScope scope) { + final Parent detachedParent = scope.fromTransaction( s -> { + return s.get( Parent.class, originalParent.getId() ); + } ); - assertFalse( Hibernate.isPropertyInitialized( detachedParent, "children" ) ); + assertFalse( Hibernate.isPropertyInitialized( detachedParent, "children" ) ); - checkInterceptor( scope, detachedParent, false ); + checkInterceptor( scope, detachedParent, false ); - // Delete the detached Parent with uninitialized children - scope.inTransaction( s -> { - s.remove( detachedParent ); - } ); - // If the lazy relation is not fetch on cascade there is a constraint violation on commit - } + // Delete the detached Parent with uninitialized children + scope.inTransaction( s -> { + s.remove( detachedParent ); + } ); + // If the lazy relation is not fetch on cascade there is a constraint violation on commit + } - @Test - @JiraKey("HHH-13129") - public void testDetachedWithInitializedAssociation(SessionFactoryScope scope) { - final Parent detachedParent = scope.fromTransaction( s -> { - Parent parent = s.get( Parent.class, originalParent.getId() ); - assertFalse( Hibernate.isPropertyInitialized( parent, "children" ) ); + @Test + @JiraKey("HHH-13129") + public void testDetachedWithInitializedAssociation(SessionFactoryScope scope) { + final Parent detachedParent = scope.fromTransaction( s -> { + Parent parent = s.get( Parent.class, originalParent.getId() ); + assertFalse( Hibernate.isPropertyInitialized( parent, "children" ) ); - // initialize collection before detaching - parent.getChildren(); - return parent; - } ); + // initialize collection before detaching + parent.getChildren(); + return parent; + } ); - assertTrue( Hibernate.isPropertyInitialized( detachedParent, "children" ) ); + assertTrue( Hibernate.isPropertyInitialized( detachedParent, "children" ) ); - checkInterceptor( scope, detachedParent, false ); + checkInterceptor( scope, detachedParent, false ); - // Delete the detached Parent with initialized children - scope.inTransaction( s -> { - s.remove( detachedParent ); - } ); - // If the lazy relation is not fetch on cascade there is a constraint violation on commit - } + // Delete the detached Parent with initialized children + scope.inTransaction( s -> { + s.remove( detachedParent ); + } ); + // If the lazy relation is not fetch on cascade there is a constraint violation on commit + } - @Test - @JiraKey("HHH-13129") - public void testDetachedOriginal(SessionFactoryScope scope) { + @Test + @JiraKey("HHH-13129") + public void testDetachedOriginal(SessionFactoryScope scope) { - // originalParent#children should be initialized - assertTrue( Hibernate.isPropertyInitialized( originalParent, "children" ) ); + // originalParent#children should be initialized + assertTrue( Hibernate.isPropertyInitialized( originalParent, "children" ) ); - checkInterceptor( scope, originalParent, true ); + checkInterceptor( scope, originalParent, true ); - // Delete the Parent - scope.inTransaction( s -> { - s.remove( originalParent ); - } ); - // If the lazy relation is not fetch on cascade there is a constraint violation on commit - } + // Delete the Parent + scope.inTransaction( s -> { + s.remove( originalParent ); + } ); + // If the lazy relation is not fetch on cascade there is a constraint violation on commit + } - private void checkInterceptor(SessionFactoryScope scope, Parent parent, boolean isNullExpected) { - final BytecodeEnhancementMetadata bytecodeEnhancementMetadata = scope.getSessionFactory().getRuntimeMetamodels() - .getMappingMetamodel() - .getEntityDescriptor( Parent.class ) - .getBytecodeEnhancementMetadata(); - if ( isNullExpected ) { - // if a null Interceptor is expected, then there shouldn't be any uninitialized attributes - assertFalse( bytecodeEnhancementMetadata.hasUnFetchedAttributes( parent ) ); - assertNull( bytecodeEnhancementMetadata.extractInterceptor( parent ) ); - } - else { - assertNotNull( bytecodeEnhancementMetadata.extractInterceptor( parent ) ); - } - } + private void checkInterceptor(SessionFactoryScope scope, Parent parent, boolean isNullExpected) { + final BytecodeEnhancementMetadata bytecodeEnhancementMetadata = scope.getSessionFactory().getRuntimeMetamodels() + .getMappingMetamodel() + .getEntityDescriptor( Parent.class ) + .getBytecodeEnhancementMetadata(); + if ( isNullExpected ) { + // if a null Interceptor is expected, then there shouldn't be any uninitialized attributes + assertFalse( bytecodeEnhancementMetadata.hasUnFetchedAttributes( parent ) ); + assertNull( bytecodeEnhancementMetadata.extractInterceptor( parent ) ); + } + else { + assertNotNull( bytecodeEnhancementMetadata.extractInterceptor( parent ) ); + } + } - // --- // + // --- // - @Entity( name = "Parent" ) - @Table( name = "PARENT" ) - public static class Parent { + @Entity( name = "Parent" ) + @Table( name = "PARENT" ) + public static class Parent { - Long id; + Long id; - String name; + String name; - List children = new ArrayList<>(); + List children = new ArrayList<>(); - String lazy; + String lazy; - @Id - @GeneratedValue( strategy = GenerationType.AUTO ) - Long getId() { - return id; - } + @Id + @GeneratedValue( strategy = GenerationType.AUTO ) + Long getId() { + return id; + } - void setId(Long id) { - this.id = id; - } + void setId(Long id) { + this.id = id; + } - @OneToMany( mappedBy = "parent", cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REMOVE}, fetch = FetchType.LAZY ) - List getChildren() { - return Collections.unmodifiableList( children ); - } + @OneToMany( mappedBy = "parent", cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REMOVE}, fetch = FetchType.LAZY ) + List getChildren() { + return Collections.unmodifiableList( children ); + } - void setChildren(List children) { - this.children = children; - } + void setChildren(List children) { + this.children = children; + } - String getName() { - return name; - } + String getName() { + return name; + } - void setName(String name) { - this.name = name; - } + void setName(String name) { + this.name = name; + } - @Basic( fetch = FetchType.LAZY ) - String getLazy() { - return lazy; - } + @Basic( fetch = FetchType.LAZY ) + String getLazy() { + return lazy; + } - void setLazy(String lazy) { - this.lazy = lazy; - } + void setLazy(String lazy) { + this.lazy = lazy; + } - void makeChild() { - Child c = new Child(); - c.setParent( this ); - children.add( c ); - } - } + void makeChild() { + Child c = new Child(); + c.setParent( this ); + children.add( c ); + } + } - @Entity - @Table( name = "CHILD" ) - static class Child { + @Entity + @Table( name = "CHILD" ) + static class Child { - @Id - @GeneratedValue( strategy = GenerationType.AUTO ) - Long id; + @Id + @GeneratedValue( strategy = GenerationType.AUTO ) + Long id; - @ManyToOne( optional = false ) - @JoinColumn( name = "parent_id" ) - Parent parent; + @ManyToOne( optional = false ) + @JoinColumn( name = "parent_id" ) + Parent parent; - Long getId() { - return id; - } + Long getId() { + return id; + } - void setId(Long id) { - this.id = id; - } + void setId(Long id) { + this.id = id; + } - Parent getParent() { - return parent; - } + Parent getParent() { + return parent; + } - void setParent(Parent parent) { - this.parent = parent; - } - } + void setParent(Parent parent) { + this.parent = parent; + } + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/cascade/CascadeDetachedTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/cascade/CascadeDetachedTest.java index 4f7c1ddd6a..e91c127955 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/cascade/CascadeDetachedTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/cascade/CascadeDetachedTest.java @@ -32,85 +32,85 @@ import java.util.List; */ @JiraKey( "HHH-10254" ) @DomainModel( - annotatedClasses = { - CascadeDetachedTest.Author.class, CascadeDetachedTest.Book.class - } + annotatedClasses = { + CascadeDetachedTest.Author.class, CascadeDetachedTest.Book.class + } ) @SessionFactory @BytecodeEnhanced public class CascadeDetachedTest { - @Test - public void test(SessionFactoryScope scope) { - Book book = new Book( "978-1118063330", "Operating System Concepts 9th Edition" ); - book.addAuthor( new Author( "Abraham", "Silberschatz", new char[] { 'a', 'b' } ) ); - book.addAuthor( new Author( "Peter", "Galvin", new char[] { 'c', 'd' } ) ); - book.addAuthor( new Author( "Greg", "Gagne", new char[] { 'e', 'f' } ) ); + @Test + public void test(SessionFactoryScope scope) { + Book book = new Book( "978-1118063330", "Operating System Concepts 9th Edition" ); + book.addAuthor( new Author( "Abraham", "Silberschatz", new char[] { 'a', 'b' } ) ); + book.addAuthor( new Author( "Peter", "Galvin", new char[] { 'c', 'd' } ) ); + book.addAuthor( new Author( "Greg", "Gagne", new char[] { 'e', 'f' } ) ); - scope.inTransaction( em -> { - em.persist( book ); - } ); + scope.inTransaction( em -> { + em.persist( book ); + } ); - scope.inTransaction( em -> { - em.merge( book ); - } ); - } + scope.inTransaction( em -> { + em.merge( book ); + } ); + } - // --- // + // --- // - @Entity - @Table( name = "BOOK" ) - public static class Book { + @Entity + @Table( name = "BOOK" ) + public static class Book { - @Id - @GeneratedValue( strategy = GenerationType.AUTO ) - Long id; + @Id + @GeneratedValue( strategy = GenerationType.AUTO ) + Long id; - String isbn; - String title; + String isbn; + String title; - @OneToMany( cascade = CascadeType.ALL, mappedBy = "book" ) - List authors = new ArrayList<>(); + @OneToMany( cascade = CascadeType.ALL, mappedBy = "book" ) + List authors = new ArrayList<>(); - public Book() { - } + public Book() { + } - public Book(String isbn, String title) { - this.isbn = isbn; - this.title = title; - } + public Book(String isbn, String title) { + this.isbn = isbn; + this.title = title; + } - public void addAuthor(Author author) { - authors.add( author ); - author.book = this; - } - } + public void addAuthor(Author author) { + authors.add( author ); + author.book = this; + } + } - @Entity - @Table( name = "AUTHOR" ) - public static class Author { + @Entity + @Table( name = "AUTHOR" ) + public static class Author { - @Id - @GeneratedValue( strategy = GenerationType.AUTO ) - Long id; + @Id + @GeneratedValue( strategy = GenerationType.AUTO ) + Long id; - String firstName; - String lastName; + String firstName; + String lastName; - @ManyToOne( fetch = FetchType.LAZY ) - @JoinColumn - Book book; + @ManyToOne( fetch = FetchType.LAZY ) + @JoinColumn + Book book; - @Basic( fetch = FetchType.LAZY ) - char[] charArrayCode; + @Basic( fetch = FetchType.LAZY ) + char[] charArrayCode; - public Author() { - } + public Author() { + } - public Author(String firstName, String lastName, char[] charArrayCode) { - this.firstName = firstName; - this.lastName = lastName; - this.charArrayCode = charArrayCode; - } - } + public Author(String firstName, String lastName, char[] charArrayCode) { + this.firstName = firstName; + this.lastName = lastName; + this.charArrayCode = charArrayCode; + } + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/cascade/CascadeWithFkConstraintTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/cascade/CascadeWithFkConstraintTest.java index dd0f17fb63..a49fcdbdb9 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/cascade/CascadeWithFkConstraintTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/cascade/CascadeWithFkConstraintTest.java @@ -32,89 +32,89 @@ import org.hibernate.testing.util.uuid.SafeRandomUUIDGenerator; */ @JiraKey( "HHH-10252" ) @DomainModel( - annotatedClasses = { - CascadeWithFkConstraintTest.Garage.class, CascadeWithFkConstraintTest.Car.class - } + annotatedClasses = { + CascadeWithFkConstraintTest.Garage.class, CascadeWithFkConstraintTest.Car.class + } ) @SessionFactory @BytecodeEnhanced public class CascadeWithFkConstraintTest { - private String garageId, car1Id, car2Id; + private String garageId, car1Id, car2Id; - @BeforeEach - public void prepare(SessionFactoryScope scope) { - // Create garage, add 2 cars to garage - scope.inTransaction( em -> { + @BeforeEach + public void prepare(SessionFactoryScope scope) { + // Create garage, add 2 cars to garage + scope.inTransaction( em -> { - Garage garage = new Garage(); - Car car1 = new Car(); - Car car2 = new Car(); - garage.insert( car1 ); - garage.insert( car2 ); + Garage garage = new Garage(); + Car car1 = new Car(); + Car car2 = new Car(); + garage.insert( car1 ); + garage.insert( car2 ); - em.persist( garage ); - em.persist( car1 ); - em.persist( car2 ); + em.persist( garage ); + em.persist( car1 ); + em.persist( car2 ); - garageId = garage.id; - car1Id = car1.id; - car2Id = car2.id; - } ); - } + garageId = garage.id; + car1Id = car1.id; + car2Id = car2.id; + } ); + } - @Test - public void test(SessionFactoryScope scope) { - // Remove garage - scope.inTransaction( em -> { - Garage toRemoveGarage = em.find( Garage.class, garageId ); - em.remove( toRemoveGarage ); - } ); + @Test + public void test(SessionFactoryScope scope) { + // Remove garage + scope.inTransaction( em -> { + Garage toRemoveGarage = em.find( Garage.class, garageId ); + em.remove( toRemoveGarage ); + } ); - // Check if there is no garage but cars are still present - scope.inTransaction( em -> { - Garage foundGarage = em.find( Garage.class, garageId ); - assertNull( foundGarage ); + // Check if there is no garage but cars are still present + scope.inTransaction( em -> { + Garage foundGarage = em.find( Garage.class, garageId ); + assertNull( foundGarage ); - Car foundCar1 = em.find( Car.class, car1Id ); - assertEquals( car1Id, foundCar1.id ); + Car foundCar1 = em.find( Car.class, car1Id ); + assertEquals( car1Id, foundCar1.id ); - Car foundCar2 = em.find( Car.class, car2Id ); - assertEquals( car2Id, foundCar2.id ); - } ); - } + Car foundCar2 = em.find( Car.class, car2Id ); + assertEquals( car2Id, foundCar2.id ); + } ); + } - // --- // + // --- // - @Entity - @Table( name = "GARAGE" ) - static class Garage { + @Entity + @Table( name = "GARAGE" ) + static class Garage { - @Id - String id; + @Id + String id; - @OneToMany - @JoinColumn( name = "GARAGE_ID" ) - Set cars = new HashSet<>(); + @OneToMany + @JoinColumn( name = "GARAGE_ID" ) + Set cars = new HashSet<>(); - Garage() { - id = SafeRandomUUIDGenerator.safeRandomUUIDAsString(); - } + Garage() { + id = SafeRandomUUIDGenerator.safeRandomUUIDAsString(); + } - void insert(Car aCar) { - cars.add( aCar ); - } - } + void insert(Car aCar) { + cars.add( aCar ); + } + } - @Entity - @Table( name = "CAR" ) - public static class Car { + @Entity + @Table( name = "CAR" ) + public static class Car { - @Id - String id; + @Id + String id; - Car() { - id = SafeRandomUUIDGenerator.safeRandomUUIDAsString(); - } - } + Car() { + id = SafeRandomUUIDGenerator.safeRandomUUIDAsString(); + } + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/detached/DetachedGetIdentifierTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/detached/DetachedGetIdentifierTest.java index a57504572c..1a1f09f32b 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/detached/DetachedGetIdentifierTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/detached/DetachedGetIdentifierTest.java @@ -27,41 +27,41 @@ import org.junit.jupiter.api.Test; */ @JiraKey( "HHH-11426" ) @DomainModel( - annotatedClasses = { - DetachedGetIdentifierTest.SimpleEntity.class - } + annotatedClasses = { + DetachedGetIdentifierTest.SimpleEntity.class + } ) @org.hibernate.testing.orm.junit.SessionFactory @BytecodeEnhanced public class DetachedGetIdentifierTest { - @Test - public void test(SessionFactoryScope scope) { - SimpleEntity[] entities = new SimpleEntity[2]; - entities[0] = new SimpleEntity(); - entities[0].name = "test"; + @Test + public void test(SessionFactoryScope scope) { + SimpleEntity[] entities = new SimpleEntity[2]; + entities[0] = new SimpleEntity(); + entities[0].name = "test"; - scope.inTransaction( em -> { - entities[1] = em.merge( entities[0] ); - assertNotNull( em.getEntityManagerFactory().getPersistenceUnitUtil().getIdentifier( entities[1] ) ); - } ); + scope.inTransaction( em -> { + entities[1] = em.merge( entities[0] ); + assertNotNull( em.getEntityManagerFactory().getPersistenceUnitUtil().getIdentifier( entities[1] ) ); + } ); - // Call as detached entity - try ( SessionFactory sessionFactory = scope.getSessionFactory() ) { - assertNotNull( sessionFactory.getPersistenceUnitUtil().getIdentifier( entities[1] ) ); - } - } + // Call as detached entity + try ( SessionFactory sessionFactory = scope.getSessionFactory() ) { + assertNotNull( sessionFactory.getPersistenceUnitUtil().getIdentifier( entities[1] ) ); + } + } - // --- // + // --- // - @Entity(name = "SimpleEntity") - @Table( name = "SIMPLE_ENTITY" ) - static class SimpleEntity { + @Entity(name = "SimpleEntity") + @Table( name = "SIMPLE_ENTITY" ) + static class SimpleEntity { - @Id - @GeneratedValue - Long id; + @Id + @GeneratedValue + Long id; - String name; - } + String name; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/dirty/DirtyTrackingCollectionInDefaultFetchGroupFalseTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/dirty/DirtyTrackingCollectionInDefaultFetchGroupFalseTest.java index 1253fc9716..7c4354f89b 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/dirty/DirtyTrackingCollectionInDefaultFetchGroupFalseTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/dirty/DirtyTrackingCollectionInDefaultFetchGroupFalseTest.java @@ -46,58 +46,58 @@ import jakarta.persistence.Table; */ @JiraKey( "HHH-14348" ) @DomainModel( - annotatedClasses = { - DirtyTrackingCollectionInDefaultFetchGroupFalseTest.StringsEntity.class - } + annotatedClasses = { + DirtyTrackingCollectionInDefaultFetchGroupFalseTest.StringsEntity.class + } ) @SessionFactory( - // We want to test with this setting set to false explicitly, - // because another test already takes care of the default. - applyCollectionsInDefaultFetchGroup = false + // We want to test with this setting set to false explicitly, + // because another test already takes care of the default. + applyCollectionsInDefaultFetchGroup = false ) @BytecodeEnhanced public class DirtyTrackingCollectionInDefaultFetchGroupFalseTest { - @BeforeEach - public void prepare(SessionFactoryScope scope) { - scope.inTransaction( em -> { - StringsEntity entity = new StringsEntity(); - entity.id = 1L; - entity.someStrings = new ArrayList<>( Arrays.asList( "a", "b", "c" ) ); - em.persist( entity ); - } ); - } + @BeforeEach + public void prepare(SessionFactoryScope scope) { + scope.inTransaction( em -> { + StringsEntity entity = new StringsEntity(); + entity.id = 1L; + entity.someStrings = new ArrayList<>( Arrays.asList( "a", "b", "c" ) ); + em.persist( entity ); + } ); + } - @Test - public void test(SessionFactoryScope scope) { - scope.inTransaction( entityManager -> { - StringsEntity entity = entityManager.find( StringsEntity.class, 1L ); - entityManager.flush(); - BytecodeLazyAttributeInterceptor interceptor = (BytecodeLazyAttributeInterceptor) ( (PersistentAttributeInterceptable) entity ) - .$$_hibernate_getInterceptor(); - assertTrue( interceptor.hasAnyUninitializedAttributes() ); - assertFalse( interceptor.isAttributeLoaded( "someStrings" ) ); - assertFalse( interceptor.isAttributeLoaded( "someStringEntities" ) ); - } ); - } + @Test + public void test(SessionFactoryScope scope) { + scope.inTransaction( entityManager -> { + StringsEntity entity = entityManager.find( StringsEntity.class, 1L ); + entityManager.flush(); + BytecodeLazyAttributeInterceptor interceptor = (BytecodeLazyAttributeInterceptor) ( (PersistentAttributeInterceptable) entity ) + .$$_hibernate_getInterceptor(); + assertTrue( interceptor.hasAnyUninitializedAttributes() ); + assertFalse( interceptor.isAttributeLoaded( "someStrings" ) ); + assertFalse( interceptor.isAttributeLoaded( "someStringEntities" ) ); + } ); + } - // --- // + // --- // - @Entity - @Table(name = "STRINGS_ENTITY") - static class StringsEntity { + @Entity + @Table(name = "STRINGS_ENTITY") + static class StringsEntity { - @Id - Long id; + @Id + Long id; - @ElementCollection - @CollectionTable(name = "STRINGS_ENTITY_SOME", joinColumns = @JoinColumn(name = "SOME_ID")) - List someStrings; + @ElementCollection + @CollectionTable(name = "STRINGS_ENTITY_SOME", joinColumns = @JoinColumn(name = "SOME_ID")) + List someStrings; - @ManyToOne(fetch = FetchType.LAZY) - StringsEntity parent; + @ManyToOne(fetch = FetchType.LAZY) + StringsEntity parent; - @OneToMany(mappedBy = "parent", cascade = CascadeType.PERSIST, fetch = FetchType.LAZY) - Set someStringEntities; - } + @OneToMany(mappedBy = "parent", cascade = CascadeType.PERSIST, fetch = FetchType.LAZY) + Set someStringEntities; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/dirty/DirtyTrackingCollectionInDefaultFetchGroupTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/dirty/DirtyTrackingCollectionInDefaultFetchGroupTest.java index b4aae20c1d..eba8deb4b6 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/dirty/DirtyTrackingCollectionInDefaultFetchGroupTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/dirty/DirtyTrackingCollectionInDefaultFetchGroupTest.java @@ -41,61 +41,61 @@ import static org.junit.jupiter.api.Assertions.assertTrue; */ @JiraKey( "HHH-14348" ) @DomainModel( - annotatedClasses = { - DirtyTrackingCollectionInDefaultFetchGroupTest.StringsEntity.class - } + annotatedClasses = { + DirtyTrackingCollectionInDefaultFetchGroupTest.StringsEntity.class + } ) @SessionFactory @BytecodeEnhanced public class DirtyTrackingCollectionInDefaultFetchGroupTest { - @BeforeEach - public void prepare(SessionFactoryScope scope) { - assertTrue( scope.getSessionFactory().getSessionFactoryOptions().isCollectionsInDefaultFetchGroupEnabled() ); - scope.inTransaction( em -> { - StringsEntity entity = new StringsEntity(); - entity.id = 1L; - entity.someStrings = new ArrayList<>( Arrays.asList( "a", "b", "c" ) ); - em.persist( entity ); - } ); - } + @BeforeEach + public void prepare(SessionFactoryScope scope) { + assertTrue( scope.getSessionFactory().getSessionFactoryOptions().isCollectionsInDefaultFetchGroupEnabled() ); + scope.inTransaction( em -> { + StringsEntity entity = new StringsEntity(); + entity.id = 1L; + entity.someStrings = new ArrayList<>( Arrays.asList( "a", "b", "c" ) ); + em.persist( entity ); + } ); + } - @Test - public void test(SessionFactoryScope scope) { - scope.inTransaction( entityManager -> { + @Test + public void test(SessionFactoryScope scope) { + scope.inTransaction( entityManager -> { - StringsEntity entity = entityManager.find( StringsEntity.class, 1L ); - entityManager.flush(); - BytecodeLazyAttributeInterceptor interceptor = (BytecodeLazyAttributeInterceptor) ( (PersistentAttributeInterceptable) entity ) - .$$_hibernate_getInterceptor(); - // the attributes are initialized with a PersistentCollection that is not initialized - assertFalse( interceptor.hasAnyUninitializedAttributes() ); + StringsEntity entity = entityManager.find( StringsEntity.class, 1L ); + entityManager.flush(); + BytecodeLazyAttributeInterceptor interceptor = (BytecodeLazyAttributeInterceptor) ( (PersistentAttributeInterceptable) entity ) + .$$_hibernate_getInterceptor(); + // the attributes are initialized with a PersistentCollection that is not initialized + assertFalse( interceptor.hasAnyUninitializedAttributes() ); - assertTrue( interceptor.isAttributeLoaded( "someStrings" ) ); - assertTrue( interceptor.isAttributeLoaded( "someStringEntities" ) ); + assertTrue( interceptor.isAttributeLoaded( "someStrings" ) ); + assertTrue( interceptor.isAttributeLoaded( "someStringEntities" ) ); - assertFalse( Hibernate.isInitialized( entity.someStrings ) ); - assertFalse( Hibernate.isInitialized( entity.someStringEntities ) ); - } ); - } + assertFalse( Hibernate.isInitialized( entity.someStrings ) ); + assertFalse( Hibernate.isInitialized( entity.someStringEntities ) ); + } ); + } - // --- // + // --- // - @Entity - @Table( name = "STRINGS_ENTITY" ) - static class StringsEntity { + @Entity + @Table( name = "STRINGS_ENTITY" ) + static class StringsEntity { - @Id - Long id; + @Id + Long id; - @ElementCollection - @CollectionTable(name = "STRINGS_ENTITY_SOME", joinColumns = @JoinColumn(name = "SOME_ID")) - List someStrings; + @ElementCollection + @CollectionTable(name = "STRINGS_ENTITY_SOME", joinColumns = @JoinColumn(name = "SOME_ID")) + List someStrings; - @ManyToOne(fetch = FetchType.LAZY) - StringsEntity parent; + @ManyToOne(fetch = FetchType.LAZY) + StringsEntity parent; - @OneToMany(mappedBy = "parent", cascade = CascadeType.PERSIST, fetch = FetchType.LAZY) - Set someStringEntities; - } + @OneToMany(mappedBy = "parent", cascade = CascadeType.PERSIST, fetch = FetchType.LAZY) + Set someStringEntities; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/dirty/DirtyTrackingCollectionNotInDefaultFetchGroupTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/dirty/DirtyTrackingCollectionNotInDefaultFetchGroupTest.java index 438922dff6..7df8fb7172 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/dirty/DirtyTrackingCollectionNotInDefaultFetchGroupTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/dirty/DirtyTrackingCollectionNotInDefaultFetchGroupTest.java @@ -41,57 +41,57 @@ import static org.junit.jupiter.api.Assertions.assertTrue; */ @JiraKey( "HHH-14348" ) @DomainModel( - annotatedClasses = { - DirtyTrackingCollectionNotInDefaultFetchGroupTest.StringsEntity.class - } + annotatedClasses = { + DirtyTrackingCollectionNotInDefaultFetchGroupTest.StringsEntity.class + } ) @SessionFactory( - applyCollectionsInDefaultFetchGroup = false + applyCollectionsInDefaultFetchGroup = false ) @BytecodeEnhanced public class DirtyTrackingCollectionNotInDefaultFetchGroupTest { - @BeforeEach - public void prepare(SessionFactoryScope scope) { - assertFalse( scope.getSessionFactory().getSessionFactoryOptions().isCollectionsInDefaultFetchGroupEnabled() ); - scope.inTransaction( em -> { - StringsEntity entity = new StringsEntity(); - entity.id = 1L; - entity.someStrings = new ArrayList<>( Arrays.asList( "a", "b", "c" ) ); - em.persist( entity ); - } ); - } + @BeforeEach + public void prepare(SessionFactoryScope scope) { + assertFalse( scope.getSessionFactory().getSessionFactoryOptions().isCollectionsInDefaultFetchGroupEnabled() ); + scope.inTransaction( em -> { + StringsEntity entity = new StringsEntity(); + entity.id = 1L; + entity.someStrings = new ArrayList<>( Arrays.asList( "a", "b", "c" ) ); + em.persist( entity ); + } ); + } - @Test - public void test(SessionFactoryScope scope) { - scope.inTransaction( entityManager -> { - StringsEntity entity = entityManager.find( StringsEntity.class, 1L ); - entityManager.flush(); - BytecodeLazyAttributeInterceptor interceptor = (BytecodeLazyAttributeInterceptor) ( (PersistentAttributeInterceptable) entity ) - .$$_hibernate_getInterceptor(); - assertTrue( interceptor.hasAnyUninitializedAttributes() ); - assertFalse( interceptor.isAttributeLoaded( "someStrings" ) ); - assertFalse( interceptor.isAttributeLoaded( "someStringEntities" ) ); - } ); - } + @Test + public void test(SessionFactoryScope scope) { + scope.inTransaction( entityManager -> { + StringsEntity entity = entityManager.find( StringsEntity.class, 1L ); + entityManager.flush(); + BytecodeLazyAttributeInterceptor interceptor = (BytecodeLazyAttributeInterceptor) ( (PersistentAttributeInterceptable) entity ) + .$$_hibernate_getInterceptor(); + assertTrue( interceptor.hasAnyUninitializedAttributes() ); + assertFalse( interceptor.isAttributeLoaded( "someStrings" ) ); + assertFalse( interceptor.isAttributeLoaded( "someStringEntities" ) ); + } ); + } - // --- // + // --- // - @Entity - @Table( name = "STRINGS_ENTITY" ) - static class StringsEntity { + @Entity + @Table( name = "STRINGS_ENTITY" ) + static class StringsEntity { - @Id - Long id; + @Id + Long id; - @ElementCollection - @CollectionTable(name = "STRINGS_ENTITY_SOME", joinColumns = @JoinColumn(name = "SOME_ID")) - List someStrings; + @ElementCollection + @CollectionTable(name = "STRINGS_ENTITY_SOME", joinColumns = @JoinColumn(name = "SOME_ID")) + List someStrings; - @ManyToOne(fetch = FetchType.LAZY) - StringsEntity parent; + @ManyToOne(fetch = FetchType.LAZY) + StringsEntity parent; - @OneToMany(mappedBy = "parent", cascade = CascadeType.PERSIST, fetch = FetchType.LAZY) - Set someStringEntities; - } + @OneToMany(mappedBy = "parent", cascade = CascadeType.PERSIST, fetch = FetchType.LAZY) + Set someStringEntities; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/dirty/DirtyTrackingCollectionTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/dirty/DirtyTrackingCollectionTest.java index 39084aa9cd..568f6b7772 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/dirty/DirtyTrackingCollectionTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/dirty/DirtyTrackingCollectionTest.java @@ -29,59 +29,59 @@ import static org.junit.jupiter.api.Assertions.assertEquals; */ @JiraKey( "HHH-11293" ) @DomainModel( - annotatedClasses = { - DirtyTrackingCollectionTest.StringsEntity.class - } + annotatedClasses = { + DirtyTrackingCollectionTest.StringsEntity.class + } ) @SessionFactory @BytecodeEnhanced public class DirtyTrackingCollectionTest { - @BeforeEach - public void prepare(SessionFactoryScope scope) { - scope.inTransaction( em -> { - StringsEntity entity = new StringsEntity(); - entity.id = 1L; - entity.someStrings = new ArrayList<>( Arrays.asList( "a", "b", "c" ) ); - em.persist( entity ); - } ); - } + @BeforeEach + public void prepare(SessionFactoryScope scope) { + scope.inTransaction( em -> { + StringsEntity entity = new StringsEntity(); + entity.id = 1L; + entity.someStrings = new ArrayList<>( Arrays.asList( "a", "b", "c" ) ); + em.persist( entity ); + } ); + } - @Test - public void test(SessionFactoryScope scope) { - scope.inTransaction( entityManager -> { - StringsEntity entity = entityManager.find( StringsEntity.class, 1L ); - entity.someStrings.clear(); - } ); + @Test + public void test(SessionFactoryScope scope) { + scope.inTransaction( entityManager -> { + StringsEntity entity = entityManager.find( StringsEntity.class, 1L ); + entity.someStrings.clear(); + } ); - scope.inTransaction( entityManager -> { - StringsEntity entity = entityManager.find( StringsEntity.class, 1L ); - assertEquals( 0, entity.someStrings.size() ); - entity.someStrings.add( "d" ); - } ); + scope.inTransaction( entityManager -> { + StringsEntity entity = entityManager.find( StringsEntity.class, 1L ); + assertEquals( 0, entity.someStrings.size() ); + entity.someStrings.add( "d" ); + } ); - scope.inTransaction( entityManager -> { - StringsEntity entity = entityManager.find( StringsEntity.class, 1L ); - assertEquals( 1, entity.someStrings.size() ); - entity.someStrings = new ArrayList<>(); - } ); + scope.inTransaction( entityManager -> { + StringsEntity entity = entityManager.find( StringsEntity.class, 1L ); + assertEquals( 1, entity.someStrings.size() ); + entity.someStrings = new ArrayList<>(); + } ); - scope.inTransaction( entityManager -> { - StringsEntity entity = entityManager.find( StringsEntity.class, 1L ); - assertEquals( 0, entity.someStrings.size() ); - } ); - } + scope.inTransaction( entityManager -> { + StringsEntity entity = entityManager.find( StringsEntity.class, 1L ); + assertEquals( 0, entity.someStrings.size() ); + } ); + } - // --- // + // --- // - @Entity - @Table( name = "STRINGS_ENTITY" ) - static class StringsEntity { + @Entity + @Table( name = "STRINGS_ENTITY" ) + static class StringsEntity { - @Id - Long id; + @Id + Long id; - @ElementCollection - List someStrings; - } + @ElementCollection + List someStrings; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/dirty/DirtyTrackingEmbeddableTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/dirty/DirtyTrackingEmbeddableTest.java index 496356e08a..4571691ad0 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/dirty/DirtyTrackingEmbeddableTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/dirty/DirtyTrackingEmbeddableTest.java @@ -21,54 +21,54 @@ import jakarta.persistence.Id; @BytecodeEnhanced public class DirtyTrackingEmbeddableTest { - @Test - public void test() { - SimpleEntity entity = new SimpleEntity(); - Address1 address1 = new Address1(); - entity.address1 = address1; - Address2 address2 = new Address2(); - entity.address2 = address2; - EnhancerTestUtils.clearDirtyTracking( entity ); + @Test + public void test() { + SimpleEntity entity = new SimpleEntity(); + Address1 address1 = new Address1(); + entity.address1 = address1; + Address2 address2 = new Address2(); + entity.address2 = address2; + EnhancerTestUtils.clearDirtyTracking( entity ); - // testing composite object - address1.city = "Arendal"; - address2.city = "Arendal"; - EnhancerTestUtils.checkDirtyTracking( entity, "address1", "address2" ); - EnhancerTestUtils.clearDirtyTracking( entity ); - } + // testing composite object + address1.city = "Arendal"; + address2.city = "Arendal"; + EnhancerTestUtils.checkDirtyTracking( entity, "address1", "address2" ); + EnhancerTestUtils.clearDirtyTracking( entity ); + } - // --- // + // --- // - @Embeddable - private static class Address1 { - String street1; - String street2; - String city; - String state; - String zip; - String phone; - } + @Embeddable + private static class Address1 { + String street1; + String street2; + String city; + String state; + String zip; + String phone; + } - private static class Address2 { - String street1; - String street2; - String city; - String state; - String zip; - String phone; - } + private static class Address2 { + String street1; + String street2; + String city; + String state; + String zip; + String phone; + } - @Entity - private static class SimpleEntity { + @Entity + private static class SimpleEntity { - @Id - Long id; + @Id + Long id; - String name; + String name; - Address1 address1; - @Embedded - Address2 address2; + Address1 address1; + @Embedded + Address2 address2; - } + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/dirty/DirtyTrackingNonUpdateableTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/dirty/DirtyTrackingNonUpdateableTest.java index c4e6173a96..2832283540 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/dirty/DirtyTrackingNonUpdateableTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/dirty/DirtyTrackingNonUpdateableTest.java @@ -26,43 +26,43 @@ import jakarta.persistence.Version; */ @JiraKey( "HHH-12051" ) @DomainModel( - annotatedClasses = { - DirtyTrackingNonUpdateableTest.Thing.class - } + annotatedClasses = { + DirtyTrackingNonUpdateableTest.Thing.class + } ) @SessionFactory @BytecodeEnhanced public class DirtyTrackingNonUpdateableTest { - @Test - public void test(SessionFactoryScope scope) { - scope.inTransaction( entityManager -> { - Thing thing = new Thing(); - entityManager.persist( thing ); + @Test + public void test(SessionFactoryScope scope) { + scope.inTransaction( entityManager -> { + Thing thing = new Thing(); + entityManager.persist( thing ); - entityManager - .createQuery( "update thing set special = :s, version = version + 1" ) - .setParameter( "s", "new" ) - .executeUpdate(); + entityManager + .createQuery( "update thing set special = :s, version = version + 1" ) + .setParameter( "s", "new" ) + .executeUpdate(); - thing.special = "If I'm flush to the DB you get an OptimisticLockException"; - } ); - } + thing.special = "If I'm flush to the DB you get an OptimisticLockException"; + } ); + } - // --- // + // --- // - @Entity( name = "thing" ) - @Table( name = "THING_ENTITY" ) - public class Thing { + @Entity( name = "thing" ) + @Table( name = "THING_ENTITY" ) + public class Thing { - @Id - @GeneratedValue( strategy = GenerationType.AUTO ) - long id; + @Id + @GeneratedValue( strategy = GenerationType.AUTO ) + long id; - @Version - long version; + @Version + long version; - @Column( updatable = false ) - String special; - } + @Column( updatable = false ) + String special; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/dirty/DirtyTrackingTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/dirty/DirtyTrackingTest.java index 20a761a4ae..d73ac03cdf 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/dirty/DirtyTrackingTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/dirty/DirtyTrackingTest.java @@ -26,134 +26,134 @@ import java.util.Set; @BytecodeEnhanced public class DirtyTrackingTest { - @Test - public void test() { - SimpleEntity entity = new SimpleEntity(); - EnhancerTestUtils.clearDirtyTracking( entity ); + @Test + public void test() { + SimpleEntity entity = new SimpleEntity(); + EnhancerTestUtils.clearDirtyTracking( entity ); - // Basic single field - Long number = entity.getSomeNumber(); - EnhancerTestUtils.checkDirtyTracking( entity ); - entity.setSomeNumber( number + 1L ); - EnhancerTestUtils.checkDirtyTracking( entity, "someNumber" ); - EnhancerTestUtils.clearDirtyTracking( entity ); - entity.setSomeNumber( entity.getSomeNumber() ); - EnhancerTestUtils.checkDirtyTracking( entity ); + // Basic single field + Long number = entity.getSomeNumber(); + EnhancerTestUtils.checkDirtyTracking( entity ); + entity.setSomeNumber( number + 1L ); + EnhancerTestUtils.checkDirtyTracking( entity, "someNumber" ); + EnhancerTestUtils.clearDirtyTracking( entity ); + entity.setSomeNumber( entity.getSomeNumber() ); + EnhancerTestUtils.checkDirtyTracking( entity ); - // Basic multi-field (Id properties are not flagged as dirty) - entity.id = 2L; - entity.active = !entity.active; - entity.someNumber = 193L; - EnhancerTestUtils.checkDirtyTracking( entity, "active", "someNumber" ); - EnhancerTestUtils.clearDirtyTracking( entity ); + // Basic multi-field (Id properties are not flagged as dirty) + entity.id = 2L; + entity.active = !entity.active; + entity.someNumber = 193L; + EnhancerTestUtils.checkDirtyTracking( entity, "active", "someNumber" ); + EnhancerTestUtils.clearDirtyTracking( entity ); - // Setting the same value should not make it dirty - entity.someNumber = 193L; - EnhancerTestUtils.checkDirtyTracking( entity ); + // Setting the same value should not make it dirty + entity.someNumber = 193L; + EnhancerTestUtils.checkDirtyTracking( entity ); - // Collection - List stringList = new ArrayList<>(); - stringList.add( "FooBar" ); - entity.someStrings = stringList; - EnhancerTestUtils.checkDirtyTracking( entity, "someStrings" ); - EnhancerTestUtils.clearDirtyTracking( entity ); + // Collection + List stringList = new ArrayList<>(); + stringList.add( "FooBar" ); + entity.someStrings = stringList; + EnhancerTestUtils.checkDirtyTracking( entity, "someStrings" ); + EnhancerTestUtils.clearDirtyTracking( entity ); - stringList.add( "BarFoo" ); - EnhancerTestUtils.checkDirtyTracking( entity, "someStrings" ); - EnhancerTestUtils.clearDirtyTracking( entity ); + stringList.add( "BarFoo" ); + EnhancerTestUtils.checkDirtyTracking( entity, "someStrings" ); + EnhancerTestUtils.clearDirtyTracking( entity ); - // Association, 1: creating the association will mark it dirty - Set associatedSet = new HashSet<>(); - OtherEntity o = new OtherEntity(); - o.id = 1l; - o.name = "other"; - associatedSet.add( o ); - entity.someAssociation = associatedSet; - EnhancerTestUtils.checkDirtyTracking( entity, "someAssociation" ); - EnhancerTestUtils.clearDirtyTracking( entity ); + // Association, 1: creating the association will mark it dirty + Set associatedSet = new HashSet<>(); + OtherEntity o = new OtherEntity(); + o.id = 1l; + o.name = "other"; + associatedSet.add( o ); + entity.someAssociation = associatedSet; + EnhancerTestUtils.checkDirtyTracking( entity, "someAssociation" ); + EnhancerTestUtils.clearDirtyTracking( entity ); - // Association, 2: modifying a related entity should not - o.name = "newName"; - EnhancerTestUtils.checkDirtyTracking( entity ); - EnhancerTestUtils.checkDirtyTracking( o, "name" ); + // Association, 2: modifying a related entity should not + o.name = "newName"; + EnhancerTestUtils.checkDirtyTracking( entity ); + EnhancerTestUtils.checkDirtyTracking( o, "name" ); - // testing composite object - Address address = new Address(); - entity.address = address; - address.city = "Arendal"; - EnhancerTestUtils.checkDirtyTracking( entity, "address" ); - EnhancerTestUtils.clearDirtyTracking( entity ); + // testing composite object + Address address = new Address(); + entity.address = address; + address.city = "Arendal"; + EnhancerTestUtils.checkDirtyTracking( entity, "address" ); + EnhancerTestUtils.clearDirtyTracking( entity ); - // make sure that new composite instances are cleared - Address address2 = new Address(); - entity.address = address2; - address.street1 = "Heggedalveien"; - EnhancerTestUtils.checkDirtyTracking( entity, "address" ); + // make sure that new composite instances are cleared + Address address2 = new Address(); + entity.address = address2; + address.street1 = "Heggedalveien"; + EnhancerTestUtils.checkDirtyTracking( entity, "address" ); - Country country = new Country(); - address2.country = country; - country.name = "Norway"; - EnhancerTestUtils.checkDirtyTracking( entity, "address", "address.country" ); + Country country = new Country(); + address2.country = country; + country.name = "Norway"; + EnhancerTestUtils.checkDirtyTracking( entity, "address", "address.country" ); - address.country = null; - entity.address = null; - } + address.country = null; + entity.address = null; + } - // --- // + // --- // - @Embeddable - private static class Address { - @Embedded - Country country; - String street1; - String street2; - String city; - String state; - String zip; - String phone; - } + @Embeddable + private static class Address { + @Embedded + Country country; + String street1; + String street2; + String city; + String state; + String zip; + String phone; + } - @Embeddable - private static class Country { - String name; - } + @Embeddable + private static class Country { + String name; + } - @Entity - private static class SimpleEntity { + @Entity + private static class SimpleEntity { - @Id - Long id; + @Id + Long id; - String name; + String name; - Boolean active = Boolean.FALSE; + Boolean active = Boolean.FALSE; - Long someNumber = 0L; + Long someNumber = 0L; - List someStrings; + List someStrings; - @OneToMany - Set someAssociation; + @OneToMany + Set someAssociation; - @Embedded - Address address; + @Embedded + Address address; - @Embedded - Address address2; + @Embedded + Address address2; - public Long getSomeNumber() { - return someNumber; - } + public Long getSomeNumber() { + return someNumber; + } - public void setSomeNumber(Long someNumber) { - this.someNumber = someNumber; - } - } + public void setSomeNumber(Long someNumber) { + this.someNumber = someNumber; + } + } - @Entity - private static class OtherEntity { - @Id - Long id; - String name; - } + @Entity + private static class OtherEntity { + @Id + Long id; + String name; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/eviction/EvictionTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/eviction/EvictionTest.java index 78a1033966..52dabf810f 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/eviction/EvictionTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/eviction/EvictionTest.java @@ -31,74 +31,74 @@ import static org.junit.jupiter.api.Assertions.assertTrue; * @author Gail Badner */ @DomainModel( - annotatedClasses = { - EvictionTest.Parent.class - } + annotatedClasses = { + EvictionTest.Parent.class + } ) @SessionFactory @BytecodeEnhanced public class EvictionTest { - @BeforeEach - public void prepare(SessionFactoryScope scope) { - // Create a Parent - scope.inTransaction( s -> { - Parent p = new Parent(); - p.name = "PARENT"; - s.persist( p ); - } ); - } + @BeforeEach + public void prepare(SessionFactoryScope scope) { + // Create a Parent + scope.inTransaction( s -> { + Parent p = new Parent(); + p.name = "PARENT"; + s.persist( p ); + } ); + } - @Test - public void test(SessionFactoryScope scope) { - scope.inTransaction( s -> { + @Test + public void test(SessionFactoryScope scope) { + scope.inTransaction( s -> { - // Delete the Parent - Parent loadedParent = (Parent) s.createQuery( "SELECT p FROM Parent p WHERE name=:name" ) - .setParameter( "name", "PARENT" ) - .uniqueResult(); - assertTyping( ManagedEntity.class, loadedParent ); - ManagedEntity managedParent = (ManagedEntity) loadedParent; + // Delete the Parent + Parent loadedParent = (Parent) s.createQuery( "SELECT p FROM Parent p WHERE name=:name" ) + .setParameter( "name", "PARENT" ) + .uniqueResult(); + assertTyping( ManagedEntity.class, loadedParent ); + ManagedEntity managedParent = (ManagedEntity) loadedParent; - // before eviction - assertNotNull( managedParent.$$_hibernate_getEntityInstance() ); - assertNotNull( managedParent.$$_hibernate_getEntityEntry() ); - assertNull( managedParent.$$_hibernate_getPreviousManagedEntity() ); - assertNull( managedParent.$$_hibernate_getNextManagedEntity() ); + // before eviction + assertNotNull( managedParent.$$_hibernate_getEntityInstance() ); + assertNotNull( managedParent.$$_hibernate_getEntityEntry() ); + assertNull( managedParent.$$_hibernate_getPreviousManagedEntity() ); + assertNull( managedParent.$$_hibernate_getNextManagedEntity() ); - assertTrue( s.contains( managedParent ) ); - s.evict( managedParent ); + assertTrue( s.contains( managedParent ) ); + s.evict( managedParent ); - // after eviction - assertFalse( s.contains( managedParent ) ); - assertNotNull( managedParent.$$_hibernate_getEntityInstance() ); - assertNull( managedParent.$$_hibernate_getEntityEntry() ); - assertNull( managedParent.$$_hibernate_getPreviousManagedEntity() ); - assertNull( managedParent.$$_hibernate_getNextManagedEntity() ); + // after eviction + assertFalse( s.contains( managedParent ) ); + assertNotNull( managedParent.$$_hibernate_getEntityInstance() ); + assertNull( managedParent.$$_hibernate_getEntityEntry() ); + assertNull( managedParent.$$_hibernate_getPreviousManagedEntity() ); + assertNull( managedParent.$$_hibernate_getNextManagedEntity() ); - // evict again - s.evict( managedParent ); + // evict again + s.evict( managedParent ); - assertFalse( s.contains( managedParent ) ); - assertNotNull( managedParent.$$_hibernate_getEntityInstance() ); - assertNull( managedParent.$$_hibernate_getEntityEntry() ); - assertNull( managedParent.$$_hibernate_getPreviousManagedEntity() ); - assertNull( managedParent.$$_hibernate_getNextManagedEntity() ); + assertFalse( s.contains( managedParent ) ); + assertNotNull( managedParent.$$_hibernate_getEntityInstance() ); + assertNull( managedParent.$$_hibernate_getEntityEntry() ); + assertNull( managedParent.$$_hibernate_getPreviousManagedEntity() ); + assertNull( managedParent.$$_hibernate_getNextManagedEntity() ); - s.remove( managedParent ); - } ); - } + s.remove( managedParent ); + } ); + } - // --- // + // --- // - @Entity( name = "Parent" ) - @Table( name = "PARENT" ) - static class Parent { + @Entity( name = "Parent" ) + @Table( name = "PARENT" ) + static class Parent { - @Id - @GeneratedValue( strategy = GenerationType.AUTO ) - Long id; + @Id + @GeneratedValue( strategy = GenerationType.AUTO ) + Long id; - String name; - } + String name; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/join/HHH3949Test.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/join/HHH3949Test.java index c1b65e9051..b69f733ca8 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/join/HHH3949Test.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/join/HHH3949Test.java @@ -39,210 +39,210 @@ import static org.junit.jupiter.api.Assertions.assertTrue; @SuppressWarnings("JUnitMalformedDeclaration") @JiraKey( "HHH-3949" ) @DomainModel( - annotatedClasses = { - HHH3949Test.Person.class, HHH3949Test.Vehicle.class - } + annotatedClasses = { + HHH3949Test.Person.class, HHH3949Test.Vehicle.class + } ) @ServiceRegistry( - settings = { - @Setting( name = AvailableSettings.USE_SECOND_LEVEL_CACHE, value = "false" ), - @Setting( name = AvailableSettings.ENABLE_LAZY_LOAD_NO_TRANS, value = "true" ), - // see HHH-3949 for further details ^^^^^ - } + settings = { + @Setting( name = AvailableSettings.USE_SECOND_LEVEL_CACHE, value = "false" ), + @Setting( name = AvailableSettings.ENABLE_LAZY_LOAD_NO_TRANS, value = "true" ), + // see HHH-3949 for further details ^^^^^ + } ) @SessionFactory @BytecodeEnhanced public class HHH3949Test { - @BeforeEach - public void prepare(SessionFactoryScope scope) { - scope.inTransaction( s -> { + @BeforeEach + public void prepare(SessionFactoryScope scope) { + scope.inTransaction( s -> { - // it is important that the data associations remain as follows: - // * Johnny <-> Volkswagen Golf - // * Ricky <-> Subaru Impreza - // * Rosy -> none - // * none <- Renault Truck - // - // see #shouldHaveVehicle and #shouldHaveDriver + // it is important that the data associations remain as follows: + // * Johnny <-> Volkswagen Golf + // * Ricky <-> Subaru Impreza + // * Rosy -> none + // * none <- Renault Truck + // + // see #shouldHaveVehicle and #shouldHaveDriver - Person person1 = new Person( "Johnny" ); - Person person2 = new Person( "Ricky" ); - Person person3 = new Person( "Rosy" ); - s.persist( person1 ); - s.persist( person2 ); - s.persist( person3 ); + Person person1 = new Person( "Johnny" ); + Person person2 = new Person( "Ricky" ); + Person person3 = new Person( "Rosy" ); + s.persist( person1 ); + s.persist( person2 ); + s.persist( person3 ); - Vehicle vehicle1 = new Vehicle( "Volkswagen Golf" ); - vehicle1.setDriver( person1 ); - s.persist( vehicle1 ); + Vehicle vehicle1 = new Vehicle( "Volkswagen Golf" ); + vehicle1.setDriver( person1 ); + s.persist( vehicle1 ); - Vehicle vehicle2 = new Vehicle( "Subaru Impreza" ); - vehicle2.setDriver( person2 ); - person2.setVehicle( vehicle2 ); - s.persist( vehicle2 ); + Vehicle vehicle2 = new Vehicle( "Subaru Impreza" ); + vehicle2.setDriver( person2 ); + person2.setVehicle( vehicle2 ); + s.persist( vehicle2 ); - Vehicle vehicle3 = new Vehicle( "Renault Truck" ); - s.persist( vehicle3 ); - } ); - } + Vehicle vehicle3 = new Vehicle( "Renault Truck" ); + s.persist( vehicle3 ); + } ); + } - @Test - public void test1(SessionFactoryScope scope) { - performQueryAndVerifyPersonResults( scope, "from Person p left join fetch p.vehicle" ); - } + @Test + public void test1(SessionFactoryScope scope) { + performQueryAndVerifyPersonResults( scope, "from Person p left join fetch p.vehicle" ); + } - @Test - public void test2(SessionFactoryScope scope) { - performQueryAndVerifyVehicleResults( scope, "from Vehicle v left join fetch v.driver" ); - } + @Test + public void test2(SessionFactoryScope scope) { + performQueryAndVerifyVehicleResults( scope, "from Vehicle v left join fetch v.driver" ); + } - @Test - @SuppressWarnings( "unchecked" ) - public void test3(SessionFactoryScope scope) { - scope.inTransaction( s -> { - CriteriaBuilder criteriaBuilder = s.getCriteriaBuilder(); - CriteriaQuery criteria = criteriaBuilder.createQuery( Person.class ); - criteria.from( Person.class ).fetch( "vehicle", JoinType.LEFT ); - List persons = s.createQuery( criteria ).list(); + @Test + @SuppressWarnings( "unchecked" ) + public void test3(SessionFactoryScope scope) { + scope.inTransaction( s -> { + CriteriaBuilder criteriaBuilder = s.getCriteriaBuilder(); + CriteriaQuery criteria = criteriaBuilder.createQuery( Person.class ); + criteria.from( Person.class ).fetch( "vehicle", JoinType.LEFT ); + List persons = s.createQuery( criteria ).list(); // List persons = (List) s.createCriteria( Person.class ).setFetchMode( "vehicle", FetchMode.JOIN ).list(); - for ( Person person : persons ) { - if ( shouldHaveVehicle( person ) ) { - assertNotNull( person.getVehicle() ); - assertNotNull( person.getVehicle().getDriver() ); - } - } - } ); - } + for ( Person person : persons ) { + if ( shouldHaveVehicle( person ) ) { + assertNotNull( person.getVehicle() ); + assertNotNull( person.getVehicle().getDriver() ); + } + } + } ); + } - @Test - @SuppressWarnings( "unchecked" ) - public void test4(SessionFactoryScope scope) { - List vehicles; + @Test + @SuppressWarnings( "unchecked" ) + public void test4(SessionFactoryScope scope) { + List vehicles; - try ( Session s = scope.getSessionFactory().openSession() ) { - CriteriaBuilder criteriaBuilder = s.getCriteriaBuilder(); - CriteriaQuery criteria = criteriaBuilder.createQuery( Vehicle.class ); - criteria.from( Vehicle.class ).fetch( "driver", JoinType.LEFT ); - vehicles = s.createQuery( criteria ).list(); + try ( Session s = scope.getSessionFactory().openSession() ) { + CriteriaBuilder criteriaBuilder = s.getCriteriaBuilder(); + CriteriaQuery criteria = criteriaBuilder.createQuery( Vehicle.class ); + criteria.from( Vehicle.class ).fetch( "driver", JoinType.LEFT ); + vehicles = s.createQuery( criteria ).list(); // vehicles = (List) s.createCriteria( Vehicle.class ).setFetchMode( "driver", FetchMode.JOIN ).list(); - } + } - for ( Vehicle vehicle : vehicles ) { - if ( shouldHaveDriver( vehicle ) ) { - assertNotNull( vehicle.getDriver() ); - assertNotNull( vehicle.getDriver().getVehicle() ); - } - } - } + for ( Vehicle vehicle : vehicles ) { + if ( shouldHaveDriver( vehicle ) ) { + assertNotNull( vehicle.getDriver() ); + assertNotNull( vehicle.getDriver().getVehicle() ); + } + } + } - // --- // + // --- // - @SuppressWarnings( "unchecked" ) - private void performQueryAndVerifyPersonResults(SessionFactoryScope scope, String query) { - List persons; - try ( Session s = scope.getSessionFactory().openSession() ) { - persons = (List) s.createQuery( query ).list(); - } - for ( Person person : persons ) { - assertTrue( isInitialized( person ) ); - if ( shouldHaveVehicle( person ) ) { - // We used a "join fetch", so the vehicle must be initialized - // before we even call the getter - // (which could trigger lazy initialization if the join fetch didn't work). - assertTrue( isPropertyInitialized( person, "vehicle" ) ); + @SuppressWarnings( "unchecked" ) + private void performQueryAndVerifyPersonResults(SessionFactoryScope scope, String query) { + List persons; + try ( Session s = scope.getSessionFactory().openSession() ) { + persons = (List) s.createQuery( query ).list(); + } + for ( Person person : persons ) { + assertTrue( isInitialized( person ) ); + if ( shouldHaveVehicle( person ) ) { + // We used a "join fetch", so the vehicle must be initialized + // before we even call the getter + // (which could trigger lazy initialization if the join fetch didn't work). + assertTrue( isPropertyInitialized( person, "vehicle" ) ); - assertNotNull( person.getVehicle() ); - assertTrue( isInitialized( person.getVehicle() ) ); - assertNotNull( person.getVehicle().getDriver() ); - } - } - } + assertNotNull( person.getVehicle() ); + assertTrue( isInitialized( person.getVehicle() ) ); + assertNotNull( person.getVehicle().getDriver() ); + } + } + } - @SuppressWarnings( "unchecked" ) - private void performQueryAndVerifyVehicleResults(SessionFactoryScope scope, String query) { - List vehicles; - try ( Session s = scope.getSessionFactory().openSession() ) { - vehicles = (List) s.createQuery( query ).list(); - } - for ( Vehicle vehicle : vehicles ) { - if ( shouldHaveDriver( vehicle ) ) { - // We used a "join fetch", so the drover must be initialized - // before we even call the getter - // (which could trigger lazy initialization if the join fetch didn't work). - assertTrue( isPropertyInitialized( vehicle, "driver" ) ); + @SuppressWarnings( "unchecked" ) + private void performQueryAndVerifyVehicleResults(SessionFactoryScope scope, String query) { + List vehicles; + try ( Session s = scope.getSessionFactory().openSession() ) { + vehicles = (List) s.createQuery( query ).list(); + } + for ( Vehicle vehicle : vehicles ) { + if ( shouldHaveDriver( vehicle ) ) { + // We used a "join fetch", so the drover must be initialized + // before we even call the getter + // (which could trigger lazy initialization if the join fetch didn't work). + assertTrue( isPropertyInitialized( vehicle, "driver" ) ); - assertNotNull( vehicle.getDriver() ); - assertNotNull( vehicle.getDriver().getVehicle() ); - } - } - } + assertNotNull( vehicle.getDriver() ); + assertNotNull( vehicle.getDriver().getVehicle() ); + } + } + } - private boolean shouldHaveVehicle(Person person) { - return "Johnny".equals( person.name ) || "Ricky".equals( person.name ); - } + private boolean shouldHaveVehicle(Person person) { + return "Johnny".equals( person.name ) || "Ricky".equals( person.name ); + } - private boolean shouldHaveDriver(Vehicle vehicle) { - return "Volkswagen Golf".equals( vehicle.name ) || "Subaru Impreza".equals( vehicle.name ); - } + private boolean shouldHaveDriver(Vehicle vehicle) { + return "Volkswagen Golf".equals( vehicle.name ) || "Subaru Impreza".equals( vehicle.name ); + } - // --- // + // --- // - @Entity( name = "Person" ) - @Table( name = "PERSON" ) - static class Person { + @Entity( name = "Person" ) + @Table( name = "PERSON" ) + static class Person { - @Id - @GeneratedValue - Long id; + @Id + @GeneratedValue + Long id; - String name; + String name; - @OneToOne( optional = true, mappedBy = "driver", fetch = FetchType.LAZY ) - Vehicle vehicle; + @OneToOne( optional = true, mappedBy = "driver", fetch = FetchType.LAZY ) + Vehicle vehicle; - Person() { - } + Person() { + } - Person(String name) { - this.name = name; - } + Person(String name) { + this.name = name; + } - Vehicle getVehicle() { - return vehicle; - } + Vehicle getVehicle() { + return vehicle; + } - void setVehicle(Vehicle vehicle) { - this.vehicle = vehicle; - } - } + void setVehicle(Vehicle vehicle) { + this.vehicle = vehicle; + } + } - @Entity( name = "Vehicle" ) - @Table( name = "VEHICLE" ) - static class Vehicle { + @Entity( name = "Vehicle" ) + @Table( name = "VEHICLE" ) + static class Vehicle { - @Id - @GeneratedValue - Long id; + @Id + @GeneratedValue + Long id; - String name; + String name; - @OneToOne( optional = true, fetch = FetchType.LAZY ) - Person driver; + @OneToOne( optional = true, fetch = FetchType.LAZY ) + Person driver; - Vehicle() { - } + Vehicle() { + } - Vehicle(String name) { - this.name = name; - } + Vehicle(String name) { + this.name = name; + } - Person getDriver() { - return driver; - } + Person getDriver() { + return driver; + } - void setDriver(Person driver) { - this.driver = driver; - } - } + void setDriver(Person driver) { + this.driver = driver; + } + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/HHH_10708/UnexpectedDeleteTest1.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/HHH_10708/UnexpectedDeleteTest1.java index ffebe26cdc..71243c5411 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/HHH_10708/UnexpectedDeleteTest1.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/HHH_10708/UnexpectedDeleteTest1.java @@ -30,66 +30,66 @@ import java.util.Set; @JiraKey( "HHH-10708" ) @DomainModel( - annotatedClasses = { - UnexpectedDeleteTest1.Foo.class, UnexpectedDeleteTest1.Bar.class - } + annotatedClasses = { + UnexpectedDeleteTest1.Foo.class, UnexpectedDeleteTest1.Bar.class + } ) @SessionFactory @BytecodeEnhanced public class UnexpectedDeleteTest1 { - private long fooId; + private long fooId; - @BeforeEach - public void prepare(SessionFactoryScope scope) { - scope.inTransaction( s -> { - Bar bar1 = new Bar(); - Bar bar2 = new Bar(); - Foo foo = new Foo(); - s.persist( bar1 ); - s.persist( bar2 ); - s.persist( foo ); - bar1.foo = foo; - bar2.foo = foo; - fooId = foo.id; - } ); - } + @BeforeEach + public void prepare(SessionFactoryScope scope) { + scope.inTransaction( s -> { + Bar bar1 = new Bar(); + Bar bar2 = new Bar(); + Foo foo = new Foo(); + s.persist( bar1 ); + s.persist( bar2 ); + s.persist( foo ); + bar1.foo = foo; + bar2.foo = foo; + fooId = foo.id; + } ); + } - @Test - public void test(SessionFactoryScope scope) { - scope.inTransaction( s -> { - Foo foo = s.get( Foo.class, fooId ); + @Test + public void test(SessionFactoryScope scope) { + scope.inTransaction( s -> { + Foo foo = s.get( Foo.class, fooId ); - // accessing the collection results in an exception - foo.bars.size(); - } ); - } + // accessing the collection results in an exception + foo.bars.size(); + } ); + } - // --- // + // --- // - @Entity(name = "Bar") - @Table( name = "BAR" ) - static class Bar { + @Entity(name = "Bar") + @Table( name = "BAR" ) + static class Bar { - @Id - @GeneratedValue - Long id; + @Id + @GeneratedValue + Long id; - @ManyToOne - @Cache( usage = CacheConcurrencyStrategy.READ_WRITE ) - Foo foo; - } + @ManyToOne + @Cache( usage = CacheConcurrencyStrategy.READ_WRITE ) + Foo foo; + } - @Entity(name = "Foo") - @Table( name = "FOO" ) - static class Foo { + @Entity(name = "Foo") + @Table( name = "FOO" ) + static class Foo { - @Id - @GeneratedValue - Long id; + @Id + @GeneratedValue + Long id; - @OneToMany( orphanRemoval = true, mappedBy = "foo", targetEntity = Bar.class ) - @Cascade( CascadeType.ALL ) - Set bars = new HashSet<>(); - } + @OneToMany( orphanRemoval = true, mappedBy = "foo", targetEntity = Bar.class ) + @Cascade( CascadeType.ALL ) + Set bars = new HashSet<>(); + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/HHH_10708/UnexpectedDeleteTest2.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/HHH_10708/UnexpectedDeleteTest2.java index 22c79b922d..0a59e4c653 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/HHH_10708/UnexpectedDeleteTest2.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/HHH_10708/UnexpectedDeleteTest2.java @@ -30,69 +30,69 @@ import java.util.Set; @JiraKey( "HHH-10708" ) @DomainModel( - annotatedClasses = { - UnexpectedDeleteTest2.Foo.class, UnexpectedDeleteTest2.Bar.class - } + annotatedClasses = { + UnexpectedDeleteTest2.Foo.class, UnexpectedDeleteTest2.Bar.class + } ) @SessionFactory @BytecodeEnhanced @ServiceRegistry(settings = @Setting(name = AvailableSettings.ALLOW_REFRESH_DETACHED_ENTITY, value = "true")) public class UnexpectedDeleteTest2 { - private Bar myBar; + private Bar myBar; - @BeforeEach - public void prepare(SessionFactoryScope scope) { - scope.inTransaction( s -> { - Bar bar = new Bar(); - Foo foo1 = new Foo(); - Foo foo2 = new Foo(); - s.persist( bar ); - s.persist( foo1 ); - s.persist( foo2 ); + @BeforeEach + public void prepare(SessionFactoryScope scope) { + scope.inTransaction( s -> { + Bar bar = new Bar(); + Foo foo1 = new Foo(); + Foo foo2 = new Foo(); + s.persist( bar ); + s.persist( foo1 ); + s.persist( foo2 ); - bar.foos.add( foo1 ); - bar.foos.add( foo2 ); + bar.foos.add( foo1 ); + bar.foos.add( foo2 ); - myBar = bar; - } ); - } + myBar = bar; + } ); + } - @Test - public void test(SessionFactoryScope scope) { - scope.inTransaction( s -> { - s.refresh( myBar ); - assertFalse( myBar.foos.isEmpty() ); + @Test + public void test(SessionFactoryScope scope) { + scope.inTransaction( s -> { + s.refresh( myBar ); + assertFalse( myBar.foos.isEmpty() ); - // The issue is that currently, for some unknown reason, foos are deleted on flush - } ); + // The issue is that currently, for some unknown reason, foos are deleted on flush + } ); - scope.inTransaction( s -> { - Bar bar = s.get( Bar.class, myBar.id ); - assertFalse( bar.foos.isEmpty() ); - } ); - } + scope.inTransaction( s -> { + Bar bar = s.get( Bar.class, myBar.id ); + assertFalse( bar.foos.isEmpty() ); + } ); + } - // --- // + // --- // - @Entity(name = "Bar") - @Table( name = "BAR" ) - static class Bar { + @Entity(name = "Bar") + @Table( name = "BAR" ) + static class Bar { - @Id - @GeneratedValue - Long id; + @Id + @GeneratedValue + Long id; - @ManyToMany( fetch = FetchType.LAZY, targetEntity = Foo.class ) - Set foos = new HashSet<>(); - } + @ManyToMany( fetch = FetchType.LAZY, targetEntity = Foo.class ) + Set foos = new HashSet<>(); + } - @Entity(name = "Foo") - @Table( name = "FOO" ) - static class Foo { + @Entity(name = "Foo") + @Table( name = "FOO" ) + static class Foo { - @Id - @GeneratedValue - Long id; - } + @Id + @GeneratedValue + Long id; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/HHH_10708/UnexpectedDeleteTest3.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/HHH_10708/UnexpectedDeleteTest3.java index 4be4636b2c..358d50a058 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/HHH_10708/UnexpectedDeleteTest3.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/HHH_10708/UnexpectedDeleteTest3.java @@ -29,107 +29,107 @@ import static org.junit.jupiter.api.Assertions.assertEquals; @JiraKey("HHH-10708") @DomainModel( - annotatedClasses = { - UnexpectedDeleteTest3.Parent.class, UnexpectedDeleteTest3.Child.class - } + annotatedClasses = { + UnexpectedDeleteTest3.Parent.class, UnexpectedDeleteTest3.Child.class + } ) @SessionFactory @BytecodeEnhanced public class UnexpectedDeleteTest3 { - @BeforeEach - public void prepare(SessionFactoryScope scope) { - scope.inTransaction( s -> { - Child child = new Child(); - child.setId( 2L ); - s.persist( child ); + @BeforeEach + public void prepare(SessionFactoryScope scope) { + scope.inTransaction( s -> { + Child child = new Child(); + child.setId( 2L ); + s.persist( child ); - Parent parent = new Parent(); - parent.setId( 1L ); - parent.setNames( Collections.singleton( "name" ) ); - parent.addChild( child ); + Parent parent = new Parent(); + parent.setId( 1L ); + parent.setNames( Collections.singleton( "name" ) ); + parent.addChild( child ); - s.persist( parent ); - } ); - } + s.persist( parent ); + } ); + } - @Test - public void test(SessionFactoryScope scope) { - scope.inTransaction( s -> { - Parent parent = s.get( Parent.class, 1L ); + @Test + public void test(SessionFactoryScope scope) { + scope.inTransaction( s -> { + Parent parent = s.get( Parent.class, 1L ); - Child child = new Child(); - child.setId( 1L ); - s.persist( child ); - parent.addChild( child ); + Child child = new Child(); + child.setId( 1L ); + s.persist( child ); + parent.addChild( child ); - // We need to leave at least one attribute unfetchd - //parent.getNames().size(); - s.persist( parent ); - } ); + // We need to leave at least one attribute unfetchd + //parent.getNames().size(); + s.persist( parent ); + } ); - scope.inTransaction( s -> { - Parent application = s.get( Parent.class, 1L ); - assertEquals( 2, application.getChildren().size(), "Loaded Children collection has unexpected size" ); - } ); - } + scope.inTransaction( s -> { + Parent application = s.get( Parent.class, 1L ); + assertEquals( 2, application.getChildren().size(), "Loaded Children collection has unexpected size" ); + } ); + } - // --- // + // --- // - @Entity - @Table( name = "CHILD" ) - static class Child { + @Entity + @Table( name = "CHILD" ) + static class Child { - Long id; + Long id; - @Id - @Column( name = "id", unique = true, nullable = false ) - Long getId() { - return id; - } + @Id + @Column( name = "id", unique = true, nullable = false ) + Long getId() { + return id; + } - void setId(Long id) { - this.id = id; - } - } + void setId(Long id) { + this.id = id; + } + } - @Entity - @Table( name = "PARENT" ) - static class Parent { + @Entity + @Table( name = "PARENT" ) + static class Parent { - Long id; - Set names; - Set children; + Long id; + Set names; + Set children; - @Id - @Column( name = "id", unique = true, nullable = false ) - Long getId() { - return id; - } + @Id + @Column( name = "id", unique = true, nullable = false ) + Long getId() { + return id; + } - void setId(Long id) { - this.id = id; - } + void setId(Long id) { + this.id = id; + } - @ElementCollection - Set getNames() { - return Collections.unmodifiableSet( names ); - } + @ElementCollection + Set getNames() { + return Collections.unmodifiableSet( names ); + } - void setNames(Set secrets) { - this.names = secrets; - } + void setNames(Set secrets) { + this.names = secrets; + } - @ManyToMany( fetch = FetchType.LAZY, targetEntity = Child.class ) - Set getChildren() { - return Collections.unmodifiableSet( children ); - } + @ManyToMany( fetch = FetchType.LAZY, targetEntity = Child.class ) + Set getChildren() { + return Collections.unmodifiableSet( children ); + } - void addChild(Child child) { - if (children == null) { - children = new HashSet<>(); - } - children.add( child ); - } - } + void addChild(Child child) { + if (children == null) { + children = new HashSet<>(); + } + children.add( child ); + } + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/JpaConstructorInitializationAndDynamicUpdateTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/JpaConstructorInitializationAndDynamicUpdateTest.java index 49b10c370f..3ac0a57eda 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/JpaConstructorInitializationAndDynamicUpdateTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/JpaConstructorInitializationAndDynamicUpdateTest.java @@ -47,157 +47,157 @@ public class JpaConstructorInitializationAndDynamicUpdateTest { @BeforeEach public void setUp(SessionFactoryScope scope) { scope.inTransaction( em -> { - Person person = new Person( 1l, "Henry" ); - LoginAccount loginAccount = new LoginAccount(); - loginAccount.setOwner( person ); - person.setLoginAccount( loginAccount ); - em.persist( person ); - } + Person person = new Person( 1l, "Henry" ); + LoginAccount loginAccount = new LoginAccount(); + loginAccount.setOwner( person ); + person.setLoginAccount( loginAccount ); + em.persist( person ); + } ); scope.inTransaction( em -> { - List accounts = em.createQuery( - "select la from LoginAccount la", - LoginAccount.class - ).getResultList(); - assertThat( accounts.size() ).isEqualTo( 1 ); + List accounts = em.createQuery( + "select la from LoginAccount la", + LoginAccount.class + ).getResultList(); + assertThat( accounts.size() ).isEqualTo( 1 ); - List preferences = em.createQuery( - "select ap from AccountPreferences ap", - AccountPreferences.class - ).getResultList(); - assertThat( preferences.size() ).isEqualTo( 1 ); - } + List preferences = em.createQuery( + "select ap from AccountPreferences ap", + AccountPreferences.class + ).getResultList(); + assertThat( preferences.size() ).isEqualTo( 1 ); + } ); } @AfterEach public void tearDown(SessionFactoryScope scope) { scope.inTransaction( em -> { - em.createQuery( "delete from Person" ).executeUpdate(); - em.createQuery( "delete from LoginAccount" ).executeUpdate(); - em.createQuery( "delete from AccountPreferences" ).executeUpdate(); - } + em.createQuery( "delete from Person" ).executeUpdate(); + em.createQuery( "delete from LoginAccount" ).executeUpdate(); + em.createQuery( "delete from AccountPreferences" ).executeUpdate(); + } ); } @Test public void findTest(SessionFactoryScope scope) { scope.inTransaction( em -> { - em.clear(); - Person person = em.find( Person.class, 1L ); - person.setFirstName( "Liza" ); - } + em.clear(); + Person person = em.find( Person.class, 1L ); + person.setFirstName( "Liza" ); + } ); scope.inTransaction( em -> { - List accounts = em.createQuery( - "select la from LoginAccount la", - LoginAccount.class - ).getResultList(); - assertThat( accounts.size() ).isEqualTo( 1 ); + List accounts = em.createQuery( + "select la from LoginAccount la", + LoginAccount.class + ).getResultList(); + assertThat( accounts.size() ).isEqualTo( 1 ); - List preferences = em.createQuery( - "select ap from AccountPreferences ap", - AccountPreferences.class - ).getResultList(); - assertThat( preferences.size() ).isEqualTo( 1 ); - } + List preferences = em.createQuery( + "select ap from AccountPreferences ap", + AccountPreferences.class + ).getResultList(); + assertThat( preferences.size() ).isEqualTo( 1 ); + } ); } @Test public void getReferenceTest(SessionFactoryScope scope) { scope.inTransaction( em -> { - em.clear(); - Person person = em.getReference( Person.class, 1L ); - person.setFirstName( "Liza" ); - } + em.clear(); + Person person = em.getReference( Person.class, 1L ); + person.setFirstName( "Liza" ); + } ); scope.inTransaction( em -> { - List accounts = em.createQuery( - "select la from LoginAccount la", - LoginAccount.class - ).getResultList(); - assertThat( accounts.size() ).isEqualTo( 1 ); + List accounts = em.createQuery( + "select la from LoginAccount la", + LoginAccount.class + ).getResultList(); + assertThat( accounts.size() ).isEqualTo( 1 ); - List preferences = em.createQuery( - "select ap from AccountPreferences ap", - AccountPreferences.class - ).getResultList(); - assertThat( preferences.size() ).isEqualTo( 1 ); - } + List preferences = em.createQuery( + "select ap from AccountPreferences ap", + AccountPreferences.class + ).getResultList(); + assertThat( preferences.size() ).isEqualTo( 1 ); + } ); } @Test public void findTest2(SessionFactoryScope scope) { scope.inTransaction( em -> { - em.clear(); - Person person = em.find( Person.class, 1L ); - person.setFirstName( "Liza" ); + em.clear(); + Person person = em.find( Person.class, 1L ); + person.setFirstName( "Liza" ); - LoginAccount loginAccount = person.getLoginAccount(); - loginAccount.setName( "abc" ); - } + LoginAccount loginAccount = person.getLoginAccount(); + loginAccount.setName( "abc" ); + } ); scope.inTransaction( em -> { - Person person = em.find( Person.class, 1L ); - assertThat( person.getFirstName() ).isEqualTo( "Liza" ); + Person person = em.find( Person.class, 1L ); + assertThat( person.getFirstName() ).isEqualTo( "Liza" ); - LoginAccount loginAccount = person.getLoginAccount(); - assertThat( loginAccount ).isNotNull(); - assertThat( loginAccount.getName() ).isEqualTo( "abc" ); + LoginAccount loginAccount = person.getLoginAccount(); + assertThat( loginAccount ).isNotNull(); + assertThat( loginAccount.getName() ).isEqualTo( "abc" ); - List accounts = em.createQuery( - "select la from LoginAccount la", - LoginAccount.class - ).getResultList(); - assertThat( accounts.size() ).isEqualTo( 1 ); + List accounts = em.createQuery( + "select la from LoginAccount la", + LoginAccount.class + ).getResultList(); + assertThat( accounts.size() ).isEqualTo( 1 ); - List preferences = em.createQuery( - "select ap from AccountPreferences ap", - AccountPreferences.class - ).getResultList(); - assertThat( preferences.size() ).isEqualTo( 1 ); - } + List preferences = em.createQuery( + "select ap from AccountPreferences ap", + AccountPreferences.class + ).getResultList(); + assertThat( preferences.size() ).isEqualTo( 1 ); + } ); } @Test public void getReferenceTest2(SessionFactoryScope scope) { scope.inTransaction( em -> { - em.clear(); - Person person = em.getReference( Person.class, 1L ); - person.setFirstName( "Liza" ); + em.clear(); + Person person = em.getReference( Person.class, 1L ); + person.setFirstName( "Liza" ); - LoginAccount loginAccount = person.getLoginAccount(); - loginAccount.setName( "abc" ); - } + LoginAccount loginAccount = person.getLoginAccount(); + loginAccount.setName( "abc" ); + } ); scope.inTransaction( em -> { - Person person = em.find( Person.class, 1L ); - assertThat( person.getFirstName() ).isEqualTo( "Liza" ); + Person person = em.find( Person.class, 1L ); + assertThat( person.getFirstName() ).isEqualTo( "Liza" ); - LoginAccount loginAccount = person.getLoginAccount(); - assertThat( loginAccount ).isNotNull(); - assertThat( loginAccount.getName() ).isEqualTo( "abc" ); + LoginAccount loginAccount = person.getLoginAccount(); + assertThat( loginAccount ).isNotNull(); + assertThat( loginAccount.getName() ).isEqualTo( "abc" ); - List accounts = em.createQuery( - "select la from LoginAccount la", - LoginAccount.class - ).getResultList(); - assertThat( accounts.size() ).isEqualTo( 1 ); + List accounts = em.createQuery( + "select la from LoginAccount la", + LoginAccount.class + ).getResultList(); + assertThat( accounts.size() ).isEqualTo( 1 ); - List preferences = em.createQuery( - "select ap from AccountPreferences ap", - AccountPreferences.class - ).getResultList(); - assertThat( preferences.size() ).isEqualTo( 1 ); - } + List preferences = em.createQuery( + "select ap from AccountPreferences ap", + AccountPreferences.class + ).getResultList(); + assertThat( preferences.size() ).isEqualTo( 1 ); + } ); } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/JpaConstructorInitializationTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/JpaConstructorInitializationTest.java index d8fb348163..23864fb1e7 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/JpaConstructorInitializationTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/JpaConstructorInitializationTest.java @@ -46,157 +46,157 @@ public class JpaConstructorInitializationTest { @BeforeEach public void setUp(SessionFactoryScope scope) { scope.inTransaction( em -> { - Person person = new Person( 1l, "Henry" ); - LoginAccount loginAccount = new LoginAccount(); - loginAccount.setOwner( person ); - person.setLoginAccount( loginAccount ); - em.persist( person ); - } + Person person = new Person( 1l, "Henry" ); + LoginAccount loginAccount = new LoginAccount(); + loginAccount.setOwner( person ); + person.setLoginAccount( loginAccount ); + em.persist( person ); + } ); scope.inTransaction( em -> { - List accounts = em.createQuery( - "select la from LoginAccount la", - LoginAccount.class - ).getResultList(); - assertThat( accounts.size() ).isEqualTo( 1 ); + List accounts = em.createQuery( + "select la from LoginAccount la", + LoginAccount.class + ).getResultList(); + assertThat( accounts.size() ).isEqualTo( 1 ); - List preferences = em.createQuery( - "select ap from AccountPreferences ap", - AccountPreferences.class - ).getResultList(); - assertThat( preferences.size() ).isEqualTo( 1 ); - } + List preferences = em.createQuery( + "select ap from AccountPreferences ap", + AccountPreferences.class + ).getResultList(); + assertThat( preferences.size() ).isEqualTo( 1 ); + } ); } @AfterEach public void tearDown(SessionFactoryScope scope) { scope.inTransaction( em -> { - em.createQuery( "delete from Person" ).executeUpdate(); - em.createQuery( "delete from LoginAccount" ).executeUpdate(); - em.createQuery( "delete from AccountPreferences" ).executeUpdate(); - } + em.createQuery( "delete from Person" ).executeUpdate(); + em.createQuery( "delete from LoginAccount" ).executeUpdate(); + em.createQuery( "delete from AccountPreferences" ).executeUpdate(); + } ); } @Test public void findTest(SessionFactoryScope scope) { scope.inTransaction( em -> { - em.clear(); - Person person = em.find( Person.class, 1L ); - person.setFirstName( "Liza" ); - } + em.clear(); + Person person = em.find( Person.class, 1L ); + person.setFirstName( "Liza" ); + } ); scope.inTransaction( em -> { - List accounts = em.createQuery( - "select la from LoginAccount la", - LoginAccount.class - ).getResultList(); - assertThat( accounts.size() ).isEqualTo( 1 ); + List accounts = em.createQuery( + "select la from LoginAccount la", + LoginAccount.class + ).getResultList(); + assertThat( accounts.size() ).isEqualTo( 1 ); - List preferences = em.createQuery( - "select ap from AccountPreferences ap", - AccountPreferences.class - ).getResultList(); - assertThat( preferences.size() ).isEqualTo( 1 ); - } + List preferences = em.createQuery( + "select ap from AccountPreferences ap", + AccountPreferences.class + ).getResultList(); + assertThat( preferences.size() ).isEqualTo( 1 ); + } ); } @Test public void getReferenceTest(SessionFactoryScope scope) { scope.inTransaction( em -> { - em.clear(); - Person person = em.getReference( Person.class, 1L ); - person.setFirstName( "Liza" ); - } + em.clear(); + Person person = em.getReference( Person.class, 1L ); + person.setFirstName( "Liza" ); + } ); scope.inTransaction( em -> { - List accounts = em.createQuery( - "select la from LoginAccount la", - LoginAccount.class - ).getResultList(); - assertThat( accounts.size() ).isEqualTo( 1 ); + List accounts = em.createQuery( + "select la from LoginAccount la", + LoginAccount.class + ).getResultList(); + assertThat( accounts.size() ).isEqualTo( 1 ); - List preferences = em.createQuery( - "select ap from AccountPreferences ap", - AccountPreferences.class - ).getResultList(); - assertThat( preferences.size() ).isEqualTo( 1 ); - } + List preferences = em.createQuery( + "select ap from AccountPreferences ap", + AccountPreferences.class + ).getResultList(); + assertThat( preferences.size() ).isEqualTo( 1 ); + } ); } @Test public void findTest2(SessionFactoryScope scope) { scope.inTransaction( em -> { - em.clear(); - Person person = em.find( Person.class, 1L ); - person.setFirstName( "Liza" ); + em.clear(); + Person person = em.find( Person.class, 1L ); + person.setFirstName( "Liza" ); - LoginAccount loginAccount = person.getLoginAccount(); - loginAccount.setName( "abc" ); - } + LoginAccount loginAccount = person.getLoginAccount(); + loginAccount.setName( "abc" ); + } ); scope.inTransaction( em -> { - Person person = em.find( Person.class, 1L ); - assertThat( person.getFirstName() ).isEqualTo( "Liza" ); + Person person = em.find( Person.class, 1L ); + assertThat( person.getFirstName() ).isEqualTo( "Liza" ); - LoginAccount loginAccount = person.getLoginAccount(); - assertThat( loginAccount ).isNotNull(); - assertThat( loginAccount.getName() ).isEqualTo( "abc" ); + LoginAccount loginAccount = person.getLoginAccount(); + assertThat( loginAccount ).isNotNull(); + assertThat( loginAccount.getName() ).isEqualTo( "abc" ); - List accounts = em.createQuery( - "select la from LoginAccount la", - LoginAccount.class - ).getResultList(); - assertThat( accounts.size() ).isEqualTo( 1 ); + List accounts = em.createQuery( + "select la from LoginAccount la", + LoginAccount.class + ).getResultList(); + assertThat( accounts.size() ).isEqualTo( 1 ); - List preferences = em.createQuery( - "select ap from AccountPreferences ap", - AccountPreferences.class - ).getResultList(); - assertThat( preferences.size() ).isEqualTo( 1 ); - } + List preferences = em.createQuery( + "select ap from AccountPreferences ap", + AccountPreferences.class + ).getResultList(); + assertThat( preferences.size() ).isEqualTo( 1 ); + } ); } @Test public void getReferenceTest2(SessionFactoryScope scope) { scope.inTransaction( em -> { - em.clear(); - Person person = em.getReference( Person.class, 1L ); - person.setFirstName( "Liza" ); + em.clear(); + Person person = em.getReference( Person.class, 1L ); + person.setFirstName( "Liza" ); - LoginAccount loginAccount = person.getLoginAccount(); - loginAccount.setName( "abc" ); - } + LoginAccount loginAccount = person.getLoginAccount(); + loginAccount.setName( "abc" ); + } ); scope.inTransaction( em -> { - Person person = em.find( Person.class, 1L ); - assertThat( person.getFirstName() ).isEqualTo( "Liza" ); + Person person = em.find( Person.class, 1L ); + assertThat( person.getFirstName() ).isEqualTo( "Liza" ); - LoginAccount loginAccount = person.getLoginAccount(); - assertThat( loginAccount ).isNotNull(); - assertThat( loginAccount.getName() ).isEqualTo( "abc" ); + LoginAccount loginAccount = person.getLoginAccount(); + assertThat( loginAccount ).isNotNull(); + assertThat( loginAccount.getName() ).isEqualTo( "abc" ); - List accounts = em.createQuery( - "select la from LoginAccount la", - LoginAccount.class - ).getResultList(); - assertThat( accounts.size() ).isEqualTo( 1 ); + List accounts = em.createQuery( + "select la from LoginAccount la", + LoginAccount.class + ).getResultList(); + assertThat( accounts.size() ).isEqualTo( 1 ); - List preferences = em.createQuery( - "select ap from AccountPreferences ap", - AccountPreferences.class - ).getResultList(); - assertThat( preferences.size() ).isEqualTo( 1 ); - } + List preferences = em.createQuery( + "select ap from AccountPreferences ap", + AccountPreferences.class + ).getResultList(); + assertThat( preferences.size() ).isEqualTo( 1 ); + } ); } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/LazyBasicFieldMergeTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/LazyBasicFieldMergeTest.java index 524a91da7a..39886363db 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/LazyBasicFieldMergeTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/LazyBasicFieldMergeTest.java @@ -33,125 +33,125 @@ import org.junit.jupiter.api.Test; */ @JiraKey("HHH-11117") @DomainModel( - annotatedClasses = { - LazyBasicFieldMergeTest.Company.class, - LazyBasicFieldMergeTest.Manager.class, - } + annotatedClasses = { + LazyBasicFieldMergeTest.Company.class, + LazyBasicFieldMergeTest.Manager.class, + } ) @SessionFactory @BytecodeEnhanced public class LazyBasicFieldMergeTest { - @Test - public void test(SessionFactoryScope scope) { - scope.inTransaction( session -> { - Manager manager = new Manager(); - manager.setName("John Doe"); - manager.setResume(new byte[] {1, 2, 3}); + @Test + public void test(SessionFactoryScope scope) { + scope.inTransaction( session -> { + Manager manager = new Manager(); + manager.setName("John Doe"); + manager.setResume(new byte[] {1, 2, 3}); - Company company = new Company(); - company.setName("Company"); - company.setManager(manager); + Company company = new Company(); + company.setName("Company"); + company.setManager(manager); - Company _company = (Company) session.merge( company); - assertEquals( company.getName(), _company.getName() ); - assertArrayEquals( company.getManager().getResume(), _company.getManager().getResume() ); - } ); - } + Company _company = (Company) session.merge( company); + assertEquals( company.getName(), _company.getName() ); + assertArrayEquals( company.getManager().getResume(), _company.getManager().getResume() ); + } ); + } - @Entity(name = "Company") - @Table(name = "COMPANY") - public static class Company { + @Entity(name = "Company") + @Table(name = "COMPANY") + public static class Company { - @Id - @GeneratedValue - @Column(name = "COMP_ID") - private Long id; + @Id + @GeneratedValue + @Column(name = "COMP_ID") + private Long id; - @Column(name = "NAME") - private String name; + @Column(name = "NAME") + private String name; - @OneToOne(mappedBy = "company", cascade = jakarta.persistence.CascadeType.ALL, orphanRemoval = true) - private Manager manager; + @OneToOne(mappedBy = "company", cascade = jakarta.persistence.CascadeType.ALL, orphanRemoval = true) + private Manager manager; - public Long getId() { - return id; - } + public Long getId() { + return id; + } - public void setId(Long id) { - this.id = id; - } + public void setId(Long id) { + this.id = id; + } - public Manager getManager() { - return manager; - } + public Manager getManager() { + return manager; + } - public void setManager(Manager manager) { - this.manager = manager; - } + public void setManager(Manager manager) { + this.manager = manager; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - } + } - @Entity(name = "Manager") - @Table(name = "MANAGER") - public static class Manager { + @Entity(name = "Manager") + @Table(name = "MANAGER") + public static class Manager { - @Id - @GeneratedValue - @Column(name = "MAN_ID") - private Long id; + @Id + @GeneratedValue + @Column(name = "MAN_ID") + private Long id; - @Column(name = "NAME") - private String name; + @Column(name = "NAME") + private String name; - @Lob - @Column(name = "RESUME") - @Basic(fetch = FetchType.LAZY) - private byte[] resume; + @Lob + @Column(name = "RESUME") + @Basic(fetch = FetchType.LAZY) + private byte[] resume; - @OneToOne(fetch = FetchType.LAZY) - @JoinColumn(name = "COMP_ID") - private Company company; + @OneToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "COMP_ID") + private Company company; - public Long getId() { - return id; - } + public Long getId() { + return id; + } - public void setId(Long id) { - this.id = id; - } + public void setId(Long id) { + this.id = id; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - public byte[] getResume() { - return resume; - } + public byte[] getResume() { + return resume; + } - public void setResume(byte[] resume) { - this.resume = resume; - } + public void setResume(byte[] resume) { + this.resume = resume; + } - public Company getCompany() { - return company; - } + public Company getCompany() { + return company; + } - public void setCompany(Company company) { - this.company = company; - } - } + public void setCompany(Company company) { + this.company = company; + } + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/LazyBasicFieldNotInitializedTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/LazyBasicFieldNotInitializedTest.java index 5e0820d180..23dbd9ce49 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/LazyBasicFieldNotInitializedTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/LazyBasicFieldNotInitializedTest.java @@ -40,65 +40,65 @@ import static org.junit.jupiter.api.Assertions.assertFalse; */ @JiraKey("HHH-9937") @DomainModel( - annotatedClasses = { - LazyBasicFieldNotInitializedTest.TestEntity.class - } + annotatedClasses = { + LazyBasicFieldNotInitializedTest.TestEntity.class + } ) @ServiceRegistry( - settings = { - @Setting( name = AvailableSettings.USE_SECOND_LEVEL_CACHE, value = "false" ), - @Setting( name = AvailableSettings.ENABLE_LAZY_LOAD_NO_TRANS, value = "true" ), - } + settings = { + @Setting( name = AvailableSettings.USE_SECOND_LEVEL_CACHE, value = "false" ), + @Setting( name = AvailableSettings.ENABLE_LAZY_LOAD_NO_TRANS, value = "true" ), + } ) @SessionFactory @BytecodeEnhanced public class LazyBasicFieldNotInitializedTest { - private Long entityId; + private Long entityId; - @BeforeEach - public void prepare(SessionFactoryScope scope) { - scope.inTransaction( s -> { - TestEntity entity = new TestEntity(); - entity.description = "desc"; - s.persist( entity ); - entityId = entity.id; - } ); - } + @BeforeEach + public void prepare(SessionFactoryScope scope) { + scope.inTransaction( s -> { + TestEntity entity = new TestEntity(); + entity.description = "desc"; + s.persist( entity ); + entityId = entity.id; + } ); + } - @Test - public void test(SessionFactoryScope scope) { - scope.inTransaction( s -> { - TestEntity entity = s.get( TestEntity.class, entityId ); - assertFalse( Hibernate.isPropertyInitialized( entity, "description" ) ); + @Test + public void test(SessionFactoryScope scope) { + scope.inTransaction( s -> { + TestEntity entity = s.get( TestEntity.class, entityId ); + assertFalse( Hibernate.isPropertyInitialized( entity, "description" ) ); - EntityPersister entityPersister = scope.getSessionFactory().getRuntimeMetamodels() - .getMappingMetamodel() - .getEntityDescriptor( TestEntity.class ); + EntityPersister entityPersister = scope.getSessionFactory().getRuntimeMetamodels() + .getMappingMetamodel() + .getEntityDescriptor( TestEntity.class ); - boolean[] propertyLaziness = entityPersister.getPropertyLaziness(); - assertEquals( 1, propertyLaziness.length ); - Assertions.assertTrue( propertyLaziness[0] ); + boolean[] propertyLaziness = entityPersister.getPropertyLaziness(); + assertEquals( 1, propertyLaziness.length ); + Assertions.assertTrue( propertyLaziness[0] ); - // Make sure NonIdentifierAttribute#isLazy is consistent (HHH-10551) - final AttributeMapping theBytesAttr = entityPersister.findAttributeMapping( "description" ); - assertThat( theBytesAttr ).isInstanceOf( BasicValuedModelPart.class ); - assertThat( theBytesAttr.getMappedFetchOptions().getTiming() ).isEqualTo( FetchTiming.DELAYED ); - } ); - } + // Make sure NonIdentifierAttribute#isLazy is consistent (HHH-10551) + final AttributeMapping theBytesAttr = entityPersister.findAttributeMapping( "description" ); + assertThat( theBytesAttr ).isInstanceOf( BasicValuedModelPart.class ); + assertThat( theBytesAttr.getMappedFetchOptions().getTiming() ).isEqualTo( FetchTiming.DELAYED ); + } ); + } - // --- // + // --- // - @Entity(name = "TestEntity") - @Table( name = "TEST_ENTITY" ) - static class TestEntity { + @Entity(name = "TestEntity") + @Table( name = "TEST_ENTITY" ) + static class TestEntity { - @Id - @GeneratedValue - Long id; + @Id + @GeneratedValue + Long id; - @Basic( fetch = FetchType.LAZY ) - String description; - } + @Basic( fetch = FetchType.LAZY ) + String description; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/LazyCollectionDeletedTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/LazyCollectionDeletedTest.java index 5df558d21f..1066f2c9a5 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/LazyCollectionDeletedTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/LazyCollectionDeletedTest.java @@ -38,112 +38,112 @@ import static org.junit.jupiter.api.Assertions.assertFalse; */ @JiraKey("HHH-11576") @DomainModel( - annotatedClasses = { - LazyCollectionDeletedTest.Post.class, - LazyCollectionDeletedTest.Tag.class, - LazyCollectionDeletedTest.AdditionalDetails.class - } + annotatedClasses = { + LazyCollectionDeletedTest.Post.class, + LazyCollectionDeletedTest.Tag.class, + LazyCollectionDeletedTest.AdditionalDetails.class + } ) @ServiceRegistry( - settings = { - @Setting( name = AvailableSettings.USE_SECOND_LEVEL_CACHE, value = "false" ), - @Setting( name = AvailableSettings.ENABLE_LAZY_LOAD_NO_TRANS, value = "true" ), - } + settings = { + @Setting( name = AvailableSettings.USE_SECOND_LEVEL_CACHE, value = "false" ), + @Setting( name = AvailableSettings.ENABLE_LAZY_LOAD_NO_TRANS, value = "true" ), + } ) @SessionFactory @BytecodeEnhanced public class LazyCollectionDeletedTest { - private Long postId; + private Long postId; - @BeforeEach - public void prepare(SessionFactoryScope scope) { - scope.inTransaction( s -> { - Post post = new Post(); + @BeforeEach + public void prepare(SessionFactoryScope scope) { + scope.inTransaction( s -> { + Post post = new Post(); - Tag tag1 = new Tag( "tag1" ); - Tag tag2 = new Tag( "tag2" ); + Tag tag1 = new Tag( "tag1" ); + Tag tag2 = new Tag( "tag2" ); - Set tagSet = new HashSet<>(); - tagSet.add( tag1 ); - tagSet.add( tag2 ); - post.tags = tagSet; + Set tagSet = new HashSet<>(); + tagSet.add( tag1 ); + tagSet.add( tag2 ); + post.tags = tagSet; - AdditionalDetails details = new AdditionalDetails(); - details.post = post; - details.details = "Some data"; - post.additionalDetails = details; - s.persist( post ); - postId = post.id; - } ); - } + AdditionalDetails details = new AdditionalDetails(); + details.post = post; + details.details = "Some data"; + post.additionalDetails = details; + s.persist( post ); + postId = post.id; + } ); + } - @Test - public void test(SessionFactoryScope scope) { - scope.inTransaction( s -> { - Query query = s.createQuery( "from AdditionalDetails where id=" + postId ); - AdditionalDetails additionalDetails = (AdditionalDetails) query.getSingleResult(); - additionalDetails.details = "New data"; - s.persist( additionalDetails ); + @Test + public void test(SessionFactoryScope scope) { + scope.inTransaction( s -> { + Query query = s.createQuery( "from AdditionalDetails where id=" + postId ); + AdditionalDetails additionalDetails = (AdditionalDetails) query.getSingleResult(); + additionalDetails.details = "New data"; + s.persist( additionalDetails ); - // additionalDetails.post.tags get deleted on commit - } ); + // additionalDetails.post.tags get deleted on commit + } ); - scope.inTransaction( s -> { - Query query = s.createQuery( "from Post where id=" + postId ); - Post retrievedPost = (Post) query.getSingleResult(); + scope.inTransaction( s -> { + Query query = s.createQuery( "from Post where id=" + postId ); + Post retrievedPost = (Post) query.getSingleResult(); - assertFalse( retrievedPost.tags.isEmpty(), "No tags found" ); - retrievedPost.tags.forEach( tag -> System.out.println( "Found tag: " + tag ) ); - } ); - } + assertFalse( retrievedPost.tags.isEmpty(), "No tags found" ); + retrievedPost.tags.forEach( tag -> System.out.println( "Found tag: " + tag ) ); + } ); + } - // --- // + // --- // - @Entity( name = "Tag" ) - @Table( name = "TAG" ) - static class Tag { + @Entity( name = "Tag" ) + @Table( name = "TAG" ) + static class Tag { - @Id - @GeneratedValue - Long id; + @Id + @GeneratedValue + Long id; - String name; + String name; - Tag() { - } + Tag() { + } - Tag(String name) { - this.name = name; - } - } + Tag(String name) { + this.name = name; + } + } - @Entity( name = "Post" ) - @Table( name = "POST" ) - static class Post { + @Entity( name = "Post" ) + @Table( name = "POST" ) + static class Post { - @Id - @GeneratedValue - Long id; + @Id + @GeneratedValue + Long id; - @ManyToMany( cascade = CascadeType.ALL ) - Set tags; + @ManyToMany( cascade = CascadeType.ALL ) + Set tags; - @OneToOne( fetch = FetchType.LAZY, mappedBy = "post", cascade = CascadeType.ALL ) - AdditionalDetails additionalDetails; - } + @OneToOne( fetch = FetchType.LAZY, mappedBy = "post", cascade = CascadeType.ALL ) + AdditionalDetails additionalDetails; + } - @Entity( name = "AdditionalDetails" ) - @Table( name = "ADDITIONAL_DETAILS" ) - static class AdditionalDetails { + @Entity( name = "AdditionalDetails" ) + @Table( name = "ADDITIONAL_DETAILS" ) + static class AdditionalDetails { - @Id - Long id; + @Id + Long id; - String details; + String details; - @OneToOne( optional = false ) - @MapsId - Post post; - } + @OneToOne( optional = false ) + @MapsId + Post post; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/LazyCollectionLoadingTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/LazyCollectionLoadingTest.java index 38f48a2709..7a7987a168 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/LazyCollectionLoadingTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/LazyCollectionLoadingTest.java @@ -56,146 +56,146 @@ import static org.junit.jupiter.api.Assertions.assertTrue; @SuppressWarnings("JUnitMalformedDeclaration") @JiraKey( "HHH-10055" ) @DomainModel( - annotatedClasses = { - LazyCollectionLoadingTest.Parent.class, LazyCollectionLoadingTest.Child.class - } + annotatedClasses = { + LazyCollectionLoadingTest.Parent.class, LazyCollectionLoadingTest.Child.class + } ) @ServiceRegistry( - settings = { - @Setting( name = AvailableSettings.USE_SECOND_LEVEL_CACHE, value = "false" ), - @Setting( name = AvailableSettings.ENABLE_LAZY_LOAD_NO_TRANS, value = "true" ), - } + settings = { + @Setting( name = AvailableSettings.USE_SECOND_LEVEL_CACHE, value = "false" ), + @Setting( name = AvailableSettings.ENABLE_LAZY_LOAD_NO_TRANS, value = "true" ), + } ) @SessionFactory @BytecodeEnhanced public class LazyCollectionLoadingTest { - private static final int CHILDREN_SIZE = 10; - private Long parentID; - private Parent parent; + private static final int CHILDREN_SIZE = 10; + private Long parentID; + private Parent parent; - @BeforeEach - public void prepare(SessionFactoryScope scope) { - scope.inTransaction( s -> { - Parent parent = new Parent(); - parent.setChildren( new ArrayList<>() ); - for ( int i = 0; i < CHILDREN_SIZE; i++ ) { - Child child = new Child(); - child.parent = parent; - s.persist( child ); - } - s.persist( parent ); - parentID = parent.id; - } ); - } + @BeforeEach + public void prepare(SessionFactoryScope scope) { + scope.inTransaction( s -> { + Parent parent = new Parent(); + parent.setChildren( new ArrayList<>() ); + for ( int i = 0; i < CHILDREN_SIZE; i++ ) { + Child child = new Child(); + child.parent = parent; + s.persist( child ); + } + s.persist( parent ); + parentID = parent.id; + } ); + } - @Test - public void testTransaction(SessionFactoryScope scope) { - scope.inTransaction( s -> { - Parent parent = s.getReference( Parent.class, parentID ); - assertThat( parent, notNullValue() ); - assertThat( parent, not( instanceOf( HibernateProxy.class ) ) ); - assertFalse( isPropertyInitialized( parent, "children" ) ); - checkDirtyTracking( parent ); + @Test + public void testTransaction(SessionFactoryScope scope) { + scope.inTransaction( s -> { + Parent parent = s.getReference( Parent.class, parentID ); + assertThat( parent, notNullValue() ); + assertThat( parent, not( instanceOf( HibernateProxy.class ) ) ); + assertFalse( isPropertyInitialized( parent, "children" ) ); + checkDirtyTracking( parent ); - List children1 = parent.children; - List children2 = parent.children; + List children1 = parent.children; + List children2 = parent.children; - assertTrue( isPropertyInitialized( parent, "children" ) ); - checkDirtyTracking( parent ); + assertTrue( isPropertyInitialized( parent, "children" ) ); + checkDirtyTracking( parent ); - assertThat( children1, sameInstance( children2 ) ); + assertThat( children1, sameInstance( children2 ) ); - assertFalse( isInitialized( children1 ) ); - assertThat( children1.size(), equalTo( CHILDREN_SIZE ) ); - assertTrue( isInitialized( children1 ) ); - } ); - } + assertFalse( isInitialized( children1 ) ); + assertThat( children1.size(), equalTo( CHILDREN_SIZE ) ); + assertTrue( isInitialized( children1 ) ); + } ); + } - @Test - @JiraKey( "HHH-14620" ) - public void testTransaction_noProxy(SessionFactoryScope scope) { - scope.inTransaction( s -> { - // find will not return a proxy, which is exactly what we want here. - Parent parent = s.find( Parent.class, parentID ); - assertThat( parent, notNullValue() ); - assertThat( parent, not( instanceOf( HibernateProxy.class ) ) ); - checkDirtyTracking( parent ); + @Test + @JiraKey( "HHH-14620" ) + public void testTransaction_noProxy(SessionFactoryScope scope) { + scope.inTransaction( s -> { + // find will not return a proxy, which is exactly what we want here. + Parent parent = s.find( Parent.class, parentID ); + assertThat( parent, notNullValue() ); + assertThat( parent, not( instanceOf( HibernateProxy.class ) ) ); + checkDirtyTracking( parent ); - List children1 = parent.children; - List children2 = parent.children; + List children1 = parent.children; + List children2 = parent.children; - checkDirtyTracking( parent ); + checkDirtyTracking( parent ); - assertThat( children1, sameInstance( children2 ) ); + assertThat( children1, sameInstance( children2 ) ); - // This check is important: a bug used to cause the collection to be initialized - // during the call to parent.children above. - // Note the same problem would occur if we were using getters: - // we only need extended enhancement to be enabled. - assertFalse( isInitialized( children1 ) ); - assertThat( children1.size(), equalTo( CHILDREN_SIZE ) ); - assertTrue( isInitialized( children1 ) ); - } ); - } + // This check is important: a bug used to cause the collection to be initialized + // during the call to parent.children above. + // Note the same problem would occur if we were using getters: + // we only need extended enhancement to be enabled. + assertFalse( isInitialized( children1 ) ); + assertThat( children1.size(), equalTo( CHILDREN_SIZE ) ); + assertTrue( isInitialized( children1 ) ); + } ); + } - @Test - public void testNoTransaction(SessionFactoryScope scope) { - scope.inTransaction( s -> { - parent = s.getReference( Parent.class, parentID ); - assertThat( parent, notNullValue() ); - assertThat( parent, not( instanceOf( HibernateProxy.class ) ) ); - assertFalse( isPropertyInitialized( parent, "children" ) ); - } ); + @Test + public void testNoTransaction(SessionFactoryScope scope) { + scope.inTransaction( s -> { + parent = s.getReference( Parent.class, parentID ); + assertThat( parent, notNullValue() ); + assertThat( parent, not( instanceOf( HibernateProxy.class ) ) ); + assertFalse( isPropertyInitialized( parent, "children" ) ); + } ); - List children1 = parent.children; - List children2 = parent.children; + List children1 = parent.children; + List children2 = parent.children; - assertTrue( isPropertyInitialized( parent, "children" ) ); + assertTrue( isPropertyInitialized( parent, "children" ) ); - checkDirtyTracking( parent ); - assertThat( children1, sameInstance( children2 ) ); + checkDirtyTracking( parent ); + assertThat( children1, sameInstance( children2 ) ); - assertFalse( isInitialized( children1 ) ); - assertThat( children1.size(), equalTo( CHILDREN_SIZE ) ); - assertTrue( isInitialized( children1 ) ); - } + assertFalse( isInitialized( children1 ) ); + assertThat( children1.size(), equalTo( CHILDREN_SIZE ) ); + assertTrue( isInitialized( children1 ) ); + } - // --- // + // --- // - @Entity - @Table( name = "PARENT" ) - static class Parent { + @Entity + @Table( name = "PARENT" ) + static class Parent { - @Id - @GeneratedValue( strategy = GenerationType.AUTO ) - Long id; + @Id + @GeneratedValue( strategy = GenerationType.AUTO ) + Long id; - @OneToMany( mappedBy = "parent", cascade = CascadeType.ALL, fetch = FetchType.LAZY ) - List children; + @OneToMany( mappedBy = "parent", cascade = CascadeType.ALL, fetch = FetchType.LAZY ) + List children; - void setChildren(List children) { - this.children = children; - } - } + void setChildren(List children) { + this.children = children; + } + } - @Entity - @Table( name = "CHILD" ) - static class Child { + @Entity + @Table( name = "CHILD" ) + static class Child { - @Id - @GeneratedValue( strategy = GenerationType.AUTO ) - Long id; + @Id + @GeneratedValue( strategy = GenerationType.AUTO ) + Long id; - @ManyToOne( cascade = CascadeType.ALL, fetch = FetchType.LAZY ) - Parent parent; + @ManyToOne( cascade = CascadeType.ALL, fetch = FetchType.LAZY ) + Parent parent; - String name; + String name; - Child() { - } + Child() { + } - Child(String name) { - this.name = name; - } - } + Child(String name) { + this.name = name; + } + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/LazyLoadingByEnhancerSetterTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/LazyLoadingByEnhancerSetterTest.java index c490d8068c..e48033c918 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/LazyLoadingByEnhancerSetterTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/LazyLoadingByEnhancerSetterTest.java @@ -39,125 +39,125 @@ import static org.junit.jupiter.api.Assertions.assertEquals; @JiraKey( "HHH-10747" ) @DomainModel( - annotatedClasses = { - LazyLoadingByEnhancerSetterTest.ItemField.class, LazyLoadingByEnhancerSetterTest.ItemProperty.class - } + annotatedClasses = { + LazyLoadingByEnhancerSetterTest.ItemField.class, LazyLoadingByEnhancerSetterTest.ItemProperty.class + } ) @ServiceRegistry( - settings = { - @Setting( name = AvailableSettings.USE_SECOND_LEVEL_CACHE, value = "false" ), - @Setting( name = AvailableSettings.ENABLE_LAZY_LOAD_NO_TRANS, value = "true" ), - } + settings = { + @Setting( name = AvailableSettings.USE_SECOND_LEVEL_CACHE, value = "false" ), + @Setting( name = AvailableSettings.ENABLE_LAZY_LOAD_NO_TRANS, value = "true" ), + } ) @SessionFactory @BytecodeEnhanced public class LazyLoadingByEnhancerSetterTest { - private Item item, mergedItem; + private Item item, mergedItem; - @Test - public void testField(SessionFactoryScope scope) { - scope.inTransaction( s -> { - ItemField input = new ItemField(); - input.name = "F"; - input.parameters = new HashMap<>(); - input.parameters.put( "aaa", "AAA" ); - input.parameters.put( "bbb", "BBB" ); - s.persist( input ); - } ); + @Test + public void testField(SessionFactoryScope scope) { + scope.inTransaction( s -> { + ItemField input = new ItemField(); + input.name = "F"; + input.parameters = new HashMap<>(); + input.parameters.put( "aaa", "AAA" ); + input.parameters.put( "bbb", "BBB" ); + s.persist( input ); + } ); - scope.inTransaction( s -> { - // A parameters map is created with the class and is being compared to the persistent map (by the generated code) -- it shouldn't - item = s.find( ItemField.class, "F" ); - } ); + scope.inTransaction( s -> { + // A parameters map is created with the class and is being compared to the persistent map (by the generated code) -- it shouldn't + item = s.find( ItemField.class, "F" ); + } ); - scope.inTransaction( s -> { - mergedItem = (Item) s.merge( item ); - } ); + scope.inTransaction( s -> { + mergedItem = (Item) s.merge( item ); + } ); - assertEquals( 2, mergedItem.getParameters().size() ); - } + assertEquals( 2, mergedItem.getParameters().size() ); + } - @Test - @FailureExpected( jiraKey = "HHH-10747" ) - public void testProperty(SessionFactoryScope scope) { - scope.inTransaction( s -> { - ItemProperty input = new ItemProperty(); - input.setName( "P" ); - Map parameters = new HashMap<>(); - parameters.put( "ccc", "CCC" ); - parameters.put( "ddd", "DDD" ); - input.setParameters( parameters ); - s.persist( input ); - } ); + @Test + @FailureExpected( jiraKey = "HHH-10747" ) + public void testProperty(SessionFactoryScope scope) { + scope.inTransaction( s -> { + ItemProperty input = new ItemProperty(); + input.setName( "P" ); + Map parameters = new HashMap<>(); + parameters.put( "ccc", "CCC" ); + parameters.put( "ddd", "DDD" ); + input.setParameters( parameters ); + s.persist( input ); + } ); - scope.inTransaction( s -> { - // A parameters map is created with the class and is being compared to the persistent map (by the generated code) -- it shouldn't - item = s.find( ItemProperty.class, "P" ); - } ); + scope.inTransaction( s -> { + // A parameters map is created with the class and is being compared to the persistent map (by the generated code) -- it shouldn't + item = s.find( ItemProperty.class, "P" ); + } ); - scope.inTransaction( s -> { - mergedItem = (Item) s.merge( item ); - } ); + scope.inTransaction( s -> { + mergedItem = (Item) s.merge( item ); + } ); - assertEquals( 2, mergedItem.getParameters().size() ); - } + assertEquals( 2, mergedItem.getParameters().size() ); + } - // --- // + // --- // - private interface Item { - Map getParameters(); - } + private interface Item { + Map getParameters(); + } - @Entity - @Table( name = "ITEM_F" ) - static class ItemField implements Item { + @Entity + @Table( name = "ITEM_F" ) + static class ItemField implements Item { - @Id - @Column( nullable = false ) - private String name; + @Id + @Column( nullable = false ) + private String name; - @ElementCollection( fetch = FetchType.EAGER ) - @MapKeyColumn( name = "NAME" ) - @Lob - @Column( name = "PARAM_VAL", length = 65535 ) - private Map parameters = new HashMap<>(); + @ElementCollection( fetch = FetchType.EAGER ) + @MapKeyColumn( name = "NAME" ) + @Lob + @Column( name = "PARAM_VAL", length = 65535 ) + private Map parameters = new HashMap<>(); - @Override - public Map getParameters() { - return parameters; - } - } + @Override + public Map getParameters() { + return parameters; + } + } - @Entity - @Table( name = "ITEM_P" ) - static class ItemProperty implements Item { + @Entity + @Table( name = "ITEM_P" ) + static class ItemProperty implements Item { - private String aName; + private String aName; - private Map parameterMap = new HashMap<>(); + private Map parameterMap = new HashMap<>(); - @Id - @Column( nullable = false ) - public String getName() { - return aName; - } + @Id + @Column( nullable = false ) + public String getName() { + return aName; + } - public void setName(String name) { - this.aName = name; - } + public void setName(String name) { + this.aName = name; + } - @ElementCollection( fetch = FetchType.EAGER ) - @MapKeyColumn( name = "NAME" ) - @Lob - @Column( name = "PARAM_VAL", length = 65535 ) - @Override - public Map getParameters() { - return parameterMap; - } + @ElementCollection( fetch = FetchType.EAGER ) + @MapKeyColumn( name = "NAME" ) + @Lob + @Column( name = "PARAM_VAL", length = 65535 ) + @Override + public Map getParameters() { + return parameterMap; + } - public void setParameters(Map parameters) { - this.parameterMap = parameters; - } - } + public void setParameters(Map parameters) { + this.parameterMap = parameters; + } + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/LazyLoadingIntegrationTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/LazyLoadingIntegrationTest.java index 999726a200..a826477d90 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/LazyLoadingIntegrationTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/LazyLoadingIntegrationTest.java @@ -37,97 +37,97 @@ import static org.junit.jupiter.api.Assertions.assertNull; * @author Luis Barreiro */ @DomainModel( - annotatedClasses = { - LazyLoadingIntegrationTest.Parent.class, LazyLoadingIntegrationTest.Child.class - } + annotatedClasses = { + LazyLoadingIntegrationTest.Parent.class, LazyLoadingIntegrationTest.Child.class + } ) @ServiceRegistry( - settings = { - @Setting( name = AvailableSettings.USE_SECOND_LEVEL_CACHE, value = "false" ), - @Setting( name = AvailableSettings.ENABLE_LAZY_LOAD_NO_TRANS, value = "true" ), - @Setting( name = AvailableSettings.DEFAULT_LIST_SEMANTICS, value = "BAG" ), - } + settings = { + @Setting( name = AvailableSettings.USE_SECOND_LEVEL_CACHE, value = "false" ), + @Setting( name = AvailableSettings.ENABLE_LAZY_LOAD_NO_TRANS, value = "true" ), + @Setting( name = AvailableSettings.DEFAULT_LIST_SEMANTICS, value = "BAG" ), + } ) @SessionFactory @BytecodeEnhanced public class LazyLoadingIntegrationTest { - private static final int CHILDREN_SIZE = 10; - private Long lastChildID; + private static final int CHILDREN_SIZE = 10; + private Long lastChildID; - @BeforeEach - public void prepare(SessionFactoryScope scope) { - scope.inTransaction( s -> { - Parent parent = new Parent(); - for ( int i = 0; i < CHILDREN_SIZE; i++ ) { - Child child = new Child(); - // Association management should kick in here - child.parent = parent; - s.persist( child ); - lastChildID = child.id; - } - s.persist( parent ); - } ); - } + @BeforeEach + public void prepare(SessionFactoryScope scope) { + scope.inTransaction( s -> { + Parent parent = new Parent(); + for ( int i = 0; i < CHILDREN_SIZE; i++ ) { + Child child = new Child(); + // Association management should kick in here + child.parent = parent; + s.persist( child ); + lastChildID = child.id; + } + s.persist( parent ); + } ); + } - @Test - public void test(SessionFactoryScope scope) { - scope.inTransaction( s -> { - Child loadedChild = s.getReference( Child.class, lastChildID ); - checkDirtyTracking( loadedChild ); + @Test + public void test(SessionFactoryScope scope) { + scope.inTransaction( s -> { + Child loadedChild = s.getReference( Child.class, lastChildID ); + checkDirtyTracking( loadedChild ); - loadedChild.name = "Barrabas"; - checkDirtyTracking( loadedChild, "name" ); + loadedChild.name = "Barrabas"; + checkDirtyTracking( loadedChild, "name" ); - Parent loadedParent = loadedChild.parent; - checkDirtyTracking( loadedChild, "name" ); - checkDirtyTracking( loadedParent ); + Parent loadedParent = loadedChild.parent; + checkDirtyTracking( loadedChild, "name" ); + checkDirtyTracking( loadedParent ); - List loadedChildren = new ArrayList<>( loadedParent.children ); - loadedChildren.remove( 0 ); - loadedChildren.remove( loadedChild ); - loadedParent.setChildren( loadedChildren ); + List loadedChildren = new ArrayList<>( loadedParent.children ); + loadedChildren.remove( 0 ); + loadedChildren.remove( loadedChild ); + loadedParent.setChildren( loadedChildren ); - assertNull( loadedChild.parent ); - } ); - } + assertNull( loadedChild.parent ); + } ); + } - // --- // + // --- // - @Entity - @Table( name = "PARENT" ) - static class Parent { + @Entity + @Table( name = "PARENT" ) + static class Parent { - @Id - @GeneratedValue( strategy = GenerationType.AUTO ) - Long id; + @Id + @GeneratedValue( strategy = GenerationType.AUTO ) + Long id; - @OneToMany( mappedBy = "parent", cascade = CascadeType.ALL, fetch = FetchType.LAZY ) - List children; + @OneToMany( mappedBy = "parent", cascade = CascadeType.ALL, fetch = FetchType.LAZY ) + List children; - void setChildren(List children) { - this.children = children; - } - } + void setChildren(List children) { + this.children = children; + } + } - @Entity - @Table( name = "CHILD" ) - static class Child { + @Entity + @Table( name = "CHILD" ) + static class Child { - @Id - @GeneratedValue( strategy = GenerationType.AUTO ) - Long id; + @Id + @GeneratedValue( strategy = GenerationType.AUTO ) + Long id; - @ManyToOne( cascade = CascadeType.ALL, fetch = FetchType.LAZY ) - Parent parent; + @ManyToOne( cascade = CascadeType.ALL, fetch = FetchType.LAZY ) + Parent parent; - String name; + String name; - Child() { - } + Child() { + } - Child(String name) { - this.name = name; - } - } + Child(String name) { + this.name = name; + } + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/LazyLoadingTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/LazyLoadingTest.java index e6fdb8bc50..1d10726148 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/LazyLoadingTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/LazyLoadingTest.java @@ -48,116 +48,116 @@ import static org.junit.Assert.assertThat; */ @SuppressWarnings("JUnitMalformedDeclaration") @DomainModel( - annotatedClasses = { - LazyLoadingTest.Parent.class, LazyLoadingTest.Child.class - } + annotatedClasses = { + LazyLoadingTest.Parent.class, LazyLoadingTest.Child.class + } ) @ServiceRegistry( - settings = { - @Setting( name = AvailableSettings.USE_SECOND_LEVEL_CACHE, value = "false" ), - @Setting( name = AvailableSettings.ENABLE_LAZY_LOAD_NO_TRANS, value = "true" ), - } + settings = { + @Setting( name = AvailableSettings.USE_SECOND_LEVEL_CACHE, value = "false" ), + @Setting( name = AvailableSettings.ENABLE_LAZY_LOAD_NO_TRANS, value = "true" ), + } ) @SessionFactory @BytecodeEnhanced public class LazyLoadingTest { - private static final int CHILDREN_SIZE = 10; - private Long parentID; - private Long lastChildID; + private static final int CHILDREN_SIZE = 10; + private Long parentID; + private Long lastChildID; - @BeforeEach - public void prepare(SessionFactoryScope scope) { - scope.inTransaction( s -> { - Parent parent = new Parent(); - for ( int i = 0; i < CHILDREN_SIZE; i++ ) { - Child child = new Child( "Child #" + i ); - child.parent = parent; - parent.addChild( child ); - s.persist( child ); - lastChildID = child.id; - } - s.persist( parent ); - parentID = parent.id; - } ); - } + @BeforeEach + public void prepare(SessionFactoryScope scope) { + scope.inTransaction( s -> { + Parent parent = new Parent(); + for ( int i = 0; i < CHILDREN_SIZE; i++ ) { + Child child = new Child( "Child #" + i ); + child.parent = parent; + parent.addChild( child ); + s.persist( child ); + lastChildID = child.id; + } + s.persist( parent ); + parentID = parent.id; + } ); + } - @Test - public void test(SessionFactoryScope scope) { - scope.inTransaction( s -> { - Child loadedChild = s.getReference( Child.class, lastChildID ); - assertThat( loadedChild, not( instanceOf( HibernateProxy.class ) ) ); - assertThat( loadedChild, instanceOf( PersistentAttributeInterceptable.class ) ); - final PersistentAttributeInterceptable interceptable = (PersistentAttributeInterceptable) loadedChild; - final PersistentAttributeInterceptor interceptor = interceptable.$$_hibernate_getInterceptor(); - assertThat( interceptor, instanceOf( EnhancementAsProxyLazinessInterceptor.class ) ); + @Test + public void test(SessionFactoryScope scope) { + scope.inTransaction( s -> { + Child loadedChild = s.getReference( Child.class, lastChildID ); + assertThat( loadedChild, not( instanceOf( HibernateProxy.class ) ) ); + assertThat( loadedChild, instanceOf( PersistentAttributeInterceptable.class ) ); + final PersistentAttributeInterceptable interceptable = (PersistentAttributeInterceptable) loadedChild; + final PersistentAttributeInterceptor interceptor = interceptable.$$_hibernate_getInterceptor(); + assertThat( interceptor, instanceOf( EnhancementAsProxyLazinessInterceptor.class ) ); - assertThat( Hibernate.isPropertyInitialized( loadedChild, "name" ), is( false ) ); - assertThat( Hibernate.isPropertyInitialized( loadedChild, "parent" ), is( false ) ); - assertThat( Hibernate.isPropertyInitialized( loadedChild, "children" ), is( false ) ); + assertThat( Hibernate.isPropertyInitialized( loadedChild, "name" ), is( false ) ); + assertThat( Hibernate.isPropertyInitialized( loadedChild, "parent" ), is( false ) ); + assertThat( Hibernate.isPropertyInitialized( loadedChild, "children" ), is( false ) ); - Parent loadedParent = loadedChild.parent; - assertThat( loadedChild.name, notNullValue() ); - assertThat( loadedParent, notNullValue() ); - assertThat( loadedChild.parent, notNullValue() ); + Parent loadedParent = loadedChild.parent; + assertThat( loadedChild.name, notNullValue() ); + assertThat( loadedParent, notNullValue() ); + assertThat( loadedChild.parent, notNullValue() ); - checkDirtyTracking( loadedChild ); + checkDirtyTracking( loadedChild ); - assertThat( Hibernate.isPropertyInitialized( loadedChild, "name" ), is( true ) ); - assertThat( Hibernate.isPropertyInitialized( loadedChild, "parent" ), is( true ) ); - assertThat( Hibernate.isPropertyInitialized( loadedChild, "children" ), is( true ) ); + assertThat( Hibernate.isPropertyInitialized( loadedChild, "name" ), is( true ) ); + assertThat( Hibernate.isPropertyInitialized( loadedChild, "parent" ), is( true ) ); + assertThat( Hibernate.isPropertyInitialized( loadedChild, "children" ), is( true ) ); - Collection loadedChildren = loadedParent.children; - assertThat( Hibernate.isInitialized( loadedChildren ), is( false ) ); + Collection loadedChildren = loadedParent.children; + assertThat( Hibernate.isInitialized( loadedChildren ), is( false ) ); - checkDirtyTracking( loadedChild ); - checkDirtyTracking( loadedParent ); + checkDirtyTracking( loadedChild ); + checkDirtyTracking( loadedParent ); - loadedChildren.size(); - assertThat( Hibernate.isInitialized( loadedChildren ), is( true ) ); - } ); - } + loadedChildren.size(); + assertThat( Hibernate.isInitialized( loadedChildren ), is( true ) ); + } ); + } - // --- // + // --- // - @Entity - @Table( name = "PARENT" ) - static class Parent { + @Entity + @Table( name = "PARENT" ) + static class Parent { - @Id - @GeneratedValue( strategy = GenerationType.AUTO ) - Long id; + @Id + @GeneratedValue( strategy = GenerationType.AUTO ) + Long id; - @OneToMany( mappedBy = "parent", cascade = CascadeType.ALL, fetch = FetchType.LAZY ) - List children; + @OneToMany( mappedBy = "parent", cascade = CascadeType.ALL, fetch = FetchType.LAZY ) + List children; - void addChild(Child child) { - if ( children == null ) { - children = new ArrayList<>(); - } - children.add( child ); - } - } + void addChild(Child child) { + if ( children == null ) { + children = new ArrayList<>(); + } + children.add( child ); + } + } - @Entity - @Table( name = "CHILD" ) - static class Child { + @Entity + @Table( name = "CHILD" ) + static class Child { - @Id - @GeneratedValue( strategy = GenerationType.AUTO ) - Long id; + @Id + @GeneratedValue( strategy = GenerationType.AUTO ) + Long id; - @ManyToOne( cascade = CascadeType.ALL, fetch = FetchType.LAZY ) - Parent parent; + @ManyToOne( cascade = CascadeType.ALL, fetch = FetchType.LAZY ) + Parent parent; - String name; + String name; - Child() { - } + Child() { + } - Child(String name) { - this.name = name; - } - } + Child(String name) { + this.name = name; + } + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/LazyOneToManyWithEqualsImplementationTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/LazyOneToManyWithEqualsImplementationTest.java index dd487f1b19..ed30eeca50 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/LazyOneToManyWithEqualsImplementationTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/LazyOneToManyWithEqualsImplementationTest.java @@ -31,95 +31,95 @@ import jakarta.persistence.OneToMany; @SuppressWarnings("JUnitMalformedDeclaration") @JiraKey("HHH-13380") @DomainModel( - annotatedClasses = { - LazyOneToManyWithEqualsImplementationTest.Person.class, LazyOneToManyWithEqualsImplementationTest.Course.class - } + annotatedClasses = { + LazyOneToManyWithEqualsImplementationTest.Person.class, LazyOneToManyWithEqualsImplementationTest.Course.class + } ) @SessionFactory @BytecodeEnhanced public class LazyOneToManyWithEqualsImplementationTest { - private Long personId; + private Long personId; - @BeforeEach - public void setUp(SessionFactoryScope scope) { - scope.inTransaction( entityManager -> { - Person p = new Person(); - entityManager.persist(p); - personId = p.getId(); + @BeforeEach + public void setUp(SessionFactoryScope scope) { + scope.inTransaction( entityManager -> { + Person p = new Person(); + entityManager.persist(p); + personId = p.getId(); - Course c1 = new Course( "First Course", p ); - p.getCourses().add( c1 ); - entityManager.persist( c1 ); + Course c1 = new Course( "First Course", p ); + p.getCourses().add( c1 ); + entityManager.persist( c1 ); - Course c2 = new Course("Second Course", p ); - p.getCourses().add( c2 ); - entityManager.persist( c2 ); - }); - } + Course c2 = new Course("Second Course", p ); + p.getCourses().add( c2 ); + entityManager.persist( c2 ); + }); + } - @Test - public void testRetrievalOfOneToMany(SessionFactoryScope scope) { - scope.inTransaction( entityManager -> { - Person p = entityManager.find( Person.class, personId ); + @Test + public void testRetrievalOfOneToMany(SessionFactoryScope scope) { + scope.inTransaction( entityManager -> { + Person p = entityManager.find( Person.class, personId ); - Set courses = p.getCourses(); - Assertions.assertEquals( courses.size(), 2 ); - }); - } + Set courses = p.getCourses(); + Assertions.assertEquals( courses.size(), 2 ); + }); + } - @Entity(name = "Person") - public static class Person { + @Entity(name = "Person") + public static class Person { - @Id - @GeneratedValue() - private Long id; - public Long getId() { - return id; - } + @Id + @GeneratedValue() + private Long id; + public Long getId() { + return id; + } - @OneToMany(mappedBy="person", fetch = FetchType.LAZY) - private Set courses = new HashSet<>(); - public Set getCourses() { return courses; } + @OneToMany(mappedBy="person", fetch = FetchType.LAZY) + private Set courses = new HashSet<>(); + public Set getCourses() { return courses; } - } + } - @Entity(name = "Course") - public static class Course { + @Entity(name = "Course") + public static class Course { - @Id - @GeneratedValue() - private Long id; - public Long getId() { return id; } + @Id + @GeneratedValue() + private Long id; + public Long getId() { return id; } - @Basic - private String title; - public String getTitle() { return title; } + @Basic + private String title; + public String getTitle() { return title; } - @ManyToOne(fetch = FetchType.LAZY) - private Person person; - public Person getPerson() { return person; } + @ManyToOne(fetch = FetchType.LAZY) + private Person person; + public Person getPerson() { return person; } - protected Course() {} - public Course(String title, Person person) { - this.title = title; - this.person = person; - } + protected Course() {} + public Course(String title, Person person) { + this.title = title; + this.person = person; + } - @Override - public boolean equals(Object o) { - if ( this == o ) return true; - if ( o == null || getClass() != o.getClass() ) return false; - Course course = (Course) o; - return title.equals( course.title ) && - person.equals( course.person ); - } + @Override + public boolean equals(Object o) { + if ( this == o ) return true; + if ( o == null || getClass() != o.getClass() ) return false; + Course course = (Course) o; + return title.equals( course.title ) && + person.equals( course.person ); + } - @Override - public int hashCode() { - return Objects.hash( title, person ); - } - } + @Override + public int hashCode() { + return Objects.hash( title, person ); + } + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/LazyProxyOnEnhancedEntityTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/LazyProxyOnEnhancedEntityTest.java index b9ee377b03..d127a81658 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/LazyProxyOnEnhancedEntityTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/LazyProxyOnEnhancedEntityTest.java @@ -36,101 +36,101 @@ import jakarta.persistence.Table; */ @JiraKey( "HHH-10922" ) @DomainModel( - annotatedClasses = { - LazyProxyOnEnhancedEntityTest.Parent.class, LazyProxyOnEnhancedEntityTest.Child.class - } + annotatedClasses = { + LazyProxyOnEnhancedEntityTest.Parent.class, LazyProxyOnEnhancedEntityTest.Child.class + } ) @SessionFactory @BytecodeEnhanced @CustomEnhancementContext( {EnhancerTestContext.class, LazyProxyOnEnhancedEntityTest.NoLazyLoadingContext.class} ) public class LazyProxyOnEnhancedEntityTest { - private Long parentID; + private Long parentID; - @BeforeEach - public void prepare(SessionFactoryScope scope) { - scope.inTransaction( em -> { - Child c = new Child(); - em.persist( c ); + @BeforeEach + public void prepare(SessionFactoryScope scope) { + scope.inTransaction( em -> { + Child c = new Child(); + em.persist( c ); - Parent parent = new Parent(); - parent.setChild( c ); - em.persist( parent ); - parentID = parent.getId(); - } ); - } + Parent parent = new Parent(); + parent.setChild( c ); + em.persist( parent ); + parentID = parent.getId(); + } ); + } - @Test - public void test(SessionFactoryScope scope) { - EventListenerRegistry registry = scope.getSessionFactory().getServiceRegistry().getService( EventListenerRegistry.class ); - registry.prependListeners( EventType.LOAD, new ImmediateLoadTrap() ); + @Test + public void test(SessionFactoryScope scope) { + EventListenerRegistry registry = scope.getSessionFactory().getServiceRegistry().getService( EventListenerRegistry.class ); + registry.prependListeners( EventType.LOAD, new ImmediateLoadTrap() ); - scope.inTransaction( em -> { + scope.inTransaction( em -> { - em.find( Parent.class, parentID ); + em.find( Parent.class, parentID ); - // unwanted lazy load occurs on flush - } ); - } + // unwanted lazy load occurs on flush + } ); + } - private static class ImmediateLoadTrap implements LoadEventListener { - @Override - public void onLoad(LoadEvent event, LoadType loadType) throws HibernateException { - if ( IMMEDIATE_LOAD == loadType ) { - String msg = loadType + ":" + event.getEntityClassName() + "#" + event.getEntityId(); - throw new RuntimeException( msg ); - } - } - } + private static class ImmediateLoadTrap implements LoadEventListener { + @Override + public void onLoad(LoadEvent event, LoadType loadType) throws HibernateException { + if ( IMMEDIATE_LOAD == loadType ) { + String msg = loadType + ":" + event.getEntityClassName() + "#" + event.getEntityId(); + throw new RuntimeException( msg ); + } + } + } - // --- // + // --- // - @Entity(name = "Parent") - @Table( name = "PARENT" ) - static class Parent { + @Entity(name = "Parent") + @Table( name = "PARENT" ) + static class Parent { - @Id - @GeneratedValue( strategy = GenerationType.AUTO ) - Long id; + @Id + @GeneratedValue( strategy = GenerationType.AUTO ) + Long id; - @OneToOne( fetch = FetchType.LAZY - ) - Child child; + @OneToOne( fetch = FetchType.LAZY + ) + Child child; - public Long getId() { - return id; - } + public Long getId() { + return id; + } - public Child getChild() { - return child; - } + public Child getChild() { + return child; + } - public void setChild(Child child) { - this.child = child; - } - } + public void setChild(Child child) { + this.child = child; + } + } - @Entity(name = "Child") - @Table( name = "CHILD" ) - static class Child { + @Entity(name = "Child") + @Table( name = "CHILD" ) + static class Child { - @Id - @GeneratedValue( strategy = GenerationType.AUTO ) - Long id; + @Id + @GeneratedValue( strategy = GenerationType.AUTO ) + Long id; - String name; + String name; - Child() { - // No-arg constructor necessary for proxy factory - } - } + Child() { + // No-arg constructor necessary for proxy factory + } + } - // --- // + // --- // - public static class NoLazyLoadingContext extends EnhancerTestContext { - @Override - public boolean hasLazyLoadableAttributes(UnloadedClass classDescriptor) { - return false; - } - } + public static class NoLazyLoadingContext extends EnhancerTestContext { + @Override + public boolean hasLazyLoadableAttributes(UnloadedClass classDescriptor) { + return false; + } + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/LazyProxyWithCollectionTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/LazyProxyWithCollectionTest.java index 3e205bd644..ccc56767df 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/LazyProxyWithCollectionTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/LazyProxyWithCollectionTest.java @@ -34,145 +34,145 @@ import static org.assertj.core.api.Assertions.assertThat; */ @Jira( "https://hibernate.atlassian.net/browse/HHH-14619" ) @DomainModel( - annotatedClasses = { - LazyProxyWithCollectionTest.Parent.class, - LazyProxyWithCollectionTest.Child.class - } + annotatedClasses = { + LazyProxyWithCollectionTest.Parent.class, + LazyProxyWithCollectionTest.Child.class + } ) @SessionFactory @BytecodeEnhanced public class LazyProxyWithCollectionTest { - private Long childId; + private Long childId; - @BeforeEach - public void prepare(SessionFactoryScope scope) { - scope.inTransaction( em -> { - Child c = new Child(); - em.persist( c ); - childId = c.getId(); - } ); - } + @BeforeEach + public void prepare(SessionFactoryScope scope) { + scope.inTransaction( em -> { + Child c = new Child(); + em.persist( c ); + childId = c.getId(); + } ); + } - @Test - public void testReference(SessionFactoryScope scope) { - scope.inTransaction( em -> { - Child child = em.getReference( Child.class, childId ); - Parent parent = new Parent(); - parent.child = child; - em.persist( parent ); - // Class cast exception occurs during auto-flush - em.find( Parent.class, parent.getId() ); - } ); - } + @Test + public void testReference(SessionFactoryScope scope) { + scope.inTransaction( em -> { + Child child = em.getReference( Child.class, childId ); + Parent parent = new Parent(); + parent.child = child; + em.persist( parent ); + // Class cast exception occurs during auto-flush + em.find( Parent.class, parent.getId() ); + } ); + } - @Test - public void testLazyCollection(SessionFactoryScope scope) { - scope.inTransaction( em -> { - Child child = em.find( Child.class, childId ); - Parent parent = new Parent(); - parent.child = child; - em.persist( parent ); - child.children = new HashSet<>(); - // Class cast exception occurs during auto-flush - em.find( Parent.class, parent.getId() ); - } ); - } + @Test + public void testLazyCollection(SessionFactoryScope scope) { + scope.inTransaction( em -> { + Child child = em.find( Child.class, childId ); + Parent parent = new Parent(); + parent.child = child; + em.persist( parent ); + child.children = new HashSet<>(); + // Class cast exception occurs during auto-flush + em.find( Parent.class, parent.getId() ); + } ); + } - @Test - @Jira( "https://hibernate.atlassian.net/browse/HHH-17750" ) - public void testMerge(SessionFactoryScope scope) { - final Child child = scope.fromTransaction( em -> em.find( Child.class, childId ) ); + @Test + @Jira( "https://hibernate.atlassian.net/browse/HHH-17750" ) + public void testMerge(SessionFactoryScope scope) { + final Child child = scope.fromTransaction( em -> em.find( Child.class, childId ) ); - final Parent parent = scope.fromTransaction( em -> { - Parent p = new Parent(); - p.setChild( child ); - return em.merge( p ); - } ); + final Parent parent = scope.fromTransaction( em -> { + Parent p = new Parent(); + p.setChild( child ); + return em.merge( p ); + } ); - scope.inTransaction( em -> em.merge( parent ) ); + scope.inTransaction( em -> em.merge( parent ) ); - scope.inTransaction( em -> { - assertThat( em.find( Parent.class, parent.getId() ).getChild().getId() ).isEqualTo( child.getId() ); - } ); - } + scope.inTransaction( em -> { + assertThat( em.find( Parent.class, parent.getId() ).getChild().getId() ).isEqualTo( child.getId() ); + } ); + } - // --- // + // --- // - @Entity - @Table( name = "PARENT" ) - static class Parent { + @Entity + @Table( name = "PARENT" ) + static class Parent { - @Id - @GeneratedValue( strategy = GenerationType.AUTO ) - Long id; + @Id + @GeneratedValue( strategy = GenerationType.AUTO ) + Long id; - @OneToOne( fetch = FetchType.LAZY ) - Child child; + @OneToOne( fetch = FetchType.LAZY ) + Child child; - public Long getId() { - return id; - } + public Long getId() { + return id; + } - public Child getChild() { - return child; - } + public Child getChild() { + return child; + } - public void setChild(Child child) { - this.child = child; - } - } + public void setChild(Child child) { + this.child = child; + } + } - @Entity - @Table( name = "CHILD" ) - static class Child { + @Entity + @Table( name = "CHILD" ) + static class Child { - @Id - @GeneratedValue( strategy = GenerationType.AUTO ) - Long id; - @Version - Long version; + @Id + @GeneratedValue( strategy = GenerationType.AUTO ) + Long id; + @Version + Long version; - String name; + String name; - @OneToMany - Set children = new HashSet<>(); + @OneToMany + Set children = new HashSet<>(); - Child() { - // No-arg constructor necessary for proxy factory - } + Child() { + // No-arg constructor necessary for proxy factory + } - public Long getId() { - return id; - } + public Long getId() { + return id; + } - public void setId(Long id) { - this.id = id; - } + public void setId(Long id) { + this.id = id; + } - public Long getVersion() { - return version; - } + public Long getVersion() { + return version; + } - public void setVersion(Long version) { - this.version = version; - } + public void setVersion(Long version) { + this.version = version; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - public Set getChildren() { - return children; - } + public Set getChildren() { + return children; + } - public void setChildren(Set children) { - this.children = children; - } - } + public void setChildren(Set children) { + this.children = children; + } + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/MultipleBagsInLazyFetchGroupTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/MultipleBagsInLazyFetchGroupTest.java index 800b8e5c09..713f0d2550 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/MultipleBagsInLazyFetchGroupTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/MultipleBagsInLazyFetchGroupTest.java @@ -30,53 +30,53 @@ import static org.junit.jupiter.api.Assertions.assertTrue; * @author Christian Beikov */ @DomainModel( - annotatedClasses = { - MultipleBagsInLazyFetchGroupTest.StringsEntity.class - } + annotatedClasses = { + MultipleBagsInLazyFetchGroupTest.StringsEntity.class + } ) @SessionFactory @BytecodeEnhanced public class MultipleBagsInLazyFetchGroupTest { - @BeforeEach - public void prepare(SessionFactoryScope scope) { - assertTrue( scope.getSessionFactory().getSessionFactoryOptions().isCollectionsInDefaultFetchGroupEnabled() ); + @BeforeEach + public void prepare(SessionFactoryScope scope) { + assertTrue( scope.getSessionFactory().getSessionFactoryOptions().isCollectionsInDefaultFetchGroupEnabled() ); - scope.inTransaction( em -> { - StringsEntity entity = new StringsEntity(); - entity.id = 1L; - entity.text = "abc"; - entity.someStrings = new ArrayList<>( Arrays.asList( "a", "b", "c" ) ); - entity.someStrings2 = new ArrayList<>( Arrays.asList( "a", "b", "c" ) ); - em.persist( entity ); - } ); - } + scope.inTransaction( em -> { + StringsEntity entity = new StringsEntity(); + entity.id = 1L; + entity.text = "abc"; + entity.someStrings = new ArrayList<>( Arrays.asList( "a", "b", "c" ) ); + entity.someStrings2 = new ArrayList<>( Arrays.asList( "a", "b", "c" ) ); + em.persist( entity ); + } ); + } - @Test - public void test(SessionFactoryScope scope) { - Assertions.assertTrue( scope.getSessionFactory().getSessionFactoryOptions().isCollectionsInDefaultFetchGroupEnabled() ); - scope.inTransaction( entityManager -> { - StringsEntity entity = entityManager.getReference( StringsEntity.class, 1L ); - assertEquals( 3, entity.someStrings.size() ); - assertEquals( 3, entity.someStrings2.size() ); - } ); - } + @Test + public void test(SessionFactoryScope scope) { + Assertions.assertTrue( scope.getSessionFactory().getSessionFactoryOptions().isCollectionsInDefaultFetchGroupEnabled() ); + scope.inTransaction( entityManager -> { + StringsEntity entity = entityManager.getReference( StringsEntity.class, 1L ); + assertEquals( 3, entity.someStrings.size() ); + assertEquals( 3, entity.someStrings2.size() ); + } ); + } - // --- // + // --- // - @Entity - @Table( name = "STRINGS_ENTITY" ) - static class StringsEntity { + @Entity + @Table( name = "STRINGS_ENTITY" ) + static class StringsEntity { - @Id - Long id; + @Id + Long id; - String text; + String text; - @ElementCollection(fetch = FetchType.EAGER) - List someStrings; + @ElementCollection(fetch = FetchType.EAGER) + List someStrings; - @ElementCollection(fetch = FetchType.EAGER) - List someStrings2; - } + @ElementCollection(fetch = FetchType.EAGER) + List someStrings2; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/MultipleBagsNotInLazyFetchGroupTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/MultipleBagsNotInLazyFetchGroupTest.java index 0622783b25..e8528fa766 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/MultipleBagsNotInLazyFetchGroupTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/MultipleBagsNotInLazyFetchGroupTest.java @@ -30,52 +30,52 @@ import static org.junit.jupiter.api.Assertions.assertFalse; * @author Christian Beikov */ @DomainModel( - annotatedClasses = { - MultipleBagsNotInLazyFetchGroupTest.StringsEntity.class - } + annotatedClasses = { + MultipleBagsNotInLazyFetchGroupTest.StringsEntity.class + } ) @SessionFactory(applyCollectionsInDefaultFetchGroup = false) @BytecodeEnhanced public class MultipleBagsNotInLazyFetchGroupTest { - @BeforeEach - public void prepare(SessionFactoryScope scope) { - assertFalse( scope.getSessionFactory().getSessionFactoryOptions().isCollectionsInDefaultFetchGroupEnabled() ); + @BeforeEach + public void prepare(SessionFactoryScope scope) { + assertFalse( scope.getSessionFactory().getSessionFactoryOptions().isCollectionsInDefaultFetchGroupEnabled() ); - scope.inTransaction( em -> { - StringsEntity entity = new StringsEntity(); - entity.id = 1L; - entity.text = "abc"; - entity.someStrings = new ArrayList<>( Arrays.asList( "a", "b", "c" ) ); - entity.someStrings2 = new ArrayList<>( Arrays.asList( "a", "b", "c" ) ); - em.persist( entity ); - } ); - } + scope.inTransaction( em -> { + StringsEntity entity = new StringsEntity(); + entity.id = 1L; + entity.text = "abc"; + entity.someStrings = new ArrayList<>( Arrays.asList( "a", "b", "c" ) ); + entity.someStrings2 = new ArrayList<>( Arrays.asList( "a", "b", "c" ) ); + em.persist( entity ); + } ); + } - @Test - public void test(SessionFactoryScope scope) { - scope.inTransaction( entityManager -> { - StringsEntity entity = entityManager.getReference( StringsEntity.class, 1L ); - assertEquals( 3, entity.someStrings.size() ); - assertEquals( 3, entity.someStrings2.size() ); - } ); - } + @Test + public void test(SessionFactoryScope scope) { + scope.inTransaction( entityManager -> { + StringsEntity entity = entityManager.getReference( StringsEntity.class, 1L ); + assertEquals( 3, entity.someStrings.size() ); + assertEquals( 3, entity.someStrings2.size() ); + } ); + } - // --- // + // --- // - @Entity - @Table(name = "STRINGS_ENTITY") - static class StringsEntity { + @Entity + @Table(name = "STRINGS_ENTITY") + static class StringsEntity { - @Id - Long id; + @Id + Long id; - String text; + String text; - @ElementCollection(fetch = FetchType.EAGER) - List someStrings; + @ElementCollection(fetch = FetchType.EAGER) + List someStrings; - @ElementCollection(fetch = FetchType.EAGER) - List someStrings2; - } + @ElementCollection(fetch = FetchType.EAGER) + List someStrings2; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/basic/LazyBasicFieldAccessTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/basic/LazyBasicFieldAccessTest.java index 9e92cf7470..7ccaceab48 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/basic/LazyBasicFieldAccessTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/basic/LazyBasicFieldAccessTest.java @@ -37,120 +37,120 @@ import static org.junit.jupiter.api.Assertions.assertTrue; * @author Gail Badner */ @DomainModel( - annotatedClasses = { - LazyBasicFieldAccessTest.LazyEntity.class - } + annotatedClasses = { + LazyBasicFieldAccessTest.LazyEntity.class + } ) @ServiceRegistry( - settings = { - @Setting( name = AvailableSettings.USE_SECOND_LEVEL_CACHE, value = "false" ), - @Setting( name = AvailableSettings.ENABLE_LAZY_LOAD_NO_TRANS, value = "true" ), - } + settings = { + @Setting( name = AvailableSettings.USE_SECOND_LEVEL_CACHE, value = "false" ), + @Setting( name = AvailableSettings.ENABLE_LAZY_LOAD_NO_TRANS, value = "true" ), + } ) @SessionFactory @BytecodeEnhanced public class LazyBasicFieldAccessTest { - private LazyEntity entity; + private LazyEntity entity; - private Long entityId; + private Long entityId; - @BeforeEach - public void prepare(SessionFactoryScope scope) { - scope.inTransaction( s -> { - LazyEntity entity = new LazyEntity(); - entity.description = "desc"; - s.persist( entity ); - entityId = entity.id; - } ); - } + @BeforeEach + public void prepare(SessionFactoryScope scope) { + scope.inTransaction( s -> { + LazyEntity entity = new LazyEntity(); + entity.description = "desc"; + s.persist( entity ); + entityId = entity.id; + } ); + } - @Test - public void testAttachedUpdate(SessionFactoryScope scope) { - scope.inTransaction( s -> { - entity = s.get( LazyEntity.class, entityId ); + @Test + public void testAttachedUpdate(SessionFactoryScope scope) { + scope.inTransaction( s -> { + entity = s.get( LazyEntity.class, entityId ); - assertFalse( isPropertyInitialized( entity, "description" ) ); - checkDirtyTracking( entity ); + assertFalse( isPropertyInitialized( entity, "description" ) ); + checkDirtyTracking( entity ); - assertEquals( "desc", entity.description ); - assertTrue( isPropertyInitialized( entity, "description" ) ); - } ); + assertEquals( "desc", entity.description ); + assertTrue( isPropertyInitialized( entity, "description" ) ); + } ); - scope.inTransaction( s -> { - entity = s.get( LazyEntity.class, entityId ); - assertFalse( isPropertyInitialized( entity, "description" ) ); - entity.description = "desc1"; + scope.inTransaction( s -> { + entity = s.get( LazyEntity.class, entityId ); + assertFalse( isPropertyInitialized( entity, "description" ) ); + entity.description = "desc1"; - checkDirtyTracking( entity, "description" ); + checkDirtyTracking( entity, "description" ); - assertEquals( "desc1", entity.description ); - assertTrue( isPropertyInitialized( entity, "description" ) ); - } ); + assertEquals( "desc1", entity.description ); + assertTrue( isPropertyInitialized( entity, "description" ) ); + } ); - scope.inTransaction( s -> { - entity = s.get( LazyEntity.class, entityId ); - assertEquals( "desc1", entity.description ); - } ); - } + scope.inTransaction( s -> { + entity = s.get( LazyEntity.class, entityId ); + assertEquals( "desc1", entity.description ); + } ); + } - @Test - @JiraKey("HHH-11882") - public void testDetachedUpdate(SessionFactoryScope scope) { - scope.inTransaction( s -> { - entity = s.get( LazyEntity.class, entityId ); + @Test + @JiraKey("HHH-11882") + public void testDetachedUpdate(SessionFactoryScope scope) { + scope.inTransaction( s -> { + entity = s.get( LazyEntity.class, entityId ); - assertFalse( isPropertyInitialized( entity, "description" ) ); - checkDirtyTracking( entity ); + assertFalse( isPropertyInitialized( entity, "description" ) ); + checkDirtyTracking( entity ); - assertEquals( "desc", entity.description ); - assertTrue( isPropertyInitialized( entity, "description" ) ); - } ); + assertEquals( "desc", entity.description ); + assertTrue( isPropertyInitialized( entity, "description" ) ); + } ); - scope.inTransaction( s -> { - entity.description = "desc1"; - LazyEntity merged = s.merge( entity ); + scope.inTransaction( s -> { + entity.description = "desc1"; + LazyEntity merged = s.merge( entity ); - checkDirtyTracking( merged, "description" ); + checkDirtyTracking( merged, "description" ); - assertEquals( "desc1", merged.description ); - assertTrue( isPropertyInitialized( merged, "description" ) ); - } ); + assertEquals( "desc1", merged.description ); + assertTrue( isPropertyInitialized( merged, "description" ) ); + } ); - scope.inTransaction( s -> { - entity = s.get( LazyEntity.class, entityId ); - assertEquals( "desc1", entity.description ); - } ); + scope.inTransaction( s -> { + entity = s.get( LazyEntity.class, entityId ); + assertEquals( "desc1", entity.description ); + } ); - scope.inTransaction( s -> { - entity.description = "desc2"; - LazyEntity mergedEntity = s.merge( entity ); + scope.inTransaction( s -> { + entity.description = "desc2"; + LazyEntity mergedEntity = s.merge( entity ); - //Assert.assertFalse( Hibernate.isPropertyInitialized( entity, "description" ) ); - checkDirtyTracking( mergedEntity, "description" ); + //Assert.assertFalse( Hibernate.isPropertyInitialized( entity, "description" ) ); + checkDirtyTracking( mergedEntity, "description" ); - assertEquals( "desc2", mergedEntity.description ); - assertTrue( isPropertyInitialized( mergedEntity, "description" ) ); - } ); + assertEquals( "desc2", mergedEntity.description ); + assertTrue( isPropertyInitialized( mergedEntity, "description" ) ); + } ); - scope.inTransaction( s -> { - entity = s.get( LazyEntity.class, entityId ); - assertEquals( "desc2", entity.description ); - } ); - } + scope.inTransaction( s -> { + entity = s.get( LazyEntity.class, entityId ); + assertEquals( "desc2", entity.description ); + } ); + } - // --- // + // --- // - @Entity - @Access( AccessType.FIELD ) - @Table( name = "LAZY_PROPERTY_ENTITY" ) - static class LazyEntity { + @Entity + @Access( AccessType.FIELD ) + @Table( name = "LAZY_PROPERTY_ENTITY" ) + static class LazyEntity { - @Id - @GeneratedValue - Long id; + @Id + @GeneratedValue + Long id; - @Basic( fetch = FetchType.LAZY ) - String description; - } + @Basic( fetch = FetchType.LAZY ) + String description; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/basic/LazyBasicPropertyAccessTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/basic/LazyBasicPropertyAccessTest.java index 8e64cc3e7b..207670b118 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/basic/LazyBasicPropertyAccessTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/basic/LazyBasicPropertyAccessTest.java @@ -35,132 +35,132 @@ import static org.junit.jupiter.api.Assertions.assertTrue; * @author Gail Badner */ @DomainModel( - annotatedClasses = { - LazyBasicPropertyAccessTest.LazyEntity.class - } + annotatedClasses = { + LazyBasicPropertyAccessTest.LazyEntity.class + } ) @ServiceRegistry( - settings = { - @Setting(name = AvailableSettings.USE_SECOND_LEVEL_CACHE, value = "false"), - @Setting(name = AvailableSettings.ENABLE_LAZY_LOAD_NO_TRANS, value = "true"), - } + settings = { + @Setting(name = AvailableSettings.USE_SECOND_LEVEL_CACHE, value = "false"), + @Setting(name = AvailableSettings.ENABLE_LAZY_LOAD_NO_TRANS, value = "true"), + } ) @SessionFactory @BytecodeEnhanced public class LazyBasicPropertyAccessTest { - private LazyEntity entity; - private Long entityId; + private LazyEntity entity; + private Long entityId; - @BeforeEach - public void prepare(SessionFactoryScope scope) { - scope.inTransaction( s -> { - LazyEntity entity = new LazyEntity(); - entity.setDescription( "desc" ); - s.persist( entity ); - entityId = entity.getId(); - } ); - } + @BeforeEach + public void prepare(SessionFactoryScope scope) { + scope.inTransaction( s -> { + LazyEntity entity = new LazyEntity(); + entity.setDescription( "desc" ); + s.persist( entity ); + entityId = entity.getId(); + } ); + } - @Test - public void testAttachedUpdate(SessionFactoryScope scope) { - scope.inTransaction( s -> { - entity = s.get( LazyEntity.class, entityId ); + @Test + public void testAttachedUpdate(SessionFactoryScope scope) { + scope.inTransaction( s -> { + entity = s.get( LazyEntity.class, entityId ); - assertFalse( isPropertyInitialized( entity, "description" ) ); - checkDirtyTracking( entity ); + assertFalse( isPropertyInitialized( entity, "description" ) ); + checkDirtyTracking( entity ); - assertEquals( "desc", entity.getDescription() ); - assertTrue( isPropertyInitialized( entity, "description" ) ); - } ); + assertEquals( "desc", entity.getDescription() ); + assertTrue( isPropertyInitialized( entity, "description" ) ); + } ); - scope.inTransaction( s -> { - entity = s.get( LazyEntity.class, entityId ); - assertFalse( isPropertyInitialized( entity, "description" ) ); - entity.setDescription( "desc1" ); + scope.inTransaction( s -> { + entity = s.get( LazyEntity.class, entityId ); + assertFalse( isPropertyInitialized( entity, "description" ) ); + entity.setDescription( "desc1" ); - checkDirtyTracking( entity, "description" ); + checkDirtyTracking( entity, "description" ); - assertEquals( "desc1", entity.getDescription() ); - assertTrue( isPropertyInitialized( entity, "description" ) ); - } ); + assertEquals( "desc1", entity.getDescription() ); + assertTrue( isPropertyInitialized( entity, "description" ) ); + } ); - scope.inTransaction( s -> { - entity = s.get( LazyEntity.class, entityId ); - assertEquals( "desc1", entity.getDescription() ); - } ); - } + scope.inTransaction( s -> { + entity = s.get( LazyEntity.class, entityId ); + assertEquals( "desc1", entity.getDescription() ); + } ); + } - @Test - @JiraKey("HHH-11882") - public void testDetachedUpdate(SessionFactoryScope scope) { - scope.inTransaction( s -> { - entity = s.get( LazyEntity.class, entityId ); + @Test + @JiraKey("HHH-11882") + public void testDetachedUpdate(SessionFactoryScope scope) { + scope.inTransaction( s -> { + entity = s.get( LazyEntity.class, entityId ); - assertFalse( isPropertyInitialized( entity, "description" ) ); - checkDirtyTracking( entity ); + assertFalse( isPropertyInitialized( entity, "description" ) ); + checkDirtyTracking( entity ); - assertEquals( "desc", entity.getDescription() ); - assertTrue( isPropertyInitialized( entity, "description" ) ); - } ); + assertEquals( "desc", entity.getDescription() ); + assertTrue( isPropertyInitialized( entity, "description" ) ); + } ); - scope.inTransaction( s -> { - entity.setDescription( "desc1" ); - LazyEntity merged = s.merge( entity ); + scope.inTransaction( s -> { + entity.setDescription( "desc1" ); + LazyEntity merged = s.merge( entity ); - checkDirtyTracking( merged, "description" ); + checkDirtyTracking( merged, "description" ); - assertEquals( "desc1", merged.getDescription() ); - assertTrue( isPropertyInitialized( merged, "description" ) ); - } ); + assertEquals( "desc1", merged.getDescription() ); + assertTrue( isPropertyInitialized( merged, "description" ) ); + } ); - scope.inTransaction( s -> { - entity = s.get( LazyEntity.class, entityId ); - assertEquals( "desc1", entity.getDescription() ); - } ); + scope.inTransaction( s -> { + entity = s.get( LazyEntity.class, entityId ); + assertEquals( "desc1", entity.getDescription() ); + } ); - scope.inTransaction( s -> { - entity.setDescription( "desc2" ); - LazyEntity mergedEntity = s.merge( entity ); + scope.inTransaction( s -> { + entity.setDescription( "desc2" ); + LazyEntity mergedEntity = s.merge( entity ); - // Assert.assertFalse( isPropertyInitialized( entity, "description" ) ); - checkDirtyTracking( mergedEntity, "description" ); + // Assert.assertFalse( isPropertyInitialized( entity, "description" ) ); + checkDirtyTracking( mergedEntity, "description" ); - assertEquals( "desc2", mergedEntity.getDescription() ); - assertTrue( isPropertyInitialized( mergedEntity, "description" ) ); - } ); + assertEquals( "desc2", mergedEntity.getDescription() ); + assertTrue( isPropertyInitialized( mergedEntity, "description" ) ); + } ); - scope.inTransaction( s -> { - entity = s.get( LazyEntity.class, entityId ); - assertEquals( "desc2", entity.getDescription() ); - } ); - } + scope.inTransaction( s -> { + entity = s.get( LazyEntity.class, entityId ); + assertEquals( "desc2", entity.getDescription() ); + } ); + } - // --- // + // --- // - @Entity - @Table( name = "LAZY_FIELD_ENTITY" ) - static class LazyEntity { - Long id; - String description; + @Entity + @Table( name = "LAZY_FIELD_ENTITY" ) + static class LazyEntity { + Long id; + String description; - @Id - @GeneratedValue - Long getId() { - return id; - } + @Id + @GeneratedValue + Long getId() { + return id; + } - void setId(Long id) { - this.id = id; - } + void setId(Long id) { + this.id = id; + } - @Basic( fetch = FetchType.LAZY ) - String getDescription() { - return description; - } + @Basic( fetch = FetchType.LAZY ) + String getDescription() { + return description; + } - void setDescription(String description) { - this.description = description; - } - } + void setDescription(String description) { + this.description = description; + } + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/cache/LazyInCacheTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/cache/LazyInCacheTest.java index 11f7c07b50..46d263b68b 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/cache/LazyInCacheTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/cache/LazyInCacheTest.java @@ -40,94 +40,94 @@ import static org.junit.jupiter.api.Assertions.assertEquals; * @author Luis Barreiro */ @DomainModel( - annotatedClasses = { - LazyInCacheTest.Order.class, LazyInCacheTest.Product.class, LazyInCacheTest.Tag.class - } + annotatedClasses = { + LazyInCacheTest.Order.class, LazyInCacheTest.Product.class, LazyInCacheTest.Tag.class + } ) @ServiceRegistry( - settings = { - @Setting( name = AvailableSettings.USE_SECOND_LEVEL_CACHE, value = "false" ), - @Setting( name = AvailableSettings.ENABLE_LAZY_LOAD_NO_TRANS, value = "true" ), - } + settings = { + @Setting( name = AvailableSettings.USE_SECOND_LEVEL_CACHE, value = "false" ), + @Setting( name = AvailableSettings.ENABLE_LAZY_LOAD_NO_TRANS, value = "true" ), + } ) @SessionFactory @BytecodeEnhanced public class LazyInCacheTest { - private Long orderId; + private Long orderId; - @BeforeEach - public void prepare(SessionFactoryScope scope) { - Order order = new Order(); - Product product = new Product(); - order.products.add( product ); - order.data = "some data".getBytes( Charset.defaultCharset() ); + @BeforeEach + public void prepare(SessionFactoryScope scope) { + Order order = new Order(); + Product product = new Product(); + order.products.add( product ); + order.data = "some data".getBytes( Charset.defaultCharset() ); - scope.inTransaction( em -> { - em.persist( product ); - em.persist( order ); - } ); + scope.inTransaction( em -> { + em.persist( product ); + em.persist( order ); + } ); - orderId = order.id; - } + orderId = order.id; + } - @Test - public void test(SessionFactoryScope scope) { - scope.inTransaction( em -> { - Order order = em.find( Order.class, orderId ); - assertEquals( 1, order.products.size() ); - } ); - } + @Test + public void test(SessionFactoryScope scope) { + scope.inTransaction( em -> { + Order order = em.find( Order.class, orderId ); + assertEquals( 1, order.products.size() ); + } ); + } - // --- // + // --- // - @Entity(name = "Order") - @Table( name = "ORDER_TABLE" ) - @Cache( usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE ) - static class Order { + @Entity(name = "Order") + @Table( name = "ORDER_TABLE" ) + @Cache( usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE ) + static class Order { - @Id - @GeneratedValue( strategy = GenerationType.AUTO ) - Long id; + @Id + @GeneratedValue( strategy = GenerationType.AUTO ) + Long id; - @OneToMany - List products = new ArrayList<>(); + @OneToMany + List products = new ArrayList<>(); - @OneToMany - List tags = new ArrayList<>(); + @OneToMany + List tags = new ArrayList<>(); - @Basic( fetch = FetchType.LAZY ) - @Type( BinaryCustomType.class ) + @Basic( fetch = FetchType.LAZY ) + @Type( BinaryCustomType.class ) // @JdbcTypeCode(Types.LONGVARBINARY) - byte[] data; - } + byte[] data; + } - @Entity(name = "Product") - @Table( name = "PRODUCT" ) - static class Product { + @Entity(name = "Product") + @Table( name = "PRODUCT" ) + static class Product { - @Id - @GeneratedValue( strategy = GenerationType.AUTO ) - Long id; + @Id + @GeneratedValue( strategy = GenerationType.AUTO ) + Long id; - String name; - } + String name; + } - @Entity(name = "Tag") - @Table( name = "TAG" ) - static class Tag { + @Entity(name = "Tag") + @Table( name = "TAG" ) + static class Tag { - @Id - @GeneratedValue( strategy = GenerationType.AUTO ) - Long id; + @Id + @GeneratedValue( strategy = GenerationType.AUTO ) + Long id; - String name; - } + String name; + } - public static class BinaryCustomType extends UserTypeLegacyBridge { - public BinaryCustomType() { - super( "binary" ); - } - } + public static class BinaryCustomType extends UserTypeLegacyBridge { + public BinaryCustomType() { + super( "binary" ); + } + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/group/LazyGroupTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/group/LazyGroupTest.java index c967e95850..08fd2dc4b8 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/group/LazyGroupTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/group/LazyGroupTest.java @@ -47,239 +47,239 @@ import static org.junit.jupiter.api.Assertions.assertTrue; @SuppressWarnings("JUnitMalformedDeclaration") @JiraKey( "HHH-11155" ) @DomainModel( - annotatedClasses = { - LazyGroupTest.Child.class, LazyGroupTest.Parent.class - } + annotatedClasses = { + LazyGroupTest.Child.class, LazyGroupTest.Parent.class + } ) @ServiceRegistry( - settings = { - @Setting( name = AvailableSettings.USE_SECOND_LEVEL_CACHE, value = "false" ), - @Setting( name = AvailableSettings.ENABLE_LAZY_LOAD_NO_TRANS, value = "true" ), - } + settings = { + @Setting( name = AvailableSettings.USE_SECOND_LEVEL_CACHE, value = "false" ), + @Setting( name = AvailableSettings.ENABLE_LAZY_LOAD_NO_TRANS, value = "true" ), + } ) @SessionFactory @BytecodeEnhanced public class LazyGroupTest { - @BeforeEach - public void prepare(SessionFactoryScope scope) { - scope.inTransaction( s -> { - Child c1 = new Child( "steve", "Hibernater" ); - Child c2 = new Child( "sally", "Joe Mama" ); + @BeforeEach + public void prepare(SessionFactoryScope scope) { + scope.inTransaction( s -> { + Child c1 = new Child( "steve", "Hibernater" ); + Child c2 = new Child( "sally", "Joe Mama" ); - Parent p1 = new Parent( "Hibernate" ); - Parent p2 = new Parent( "Swimming" ); + Parent p1 = new Parent( "Hibernate" ); + Parent p2 = new Parent( "Swimming" ); - c1.parent = p1; - p1.children.add( c1 ); + c1.parent = p1; + p1.children.add( c1 ); - c1.alternateParent = p2; - p2.alternateChildren.add( c1 ); + c1.alternateParent = p2; + p2.alternateChildren.add( c1 ); - c2.parent = p2; - p2.children.add( c2 ); + c2.parent = p2; + p2.children.add( c2 ); - c2.alternateParent = p1; - p1.alternateChildren.add( c2 ); + c2.alternateParent = p1; + p1.alternateChildren.add( c2 ); - s.persist( p1 ); - s.persist( p2 ); - } ); - } + s.persist( p1 ); + s.persist( p2 ); + } ); + } - @Test - @JiraKey( "HHH-10267" ) - public void testAccess(SessionFactoryScope scope) { - scope.inTransaction( - (s) -> { - SQLStatementInspector statementInspector = (SQLStatementInspector) scope.getSessionFactory() - .getSessionFactoryOptions() - .getStatementInspector(); - statementInspector.clear(); + @Test + @JiraKey( "HHH-10267" ) + public void testAccess(SessionFactoryScope scope) { + scope.inTransaction( + (s) -> { + SQLStatementInspector statementInspector = (SQLStatementInspector) scope.getSessionFactory() + .getSessionFactoryOptions() + .getStatementInspector(); + statementInspector.clear(); - final Child c1 = s.createQuery( "from Child c where c.name = :name", Child.class ) - .setParameter( "name", "steve" ) - .uniqueResult(); + final Child c1 = s.createQuery( "from Child c where c.name = :name", Child.class ) + .setParameter( "name", "steve" ) + .uniqueResult(); - statementInspector.assertExecutedCount( 1 ); + statementInspector.assertExecutedCount( 1 ); - assertTrue( Hibernate.isPropertyInitialized( c1, "name" ) ); + assertTrue( Hibernate.isPropertyInitialized( c1, "name" ) ); - assertFalse( Hibernate.isPropertyInitialized( c1, "nickName" ) ); + assertFalse( Hibernate.isPropertyInitialized( c1, "nickName" ) ); - // parent should be an uninitialized enhanced-proxy - assertTrue( Hibernate.isPropertyInitialized( c1, "parent" ) ); - assertThat( c1.getParent() ).isNotInstanceOf( HibernateProxy.class ); - assertFalse( Hibernate.isInitialized( c1.getParent() ) ); + // parent should be an uninitialized enhanced-proxy + assertTrue( Hibernate.isPropertyInitialized( c1, "parent" ) ); + assertThat( c1.getParent() ).isNotInstanceOf( HibernateProxy.class ); + assertFalse( Hibernate.isInitialized( c1.getParent() ) ); - // alternateParent should be an uninitialized enhanced-proxy - assertTrue( Hibernate.isPropertyInitialized( c1, "alternateParent" ) ); - assertThat( c1.getAlternateParent() ).isNotInstanceOf( HibernateProxy.class ); - assertFalse( Hibernate.isInitialized( c1.getAlternateParent() ) ); + // alternateParent should be an uninitialized enhanced-proxy + assertTrue( Hibernate.isPropertyInitialized( c1, "alternateParent" ) ); + assertThat( c1.getAlternateParent() ).isNotInstanceOf( HibernateProxy.class ); + assertFalse( Hibernate.isInitialized( c1.getAlternateParent() ) ); - // Now lets access nickName which ought to initialize nickName - c1.getNickName(); - statementInspector.assertExecutedCount( 2 ); + // Now lets access nickName which ought to initialize nickName + c1.getNickName(); + statementInspector.assertExecutedCount( 2 ); - assertTrue( Hibernate.isPropertyInitialized( c1, "nickName" ) ); + assertTrue( Hibernate.isPropertyInitialized( c1, "nickName" ) ); - // parent should be an uninitialized enhanced-proxy - assertTrue( Hibernate.isPropertyInitialized( c1, "parent" ) ); - assertThat( c1.getParent() ).isNotInstanceOf( HibernateProxy.class ); - assertFalse( Hibernate.isInitialized( c1.getParent() ) ); + // parent should be an uninitialized enhanced-proxy + assertTrue( Hibernate.isPropertyInitialized( c1, "parent" ) ); + assertThat( c1.getParent() ).isNotInstanceOf( HibernateProxy.class ); + assertFalse( Hibernate.isInitialized( c1.getParent() ) ); - // alternateParent should be an uninitialized enhanced-proxy - assertTrue( Hibernate.isPropertyInitialized( c1, "alternateParent" ) ); - assertThat( c1.getAlternateParent() ).isNotInstanceOf( HibernateProxy.class ); - assertFalse( Hibernate.isInitialized( c1.getAlternateParent() ) ); - } - ); - } + // alternateParent should be an uninitialized enhanced-proxy + assertTrue( Hibernate.isPropertyInitialized( c1, "alternateParent" ) ); + assertThat( c1.getAlternateParent() ).isNotInstanceOf( HibernateProxy.class ); + assertFalse( Hibernate.isInitialized( c1.getAlternateParent() ) ); + } + ); + } - @Test - @JiraKey( "HHH-11155" ) - public void testUpdate(SessionFactoryScope scope) { - Parent p1New = new Parent(); - p1New.nombre = "p1New"; + @Test + @JiraKey( "HHH-11155" ) + public void testUpdate(SessionFactoryScope scope) { + Parent p1New = new Parent(); + p1New.nombre = "p1New"; - scope.inTransaction( - (s) -> { - SQLStatementInspector statementInspector = (SQLStatementInspector) scope.getSessionFactory() - .getSessionFactoryOptions() - .getStatementInspector(); - statementInspector.clear(); + scope.inTransaction( + (s) -> { + SQLStatementInspector statementInspector = (SQLStatementInspector) scope.getSessionFactory() + .getSessionFactoryOptions() + .getStatementInspector(); + statementInspector.clear(); - final Child c1 = s.createQuery( "from Child c where c.name = :name", Child.class ) - .setParameter( "name", "steve" ) - .uniqueResult(); - statementInspector.assertExecutedCount( 1 ); + final Child c1 = s.createQuery( "from Child c where c.name = :name", Child.class ) + .setParameter( "name", "steve" ) + .uniqueResult(); + statementInspector.assertExecutedCount( 1 ); - assertTrue( Hibernate.isPropertyInitialized( c1, "name" ) ); + assertTrue( Hibernate.isPropertyInitialized( c1, "name" ) ); - assertFalse( Hibernate.isPropertyInitialized( c1, "nickName" ) ); + assertFalse( Hibernate.isPropertyInitialized( c1, "nickName" ) ); - // parent should be an uninitialized enhanced-proxy - assertTrue( Hibernate.isPropertyInitialized( c1, "parent" ) ); - assertThat( c1.getParent() ).isNotInstanceOf( HibernateProxy.class ); - assertFalse( Hibernate.isInitialized( c1.getParent() ) ); + // parent should be an uninitialized enhanced-proxy + assertTrue( Hibernate.isPropertyInitialized( c1, "parent" ) ); + assertThat( c1.getParent() ).isNotInstanceOf( HibernateProxy.class ); + assertFalse( Hibernate.isInitialized( c1.getParent() ) ); - // alternateParent should be an uninitialized enhanced-proxy - assertTrue( Hibernate.isPropertyInitialized( c1, "alternateParent" ) ); - assertThat( c1.getAlternateParent() ).isNotInstanceOf( HibernateProxy.class ); - assertFalse( Hibernate.isInitialized( c1.getAlternateParent() ) ); + // alternateParent should be an uninitialized enhanced-proxy + assertTrue( Hibernate.isPropertyInitialized( c1, "alternateParent" ) ); + assertThat( c1.getAlternateParent() ).isNotInstanceOf( HibernateProxy.class ); + assertFalse( Hibernate.isInitialized( c1.getAlternateParent() ) ); - // Now lets update nickName - c1.nickName = "new nickName"; + // Now lets update nickName + c1.nickName = "new nickName"; - statementInspector.assertExecutedCount( 1 ); + statementInspector.assertExecutedCount( 1 ); - assertTrue( Hibernate.isPropertyInitialized( c1, "name" ) ); + assertTrue( Hibernate.isPropertyInitialized( c1, "name" ) ); - assertTrue( Hibernate.isPropertyInitialized( c1, "nickName" ) ); + assertTrue( Hibernate.isPropertyInitialized( c1, "nickName" ) ); - // parent should be an uninitialized enhanced-proxy - assertTrue( Hibernate.isPropertyInitialized( c1, "parent" ) ); - assertThat( c1.getParent() ).isNotInstanceOf( HibernateProxy.class ); - assertFalse( Hibernate.isInitialized( c1.getParent() ) ); + // parent should be an uninitialized enhanced-proxy + assertTrue( Hibernate.isPropertyInitialized( c1, "parent" ) ); + assertThat( c1.getParent() ).isNotInstanceOf( HibernateProxy.class ); + assertFalse( Hibernate.isInitialized( c1.getParent() ) ); - // alternateParent should be an uninitialized enhanced-proxy - assertTrue( Hibernate.isPropertyInitialized( c1, "alternateParent" ) ); - assertThat( c1.getAlternateParent() ).isNotInstanceOf( HibernateProxy.class ); - assertFalse( Hibernate.isInitialized( c1.getAlternateParent() ) ); + // alternateParent should be an uninitialized enhanced-proxy + assertTrue( Hibernate.isPropertyInitialized( c1, "alternateParent" ) ); + assertThat( c1.getAlternateParent() ).isNotInstanceOf( HibernateProxy.class ); + assertFalse( Hibernate.isInitialized( c1.getAlternateParent() ) ); - // Now update c1.parent - c1.parent.children.remove( c1 ); - c1.parent = p1New; - p1New.children.add( c1 ); - } - ); + // Now update c1.parent + c1.parent.children.remove( c1 ); + c1.parent = p1New; + p1New.children.add( c1 ); + } + ); - // verify updates - scope.inTransaction( - (s) -> { - final Child c1 = s.createQuery( "from Child c where c.name = :name", Child.class ) - .setParameter( "name", "steve" ) - .uniqueResult(); + // verify updates + scope.inTransaction( + (s) -> { + final Child c1 = s.createQuery( "from Child c where c.name = :name", Child.class ) + .setParameter( "name", "steve" ) + .uniqueResult(); - assertThat( c1.getNickName() ).isEqualTo( "new nickName" ); - assertThat( c1.parent.nombre ).isEqualTo( "p1New" ); - } - ); - } + assertThat( c1.getNickName() ).isEqualTo( "new nickName" ); + assertThat( c1.parent.nombre ).isEqualTo( "p1New" ); + } + ); + } - @AfterEach - public void cleanup(SessionFactoryScope scope) { - scope.inTransaction( s -> { - s.createQuery( "delete Child" ).executeUpdate(); - s.createQuery( "delete Parent" ).executeUpdate(); - } ); - } + @AfterEach + public void cleanup(SessionFactoryScope scope) { + scope.inTransaction( s -> { + s.createQuery( "delete Child" ).executeUpdate(); + s.createQuery( "delete Parent" ).executeUpdate(); + } ); + } - // --- // + // --- // - // --- // + // --- // - @Entity( name = "Parent" ) - @Table( name = "PARENT" ) - static class Parent { - @Id - @GeneratedValue( strategy = GenerationType.AUTO ) - Long id; + @Entity( name = "Parent" ) + @Table( name = "PARENT" ) + static class Parent { + @Id + @GeneratedValue( strategy = GenerationType.AUTO ) + Long id; - String nombre; + String nombre; - @OneToMany( mappedBy = "parent", cascade = CascadeType.ALL, fetch = FetchType.LAZY ) - List children = new ArrayList<>(); + @OneToMany( mappedBy = "parent", cascade = CascadeType.ALL, fetch = FetchType.LAZY ) + List children = new ArrayList<>(); - @OneToMany( mappedBy = "alternateParent", cascade = CascadeType.ALL, fetch = FetchType.LAZY ) - List alternateChildren = new ArrayList<>(); + @OneToMany( mappedBy = "alternateParent", cascade = CascadeType.ALL, fetch = FetchType.LAZY ) + List alternateChildren = new ArrayList<>(); - Parent() { - } + Parent() { + } - Parent(String nombre) { - this.nombre = nombre; - } - } + Parent(String nombre) { + this.nombre = nombre; + } + } - @Entity( name = "Child" ) - @Table( name = "CHILD" ) - static class Child { + @Entity( name = "Child" ) + @Table( name = "CHILD" ) + static class Child { - @Id - @GeneratedValue( strategy = GenerationType.AUTO ) - Long id; + @Id + @GeneratedValue( strategy = GenerationType.AUTO ) + Long id; - String name; + String name; - @Basic( fetch = FetchType.LAZY ) - String nickName; + @Basic( fetch = FetchType.LAZY ) + String nickName; - @ManyToOne( cascade = CascadeType.ALL, fetch = FetchType.LAZY ) - Parent parent; + @ManyToOne( cascade = CascadeType.ALL, fetch = FetchType.LAZY ) + Parent parent; - @ManyToOne( cascade = CascadeType.ALL, fetch = FetchType.LAZY ) - @LazyGroup( "SECONDARY" ) - Parent alternateParent; + @ManyToOne( cascade = CascadeType.ALL, fetch = FetchType.LAZY ) + @LazyGroup( "SECONDARY" ) + Parent alternateParent; - Child() { - } + Child() { + } - Child(String name, String nickName) { - this.name = name; - this.nickName = nickName; - } + Child(String name, String nickName) { + this.name = name; + this.nickName = nickName; + } - public Parent getParent() { - return parent; - } + public Parent getParent() { + return parent; + } - Parent getAlternateParent() { - return alternateParent; - } + Parent getAlternateParent() { + return alternateParent; + } - String getNickName() { - return nickName; - } - } + String getNickName() { + return nickName; + } + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/group/SimpleLazyGroupUpdateTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/group/SimpleLazyGroupUpdateTest.java index 1ccc924e5d..eccd0e88f7 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/group/SimpleLazyGroupUpdateTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/group/SimpleLazyGroupUpdateTest.java @@ -40,111 +40,111 @@ import static org.junit.jupiter.api.Assertions.assertNull; @JiraKey("HHH-11155") @JiraKey("HHH-11506") @DomainModel( - annotatedClasses = { - SimpleLazyGroupUpdateTest.TestEntity.class - } + annotatedClasses = { + SimpleLazyGroupUpdateTest.TestEntity.class + } ) @ServiceRegistry( - settings = { - @Setting(name = AvailableSettings.USE_SECOND_LEVEL_CACHE, value = "false"), - @Setting(name = AvailableSettings.ENABLE_LAZY_LOAD_NO_TRANS, value = "true"), - } + settings = { + @Setting(name = AvailableSettings.USE_SECOND_LEVEL_CACHE, value = "false"), + @Setting(name = AvailableSettings.ENABLE_LAZY_LOAD_NO_TRANS, value = "true"), + } ) @SessionFactory @BytecodeEnhanced @CustomEnhancementContext({ EnhancerTestContext.class, SimpleLazyGroupUpdateTest.NoDirtyCheckingContext.class }) public class SimpleLazyGroupUpdateTest { - public static final String REALLY_BIG_STRING = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; + public static final String REALLY_BIG_STRING = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; - @BeforeEach - public void prepare(SessionFactoryScope scope) { - scope.inTransaction( s -> { - s.persist( new TestEntity( 1L, "entity 1", "blah", REALLY_BIG_STRING ) ); - } ); - } + @BeforeEach + public void prepare(SessionFactoryScope scope) { + scope.inTransaction( s -> { + s.persist( new TestEntity( 1L, "entity 1", "blah", REALLY_BIG_STRING ) ); + } ); + } - @Test - public void test(SessionFactoryScope scope) { - scope.inTransaction( s -> { - TestEntity entity = s.get( TestEntity.class, 1L ); - assertLoaded( entity, "name" ); - assertNotLoaded( entity, "lifeStory" ); - assertNotLoaded( entity, "reallyBigString" ); + @Test + public void test(SessionFactoryScope scope) { + scope.inTransaction( s -> { + TestEntity entity = s.get( TestEntity.class, 1L ); + assertLoaded( entity, "name" ); + assertNotLoaded( entity, "lifeStory" ); + assertNotLoaded( entity, "reallyBigString" ); - entity.lifeStory = "blah blah blah"; - assertLoaded( entity, "name" ); - assertLoaded( entity, "lifeStory" ); - assertNotLoaded( entity, "reallyBigString" ); - } ); + entity.lifeStory = "blah blah blah"; + assertLoaded( entity, "name" ); + assertLoaded( entity, "lifeStory" ); + assertNotLoaded( entity, "reallyBigString" ); + } ); - scope.inTransaction( s -> { - TestEntity entity = s.get( TestEntity.class, 1L ); + scope.inTransaction( s -> { + TestEntity entity = s.get( TestEntity.class, 1L ); - assertLoaded( entity, "name" ); - assertNotLoaded( entity, "lifeStory" ); - assertNotLoaded( entity, "reallyBigString" ); - assertEquals( "blah blah blah", entity.lifeStory ); - assertEquals( REALLY_BIG_STRING, entity.reallyBigString ); - } ); - } + assertLoaded( entity, "name" ); + assertNotLoaded( entity, "lifeStory" ); + assertNotLoaded( entity, "reallyBigString" ); + assertEquals( "blah blah blah", entity.lifeStory ); + assertEquals( REALLY_BIG_STRING, entity.reallyBigString ); + } ); + } - private void assertLoaded(Object owner, String name) { - // NOTE we assume null == not-loaded - Object fieldByReflection = getFieldByReflection( owner, name ); - assertNotNull( fieldByReflection, "Expecting field '" + name + "' to be loaded, but it was not" ); - } + private void assertLoaded(Object owner, String name) { + // NOTE we assume null == not-loaded + Object fieldByReflection = getFieldByReflection( owner, name ); + assertNotNull( fieldByReflection, "Expecting field '" + name + "' to be loaded, but it was not" ); + } - private void assertNotLoaded(Object owner, String name) { - // NOTE we assume null == not-loaded - Object fieldByReflection = getFieldByReflection( owner, name ); - assertNull( fieldByReflection, "Expecting field '" + name + "' to be not loaded, but it was" ); - } + private void assertNotLoaded(Object owner, String name) { + // NOTE we assume null == not-loaded + Object fieldByReflection = getFieldByReflection( owner, name ); + assertNull( fieldByReflection, "Expecting field '" + name + "' to be not loaded, but it was" ); + } - @AfterEach - public void cleanup(SessionFactoryScope scope) { - scope.inTransaction( s -> { - s.createQuery( "delete TestEntity" ).executeUpdate(); - } ); - } + @AfterEach + public void cleanup(SessionFactoryScope scope) { + scope.inTransaction( s -> { + s.createQuery( "delete TestEntity" ).executeUpdate(); + } ); + } - // --- // + // --- // - @Entity( name = "TestEntity" ) - @Table( name = "TEST_ENTITY" ) - static class TestEntity { + @Entity( name = "TestEntity" ) + @Table( name = "TEST_ENTITY" ) + static class TestEntity { - @Id - Long id; + @Id + Long id; - String name; + String name; - @Basic( fetch = FetchType.LAZY ) - @LazyGroup( "grp1" ) - String lifeStory; + @Basic( fetch = FetchType.LAZY ) + @LazyGroup( "grp1" ) + String lifeStory; - @Basic( fetch = FetchType.LAZY ) - @LazyGroup( "grp2" ) - String reallyBigString; + @Basic( fetch = FetchType.LAZY ) + @LazyGroup( "grp2" ) + String reallyBigString; - TestEntity() { - } + TestEntity() { + } - TestEntity(Long id, String name, String lifeStory, String reallyBigString) { - this.id = id; - this.name = name; - this.lifeStory = lifeStory; - this.reallyBigString = reallyBigString; - } - } + TestEntity(Long id, String name, String lifeStory, String reallyBigString) { + this.id = id; + this.name = name; + this.lifeStory = lifeStory; + this.reallyBigString = reallyBigString; + } + } - // --- // + // --- // - public static class NoDirtyCheckingContext extends EnhancerTestContext { + public static class NoDirtyCheckingContext extends EnhancerTestContext { - @Override - public boolean doDirtyCheckingInline(UnloadedClass classDescriptor) { - return false; - } - } + @Override + public boolean doDirtyCheckingInline(UnloadedClass classDescriptor) { + return false; + } + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/proxy/LazyToOnesNoProxyFactoryWithSubclassesStatefulTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/proxy/LazyToOnesNoProxyFactoryWithSubclassesStatefulTest.java index a39b1b9e82..b5855303fb 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/proxy/LazyToOnesNoProxyFactoryWithSubclassesStatefulTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/proxy/LazyToOnesNoProxyFactoryWithSubclassesStatefulTest.java @@ -193,7 +193,7 @@ public class LazyToOnesNoProxyFactoryWithSubclassesStatefulTest { @Entity(name = "Animal") @Table(name = "Animal") @Inheritance(strategy = InheritanceType.TABLE_PER_CLASS) - public static abstract class Animal { + public static abstract class Animal { @Id private String name; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/proxy/LazyToOnesNoProxyFactoryWithSubclassesStatelessTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/proxy/LazyToOnesNoProxyFactoryWithSubclassesStatelessTest.java index a660530562..114f08b75a 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/proxy/LazyToOnesNoProxyFactoryWithSubclassesStatelessTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/proxy/LazyToOnesNoProxyFactoryWithSubclassesStatelessTest.java @@ -193,7 +193,7 @@ public class LazyToOnesNoProxyFactoryWithSubclassesStatelessTest { @Entity(name = "Animal") @Table(name = "Animal") @Inheritance(strategy = InheritanceType.TABLE_PER_CLASS) - public static abstract class Animal { + public static abstract class Animal { @Id private String name; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/proxy/crosspackage/base/BaseEntity.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/proxy/crosspackage/base/BaseEntity.java index 40331dea45..05bea11e4d 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/proxy/crosspackage/base/BaseEntity.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/proxy/crosspackage/base/BaseEntity.java @@ -14,26 +14,26 @@ import jakarta.persistence.MappedSuperclass; @MappedSuperclass public abstract class BaseEntity { - @Id - @GeneratedValue - private Long id; + @Id + @GeneratedValue + private Long id; - @Embedded - protected EmbeddableType embeddedField; + @Embedded + protected EmbeddableType embeddedField; - public Long getId() { - return id; - } + public Long getId() { + return id; + } - public void setId(final Long id) { - this.id = id; - } + public void setId(final Long id) { + this.id = id; + } - public EmbeddableType getEmbeddedField() { - return embeddedField; - } + public EmbeddableType getEmbeddedField() { + return embeddedField; + } - public void setEmbeddedField(final EmbeddableType embeddedField) { - this.embeddedField = embeddedField; - } + public void setEmbeddedField(final EmbeddableType embeddedField) { + this.embeddedField = embeddedField; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/proxy/crosspackage/base/EmbeddableType.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/proxy/crosspackage/base/EmbeddableType.java index 27ad53df24..fc8f8356fa 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/proxy/crosspackage/base/EmbeddableType.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/proxy/crosspackage/base/EmbeddableType.java @@ -12,14 +12,14 @@ import jakarta.persistence.Embeddable; @Embeddable public class EmbeddableType { - @Column - private String field; + @Column + private String field; - public String getField() { - return field; - } + public String getField() { + return field; + } - public void setField(final String field) { - this.field = field; - } + public void setField(final String field) { + this.field = field; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/proxy/inlinedirtychecking/LoadUninitializedCollectionTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/proxy/inlinedirtychecking/LoadUninitializedCollectionTest.java index cec36c1cd6..48af72ef64 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/proxy/inlinedirtychecking/LoadUninitializedCollectionTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/proxy/inlinedirtychecking/LoadUninitializedCollectionTest.java @@ -81,50 +81,50 @@ public class LoadUninitializedCollectionTest { @Test public void testLoadAfterNativeQueryExecution(SessionFactoryScope scope) { scope.inTransaction( entityManager -> { - BankAccount account = entityManager.find( BankAccount.class, 1L ); + BankAccount account = entityManager.find( BankAccount.class, 1L ); - Query nativeQuery = entityManager.createNativeQuery( "SELECT ID FROM BANK" ); - nativeQuery.getResultList(); + Query nativeQuery = entityManager.createNativeQuery( "SELECT ID FROM BANK" ); + nativeQuery.getResultList(); - Bank bank = account.getBank(); - List deps = bank.getDepartments(); + Bank bank = account.getBank(); + List deps = bank.getDepartments(); - assertEquals( deps.size(), 3 ); - } + assertEquals( deps.size(), 3 ); + } ); } @Test public void testLoadAfterFlush(SessionFactoryScope scope) { scope.inTransaction( entityManager -> { - BankAccount account = entityManager.find( BankAccount.class, 1L ); + BankAccount account = entityManager.find( BankAccount.class, 1L ); - entityManager.flush(); + entityManager.flush(); - Bank bank = account.getBank(); - List deps = bank.getDepartments(); + Bank bank = account.getBank(); + List deps = bank.getDepartments(); - assertEquals( deps.size(), 3 ); - } + assertEquals( deps.size(), 3 ); + } ); } @AfterEach public void tearDown(SessionFactoryScope scope) { scope.inTransaction( entityManager -> { - Bank bank = entityManager.find( Bank.class, 1L ); - bank.getDepartments().forEach( - department -> entityManager.remove( department ) - ); - bank.getDepartments().clear(); - List accounts = entityManager.createQuery( "from BankAccount" ).getResultList(); + Bank bank = entityManager.find( Bank.class, 1L ); + bank.getDepartments().forEach( + department -> entityManager.remove( department ) + ); + bank.getDepartments().clear(); + List accounts = entityManager.createQuery( "from BankAccount" ).getResultList(); - accounts.forEach( - account -> entityManager.remove( account ) - ); + accounts.forEach( + account -> entityManager.remove( account ) + ); - entityManager.remove( bank ); - } + entityManager.remove( bank ); + } ); } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazyCache/InitFromCacheTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazyCache/InitFromCacheTest.java index b4b23bd8ca..3bc06fb893 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazyCache/InitFromCacheTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazyCache/InitFromCacheTest.java @@ -50,52 +50,52 @@ import static org.junit.jupiter.api.Assertions.assertTrue; * @author Steve EbersolenPropertyRefTest */ @DomainModel( - annotatedClasses = { - InitFromCacheTest.Document.class - } + annotatedClasses = { + InitFromCacheTest.Document.class + } ) @ServiceRegistry( - settings = { - @Setting( name = AvailableSettings.USE_SECOND_LEVEL_CACHE, value = "true" ), - @Setting( name = AvailableSettings.GENERATE_STATISTICS, value = "true" ), - } + settings = { + @Setting( name = AvailableSettings.USE_SECOND_LEVEL_CACHE, value = "true" ), + @Setting( name = AvailableSettings.GENERATE_STATISTICS, value = "true" ), + } ) @SessionFactory @BytecodeEnhanced public class InitFromCacheTest { - private EntityPersister persister; + private EntityPersister persister; - private Long documentID; + private Long documentID; - @BeforeEach - public void prepare(SessionFactoryScope scope) { - persister = scope.getSessionFactory().getRuntimeMetamodels() - .getMappingMetamodel() - .getEntityDescriptor( Document.class ); - assertTrue( persister.hasCache() ); + @BeforeEach + public void prepare(SessionFactoryScope scope) { + persister = scope.getSessionFactory().getRuntimeMetamodels() + .getMappingMetamodel() + .getEntityDescriptor( Document.class ); + assertTrue( persister.hasCache() ); - scope.inTransaction( s -> { - Document document = new Document( "HiA", "Hibernate book", "Hibernate is...." ); - s.persist( document ); - documentID = document.id; - } ); - } + scope.inTransaction( s -> { + Document document = new Document( "HiA", "Hibernate book", "Hibernate is...." ); + s.persist( document ); + documentID = document.id; + } ); + } - @Test - public void execute(SessionFactoryScope scope) { - scope.inTransaction( s -> { - final RootGraph entityGraph = s.createEntityGraph( Document.class ); - entityGraph.addAttributeNodes( "text", "summary" ); - final Document document = s.createQuery( "from Document", Document.class ) - .setHint( HINT_SPEC_FETCH_GRAPH, entityGraph ) - .uniqueResult(); + @Test + public void execute(SessionFactoryScope scope) { + scope.inTransaction( s -> { + final RootGraph entityGraph = s.createEntityGraph( Document.class ); + entityGraph.addAttributeNodes( "text", "summary" ); + final Document document = s.createQuery( "from Document", Document.class ) + .setHint( HINT_SPEC_FETCH_GRAPH, entityGraph ) + .uniqueResult(); assertTrue( isPropertyInitialized( document, "text" ) ); assertTrue( isPropertyInitialized( document, "summary" ) ); final EntityDataAccess entityDataAccess = persister.getCacheAccessStrategy(); final Object cacheKey = entityDataAccess.generateCacheKey( - document.id, + document.id, persister, scope.getSessionFactory(), null @@ -103,69 +103,69 @@ public class InitFromCacheTest { final Object cachedItem = entityDataAccess.get( (SharedSessionContractImplementor) s, cacheKey ); assertNotNull( cachedItem ); assertTyping( StandardCacheEntryImpl.class, cachedItem ); - } - ); + } + ); - scope.getSessionFactory().getStatistics().clear(); + scope.getSessionFactory().getStatistics().clear(); - scope.inTransaction( s -> { - CriteriaBuilder criteriaBuilder = s.getCriteriaBuilder(); - CriteriaQuery criteria = criteriaBuilder.createQuery( Document.class ); - criteria.from( Document.class ); - Document d = s.createQuery( criteria ).uniqueResult(); + scope.inTransaction( s -> { + CriteriaBuilder criteriaBuilder = s.getCriteriaBuilder(); + CriteriaQuery criteria = criteriaBuilder.createQuery( Document.class ); + criteria.from( Document.class ); + Document d = s.createQuery( criteria ).uniqueResult(); // Document d = (Document) s.createCriteria( Document.class ).uniqueResult(); - assertFalse( isPropertyInitialized( d, "text" ) ); - assertFalse( isPropertyInitialized( d, "summary" ) ); - assertEquals( "Hibernate is....", d.text ); - assertTrue( isPropertyInitialized( d, "text" ) ); - assertTrue( isPropertyInitialized( d, "summary" ) ); - } ); + assertFalse( isPropertyInitialized( d, "text" ) ); + assertFalse( isPropertyInitialized( d, "summary" ) ); + assertEquals( "Hibernate is....", d.text ); + assertTrue( isPropertyInitialized( d, "text" ) ); + assertTrue( isPropertyInitialized( d, "summary" ) ); + } ); - assertEquals( 2, scope.getSessionFactory().getStatistics().getPrepareStatementCount() ); + assertEquals( 2, scope.getSessionFactory().getStatistics().getPrepareStatementCount() ); - scope.inTransaction( s -> { - Document d = s.get( Document.class, documentID ); - assertFalse( isPropertyInitialized( d, "text" ) ); - assertFalse( isPropertyInitialized( d, "summary" ) ); - } ); - } + scope.inTransaction( s -> { + Document d = s.get( Document.class, documentID ); + assertFalse( isPropertyInitialized( d, "text" ) ); + assertFalse( isPropertyInitialized( d, "summary" ) ); + } ); + } - // --- // + // --- // - @Entity( name = "Document" ) - @Table( name = "DOCUMENT" ) - @Cacheable - @Cache( usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE, include = "non-lazy", region = "foo" ) - static class Document { + @Entity( name = "Document" ) + @Table( name = "DOCUMENT" ) + @Cacheable + @Cache( usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE, include = "non-lazy", region = "foo" ) + static class Document { - @Id - @GeneratedValue - Long id; + @Id + @GeneratedValue + Long id; - String name; + String name; - @Basic( fetch = FetchType.LAZY ) - @Formula( "upper(name)" ) - String upperCaseName; + @Basic( fetch = FetchType.LAZY ) + @Formula( "upper(name)" ) + String upperCaseName; - @Basic( fetch = FetchType.LAZY ) - String summary; + @Basic( fetch = FetchType.LAZY ) + String summary; - @Basic( fetch = FetchType.LAZY ) - String text; + @Basic( fetch = FetchType.LAZY ) + String text; - @Basic( fetch = FetchType.LAZY ) - Date lastTextModification; + @Basic( fetch = FetchType.LAZY ) + Date lastTextModification; - Document() { - } + Document() { + } - Document(String name, String summary, String text) { - this.lastTextModification = new Date(); - this.name = name; - this.upperCaseName = name.toUpperCase( Locale.ROOT ); - this.summary = summary; - this.text = text; - } - } + Document(String name, String summary, String text) { + this.lastTextModification = new Date(); + this.name = name; + this.upperCaseName = name.toUpperCase( Locale.ROOT ); + this.summary = summary; + this.text = text; + } + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/merge/CompositeMergeTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/merge/CompositeMergeTest.java index 7d9abf776e..647643b51c 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/merge/CompositeMergeTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/merge/CompositeMergeTest.java @@ -34,111 +34,111 @@ import static org.junit.jupiter.api.Assertions.assertEquals; * @author Luis Barreiro */ @DomainModel( - annotatedClasses = { - CompositeMergeTest.ParentEntity.class, CompositeMergeTest.Address.class, CompositeMergeTest.Country.class - } + annotatedClasses = { + CompositeMergeTest.ParentEntity.class, CompositeMergeTest.Address.class, CompositeMergeTest.Country.class + } ) @SessionFactory @BytecodeEnhanced public class CompositeMergeTest { - private long entityId; + private long entityId; - @BeforeEach - public void prepare(SessionFactoryScope scope) { - ParentEntity parent = new ParentEntity(); - parent.description = "desc"; - parent.address = new Address(); - parent.address.street = "Sesame street"; - parent.address.country = new Country(); - parent.address.country.name = "Suriname"; - parent.address.country.languages = Arrays.asList( "english", "spanish" ); + @BeforeEach + public void prepare(SessionFactoryScope scope) { + ParentEntity parent = new ParentEntity(); + parent.description = "desc"; + parent.address = new Address(); + parent.address.street = "Sesame street"; + parent.address.country = new Country(); + parent.address.country.name = "Suriname"; + parent.address.country.languages = Arrays.asList( "english", "spanish" ); - parent.lazyField = new byte[100]; + parent.lazyField = new byte[100]; - scope.inTransaction( s -> { - s.persist( parent ); - } ); + scope.inTransaction( s -> { + s.persist( parent ); + } ); - checkDirtyTracking( parent ); - entityId = parent.id; - } + checkDirtyTracking( parent ); + entityId = parent.id; + } - @Test - public void test(SessionFactoryScope scope) { - ParentEntity[] parent = new ParentEntity[3]; + @Test + public void test(SessionFactoryScope scope) { + ParentEntity[] parent = new ParentEntity[3]; - scope.inTransaction( s -> { - parent[0] = s.get( ParentEntity.class, entityId ); - } ); + scope.inTransaction( s -> { + parent[0] = s.get( ParentEntity.class, entityId ); + } ); - checkDirtyTracking( parent[0] ); + checkDirtyTracking( parent[0] ); - parent[0].address.country.name = "Paraguai"; + parent[0].address.country.name = "Paraguai"; - checkDirtyTracking( parent[0], "address.country" ); + checkDirtyTracking( parent[0], "address.country" ); - scope.inTransaction( s -> { - parent[1] = (ParentEntity) s.merge( parent[0] ); - checkDirtyTracking( parent[0], "address.country" ); - checkDirtyTracking( parent[1], "address.country" ); - } ); + scope.inTransaction( s -> { + parent[1] = (ParentEntity) s.merge( parent[0] ); + checkDirtyTracking( parent[0], "address.country" ); + checkDirtyTracking( parent[1], "address.country" ); + } ); - checkDirtyTracking( parent[0], "address.country" ); - checkDirtyTracking( parent[1] ); + checkDirtyTracking( parent[0], "address.country" ); + checkDirtyTracking( parent[1] ); - parent[1].address.country.name = "Honduras"; + parent[1].address.country.name = "Honduras"; - checkDirtyTracking( parent[1], "address.country" ); + checkDirtyTracking( parent[1], "address.country" ); - scope.inTransaction( s -> { - s.merge( parent[1] ); - checkDirtyTracking( parent[1], "address.country" ); - } ); + scope.inTransaction( s -> { + s.merge( parent[1] ); + checkDirtyTracking( parent[1], "address.country" ); + } ); - scope.inTransaction( s -> { - parent[2] = s.get( ParentEntity.class, entityId ); - assertEquals( "Honduras", parent[2].address.country.name ); - } ); - } + scope.inTransaction( s -> { + parent[2] = s.get( ParentEntity.class, entityId ); + assertEquals( "Honduras", parent[2].address.country.name ); + } ); + } - // --- // + // --- // - @Entity(name = "Parent") - @Table( name = "PARENT_ENTITY" ) - static class ParentEntity { + @Entity(name = "Parent") + @Table( name = "PARENT_ENTITY" ) + static class ParentEntity { - @Id - @GeneratedValue - Long id; + @Id + @GeneratedValue + Long id; - String description; + String description; - @Embedded - Address address; + @Embedded + Address address; - @Basic( fetch = FetchType.LAZY ) - byte[] lazyField; - } + @Basic( fetch = FetchType.LAZY ) + byte[] lazyField; + } - @Embeddable - @Table( name = "ADDRESS" ) - static class Address { + @Embeddable + @Table( name = "ADDRESS" ) + static class Address { - String street; + String street; - @Embedded - Country country; - } + @Embedded + Country country; + } - @Embeddable - @Table( name = "COUNTRY" ) - static class Country { + @Embeddable + @Table( name = "COUNTRY" ) + static class Country { - String name; + String name; - @ElementCollection - @CollectionTable( name = "languages", joinColumns = @JoinColumn( name = "id", referencedColumnName = "id" ) ) - List languages; - } + @ElementCollection + @CollectionTable( name = "languages", joinColumns = @JoinColumn( name = "id", referencedColumnName = "id" ) ) + List languages; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/merge/CompositeNullTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/merge/CompositeNullTest.java index 319e95f68b..b7e34153a2 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/merge/CompositeNullTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/merge/CompositeNullTest.java @@ -30,59 +30,59 @@ import org.junit.jupiter.api.Test; * @author Luis Barreiro */ @DomainModel( - annotatedClasses = { - CompositeNullTest.ParentEntity.class, CompositeNullTest.Address.class - } + annotatedClasses = { + CompositeNullTest.ParentEntity.class, CompositeNullTest.Address.class + } ) @SessionFactory @BytecodeEnhanced @EnhancementOptions(lazyLoading = true, inlineDirtyChecking = true) public class CompositeNullTest { - private long entityId; + private long entityId; - @BeforeEach - public void prepare(SessionFactoryScope scope) { - ParentEntity parent = new ParentEntity(); - parent.description = "Test"; + @BeforeEach + public void prepare(SessionFactoryScope scope) { + ParentEntity parent = new ParentEntity(); + parent.description = "Test"; - scope.inTransaction( s -> { - s.persist( parent ); - } ); + scope.inTransaction( s -> { + s.persist( parent ); + } ); - entityId = parent.id; - } + entityId = parent.id; + } - @Test - @JiraKey("HHH-15730") - public void testNullComposite(SessionFactoryScope scope) { - scope.inTransaction( s -> { - ParentEntity parentEntity = s.find( ParentEntity.class, entityId ); - assertNull( parentEntity.address ); - } ); - } + @Test + @JiraKey("HHH-15730") + public void testNullComposite(SessionFactoryScope scope) { + scope.inTransaction( s -> { + ParentEntity parentEntity = s.find( ParentEntity.class, entityId ); + assertNull( parentEntity.address ); + } ); + } - // --- // + // --- // - @Entity(name = "Parent") - @Table( name = "PARENT_ENTITY" ) - static class ParentEntity { + @Entity(name = "Parent") + @Table( name = "PARENT_ENTITY" ) + static class ParentEntity { - @Id - @GeneratedValue - Long id; + @Id + @GeneratedValue + Long id; - String description; + String description; - @Embedded - Address address; - } + @Embedded + Address address; + } - @Embeddable - @Table( name = "ADDRESS" ) - static class Address { + @Embeddable + @Table( name = "ADDRESS" ) + static class Address { - String street; + String street; - } + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/merge/MergeEnhancedEntityDynamicUpdateTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/merge/MergeEnhancedEntityDynamicUpdateTest.java index d910849472..1e0c353c10 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/merge/MergeEnhancedEntityDynamicUpdateTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/merge/MergeEnhancedEntityDynamicUpdateTest.java @@ -39,155 +39,155 @@ import static org.junit.Assert.fail; @JiraKey( value = "HHH-11459" ) @RunWith( BytecodeEnhancerRunner.class ) public class MergeEnhancedEntityDynamicUpdateTest extends BaseCoreFunctionalTestCase { - private Person person; - @Override - public Class[] getAnnotatedClasses() { - return new Class[]{Person.class, PersonAddress.class, NullablePerson.class}; - } + private Person person; + @Override + public Class[] getAnnotatedClasses() { + return new Class[]{Person.class, PersonAddress.class, NullablePerson.class}; + } - @Before - public void prepare() { - person = new Person( 1L, "Sam" ); - doInHibernate( this::sessionFactory, s -> { - s.persist( person ); - } ); - } + @Before + public void prepare() { + person = new Person( 1L, "Sam" ); + doInHibernate( this::sessionFactory, s -> { + s.persist( person ); + } ); + } - @Test - public void testMerge() { - doInHibernate( this::sessionFactory, s -> { - Person entity = s.find( Person.class, 1L ); - entity.name = "John"; - try { - s.merge( entity ); - } catch ( RuntimeException e ) { - fail( "Enhanced entity can't be merged: " + e.getMessage() ); - } - } ); - } + @Test + public void testMerge() { + doInHibernate( this::sessionFactory, s -> { + Person entity = s.find( Person.class, 1L ); + entity.name = "John"; + try { + s.merge( entity ); + } catch ( RuntimeException e ) { + fail( "Enhanced entity can't be merged: " + e.getMessage() ); + } + } ); + } - @Test - public void testRefresh() { - doInHibernate( this::sessionFactory, s -> { - Person entity = s.find( Person.class, 1L ); - entity.name = "John"; + @Test + public void testRefresh() { + doInHibernate( this::sessionFactory, s -> { + Person entity = s.find( Person.class, 1L ); + entity.name = "John"; - s.refresh( entity ); + s.refresh( entity ); // try { // s.refresh( entity ); // } catch ( RuntimeException e ) { // fail( "Enhanced entity can't be refreshed: " + e.getMessage() ); // } - } ); - } + } ); + } - @Test - public void testMergeWithNullValues() { - doInHibernate( this::sessionFactory, em -> { - NullablePerson nullablePerson = new NullablePerson( 1L, "Sam", 100 ); - em.persist( nullablePerson ); - } ); - doInHibernate( this::sessionFactory, em -> { - NullablePerson updated = em.find( NullablePerson.class, 1L ); - assertThat( updated.name ).isEqualTo( "Sam" ); - assertThat( updated.number ).isEqualTo( 100 ); - } ); + @Test + public void testMergeWithNullValues() { + doInHibernate( this::sessionFactory, em -> { + NullablePerson nullablePerson = new NullablePerson( 1L, "Sam", 100 ); + em.persist( nullablePerson ); + } ); + doInHibernate( this::sessionFactory, em -> { + NullablePerson updated = em.find( NullablePerson.class, 1L ); + assertThat( updated.name ).isEqualTo( "Sam" ); + assertThat( updated.number ).isEqualTo( 100 ); + } ); - // only some properties are null - doInHibernate( this::sessionFactory, em -> { - NullablePerson nullablePerson = new NullablePerson( 1L, "Joe", null ); - em.merge( nullablePerson ); - } ); - doInHibernate( this::sessionFactory, em -> { - NullablePerson updated = em.find( NullablePerson.class, 1L ); - assertThat( updated.name ).isEqualTo( "Joe" ); - assertThat( updated.number ).isNull(); - } ); + // only some properties are null + doInHibernate( this::sessionFactory, em -> { + NullablePerson nullablePerson = new NullablePerson( 1L, "Joe", null ); + em.merge( nullablePerson ); + } ); + doInHibernate( this::sessionFactory, em -> { + NullablePerson updated = em.find( NullablePerson.class, 1L ); + assertThat( updated.name ).isEqualTo( "Joe" ); + assertThat( updated.number ).isNull(); + } ); - // all properties are null: - doInHibernate( this::sessionFactory, em -> { - NullablePerson nullablePerson = new NullablePerson( 1L, null, null ); - em.merge( nullablePerson ); - } ); - doInHibernate( this::sessionFactory, em -> { - NullablePerson updated = em.find( NullablePerson.class, 1L ); - assertThat( updated.name ).isNull(); - assertThat( updated.number ).isNull(); - } ); - } + // all properties are null: + doInHibernate( this::sessionFactory, em -> { + NullablePerson nullablePerson = new NullablePerson( 1L, null, null ); + em.merge( nullablePerson ); + } ); + doInHibernate( this::sessionFactory, em -> { + NullablePerson updated = em.find( NullablePerson.class, 1L ); + assertThat( updated.name ).isNull(); + assertThat( updated.number ).isNull(); + } ); + } - @After - public void cleanup() { - doInHibernate( this::sessionFactory, s -> { - s.remove( person ); - } ); - doInHibernate( this::sessionFactory, s -> { - s.createQuery( "delete from NullablePerson" ); - } ); - } + @After + public void cleanup() { + doInHibernate( this::sessionFactory, s -> { + s.remove( person ); + } ); + doInHibernate( this::sessionFactory, s -> { + s.createQuery( "delete from NullablePerson" ); + } ); + } - // --- // + // --- // - @Entity - @Table( name = "PERSON" ) - @DynamicUpdate - @DynamicInsert - private static class Person { + @Entity + @Table( name = "PERSON" ) + @DynamicUpdate + @DynamicInsert + private static class Person { - @Id - Long id; + @Id + Long id; - @Column( name = "name", length = 10, nullable = false ) - String name; + @Column( name = "name", length = 10, nullable = false ) + String name; - @OneToMany( fetch = FetchType.LAZY, mappedBy = "parent", orphanRemoval = true, cascade = CascadeType.ALL ) - List details = new ArrayList<>(); + @OneToMany( fetch = FetchType.LAZY, mappedBy = "parent", orphanRemoval = true, cascade = CascadeType.ALL ) + List details = new ArrayList<>(); - Person() { - } + Person() { + } - Person(Long id, String name) { - this.id = id; - this.name = name; - } - } + Person(Long id, String name) { + this.id = id; + this.name = name; + } + } - @Entity - @Table( name = "PERSON_ADDRESS" ) - @DynamicUpdate - @DynamicInsert - private static class PersonAddress { + @Entity + @Table( name = "PERSON_ADDRESS" ) + @DynamicUpdate + @DynamicInsert + private static class PersonAddress { - @Id - Long id; + @Id + Long id; - @ManyToOne( optional = false, fetch = FetchType.LAZY ) - Person parent; - } + @ManyToOne( optional = false, fetch = FetchType.LAZY ) + Person parent; + } - @Entity(name = "NullablePerson") - @Table(name = "NULLABLE_PERSON") - @DynamicUpdate - @DynamicInsert - private static class NullablePerson { + @Entity(name = "NullablePerson") + @Table(name = "NULLABLE_PERSON") + @DynamicUpdate + @DynamicInsert + private static class NullablePerson { - @Id - Long id; + @Id + Long id; - @Column - String name; + @Column + String name; - @Column(name = "NUMBER_COLUMN") - Integer number; + @Column(name = "NUMBER_COLUMN") + Integer number; - NullablePerson() { - } + NullablePerson() { + } - NullablePerson(Long id, String name, Integer number) { - this.id = id; - this.name = name; - this.number = number; - } - } + NullablePerson(Long id, String name, Integer number) { + this.id = id; + this.name = name; + this.number = number; + } + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/merge/MergeEnhancedEntityTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/merge/MergeEnhancedEntityTest.java index f02ace68f7..6ef4136ec2 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/merge/MergeEnhancedEntityTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/merge/MergeEnhancedEntityTest.java @@ -34,53 +34,53 @@ import static org.junit.jupiter.api.Assertions.fail; */ @JiraKey( "HHH-11459" ) @DomainModel( - annotatedClasses = { - MergeEnhancedEntityTest.Person.class, + annotatedClasses = { + MergeEnhancedEntityTest.Person.class, MergeEnhancedEntityTest.PersonAddress.class, MergeEnhancedEntityTest.NullablePerson.class - } + } ) @SessionFactory @BytecodeEnhanced public class MergeEnhancedEntityTest { - private Person person; + private Person person; - @BeforeEach - public void prepare(SessionFactoryScope scope) { - person = new Person( 1L, "Sam" ); - scope.inTransaction( s -> { - s.persist( person ); - } ); - } + @BeforeEach + public void prepare(SessionFactoryScope scope) { + person = new Person( 1L, "Sam" ); + scope.inTransaction( s -> { + s.persist( person ); + } ); + } - @Test - public void testMerge(SessionFactoryScope scope) { - scope.inTransaction( s -> { - Person entity = s.find( Person.class, 1L ); - entity.name = "John"; - try { - s.merge( entity ); - } catch ( RuntimeException e ) { - fail( "Enhanced entity can't be merged: " + e.getMessage() ); - } - } ); - } + @Test + public void testMerge(SessionFactoryScope scope) { + scope.inTransaction( s -> { + Person entity = s.find( Person.class, 1L ); + entity.name = "John"; + try { + s.merge( entity ); + } catch ( RuntimeException e ) { + fail( "Enhanced entity can't be merged: " + e.getMessage() ); + } + } ); + } - @Test - public void testRefresh(SessionFactoryScope scope) { - scope.inTransaction( s -> { - Person entity = s.find( Person.class, 1L ); - entity.name = "John"; + @Test + public void testRefresh(SessionFactoryScope scope) { + scope.inTransaction( s -> { + Person entity = s.find( Person.class, 1L ); + entity.name = "John"; - s.refresh( entity ); + s.refresh( entity ); // try { // s.refresh( entity ); // } catch ( RuntimeException e ) { // fail( "Enhanced entity can't be refreshed: " + e.getMessage() ); // } - } ); - } + } ); + } @Test public void testMergeWithNullValues(SessionFactoryScope scope) { @@ -117,71 +117,71 @@ public class MergeEnhancedEntityTest { } ); } - @AfterEach - public void cleanup(SessionFactoryScope scope) { - scope.inTransaction( s -> { - s.remove( person ); - } ); + @AfterEach + public void cleanup(SessionFactoryScope scope) { scope.inTransaction( s -> { - s.createQuery( "delete from NullablePerson" ); - } ); - } + s.remove( person ); + } ); + scope.inTransaction( s -> { + s.createQuery( "delete from NullablePerson" ); + } ); + } - // --- // + // --- // - @Entity - @Table( name = "PERSON" ) - static class Person { + @Entity + @Table( name = "PERSON" ) + static class Person { - @Id - Long id; + @Id + Long id; - @Column( name = "name", length = 10, nullable = false ) - String name; + @Column( name = "name", length = 10, nullable = false ) + String name; - @OneToMany( fetch = FetchType.LAZY, mappedBy = "parent", orphanRemoval = true, cascade = CascadeType.ALL ) - List details = new ArrayList<>(); + @OneToMany( fetch = FetchType.LAZY, mappedBy = "parent", orphanRemoval = true, cascade = CascadeType.ALL ) + List details = new ArrayList<>(); - Person() { - } + Person() { + } - Person(Long id, String name) { - this.id = id; - this.name = name; - } - } + Person(Long id, String name) { + this.id = id; + this.name = name; + } + } - @Entity - @Table( name = "PERSON_ADDRESS" ) - static class PersonAddress { + @Entity + @Table( name = "PERSON_ADDRESS" ) + static class PersonAddress { - @Id - Long id; + @Id + Long id; - @ManyToOne( optional = false, fetch = FetchType.LAZY ) - Person parent; - } + @ManyToOne( optional = false, fetch = FetchType.LAZY ) + Person parent; + } - @Entity(name = "NullablePerson") - @Table(name = "NULLABLE_PERSON") - static class NullablePerson { + @Entity(name = "NullablePerson") + @Table(name = "NULLABLE_PERSON") + static class NullablePerson { - @Id - Long id; + @Id + Long id; - @Column - String name; + @Column + String name; - @Column(name = "NUMBER_COLUMN") - Integer number; + @Column(name = "NUMBER_COLUMN") + Integer number; - NullablePerson() { - } + NullablePerson() { + } - NullablePerson(Long id, String name, Integer number) { - this.id = id; - this.name = name; - this.number = number; - } - } + NullablePerson(Long id, String name, Integer number) { + this.id = id; + this.name = name; + this.number = number; + } + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/ondemandload/OnDemandLoadTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/ondemandload/OnDemandLoadTest.java index bc8d3e2d74..6e07ee881b 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/ondemandload/OnDemandLoadTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/ondemandload/OnDemandLoadTest.java @@ -47,250 +47,250 @@ import org.junit.jupiter.api.Test; */ @JiraKey( "HHH-10055" ) @DomainModel( - annotatedClasses = { - OnDemandLoadTest.Store.class, OnDemandLoadTest.Inventory.class, OnDemandLoadTest.Product.class - } + annotatedClasses = { + OnDemandLoadTest.Store.class, OnDemandLoadTest.Inventory.class, OnDemandLoadTest.Product.class + } ) @ServiceRegistry( - settings = { - @Setting( name = AvailableSettings.USE_SECOND_LEVEL_CACHE, value = "false" ), - @Setting( name = AvailableSettings.ENABLE_LAZY_LOAD_NO_TRANS, value = "true" ), - @Setting( name = AvailableSettings.GENERATE_STATISTICS, value = "true" ), - } + settings = { + @Setting( name = AvailableSettings.USE_SECOND_LEVEL_CACHE, value = "false" ), + @Setting( name = AvailableSettings.ENABLE_LAZY_LOAD_NO_TRANS, value = "true" ), + @Setting( name = AvailableSettings.GENERATE_STATISTICS, value = "true" ), + } ) @SessionFactory @BytecodeEnhanced public class OnDemandLoadTest { - @BeforeEach - public void prepare(SessionFactoryScope scope) { - scope.inTransaction( s -> { - Store store = new Store( 1L ).setName( "Acme Super Outlet" ); - s.persist( store ); + @BeforeEach + public void prepare(SessionFactoryScope scope) { + scope.inTransaction( s -> { + Store store = new Store( 1L ).setName( "Acme Super Outlet" ); + s.persist( store ); - Product product = new Product( "007" ).setName( "widget" ).setDescription( "FooBar" ); - s.persist( product ); + Product product = new Product( "007" ).setName( "widget" ).setDescription( "FooBar" ); + s.persist( product ); - store.addInventoryProduct( product ).setQuantity( 10L ).setStorePrice( new BigDecimal( 500 ) ); - } ); - } + store.addInventoryProduct( product ).setQuantity( 10L ).setStorePrice( new BigDecimal( 500 ) ); + } ); + } - @Test - public void testClosedSession(SessionFactoryScope scope) { - scope.getSessionFactory().getStatistics().clear(); - Store[] store = new Store[1]; + @Test + public void testClosedSession(SessionFactoryScope scope) { + scope.getSessionFactory().getStatistics().clear(); + Store[] store = new Store[1]; - scope.inTransaction( s -> { - // first load the store, making sure it is not initialized - store[0] = s.getReference( Store.class, 1L ); - assertNotNull( store[0] ); - assertFalse( isPropertyInitialized( store[0], "inventories" ) ); + scope.inTransaction( s -> { + // first load the store, making sure it is not initialized + store[0] = s.getReference( Store.class, 1L ); + assertNotNull( store[0] ); + assertFalse( isPropertyInitialized( store[0], "inventories" ) ); - assertEquals( 1, scope.getSessionFactory().getStatistics().getSessionOpenCount() ); - assertEquals( 0, scope.getSessionFactory().getStatistics().getSessionCloseCount() ); - } ); + assertEquals( 1, scope.getSessionFactory().getStatistics().getSessionOpenCount() ); + assertEquals( 0, scope.getSessionFactory().getStatistics().getSessionCloseCount() ); + } ); - assertEquals( 1, scope.getSessionFactory().getStatistics().getSessionOpenCount() ); - assertEquals( 1, scope.getSessionFactory().getStatistics().getSessionCloseCount() ); + assertEquals( 1, scope.getSessionFactory().getStatistics().getSessionOpenCount() ); + assertEquals( 1, scope.getSessionFactory().getStatistics().getSessionCloseCount() ); - store[0].getInventories(); - assertTrue( isPropertyInitialized( store[0], "inventories" ) ); + store[0].getInventories(); + assertTrue( isPropertyInitialized( store[0], "inventories" ) ); - assertEquals( 2, scope.getSessionFactory().getStatistics().getSessionOpenCount() ); - assertEquals( 2, scope.getSessionFactory().getStatistics().getSessionCloseCount() ); - } + assertEquals( 2, scope.getSessionFactory().getStatistics().getSessionOpenCount() ); + assertEquals( 2, scope.getSessionFactory().getStatistics().getSessionCloseCount() ); + } - @Test - public void testClearedSession(SessionFactoryScope scope) { - scope.getSessionFactory().getStatistics().clear(); + @Test + public void testClearedSession(SessionFactoryScope scope) { + scope.getSessionFactory().getStatistics().clear(); - scope.inTransaction( s -> { - // first load the store, making sure collection is not initialized - Store store = s.get( Store.class, 1L ); - assertNotNull( store ); - assertFalse( isInitialized( store.getInventories() ) ); - assertEquals( 1, scope.getSessionFactory().getStatistics().getSessionOpenCount() ); - assertEquals( 0, scope.getSessionFactory().getStatistics().getSessionCloseCount() ); + scope.inTransaction( s -> { + // first load the store, making sure collection is not initialized + Store store = s.get( Store.class, 1L ); + assertNotNull( store ); + assertFalse( isInitialized( store.getInventories() ) ); + assertEquals( 1, scope.getSessionFactory().getStatistics().getSessionOpenCount() ); + assertEquals( 0, scope.getSessionFactory().getStatistics().getSessionCloseCount() ); - // then clear session and try to initialize collection - s.clear(); - assertNotNull( store ); - assertFalse( isInitialized( store.getInventories() ) ); - store.getInventories().size(); - assertTrue( isInitialized( store.getInventories() ) ); + // then clear session and try to initialize collection + s.clear(); + assertNotNull( store ); + assertFalse( isInitialized( store.getInventories() ) ); + store.getInventories().size(); + assertTrue( isInitialized( store.getInventories() ) ); - // the extra Session is the temp Sessions needed to perform the collection init (since it's lazy) - assertEquals( 2, scope.getSessionFactory().getStatistics().getSessionOpenCount() ); - assertEquals( 1, scope.getSessionFactory().getStatistics().getSessionCloseCount() ); + // the extra Session is the temp Sessions needed to perform the collection init (since it's lazy) + assertEquals( 2, scope.getSessionFactory().getStatistics().getSessionOpenCount() ); + assertEquals( 1, scope.getSessionFactory().getStatistics().getSessionCloseCount() ); - // clear Session again. The collection should still be recognized as initialized from above - s.clear(); - assertNotNull( store ); - assertTrue( isInitialized( store.getInventories() ) ); - assertEquals( 2, scope.getSessionFactory().getStatistics().getSessionOpenCount() ); - assertEquals( 1, scope.getSessionFactory().getStatistics().getSessionCloseCount() ); + // clear Session again. The collection should still be recognized as initialized from above + s.clear(); + assertNotNull( store ); + assertTrue( isInitialized( store.getInventories() ) ); + assertEquals( 2, scope.getSessionFactory().getStatistics().getSessionOpenCount() ); + assertEquals( 1, scope.getSessionFactory().getStatistics().getSessionCloseCount() ); - // lets clear the Session again and this time reload the Store - s.clear(); - store = s.get( Store.class, 1L ); - s.clear(); - assertNotNull( store ); + // lets clear the Session again and this time reload the Store + s.clear(); + store = s.get( Store.class, 1L ); + s.clear(); + assertNotNull( store ); - // collection should be back to uninitialized since we have a new entity instance - assertFalse( isInitialized( store.getInventories() ) ); - assertEquals( 2, scope.getSessionFactory().getStatistics().getSessionOpenCount() ); - assertEquals( 1, scope.getSessionFactory().getStatistics().getSessionCloseCount() ); - store.getInventories().size(); - assertTrue( isInitialized( store.getInventories() ) ); + // collection should be back to uninitialized since we have a new entity instance + assertFalse( isInitialized( store.getInventories() ) ); + assertEquals( 2, scope.getSessionFactory().getStatistics().getSessionOpenCount() ); + assertEquals( 1, scope.getSessionFactory().getStatistics().getSessionCloseCount() ); + store.getInventories().size(); + assertTrue( isInitialized( store.getInventories() ) ); - // the extra Session is the temp Sessions needed to perform the collection init (since it's lazy) - assertEquals( 3, scope.getSessionFactory().getStatistics().getSessionOpenCount() ); - assertEquals( 2, scope.getSessionFactory().getStatistics().getSessionCloseCount() ); + // the extra Session is the temp Sessions needed to perform the collection init (since it's lazy) + assertEquals( 3, scope.getSessionFactory().getStatistics().getSessionOpenCount() ); + assertEquals( 2, scope.getSessionFactory().getStatistics().getSessionCloseCount() ); - // clear Session again. The collection should still be recognized as initialized from above - s.clear(); - assertNotNull( store ); - assertTrue( isInitialized( store.getInventories() ) ); - assertEquals( 3, scope.getSessionFactory().getStatistics().getSessionOpenCount() ); - assertEquals( 2, scope.getSessionFactory().getStatistics().getSessionCloseCount() ); - } ); - } + // clear Session again. The collection should still be recognized as initialized from above + s.clear(); + assertNotNull( store ); + assertTrue( isInitialized( store.getInventories() ) ); + assertEquals( 3, scope.getSessionFactory().getStatistics().getSessionOpenCount() ); + assertEquals( 2, scope.getSessionFactory().getStatistics().getSessionCloseCount() ); + } ); + } - @AfterEach - public void cleanup(SessionFactoryScope scope) throws Exception { - scope.inTransaction( s -> { - Store store = s.find( Store.class, 1L ); - s.remove( store ); + @AfterEach + public void cleanup(SessionFactoryScope scope) throws Exception { + scope.inTransaction( s -> { + Store store = s.find( Store.class, 1L ); + s.remove( store ); - Product product= s.find( Product.class, "007" ); - s.remove( product ); - } ); - } + Product product= s.find( Product.class, "007" ); + s.remove( product ); + } ); + } - // --- // + // --- // - @Entity - @Table( name = "STORE" ) - static class Store { - @Id - Long id; + @Entity + @Table( name = "STORE" ) + static class Store { + @Id + Long id; - String name; + String name; - @OneToMany( mappedBy = "store", cascade = CascadeType.ALL, fetch = FetchType.LAZY ) - List inventories = new ArrayList<>(); + @OneToMany( mappedBy = "store", cascade = CascadeType.ALL, fetch = FetchType.LAZY ) + List inventories = new ArrayList<>(); - @Version - Integer version; + @Version + Integer version; - Store() { - } + Store() { + } - Store(long id) { - this.id = id; - } + Store(long id) { + this.id = id; + } - Store setName(String name) { - this.name = name; - return this; - } + Store setName(String name) { + this.name = name; + return this; + } - Inventory addInventoryProduct(Product product) { - Inventory inventory = new Inventory( this, product ); - inventories.add( inventory ); - return inventory; - } + Inventory addInventoryProduct(Product product) { + Inventory inventory = new Inventory( this, product ); + inventories.add( inventory ); + return inventory; + } - public List getInventories() { - return inventories; - } - } + public List getInventories() { + return inventories; + } + } - @Entity - @Table( name = "INVENTORY" ) - static class Inventory { + @Entity + @Table( name = "INVENTORY" ) + static class Inventory { - @Id - @GeneratedValue - @GenericGenerator( name = "increment", strategy = "increment" ) - Long id = -1L; + @Id + @GeneratedValue + @GenericGenerator( name = "increment", strategy = "increment" ) + Long id = -1L; - @ManyToOne - @JoinColumn( name = "STORE_ID" ) - Store store; + @ManyToOne + @JoinColumn( name = "STORE_ID" ) + Store store; - @ManyToOne - @JoinColumn( name = "PRODUCT_ID" ) - Product product; + @ManyToOne + @JoinColumn( name = "PRODUCT_ID" ) + Product product; - Long quantity; + Long quantity; - BigDecimal storePrice; + BigDecimal storePrice; - public Inventory() { - } + public Inventory() { + } - public Inventory(Store store, Product product) { - this.store = store; - this.product = product; - } + public Inventory(Store store, Product product) { + this.store = store; + this.product = product; + } - Inventory setStore(Store store) { - this.store = store; - return this; - } + Inventory setStore(Store store) { + this.store = store; + return this; + } - Inventory setProduct(Product product) { - this.product = product; - return this; - } + Inventory setProduct(Product product) { + this.product = product; + return this; + } - Inventory setQuantity(Long quantity) { - this.quantity = quantity; - return this; - } + Inventory setQuantity(Long quantity) { + this.quantity = quantity; + return this; + } - Inventory setStorePrice(BigDecimal storePrice) { - this.storePrice = storePrice; - return this; - } - } + Inventory setStorePrice(BigDecimal storePrice) { + this.storePrice = storePrice; + return this; + } + } - @Entity - @Table( name = "PRODUCT" ) - static class Product { - @Id - String id; + @Entity + @Table( name = "PRODUCT" ) + static class Product { + @Id + String id; - String name; + String name; - String description; + String description; - BigDecimal msrp; + BigDecimal msrp; - @Version - Long version; + @Version + Long version; - Product() { - } + Product() { + } - Product(String id) { - this.id = id; - } + Product(String id) { + this.id = id; + } - Product setName(String name) { - this.name = name; - return this; - } + Product setName(String name) { + this.name = name; + return this; + } - Product setDescription(String description) { - this.description = description; - return this; - } + Product setDescription(String description) { + this.description = description; + return this; + } - Product setMsrp(BigDecimal msrp) { - this.msrp = msrp; - return this; - } - } + Product setMsrp(BigDecimal msrp) { + this.msrp = msrp; + return this; + } + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/ondemandload/OnDemandLoadWithCollectionInDefaultFetchGroupFalseTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/ondemandload/OnDemandLoadWithCollectionInDefaultFetchGroupFalseTest.java index 6dace59a10..63a1f13b52 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/ondemandload/OnDemandLoadWithCollectionInDefaultFetchGroupFalseTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/ondemandload/OnDemandLoadWithCollectionInDefaultFetchGroupFalseTest.java @@ -53,256 +53,256 @@ import jakarta.persistence.Version; */ @JiraKey( "HHH-10055" ) @DomainModel( - annotatedClasses = { - Store.class, Inventory.class, Product.class - } + annotatedClasses = { + Store.class, Inventory.class, Product.class + } ) @ServiceRegistry( - settings = { - @Setting( name = AvailableSettings.USE_SECOND_LEVEL_CACHE, value = "false" ), - @Setting( name = AvailableSettings.ENABLE_LAZY_LOAD_NO_TRANS, value = "true" ), - @Setting( name = AvailableSettings.GENERATE_STATISTICS, value = "true" ), - } + settings = { + @Setting( name = AvailableSettings.USE_SECOND_LEVEL_CACHE, value = "false" ), + @Setting( name = AvailableSettings.ENABLE_LAZY_LOAD_NO_TRANS, value = "true" ), + @Setting( name = AvailableSettings.GENERATE_STATISTICS, value = "true" ), + } ) @SessionFactory( - // We want to test with this setting set to false explicitly, - // because another test already takes care of the default. - applyCollectionsInDefaultFetchGroup = false + // We want to test with this setting set to false explicitly, + // because another test already takes care of the default. + applyCollectionsInDefaultFetchGroup = false ) @BytecodeEnhanced public class OnDemandLoadWithCollectionInDefaultFetchGroupFalseTest { - @BeforeEach - public void prepare(SessionFactoryScope scope) { - scope.inTransaction( s -> { - Store store = new Store( 1L ).setName( "Acme Super Outlet" ); - s.persist( store ); + @BeforeEach + public void prepare(SessionFactoryScope scope) { + scope.inTransaction( s -> { + Store store = new Store( 1L ).setName( "Acme Super Outlet" ); + s.persist( store ); - Product product = new Product( "007" ).setName( "widget" ).setDescription( "FooBar" ); - s.persist( product ); + Product product = new Product( "007" ).setName( "widget" ).setDescription( "FooBar" ); + s.persist( product ); - store.addInventoryProduct( product ).setQuantity( 10L ).setStorePrice( new BigDecimal( 500 ) ); - } ); - } + store.addInventoryProduct( product ).setQuantity( 10L ).setStorePrice( new BigDecimal( 500 ) ); + } ); + } - @Test - public void testClosedSession(SessionFactoryScope scope) { - scope.getSessionFactory().getStatistics().clear(); - Store[] store = new Store[1]; + @Test + public void testClosedSession(SessionFactoryScope scope) { + scope.getSessionFactory().getStatistics().clear(); + Store[] store = new Store[1]; - scope.inTransaction( s -> { - // first load the store, making sure it is not initialized - store[0] = s.getReference( Store.class, 1L ); - assertNotNull( store[0] ); - assertFalse( isPropertyInitialized( store[0], "inventories" ) ); + scope.inTransaction( s -> { + // first load the store, making sure it is not initialized + store[0] = s.getReference( Store.class, 1L ); + assertNotNull( store[0] ); + assertFalse( isPropertyInitialized( store[0], "inventories" ) ); - assertEquals( 1, scope.getSessionFactory().getStatistics().getSessionOpenCount() ); - assertEquals( 0, scope.getSessionFactory().getStatistics().getSessionCloseCount() ); - } ); + assertEquals( 1, scope.getSessionFactory().getStatistics().getSessionOpenCount() ); + assertEquals( 0, scope.getSessionFactory().getStatistics().getSessionCloseCount() ); + } ); - assertEquals( 1, scope.getSessionFactory().getStatistics().getSessionOpenCount() ); - assertEquals( 1, scope.getSessionFactory().getStatistics().getSessionCloseCount() ); + assertEquals( 1, scope.getSessionFactory().getStatistics().getSessionOpenCount() ); + assertEquals( 1, scope.getSessionFactory().getStatistics().getSessionCloseCount() ); - store[0].getInventories(); - assertTrue( isPropertyInitialized( store[0], "inventories" ) ); + store[0].getInventories(); + assertTrue( isPropertyInitialized( store[0], "inventories" ) ); - assertEquals( 2, scope.getSessionFactory().getStatistics().getSessionOpenCount() ); - assertEquals( 2, scope.getSessionFactory().getStatistics().getSessionCloseCount() ); - } + assertEquals( 2, scope.getSessionFactory().getStatistics().getSessionOpenCount() ); + assertEquals( 2, scope.getSessionFactory().getStatistics().getSessionCloseCount() ); + } - @Test - public void testClearedSession(SessionFactoryScope scope) { - scope.getSessionFactory().getStatistics().clear(); + @Test + public void testClearedSession(SessionFactoryScope scope) { + scope.getSessionFactory().getStatistics().clear(); - scope.inTransaction( s -> { - // first load the store, making sure collection is not initialized - Store store = s.get( Store.class, 1L ); - assertNotNull( store ); - assertFalse( isPropertyInitialized( store, "inventories" ) ); - assertEquals( 1, scope.getSessionFactory().getStatistics().getSessionOpenCount() ); - assertEquals( 0, scope.getSessionFactory().getStatistics().getSessionCloseCount() ); + scope.inTransaction( s -> { + // first load the store, making sure collection is not initialized + Store store = s.get( Store.class, 1L ); + assertNotNull( store ); + assertFalse( isPropertyInitialized( store, "inventories" ) ); + assertEquals( 1, scope.getSessionFactory().getStatistics().getSessionOpenCount() ); + assertEquals( 0, scope.getSessionFactory().getStatistics().getSessionCloseCount() ); - // then clear session and try to initialize collection - s.clear(); - assertNotNull( store ); - assertFalse( isPropertyInitialized( store, "inventories" ) ); - store.getInventories().size(); - assertTrue( isPropertyInitialized( store, "inventories" ) ); + // then clear session and try to initialize collection + s.clear(); + assertNotNull( store ); + assertFalse( isPropertyInitialized( store, "inventories" ) ); + store.getInventories().size(); + assertTrue( isPropertyInitialized( store, "inventories" ) ); - // the extra Sessions are the temp Sessions needed to perform the init: - // first the entity, then the collection (since it's lazy) - assertEquals( 3, scope.getSessionFactory().getStatistics().getSessionOpenCount() ); - assertEquals( 2, scope.getSessionFactory().getStatistics().getSessionCloseCount() ); + // the extra Sessions are the temp Sessions needed to perform the init: + // first the entity, then the collection (since it's lazy) + assertEquals( 3, scope.getSessionFactory().getStatistics().getSessionOpenCount() ); + assertEquals( 2, scope.getSessionFactory().getStatistics().getSessionCloseCount() ); - // clear Session again. The collection should still be recognized as initialized from above - s.clear(); - assertNotNull( store ); - assertTrue( isPropertyInitialized( store, "inventories" ) ); - assertEquals( 3, scope.getSessionFactory().getStatistics().getSessionOpenCount() ); - assertEquals( 2, scope.getSessionFactory().getStatistics().getSessionCloseCount() ); + // clear Session again. The collection should still be recognized as initialized from above + s.clear(); + assertNotNull( store ); + assertTrue( isPropertyInitialized( store, "inventories" ) ); + assertEquals( 3, scope.getSessionFactory().getStatistics().getSessionOpenCount() ); + assertEquals( 2, scope.getSessionFactory().getStatistics().getSessionCloseCount() ); - // lets clear the Session again and this time reload the Store - s.clear(); - store = s.get( Store.class, 1L ); - s.clear(); - assertNotNull( store ); + // lets clear the Session again and this time reload the Store + s.clear(); + store = s.get( Store.class, 1L ); + s.clear(); + assertNotNull( store ); - // collection should be back to uninitialized since we have a new entity instance - assertFalse( isPropertyInitialized( store, "inventories" ) ); - assertEquals( 3, scope.getSessionFactory().getStatistics().getSessionOpenCount() ); - assertEquals( 2, scope.getSessionFactory().getStatistics().getSessionCloseCount() ); - store.getInventories().size(); - assertTrue( isPropertyInitialized( store, "inventories" ) ); + // collection should be back to uninitialized since we have a new entity instance + assertFalse( isPropertyInitialized( store, "inventories" ) ); + assertEquals( 3, scope.getSessionFactory().getStatistics().getSessionOpenCount() ); + assertEquals( 2, scope.getSessionFactory().getStatistics().getSessionCloseCount() ); + store.getInventories().size(); + assertTrue( isPropertyInitialized( store, "inventories" ) ); - // the extra Sessions are the temp Sessions needed to perform the init: - // first the entity, then the collection (since it's lazy) - assertEquals( 5, scope.getSessionFactory().getStatistics().getSessionOpenCount() ); - assertEquals( 4, scope.getSessionFactory().getStatistics().getSessionCloseCount() ); + // the extra Sessions are the temp Sessions needed to perform the init: + // first the entity, then the collection (since it's lazy) + assertEquals( 5, scope.getSessionFactory().getStatistics().getSessionOpenCount() ); + assertEquals( 4, scope.getSessionFactory().getStatistics().getSessionCloseCount() ); - // clear Session again. The collection should still be recognized as initialized from above - s.clear(); - assertNotNull( store ); - assertTrue( isPropertyInitialized( store, "inventories" ) ); - assertEquals( 5, scope.getSessionFactory().getStatistics().getSessionOpenCount() ); - assertEquals( 4, scope.getSessionFactory().getStatistics().getSessionCloseCount() ); - } ); - } + // clear Session again. The collection should still be recognized as initialized from above + s.clear(); + assertNotNull( store ); + assertTrue( isPropertyInitialized( store, "inventories" ) ); + assertEquals( 5, scope.getSessionFactory().getStatistics().getSessionOpenCount() ); + assertEquals( 4, scope.getSessionFactory().getStatistics().getSessionCloseCount() ); + } ); + } - @AfterEach - public void cleanup(SessionFactoryScope scope) throws Exception { - scope.inTransaction( s -> { - Store store = s.find( Store.class, 1L ); - s.remove( store ); + @AfterEach + public void cleanup(SessionFactoryScope scope) throws Exception { + scope.inTransaction( s -> { + Store store = s.find( Store.class, 1L ); + s.remove( store ); - Product product= s.find( Product.class, "007" ); - s.remove( product ); - } ); - } + Product product= s.find( Product.class, "007" ); + s.remove( product ); + } ); + } - // --- // + // --- // - @Entity - @Table( name = "STORE" ) - static class Store { - @Id - Long id; + @Entity + @Table( name = "STORE" ) + static class Store { + @Id + Long id; - String name; + String name; - @OneToMany( mappedBy = "store", cascade = CascadeType.ALL, fetch = FetchType.LAZY ) - List inventories = new ArrayList<>(); + @OneToMany( mappedBy = "store", cascade = CascadeType.ALL, fetch = FetchType.LAZY ) + List inventories = new ArrayList<>(); - @Version - Integer version; + @Version + Integer version; - Store() { - } + Store() { + } - Store(long id) { - this.id = id; - } + Store(long id) { + this.id = id; + } - Store setName(String name) { - this.name = name; - return this; - } + Store setName(String name) { + this.name = name; + return this; + } - Inventory addInventoryProduct(Product product) { - Inventory inventory = new Inventory( this, product ); - inventories.add( inventory ); - return inventory; - } + Inventory addInventoryProduct(Product product) { + Inventory inventory = new Inventory( this, product ); + inventories.add( inventory ); + return inventory; + } - public List getInventories() { - return Collections.unmodifiableList( inventories ); - } - } + public List getInventories() { + return Collections.unmodifiableList( inventories ); + } + } - @Entity - @Table( name = "INVENTORY" ) - static class Inventory { + @Entity + @Table( name = "INVENTORY" ) + static class Inventory { - @Id - @GeneratedValue - @GenericGenerator( name = "increment", strategy = "increment" ) - Long id = -1L; + @Id + @GeneratedValue + @GenericGenerator( name = "increment", strategy = "increment" ) + Long id = -1L; - @ManyToOne - @JoinColumn( name = "STORE_ID" ) - Store store; + @ManyToOne + @JoinColumn( name = "STORE_ID" ) + Store store; - @ManyToOne - @JoinColumn( name = "PRODUCT_ID" ) - Product product; + @ManyToOne + @JoinColumn( name = "PRODUCT_ID" ) + Product product; - Long quantity; + Long quantity; - BigDecimal storePrice; + BigDecimal storePrice; - public Inventory() { - } + public Inventory() { + } - public Inventory(Store store, Product product) { - this.store = store; - this.product = product; - } + public Inventory(Store store, Product product) { + this.store = store; + this.product = product; + } - Inventory setStore(Store store) { - this.store = store; - return this; - } + Inventory setStore(Store store) { + this.store = store; + return this; + } - Inventory setProduct(Product product) { - this.product = product; - return this; - } + Inventory setProduct(Product product) { + this.product = product; + return this; + } - Inventory setQuantity(Long quantity) { - this.quantity = quantity; - return this; - } + Inventory setQuantity(Long quantity) { + this.quantity = quantity; + return this; + } - Inventory setStorePrice(BigDecimal storePrice) { - this.storePrice = storePrice; - return this; - } - } + Inventory setStorePrice(BigDecimal storePrice) { + this.storePrice = storePrice; + return this; + } + } - @Entity - @Table( name = "PRODUCT" ) - static class Product { - @Id - String id; + @Entity + @Table( name = "PRODUCT" ) + static class Product { + @Id + String id; - String name; + String name; - String description; + String description; - BigDecimal msrp; + BigDecimal msrp; - @Version - Long version; + @Version + Long version; - Product() { - } + Product() { + } - Product(String id) { - this.id = id; - } + Product(String id) { + this.id = id; + } - Product setName(String name) { - this.name = name; - return this; - } + Product setName(String name) { + this.name = name; + return this; + } - Product setDescription(String description) { - this.description = description; - return this; - } + Product setDescription(String description) { + this.description = description; + return this; + } - Product setMsrp(BigDecimal msrp) { - this.msrp = msrp; - return this; - } - } + Product setMsrp(BigDecimal msrp) { + this.msrp = msrp; + return this; + } + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/otherentityentrycontext/OtherEntityEntryContextTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/otherentityentrycontext/OtherEntityEntryContextTest.java index 308a5db267..6cd6cd22ae 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/otherentityentrycontext/OtherEntityEntryContextTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/otherentityentrycontext/OtherEntityEntryContextTest.java @@ -28,56 +28,56 @@ import static org.junit.jupiter.api.Assertions.assertTrue; * @author Gail Badner */ @DomainModel( - annotatedClasses = { - OtherEntityEntryContextTest.Parent.class - } + annotatedClasses = { + OtherEntityEntryContextTest.Parent.class + } ) @SessionFactory @BytecodeEnhanced public class OtherEntityEntryContextTest { - @BeforeEach - public void prepare(SessionFactoryScope scope) { - // Create a Parent - scope.inTransaction( s -> { - s.persist( new Parent( 1L, "first" ) ); - } ); - } + @BeforeEach + public void prepare(SessionFactoryScope scope) { + // Create a Parent + scope.inTransaction( s -> { + s.persist( new Parent( 1L, "first" ) ); + } ); + } - @Test - public void test(SessionFactoryScope scope) { - scope.inTransaction( s -> { - Parent p = s.get( Parent.class, 1L ); - p.name = "third"; + @Test + public void test(SessionFactoryScope scope) { + scope.inTransaction( s -> { + Parent p = s.get( Parent.class, 1L ); + p.name = "third"; - s.merge( p ); - assertTrue( s.contains( p ) ); - s.evict( p ); - assertFalse( s.contains( p ) ); + s.merge( p ); + assertTrue( s.contains( p ) ); + s.evict( p ); + assertFalse( s.contains( p ) ); - p = s.get( Parent.class, p.id ); + p = s.get( Parent.class, p.id ); - assertEquals( "first", p.name ); - } ); - } + assertEquals( "first", p.name ); + } ); + } - // --- // + // --- // - @Entity - @Table( name = "PARENT" ) - static class Parent { + @Entity + @Table( name = "PARENT" ) + static class Parent { - @Id - Long id; + @Id + Long id; - String name; + String name; - Parent() { - } + Parent() { + } - Parent(Long id, String name) { - this.id = id; - this.name = name; - } - } + Parent(Long id, String name) { + this.id = id; + this.name = name; + } + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/pk/EmbeddedPKTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/pk/EmbeddedPKTest.java index 2e3052d0f3..9ca9984003 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/pk/EmbeddedPKTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/pk/EmbeddedPKTest.java @@ -26,194 +26,194 @@ import java.util.Calendar; * @author Gail Badner */ @DomainModel( - annotatedClasses = { - EmbeddedPKTest.WorkOrder.class, EmbeddedPKTest.WorkOrderPK.class - } + annotatedClasses = { + EmbeddedPKTest.WorkOrder.class, EmbeddedPKTest.WorkOrderPK.class + } ) @SessionFactory @BytecodeEnhanced public class EmbeddedPKTest { - @Test - public void test(SessionFactoryScope scope) { - scope.inTransaction( s -> { - s.persist( new WorkOrder() ); - } ); - } + @Test + public void test(SessionFactoryScope scope) { + scope.inTransaction( s -> { + s.persist( new WorkOrder() ); + } ); + } - // --- // + // --- // - @Entity - @IdClass( WorkOrderPK.class ) - @Table( name = "WORK_ORDER" ) - static class WorkOrder { + @Entity + @IdClass( WorkOrderPK.class ) + @Table( name = "WORK_ORDER" ) + static class WorkOrder { - @Id - long id; + @Id + long id; - @Id - long location; + @Id + long location; - int originalQuantity; + int originalQuantity; - int completedQuantity; + int completedQuantity; - @Temporal( TemporalType.TIMESTAMP ) - Calendar dueDate; + @Temporal( TemporalType.TIMESTAMP ) + Calendar dueDate; - @Temporal( TemporalType.TIMESTAMP ) - Calendar startDate; + @Temporal( TemporalType.TIMESTAMP ) + Calendar startDate; - String assemblyId; + String assemblyId; - @Version - long version; + @Version + long version; - WorkOrder() { - this( "", 1, 0, Calendar.getInstance() ); - } + WorkOrder() { + this( "", 1, 0, Calendar.getInstance() ); + } - WorkOrder(String assemblyId, int origQty, int location, Calendar dueDate) { - if ( origQty < 1 ) { - throw new IllegalArgumentException( "WorkOrder can not be created with original quantity " + origQty + ". Must be > 0" ); - } - if ( dueDate == null ) { - throw new IllegalArgumentException( "WorkOrder can not be created with null due Date" ); - } - this.assemblyId = assemblyId; - this.originalQuantity = origQty; - this.dueDate = dueDate; - this.location = location; - } + WorkOrder(String assemblyId, int origQty, int location, Calendar dueDate) { + if ( origQty < 1 ) { + throw new IllegalArgumentException( "WorkOrder can not be created with original quantity " + origQty + ". Must be > 0" ); + } + if ( dueDate == null ) { + throw new IllegalArgumentException( "WorkOrder can not be created with null due Date" ); + } + this.assemblyId = assemblyId; + this.originalQuantity = origQty; + this.dueDate = dueDate; + this.location = location; + } - public long getId() { - return id; - } + public long getId() { + return id; + } - public void setId(long id) { - this.id = id; - } + public void setId(long id) { + this.id = id; + } - // --- // + // --- // - String getAssemblyId() { - return assemblyId; - } + String getAssemblyId() { + return assemblyId; + } - void setAssemblyId(String assemblyId) { - this.assemblyId = assemblyId; - } + void setAssemblyId(String assemblyId) { + this.assemblyId = assemblyId; + } - int getCompletedQuantity() { - return completedQuantity; - } + int getCompletedQuantity() { + return completedQuantity; + } - void setCompletedQuantity(int compQty) { - this.completedQuantity = compQty; - } + void setCompletedQuantity(int compQty) { + this.completedQuantity = compQty; + } - Calendar getDueDate() { - return (Calendar) dueDate.clone(); - } + Calendar getDueDate() { + return (Calendar) dueDate.clone(); + } - void setDueDate(Calendar dueDate) { - this.dueDate = dueDate; - } + void setDueDate(Calendar dueDate) { + this.dueDate = dueDate; + } - int getOriginalQuantity() { - return originalQuantity; - } + int getOriginalQuantity() { + return originalQuantity; + } - void setOriginalQuantity(int originalQuantity) { - this.originalQuantity = originalQuantity; - } + void setOriginalQuantity(int originalQuantity) { + this.originalQuantity = originalQuantity; + } - // --- // + // --- // - long getLocation() { - return location; - } + long getLocation() { + return location; + } - void setLocation(int location) { - this.location = location; - } + void setLocation(int location) { + this.location = location; + } - Calendar getStartDate() { - return (Calendar) startDate.clone(); - } + Calendar getStartDate() { + return (Calendar) startDate.clone(); + } - void setStartDate(Calendar instance) { - startDate = instance; - } + void setStartDate(Calendar instance) { + startDate = instance; + } - long getVersion() { - return version; - } + long getVersion() { + return version; + } - // Processing methods + // Processing methods - boolean update() { - return true; - } + boolean update() { + return true; + } - boolean setStatusCompleted() { - return true; - } + boolean setStatusCompleted() { + return true; + } - void advanceStatus() { - } + void advanceStatus() { + } - void setStatusCancelled() { - } + void setStatusCancelled() { + } - // --- // + // --- // - @Override - public boolean equals(Object other) { - return this == other || other != null && other instanceof WorkOrder && id == ( (WorkOrder) other ).id; - } + @Override + public boolean equals(Object other) { + return this == other || other != null && other instanceof WorkOrder && id == ( (WorkOrder) other ).id; + } - @Override - public int hashCode() { - return (int) ( id ^ id >>> 32 ); - } + @Override + public int hashCode() { + return (int) ( id ^ id >>> 32 ); + } - @Override - public String toString() { - return "WorkOrder:[" + id + "]"; - } - } + @Override + public String toString() { + return "WorkOrder:[" + id + "]"; + } + } - static class WorkOrderPK implements Serializable { - long id; - long location; + static class WorkOrderPK implements Serializable { + long id; + long location; - WorkOrderPK() { - } + WorkOrderPK() { + } - public WorkOrderPK(int location, int id) { - this.location = location; - this.id = id; - } + public WorkOrderPK(int location, int id) { + this.location = location; + this.id = id; + } - public long getId() { - return id; - } + public long getId() { + return id; + } - public long getLocation() { - return location; - } + public long getLocation() { + return location; + } - // --- // + // --- // - @Override - public boolean equals(Object other) { - return this == other || other != null && other instanceof WorkOrder && id == ( (WorkOrder) other ).id && location == ( (WorkOrder) other ).location; - } + @Override + public boolean equals(Object other) { + return this == other || other != null && other instanceof WorkOrder && id == ( (WorkOrder) other ).id && location == ( (WorkOrder) other ).location; + } - @Override - public int hashCode() { - return (int) ( 31 * ( id ^ id >>> 32 ) + ( location ^ location >>> 32 ) ); - } - } + @Override + public int hashCode() { + return (int) ( 31 * ( id ^ id >>> 32 ) + ( location ^ location >>> 32 ) ); + } + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/tracker/CompositeOwnerTrackerTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/tracker/CompositeOwnerTrackerTest.java index f385b85291..a9a962e613 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/tracker/CompositeOwnerTrackerTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/tracker/CompositeOwnerTrackerTest.java @@ -17,53 +17,53 @@ import static org.junit.Assert.assertEquals; */ public class CompositeOwnerTrackerTest { - private int counter = 0; + private int counter = 0; - @Test - public void testCompositeOwnerTracker() { + @Test + public void testCompositeOwnerTracker() { - CompositeOwnerTracker tracker = new CompositeOwnerTracker(); - tracker.add( "foo", new TestCompositeOwner() ); + CompositeOwnerTracker tracker = new CompositeOwnerTracker(); + tracker.add( "foo", new TestCompositeOwner() ); - tracker.callOwner( ".street1" ); - assertEquals( 1, counter ); - tracker.add( "bar", new TestCompositeOwner() ); - tracker.callOwner( ".city" ); - assertEquals( 3, counter ); + tracker.callOwner( ".street1" ); + assertEquals( 1, counter ); + tracker.add( "bar", new TestCompositeOwner() ); + tracker.callOwner( ".city" ); + assertEquals( 3, counter ); - tracker.removeOwner( "foo" ); + tracker.removeOwner( "foo" ); - tracker.callOwner( ".country" ); - assertEquals( 4, counter ); - tracker.removeOwner( "bar" ); + tracker.callOwner( ".country" ); + assertEquals( 4, counter ); + tracker.removeOwner( "bar" ); - tracker.callOwner( ".country" ); + tracker.callOwner( ".country" ); - tracker.add( "moo", new TestCompositeOwner() ); - tracker.callOwner( ".country" ); - assertEquals( 5, counter ); - } + tracker.add( "moo", new TestCompositeOwner() ); + tracker.callOwner( ".country" ); + assertEquals( 5, counter ); + } - class TestCompositeOwner implements CompositeOwner { + class TestCompositeOwner implements CompositeOwner { - @Override - public void $$_hibernate_trackChange(String attributeName) { - if ( counter == 0 ) { - assertEquals( "foo.street1", attributeName ); - } - if ( counter == 1 ) { - assertEquals( "foo.city", attributeName ); - } - if ( counter == 2 ) { - assertEquals( "bar.city", attributeName ); - } - if ( counter == 3 ) { - assertEquals( "bar.country", attributeName ); - } - if ( counter == 4 ) { - assertEquals( "moo.country", attributeName ); - } - counter++; - } - } + @Override + public void $$_hibernate_trackChange(String attributeName) { + if ( counter == 0 ) { + assertEquals( "foo.street1", attributeName ); + } + if ( counter == 1 ) { + assertEquals( "foo.city", attributeName ); + } + if ( counter == 2 ) { + assertEquals( "bar.city", attributeName ); + } + if ( counter == 3 ) { + assertEquals( "bar.country", attributeName ); + } + if ( counter == 4 ) { + assertEquals( "moo.country", attributeName ); + } + counter++; + } + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/tracker/DirtyTrackerTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/tracker/DirtyTrackerTest.java index 04ff5fe545..b0fdb50e2b 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/tracker/DirtyTrackerTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/tracker/DirtyTrackerTest.java @@ -21,69 +21,69 @@ import static org.junit.Assert.assertTrue; */ public class DirtyTrackerTest { - @Test - public void testSimpleTracker() { - DirtyTracker tracker = new SimpleFieldTracker(); - assertTrue( tracker.isEmpty() ); - assertEquals( 0, tracker.get().length ); + @Test + public void testSimpleTracker() { + DirtyTracker tracker = new SimpleFieldTracker(); + assertTrue( tracker.isEmpty() ); + assertEquals( 0, tracker.get().length ); - tracker.add( "foo" ); - assertFalse( tracker.isEmpty() ); - assertArrayEquals( tracker.get(), new String[]{"foo"} ); + tracker.add( "foo" ); + assertFalse( tracker.isEmpty() ); + assertArrayEquals( tracker.get(), new String[]{"foo"} ); - tracker.clear(); - assertTrue( tracker.isEmpty() ); - assertEquals( 0, tracker.get().length ); + tracker.clear(); + assertTrue( tracker.isEmpty() ); + assertEquals( 0, tracker.get().length ); - tracker.add( "foo" ); - tracker.add( "bar" ); - tracker.add( "another.bar" ); - tracker.add( "foo" ); - tracker.add( "another.foo" ); - tracker.add( "another.bar" ); - assertEquals( 4, tracker.get().length ); + tracker.add( "foo" ); + tracker.add( "bar" ); + tracker.add( "another.bar" ); + tracker.add( "foo" ); + tracker.add( "another.foo" ); + tracker.add( "another.bar" ); + assertEquals( 4, tracker.get().length ); - tracker.suspend( true ); - tracker.add( "one more" ); - assertEquals( 4, tracker.get().length ); - } + tracker.suspend( true ); + tracker.add( "one more" ); + assertEquals( 4, tracker.get().length ); + } - @Test - public void testSortedTracker() { - DirtyTracker tracker = new SortedFieldTracker(); - assertTrue( tracker.isEmpty() ); - assertEquals( 0, tracker.get().length ); + @Test + public void testSortedTracker() { + DirtyTracker tracker = new SortedFieldTracker(); + assertTrue( tracker.isEmpty() ); + assertEquals( 0, tracker.get().length ); - tracker.add( "foo" ); - assertFalse( tracker.isEmpty() ); - assertArrayEquals( tracker.get(), new String[]{"foo"} ); + tracker.add( "foo" ); + assertFalse( tracker.isEmpty() ); + assertArrayEquals( tracker.get(), new String[]{"foo"} ); - tracker.clear(); - assertTrue( tracker.isEmpty() ); - assertEquals( 0, tracker.get().length ); + tracker.clear(); + assertTrue( tracker.isEmpty() ); + assertEquals( 0, tracker.get().length ); - tracker.add( "foo" ); - tracker.add( "bar" ); - tracker.add( "another.bar" ); - tracker.add( "foo" ); - tracker.add( "another.foo" ); - tracker.add( "another.bar" ); - assertEquals( 4, tracker.get().length ); + tracker.add( "foo" ); + tracker.add( "bar" ); + tracker.add( "another.bar" ); + tracker.add( "foo" ); + tracker.add( "another.foo" ); + tracker.add( "another.bar" ); + assertEquals( 4, tracker.get().length ); - // the algorithm for this implementation relies on the fact that the array is kept sorted, so let's check it really is - assertTrue( isSorted( tracker.get() ) ); + // the algorithm for this implementation relies on the fact that the array is kept sorted, so let's check it really is + assertTrue( isSorted( tracker.get() ) ); - tracker.suspend( true ); - tracker.add( "one more" ); - assertEquals( 4, tracker.get().length ); - } + tracker.suspend( true ); + tracker.add( "one more" ); + assertEquals( 4, tracker.get().length ); + } - private boolean isSorted(String[] arr) { - for ( int i = 1; i < arr.length; i++ ) { - if ( arr[i - 1].compareTo( arr[i] ) > 0 ) { - return false; - } - } - return true; - } + private boolean isSorted(String[] arr) { + for ( int i = 1; i < arr.length; i++ ) { + if ( arr[i - 1].compareTo( arr[i] ) > 0 ) { + return false; + } + } + return true; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/version/VersionedEntityTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/version/VersionedEntityTest.java index d89a3a3b46..bfb61e3740 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/version/VersionedEntityTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/version/VersionedEntityTest.java @@ -38,211 +38,211 @@ import static org.junit.jupiter.api.Assertions.assertTrue; @JiraKey("HHH-15134") @DomainModel( - annotatedClasses = { - VersionedEntityTest.FooEntity.class, VersionedEntityTest.BarEntity.class, VersionedEntityTest.BazEntity.class - } + annotatedClasses = { + VersionedEntityTest.FooEntity.class, VersionedEntityTest.BarEntity.class, VersionedEntityTest.BazEntity.class + } ) @SessionFactory @BytecodeEnhanced public class VersionedEntityTest { - private final Long parentID = 1L; + private final Long parentID = 1L; - @BeforeEach - public void prepare(SessionFactoryScope scope) { - scope.inTransaction( em -> { - final FooEntity entity = FooEntity.of( parentID, "foo" ); - em.persist( entity ); - } ); - } + @BeforeEach + public void prepare(SessionFactoryScope scope) { + scope.inTransaction( em -> { + final FooEntity entity = FooEntity.of( parentID, "foo" ); + em.persist( entity ); + } ); + } - @Test - public void testUpdateVersionedEntity(SessionFactoryScope scope) { - scope.inTransaction( em -> { - final FooEntity entity = em.getReference( FooEntity.class, parentID ); + @Test + public void testUpdateVersionedEntity(SessionFactoryScope scope) { + scope.inTransaction( em -> { + final FooEntity entity = em.getReference( FooEntity.class, parentID ); - assertFalse( isInitialized( entity ) ); - assertTrue( Hibernate.isPropertyInitialized( entity, "id" ) ); - assertFalse( Hibernate.isPropertyInitialized( entity, "name" ) ); - assertFalse( Hibernate.isPropertyInitialized( entity, "version" ) ); - assertFalse( Hibernate.isPropertyInitialized( entity, "bars" ) ); - assertFalse( Hibernate.isPropertyInitialized( entity, "bazzes" ) ); + assertFalse( isInitialized( entity ) ); + assertTrue( Hibernate.isPropertyInitialized( entity, "id" ) ); + assertFalse( Hibernate.isPropertyInitialized( entity, "name" ) ); + assertFalse( Hibernate.isPropertyInitialized( entity, "version" ) ); + assertFalse( Hibernate.isPropertyInitialized( entity, "bars" ) ); + assertFalse( Hibernate.isPropertyInitialized( entity, "bazzes" ) ); - entity.setName( "bar" ); - }); - } + entity.setName( "bar" ); + }); + } - @MappedSuperclass - public static abstract class AbstractEntity { + @MappedSuperclass + public static abstract class AbstractEntity { - public abstract T getId(); + public abstract T getId(); - public abstract void setId(T id); + public abstract void setId(T id); - @Override - public int hashCode() { - return getClass().hashCode(); - } + @Override + public int hashCode() { + return getClass().hashCode(); + } - @Override - public boolean equals(Object obj) { - if (obj == this) return true; - if (obj == null || obj.getClass() != getClass()) return false; + @Override + public boolean equals(Object obj) { + if (obj == this) return true; + if (obj == null || obj.getClass() != getClass()) return false; - final AbstractEntity other = (AbstractEntity) obj; - return getId() != null && getId().equals(other.getId()); - } - } + final AbstractEntity other = (AbstractEntity) obj; + return getId() != null && getId().equals(other.getId()); + } + } - @Entity(name = "FooEntity") - public static class FooEntity extends AbstractEntity { + @Entity(name = "FooEntity") + public static class FooEntity extends AbstractEntity { - @Id - private long id; - @Version - private int version; + @Id + private long id; + @Version + private int version; - private String name; + private String name; - @OneToMany(mappedBy = "foo", cascade = CascadeType.ALL, targetEntity = BarEntity.class, orphanRemoval = true) - public Set bars = new HashSet<>(); + @OneToMany(mappedBy = "foo", cascade = CascadeType.ALL, targetEntity = BarEntity.class, orphanRemoval = true) + public Set bars = new HashSet<>(); - @OneToMany(mappedBy = "foo", cascade = CascadeType.ALL, targetEntity = BazEntity.class, orphanRemoval = true) - public Set bazzes = new HashSet<>(); + @OneToMany(mappedBy = "foo", cascade = CascadeType.ALL, targetEntity = BazEntity.class, orphanRemoval = true) + public Set bazzes = new HashSet<>(); - public static FooEntity of(long id, String name) { - final FooEntity f = new FooEntity(); - f.id = id; - f.name = name; - return f; - } + public static FooEntity of(long id, String name) { + final FooEntity f = new FooEntity(); + f.id = id; + f.name = name; + return f; + } - @Override - public Long getId() { - return id; - } + @Override + public Long getId() { + return id; + } - @Override - public void setId(Long id) { - this.id = id; - } + @Override + public void setId(Long id) { + this.id = id; + } - public int getVersion() { - return version; - } + public int getVersion() { + return version; + } - public void setVersion(int version) { - this.version = version; - } + public void setVersion(int version) { + this.version = version; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - public Set getBars() { - return bars; - } + public Set getBars() { + return bars; + } - public void addBar(BarEntity bar) { - bars.add(bar); - bar.setFoo(this); - } + public void addBar(BarEntity bar) { + bars.add(bar); + bar.setFoo(this); + } - public void removeBar(BarEntity bar) { - bars.remove(bar); - bar.setFoo(null); - } + public void removeBar(BarEntity bar) { + bars.remove(bar); + bar.setFoo(null); + } - public Set getBazzes() { - return bazzes; - } + public Set getBazzes() { + return bazzes; + } - public void addBaz(BazEntity baz) { - bazzes.add(baz); - baz.setFoo(this); - } + public void addBaz(BazEntity baz) { + bazzes.add(baz); + baz.setFoo(this); + } - public void removeBaz(BazEntity baz) { - bazzes.remove(baz); - baz.setFoo(null); - } + public void removeBaz(BazEntity baz) { + bazzes.remove(baz); + baz.setFoo(null); + } - @Override - public String toString() { - return String.format("FooEntity: id=%d, version=%d, name=%s", id, version, name); - } - } + @Override + public String toString() { + return String.format("FooEntity: id=%d, version=%d, name=%s", id, version, name); + } + } - @Entity(name = "BazEntity") - public static class BazEntity extends AbstractEntity { + @Entity(name = "BazEntity") + public static class BazEntity extends AbstractEntity { - @Id - @GeneratedValue - private long id; + @Id + @GeneratedValue + private long id; - @ManyToOne(fetch = FetchType.LAZY, optional = false) - @JoinColumn(foreignKey = @ForeignKey(name = "fk_baz_foo"), nullable = false) - private FooEntity foo; + @ManyToOne(fetch = FetchType.LAZY, optional = false) + @JoinColumn(foreignKey = @ForeignKey(name = "fk_baz_foo"), nullable = false) + private FooEntity foo; - @Override - public Long getId() { - return id; - } + @Override + public Long getId() { + return id; + } - @Override - public void setId(Long id) { - this.id = id; - } + @Override + public void setId(Long id) { + this.id = id; + } - public FooEntity getFoo() { - return foo; - } + public FooEntity getFoo() { + return foo; + } - public void setFoo(FooEntity foo) { - this.foo = foo; - } + public void setFoo(FooEntity foo) { + this.foo = foo; + } - @Override - public String toString() { - return String.format("BazEntity: id=%d", id); - } - } + @Override + public String toString() { + return String.format("BazEntity: id=%d", id); + } + } - @Entity(name = "BarEntity") - public static class BarEntity extends AbstractEntity { + @Entity(name = "BarEntity") + public static class BarEntity extends AbstractEntity { - @Id - @GeneratedValue - private long id; + @Id + @GeneratedValue + private long id; - @ManyToOne(fetch = FetchType.LAZY, optional = false) - @JoinColumn(foreignKey = @ForeignKey(name = "fk_bar_foo"), nullable = false) - private FooEntity foo; + @ManyToOne(fetch = FetchType.LAZY, optional = false) + @JoinColumn(foreignKey = @ForeignKey(name = "fk_bar_foo"), nullable = false) + private FooEntity foo; - @Override - public Long getId() { - return id; - } + @Override + public Long getId() { + return id; + } - @Override - public void setId(Long id) { - this.id = id; - } + @Override + public void setId(Long id) { + this.id = id; + } - public FooEntity getFoo() { - return foo; - } + public FooEntity getFoo() { + return foo; + } - public void setFoo(FooEntity foo) { - this.foo = foo; - } + public void setFoo(FooEntity foo) { + this.foo = foo; + } - @Override - public String toString() { - return String.format("BarEntity: id=%d", id); - } - } + @Override + public String toString() { + return String.format("BarEntity: id=%d", id); + } + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/cache/ByteCodeEnhancedImmutableReferenceCacheTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/cache/ByteCodeEnhancedImmutableReferenceCacheTest.java index 5c9279a458..34b5e45bde 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/cache/ByteCodeEnhancedImmutableReferenceCacheTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/cache/ByteCodeEnhancedImmutableReferenceCacheTest.java @@ -118,7 +118,7 @@ public class ByteCodeEnhancedImmutableReferenceCacheTest extends BaseCoreFunctio s1 = openSession(); s1.beginTransaction(); myReferenceData = s1.get( MyEnhancedReferenceData.class, myReferenceData.getId() ); - myOtherReferenceData = s1.get( MyEnhancedReferenceData.class, myOtherReferenceData.getId() ); + myOtherReferenceData = s1.get( MyEnhancedReferenceData.class, myOtherReferenceData.getId() ); assertTrue( s1.contains( myReferenceData ) ); assertTrue( s1.contains( myOtherReferenceData ) ); // prev/next references should be null; entityEntry should be non-null; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/cache/CollectionCacheEvictionTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/cache/CollectionCacheEvictionTest.java index ad13089285..1f1c743e1b 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/cache/CollectionCacheEvictionTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/cache/CollectionCacheEvictionTest.java @@ -89,7 +89,7 @@ public class CollectionCacheEvictionTest extends BaseCoreFunctionalTestCase { @Test public void testCachedValueAfterEviction() { - CollectionPersister persister = sessionFactory().getRuntimeMetamodels() + CollectionPersister persister = sessionFactory().getRuntimeMetamodels() .getMappingMetamodel() .getCollectionDescriptor(Company.class.getName() + ".users"); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/cache/hhh13179/DiscriminatorSubclassPerson.java b/hibernate-core/src/test/java/org/hibernate/orm/test/cache/hhh13179/DiscriminatorSubclassPerson.java index 20de0a348e..b17ee5f605 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/cache/hhh13179/DiscriminatorSubclassPerson.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/cache/hhh13179/DiscriminatorSubclassPerson.java @@ -8,13 +8,13 @@ package org.hibernate.orm.test.cache.hhh13179; public abstract class DiscriminatorSubclassPerson { - private Long oid; +private Long oid; - public Long getOid() { - return oid; - } - - public void setOid(Long oid) { - this.oid = oid; - } +public Long getOid() { + return oid; +} + +public void setOid(Long oid) { + this.oid = oid; +} } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/cache/hhh13179/JoinedSubclassPerson.java b/hibernate-core/src/test/java/org/hibernate/orm/test/cache/hhh13179/JoinedSubclassPerson.java index 6856b3cffb..a1d5424011 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/cache/hhh13179/JoinedSubclassPerson.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/cache/hhh13179/JoinedSubclassPerson.java @@ -8,13 +8,13 @@ package org.hibernate.orm.test.cache.hhh13179; public abstract class JoinedSubclassPerson { - private Long oid; +private Long oid; - public Long getOid() { - return oid; - } - - public void setOid(Long oid) { - this.oid = oid; - } +public Long getOid() { + return oid; +} + +public void setOid(Long oid) { + this.oid = oid; +} } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/cache/hhh13179/UnionSubclassPerson.java b/hibernate-core/src/test/java/org/hibernate/orm/test/cache/hhh13179/UnionSubclassPerson.java index 8fc9cb90ea..a03ad997d6 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/cache/hhh13179/UnionSubclassPerson.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/cache/hhh13179/UnionSubclassPerson.java @@ -8,13 +8,13 @@ package org.hibernate.orm.test.cache.hhh13179; public abstract class UnionSubclassPerson { - private Long oid; +private Long oid; - public Long getOid() { - return oid; - } - - public void setOid(Long oid) { - this.oid = oid; - } +public Long getOid() { + return oid; +} + +public void setOid(Long oid) { + this.oid = oid; +} } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/caching/CacheReadOnlyStrategyTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/caching/CacheReadOnlyStrategyTest.java index 34f882da9e..c88f0d4c6e 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/caching/CacheReadOnlyStrategyTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/caching/CacheReadOnlyStrategyTest.java @@ -98,8 +98,8 @@ public class CacheReadOnlyStrategyTest { scope.inTransaction( entityManager -> { assertFalse( scope.getEntityManagerFactory() - .getCache() - .contains( TestEntity.class, testEntityId ) ); + .getCache() + .contains( TestEntity.class, testEntityId ) ); List results = entityManager.createQuery( "select t from TestEntity t where t.id = :id", TestEntity.class diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/caching/mocked/NaturalIdCacheKeyTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/caching/mocked/NaturalIdCacheKeyTest.java index be81be6637..494371c996 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/caching/mocked/NaturalIdCacheKeyTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/caching/mocked/NaturalIdCacheKeyTest.java @@ -31,45 +31,45 @@ import static org.mockito.Mockito.when; public class NaturalIdCacheKeyTest { - @Test - public void testSerializationRoundTrip() throws Exception { - final SessionFactoryImplementor sessionFactoryImplementor = mock( SessionFactoryImplementor.class ); - final SessionImplementor sessionImplementor = mock( SessionImplementor.class ); + @Test + public void testSerializationRoundTrip() throws Exception { + final SessionFactoryImplementor sessionFactoryImplementor = mock( SessionFactoryImplementor.class ); + final SessionImplementor sessionImplementor = mock( SessionImplementor.class ); - final RuntimeMetamodelsImplementor runtimeMetamodels = mock( RuntimeMetamodelsImplementor.class ); - final EntityPersister entityPersister = mock( EntityPersister.class ); - final NaturalIdMapping naturalIdMapping = mock( NaturalIdMapping.class ); + final RuntimeMetamodelsImplementor runtimeMetamodels = mock( RuntimeMetamodelsImplementor.class ); + final EntityPersister entityPersister = mock( EntityPersister.class ); + final NaturalIdMapping naturalIdMapping = mock( NaturalIdMapping.class ); - when( sessionImplementor.getFactory() ).thenReturn( sessionFactoryImplementor ); - when( sessionFactoryImplementor.getRuntimeMetamodels()).thenReturn( runtimeMetamodels ); - when( runtimeMetamodels.getEntityMappingType( anyString() ) ).thenReturn( entityPersister ); - when( entityPersister.getRootEntityName() ).thenReturn( "EntityName" ); - when( entityPersister.getNaturalIdMapping() ).thenReturn( naturalIdMapping ); - when( naturalIdMapping.disassemble( any(), eq( sessionImplementor ) ) ).thenAnswer( invocation -> invocation.getArguments()[0] ); - when( naturalIdMapping.calculateHashCode( any() ) ).thenAnswer( invocation -> invocation.getArguments()[0].hashCode() ); + when( sessionImplementor.getFactory() ).thenReturn( sessionFactoryImplementor ); + when( sessionFactoryImplementor.getRuntimeMetamodels()).thenReturn( runtimeMetamodels ); + when( runtimeMetamodels.getEntityMappingType( anyString() ) ).thenReturn( entityPersister ); + when( entityPersister.getRootEntityName() ).thenReturn( "EntityName" ); + when( entityPersister.getNaturalIdMapping() ).thenReturn( naturalIdMapping ); + when( naturalIdMapping.disassemble( any(), eq( sessionImplementor ) ) ).thenAnswer( invocation -> invocation.getArguments()[0] ); + when( naturalIdMapping.calculateHashCode( any() ) ).thenAnswer( invocation -> invocation.getArguments()[0].hashCode() ); - final NaturalIdCacheKey key = (NaturalIdCacheKey) DefaultCacheKeysFactory.staticCreateNaturalIdKey( new Object[] {"a", "b", "c"}, entityPersister, sessionImplementor ); + final NaturalIdCacheKey key = (NaturalIdCacheKey) DefaultCacheKeysFactory.staticCreateNaturalIdKey( new Object[] {"a", "b", "c"}, entityPersister, sessionImplementor ); - final ByteArrayOutputStream baos = new ByteArrayOutputStream(); - final ObjectOutputStream oos = new ObjectOutputStream(baos); - oos.writeObject(key); + final ByteArrayOutputStream baos = new ByteArrayOutputStream(); + final ObjectOutputStream oos = new ObjectOutputStream(baos); + oos.writeObject(key); - final ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray())); - final NaturalIdCacheKey keyClone = (NaturalIdCacheKey) ois.readObject(); + final ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray())); + final NaturalIdCacheKey keyClone = (NaturalIdCacheKey) ois.readObject(); - assertEquals(key, keyClone); - assertEquals(key.hashCode(), keyClone.hashCode()); - assertEquals(key.toString(), keyClone.toString()); - assertEquals(key.getEntityName(), keyClone.getEntityName()); - assertArrayEquals( (Object[]) key.getNaturalIdValues(), (Object[]) keyClone.getNaturalIdValues() ); - assertEquals(key.getTenantId(), keyClone.getTenantId()); + assertEquals(key, keyClone); + assertEquals(key.hashCode(), keyClone.hashCode()); + assertEquals(key.toString(), keyClone.toString()); + assertEquals(key.getEntityName(), keyClone.getEntityName()); + assertArrayEquals( (Object[]) key.getNaturalIdValues(), (Object[]) keyClone.getNaturalIdValues() ); + assertEquals(key.getTenantId(), keyClone.getTenantId()); - } + } - @Test - public void testSimpleKeyCreation() { + @Test + public void testSimpleKeyCreation() { - } + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/cascade/A.java b/hibernate-core/src/test/java/org/hibernate/orm/test/cascade/A.java index dfcc1674cd..ceb270c2e5 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/cascade/A.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/cascade/A.java @@ -11,94 +11,94 @@ import java.util.Set; public class A { - // Constants ----------------------------------------------------------------------------------- + // Constants ----------------------------------------------------------------------------------- - // Static -------------------------------------------------------------------------------------- + // Static -------------------------------------------------------------------------------------- - // Attributes ---------------------------------------------------------------------------------- + // Attributes ---------------------------------------------------------------------------------- - private long id; + private long id; - private String data; + private String data; - // A 1 - * H - private Set hs; + // A 1 - * H + private Set hs; - // A 1 - 1 G - private G g; + // A 1 - 1 G + private G g; - // Constructors -------------------------------------------------------------------------------- + // Constructors -------------------------------------------------------------------------------- - public A() - { - hs = new HashSet(); - } + public A() + { + hs = new HashSet(); + } - public A(String data) - { - this(); - this.data = data; - } + public A(String data) + { + this(); + this.data = data; + } - // Public -------------------------------------------------------------------------------------- + // Public -------------------------------------------------------------------------------------- - public long getId() - { - return id; - } + public long getId() + { + return id; + } - public void setId(long id) - { - this.id = id; - } + public void setId(long id) + { + this.id = id; + } - public void setData(String data) - { - this.data = data; - } + public void setData(String data) + { + this.data = data; + } - public String getData() - { - return data; - } + public String getData() + { + return data; + } - public void setHs(Set hs) - { - this.hs = hs; - } + public void setHs(Set hs) + { + this.hs = hs; + } - public Set getHs() - { - return hs; - } + public Set getHs() + { + return hs; + } - public void setG(G g) - { - this.g = g; - } + public void setG(G g) + { + this.g = g; + } - public G getG() - { - return g; - } + public G getG() + { + return g; + } - public void addH(H h) - { - hs.add(h); - h.setA(this); - } + public void addH(H h) + { + hs.add(h); + h.setA(this); + } - public String toString() - { - return "A[" + id + ", " + data + "]"; - } + public String toString() + { + return "A[" + id + ", " + data + "]"; + } - // Package protected --------------------------------------------------------------------------- + // Package protected --------------------------------------------------------------------------- - // Protected ----------------------------------------------------------------------------------- + // Protected ----------------------------------------------------------------------------------- - // Private ------------------------------------------------------------------------------------- + // Private ------------------------------------------------------------------------------------- - // Inner classes ------------------------------------------------------------------------------- + // Inner classes ------------------------------------------------------------------------------- } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/cascade/G.java b/hibernate-core/src/test/java/org/hibernate/orm/test/cascade/G.java index f12893ccc0..876965e46c 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/cascade/G.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/cascade/G.java @@ -11,82 +11,82 @@ import java.util.Set; public class G { - // Constants ----------------------------------------------------------------------------------- + // Constants ----------------------------------------------------------------------------------- - // Static -------------------------------------------------------------------------------------- + // Static -------------------------------------------------------------------------------------- - // Attributes ---------------------------------------------------------------------------------- + // Attributes ---------------------------------------------------------------------------------- - private long id; + private long id; - private String data; + private String data; - // A 1 <-> 1 G - private A a; + // A 1 <-> 1 G + private A a; - // G * <-> * H - private Set hs; + // G * <-> * H + private Set hs; - // Constructors -------------------------------------------------------------------------------- + // Constructors -------------------------------------------------------------------------------- - public G() - { - this(null); - } + public G() + { + this(null); + } - public G(String data) - { - this.data = data; - hs = new HashSet(); - } + public G(String data) + { + this.data = data; + hs = new HashSet(); + } - // Public -------------------------------------------------------------------------------------- + // Public -------------------------------------------------------------------------------------- - public String getData() - { - return data; - } + public String getData() + { + return data; + } - public void setData(String data) - { - this.data = data; - } + public void setData(String data) + { + this.data = data; + } - public A getA() - { - return a; - } + public A getA() + { + return a; + } - public void setA(A a) - { - this.a = a; - } + public void setA(A a) + { + this.a = a; + } - public Set getHs() - { - return hs; - } + public Set getHs() + { + return hs; + } - public void setHs(Set s) - { - hs = s; - } + public void setHs(Set s) + { + hs = s; + } - // Package protected --------------------------------------------------------------------------- + // Package protected --------------------------------------------------------------------------- - long getId() - { - return id; - } + long getId() + { + return id; + } - // Protected ----------------------------------------------------------------------------------- + // Protected ----------------------------------------------------------------------------------- - // Private ------------------------------------------------------------------------------------- + // Private ------------------------------------------------------------------------------------- - private void setId(long id) - { - this.id = id; - } + private void setId(long id) + { + this.id = id; + } - // Inner classes ------------------------------------------------------------------------------- + // Inner classes ------------------------------------------------------------------------------- } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/cascade/H.java b/hibernate-core/src/test/java/org/hibernate/orm/test/cascade/H.java index 5f0401772d..2440589195 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/cascade/H.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/cascade/H.java @@ -11,81 +11,81 @@ import java.util.Set; public class H { - // Constants ----------------------------------------------------------------------------------- + // Constants ----------------------------------------------------------------------------------- - // Static -------------------------------------------------------------------------------------- + // Static -------------------------------------------------------------------------------------- - // Attributes ---------------------------------------------------------------------------------- + // Attributes ---------------------------------------------------------------------------------- - private long id; + private long id; - private String data; + private String data; - private A a; + private A a; - // G * <-> * H - private Set gs; + // G * <-> * H + private Set gs; - // Constructors -------------------------------------------------------------------------------- + // Constructors -------------------------------------------------------------------------------- - public H() - { - this(null); - } + public H() + { + this(null); + } - public H(String data) - { - this.data = data; - gs = new HashSet(); - } + public H(String data) + { + this.data = data; + gs = new HashSet(); + } - // Public -------------------------------------------------------------------------------------- + // Public -------------------------------------------------------------------------------------- - public long getId() - { - return id; - } + public long getId() + { + return id; + } - public String getData() - { - return data; - } + public String getData() + { + return data; + } - public void setData(String data) - { - this.data = data; - } + public void setData(String data) + { + this.data = data; + } - public A getA() - { - return a; - } + public A getA() + { + return a; + } - public void setA(A a) - { - this.a = a; - } + public void setA(A a) + { + this.a = a; + } - public Set getGs() - { - return gs; - } + public Set getGs() + { + return gs; + } - public void setGs(Set gs) - { - this.gs = gs; - } + public void setGs(Set gs) + { + this.gs = gs; + } - // Package protected --------------------------------------------------------------------------- + // Package protected --------------------------------------------------------------------------- - // Protected ----------------------------------------------------------------------------------- + // Protected ----------------------------------------------------------------------------------- - // Private ------------------------------------------------------------------------------------- + // Private ------------------------------------------------------------------------------------- - private void setId(long id) - { - this.id = id; - } + private void setId(long id) + { + this.id = id; + } - // Inner classes ------------------------------------------------------------------------------- + // Inner classes ------------------------------------------------------------------------------- } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/cascade/circle/delete/Address.java b/hibernate-core/src/test/java/org/hibernate/orm/test/cascade/circle/delete/Address.java index c7d07f994f..c2489747e1 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/cascade/circle/delete/Address.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/cascade/circle/delete/Address.java @@ -13,43 +13,43 @@ import jakarta.persistence.ManyToOne; @Entity public class Address { - @Id - @GeneratedValue - private Long id; + @Id + @GeneratedValue + private Long id; - @ManyToOne - private Person person; + @ManyToOne + private Person person; - private String description; + private String description; - public Address() { - } + public Address() { + } - public Address(String description) { - this.description = description; - } + public Address(String description) { + this.description = description; + } - public Long getId() { - return id; - } + public Long getId() { + return id; + } - public void setId(final Long id) { - this.id = id; - } + public void setId(final Long id) { + this.id = id; + } - public Person getPerson() { - return person; - } + public Person getPerson() { + return person; + } - public void setPerson(Person person) { - this.person = person; - } + public void setPerson(Person person) { + this.person = person; + } - public String getDescription() { - return description; - } + public String getDescription() { + return description; + } - public void setDescription(String description) { - this.description = description; - } + public void setDescription(String description) { + this.description = description; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/cascade/circle/delete/Person.java b/hibernate-core/src/test/java/org/hibernate/orm/test/cascade/circle/delete/Person.java index 28eeb3e076..24095dffd1 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/cascade/circle/delete/Person.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/cascade/circle/delete/Person.java @@ -23,49 +23,49 @@ import org.hibernate.annotations.OptimisticLocking; @OptimisticLocking(type = OptimisticLockType.DIRTY) @DynamicUpdate public class Person { - @Id - @GeneratedValue - private Long id; + @Id + @GeneratedValue + private Long id; - private String name; + private String name; - @OneToMany(cascade = CascadeType.ALL, mappedBy = "person") - private final List
addresses = new ArrayList<>(); + @OneToMany(cascade = CascadeType.ALL, mappedBy = "person") + private final List
addresses = new ArrayList<>(); - @OneToOne(cascade = { CascadeType.ALL }) - private Address currentAddress; + @OneToOne(cascade = { CascadeType.ALL }) + private Address currentAddress; - public Long getId() { - return id; - } + public Long getId() { + return id; + } - public void setId(final Long id) { - this.id = id; - } + public void setId(final Long id) { + this.id = id; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - public List
getAddresses() { - return addresses; - } + public List
getAddresses() { + return addresses; + } - public Address getCurrentAddress() { - return currentAddress; - } + public Address getCurrentAddress() { + return currentAddress; + } - public void setCurrentAddress(Address currentAddress) { - this.currentAddress = currentAddress; - } + public void setCurrentAddress(Address currentAddress) { + this.currentAddress = currentAddress; + } - public void addCurrentAddress(Address currentAddress){ - this.addresses.add( currentAddress ); - currentAddress.setPerson( this ); - this.currentAddress = currentAddress; - } + public void addCurrentAddress(Address currentAddress){ + this.addresses.add( currentAddress ); + currentAddress.setPerson( this ); + this.currentAddress = currentAddress; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/cfg/persister/GoofyPersisterClassProvider.java b/hibernate-core/src/test/java/org/hibernate/orm/test/cfg/persister/GoofyPersisterClassProvider.java index 1dac9fbfa4..943a76756a 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/cfg/persister/GoofyPersisterClassProvider.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/cfg/persister/GoofyPersisterClassProvider.java @@ -735,10 +735,10 @@ public class GoofyPersisterClassProvider implements PersisterClassResolver { return null; } - @Override - public int[] resolveAttributeIndexes(String[] attributeNames) { - return null; - } + @Override + public int[] resolveAttributeIndexes(String[] attributeNames) { + return null; + } @Override public boolean canUseReferenceCacheEntries() { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/cfg/persister/Palmtree.java b/hibernate-core/src/test/java/org/hibernate/orm/test/cfg/persister/Palmtree.java index c26e6231c5..73b7a6efdf 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/cfg/persister/Palmtree.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/cfg/persister/Palmtree.java @@ -13,13 +13,13 @@ import jakarta.persistence.Entity; */ @Entity public class Palmtree extends Tree { - private double leaveSize; + private double leaveSize; - public double getLeaveSize() { - return leaveSize; - } + public double getLeaveSize() { + return leaveSize; + } - public void setLeaveSize(double leaveSize) { - this.leaveSize = leaveSize; - } + public void setLeaveSize(double leaveSize) { + this.leaveSize = leaveSize; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/cfg/persister/PersisterClassProviderTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/cfg/persister/PersisterClassProviderTest.java index 14c4cd8465..3d9aff0aba 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/cfg/persister/PersisterClassProviderTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/cfg/persister/PersisterClassProviderTest.java @@ -53,7 +53,7 @@ public class PersisterClassProviderTest extends BaseUnitTestCase { try { sessionFactory = cfg.buildSessionFactory( serviceRegistry ); sessionFactory.close(); - fail("The entity persister should be overridden"); + fail("The entity persister should be overridden"); } catch ( MappingException e ) { // expected @@ -75,7 +75,7 @@ public class PersisterClassProviderTest extends BaseUnitTestCase { try { sessionFactory = cfg.buildSessionFactory( serviceRegistry ); sessionFactory.close(); - fail("The collection persister should be overridden but not the entity persister"); + fail("The collection persister should be overridden but not the entity persister"); } catch ( MappingException e ) { // expected @@ -86,7 +86,7 @@ public class PersisterClassProviderTest extends BaseUnitTestCase { } - cfg = new Configuration(); + cfg = new Configuration(); cfg.addAnnotatedClass( Tree.class ); cfg.addAnnotatedClass( Palmtree.class ); serviceRegistry = ServiceRegistryUtil.serviceRegistryBuilder() @@ -96,7 +96,7 @@ public class PersisterClassProviderTest extends BaseUnitTestCase { try { sessionFactory = cfg.buildSessionFactory( serviceRegistry ); sessionFactory.close(); - fail("The entity persisters should be overridden in a class hierarchy"); + fail("The entity persisters should be overridden in a class hierarchy"); } catch ( MappingException e ) { // expected diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/cfg/persister/Tree.java b/hibernate-core/src/test/java/org/hibernate/orm/test/cfg/persister/Tree.java index cf8a38fcea..fe7f572f04 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/cfg/persister/Tree.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/cfg/persister/Tree.java @@ -14,7 +14,7 @@ import jakarta.persistence.Id; */ @Entity public class Tree { - @Id + @Id public Long getId() { return id; } public void setId(Long id) { this.id = id; } private Long id; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/collection/basic/Contact.java b/hibernate-core/src/test/java/org/hibernate/orm/test/collection/basic/Contact.java index 79d1b35738..365307b4a6 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/collection/basic/Contact.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/collection/basic/Contact.java @@ -26,89 +26,89 @@ import jakarta.persistence.Table; @Table(name="contact") public class Contact implements Serializable { - private static final long serialVersionUID = 1L; - private Long id; - private String name; - private Set emailAddresses = new HashSet<>(); - private Set emailAddresses2 = new HashSet<>(); - private Map contactsByEmail = new HashMap<>(); + private static final long serialVersionUID = 1L; + private Long id; + private String name; + private Set emailAddresses = new HashSet<>(); + private Set emailAddresses2 = new HashSet<>(); + private Map contactsByEmail = new HashMap<>(); - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - public Long getId() { - return id; - } + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + public Long getId() { + return id; + } - public void setId(Long id) { - this.id = id; - } + public void setId(Long id) { + this.id = id; + } - @Basic - public String getName() { - return name; - } + @Basic + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - @ElementCollection - @CollectionTable(name = "user_email_addresses2", joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id")) - public Set getEmailAddresses2() { - return emailAddresses2; - } + @ElementCollection + @CollectionTable(name = "user_email_addresses2", joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id")) + public Set getEmailAddresses2() { + return emailAddresses2; + } - public void setEmailAddresses2(Set emailAddresses2) { - this.emailAddresses2 = emailAddresses2; - } + public void setEmailAddresses2(Set emailAddresses2) { + this.emailAddresses2 = emailAddresses2; + } - @ElementCollection - @CollectionTable(name = "user_email_addresses", joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id")) - public Set getEmailAddresses() { - return emailAddresses; - } + @ElementCollection + @CollectionTable(name = "user_email_addresses", joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id")) + public Set getEmailAddresses() { + return emailAddresses; + } - public void setEmailAddresses(Set emailAddresses) { - this.emailAddresses = emailAddresses; - } + public void setEmailAddresses(Set emailAddresses) { + this.emailAddresses = emailAddresses; + } - @ManyToMany - @CollectionTable(name="contact_email_addresses") - public Map getContactsByEmail() { - return contactsByEmail; - } + @ManyToMany + @CollectionTable(name="contact_email_addresses") + public Map getContactsByEmail() { + return contactsByEmail; + } - public void setContactsByEmail(Map contactsByEmail) { - this.contactsByEmail = contactsByEmail; - } + public void setContactsByEmail(Map contactsByEmail) { + this.contactsByEmail = contactsByEmail; + } - @Override - public int hashCode() { - int hash = 0; - hash += (id != null ? id.hashCode() : 0); - return hash; - } + @Override + public int hashCode() { + int hash = 0; + hash += (id != null ? id.hashCode() : 0); + return hash; + } - @Override - public boolean equals(Object obj) { - if (obj == null) { - return false; - } - if (!(obj instanceof Contact)) { - return false; - } - final Contact other = (Contact) obj; - if (this.id == null || other.id == null) { - return this == obj; - } - if(!this.id.equals(other.id)) { - return this == obj; - } - return true; - } + @Override + public boolean equals(Object obj) { + if (obj == null) { + return false; + } + if (!(obj instanceof Contact)) { + return false; + } + final Contact other = (Contact) obj; + if (this.id == null || other.id == null) { + return this == obj; + } + if(!this.id.equals(other.id)) { + return this == obj; + } + return true; + } - @Override - public String toString() { - return "com.clevercure.web.hibernateissuecache.User[ id=" + id + " ]"; - } + @Override + public String toString() { + return "com.clevercure.web.hibernateissuecache.User[ id=" + id + " ]"; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/collection/basic/EmailAddress.java b/hibernate-core/src/test/java/org/hibernate/orm/test/collection/basic/EmailAddress.java index cd21f642fb..3a68f1d636 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/collection/basic/EmailAddress.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/collection/basic/EmailAddress.java @@ -12,51 +12,51 @@ import jakarta.persistence.*; @Embeddable public class EmailAddress implements Serializable { - private static final long serialVersionUID = 1L; - private String email; + private static final long serialVersionUID = 1L; + private String email; - public EmailAddress() { - } + public EmailAddress() { + } - public EmailAddress(String email) { - this.email = email; - } + public EmailAddress(String email) { + this.email = email; + } - public String getEmail() { - return email; - } + public String getEmail() { + return email; + } - public void setEmail(String email) { - this.email = email; - } + public void setEmail(String email) { + this.email = email; + } - @Override - public int hashCode() { - int hash = 0; - hash += (email != null ? email.hashCode() : 0); - return hash; - } + @Override + public int hashCode() { + int hash = 0; + hash += (email != null ? email.hashCode() : 0); + return hash; + } - @Override - public boolean equals(Object obj) { - if (obj == null) { - return false; - } - if (!(obj instanceof EmailAddress)) { - return false; - } - final EmailAddress other = (EmailAddress) obj; - if (this.email == null || other.email == null) { - return this == obj; - } - if(!this.email.equals(other.email)) { - return this == obj; - } - return true; - } + @Override + public boolean equals(Object obj) { + if (obj == null) { + return false; + } + if (!(obj instanceof EmailAddress)) { + return false; + } + final EmailAddress other = (EmailAddress) obj; + if (this.email == null || other.email == null) { + return this == obj; + } + if(!this.email.equals(other.email)) { + return this == obj; + } + return true; + } - @Override - public String toString() { - return "com.clevercure.web.hibernateissuecache.EmailAddress[ email=" + email + " ]"; - } + @Override + public String toString() { + return "com.clevercure.web.hibernateissuecache.EmailAddress[ email=" + email + " ]"; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/collection/basic/User.java b/hibernate-core/src/test/java/org/hibernate/orm/test/collection/basic/User.java index 070ec599b4..c1bc56fc1a 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/collection/basic/User.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/collection/basic/User.java @@ -20,67 +20,67 @@ import jakarta.persistence.Table; @Table(name="users") public class User implements Serializable { - private static final long serialVersionUID = 1L; - private Long id; - private String name; - private Contact contact; + private static final long serialVersionUID = 1L; + private Long id; + private String name; + private Contact contact; - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - public Long getId() { - return id; - } + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + public Long getId() { + return id; + } - public void setId(Long id) { - this.id = id; - } + public void setId(Long id) { + this.id = id; + } - @Basic - public String getName() { - return name; - } + @Basic + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - @ManyToOne(optional = true) - @JoinColumn(name = "contact_id", nullable = true, unique = true) - public Contact getContact() { - return contact; - } + @ManyToOne(optional = true) + @JoinColumn(name = "contact_id", nullable = true, unique = true) + public Contact getContact() { + return contact; + } - public void setContact(Contact contact) { - this.contact = contact; - } + public void setContact(Contact contact) { + this.contact = contact; + } - @Override - public int hashCode() { - int hash = 0; - hash += (id != null ? id.hashCode() : 0); - return hash; - } + @Override + public int hashCode() { + int hash = 0; + hash += (id != null ? id.hashCode() : 0); + return hash; + } - @Override - public boolean equals(Object obj) { - if (obj == null) { - return false; - } - if (!(obj instanceof User)) { - return false; - } - final User other = (User) obj; - if (this.id == null || other.id == null) { - return this == obj; - } - if(!this.id.equals(other.id)) { - return this == obj; - } - return true; - } + @Override + public boolean equals(Object obj) { + if (obj == null) { + return false; + } + if (!(obj instanceof User)) { + return false; + } + final User other = (User) obj; + if (this.id == null || other.id == null) { + return this == obj; + } + if(!this.id.equals(other.id)) { + return this == obj; + } + return true; + } - @Override - public String toString() { - return "com.clevercure.web.hibernateissuecache.User[ id=" + id + " ]"; - } + @Override + public String toString() { + return "com.clevercure.web.hibernateissuecache.User[ id=" + id + " ]"; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/collection/dereferenced/UnversionedCascadeDereferencedCollectionTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/collection/dereferenced/UnversionedCascadeDereferencedCollectionTest.java index 03fef539de..034b7a6945 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/collection/dereferenced/UnversionedCascadeDereferencedCollectionTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/collection/dereferenced/UnversionedCascadeDereferencedCollectionTest.java @@ -79,8 +79,8 @@ public class UnversionedCascadeDereferencedCollectionTest extends AbstractDerefe CollectionEntry ceManiesOrig = getCollectionEntry( session, maniesEEOneStateOrig ); assertNotNull( ceManiesOrig ); assertEquals( role, ceManiesOrig.getRole() ); - assertSame( - scope.getSessionFactory().getRuntimeMetamodels() + assertSame( + scope.getSessionFactory().getRuntimeMetamodels() .getMappingMetamodel() .getCollectionDescriptor(role), ceManiesOrig.getLoadedPersister() @@ -162,8 +162,8 @@ public class UnversionedCascadeDereferencedCollectionTest extends AbstractDerefe CollectionEntry ceManies = getCollectionEntry( session, maniesEEOneStateOrig ); assertNotNull( ceManies ); assertEquals( role, ceManies.getRole() ); - assertSame( - scope.getSessionFactory().getRuntimeMetamodels() + assertSame( + scope.getSessionFactory().getRuntimeMetamodels() .getMappingMetamodel() .getCollectionDescriptor(role), ceManies.getLoadedPersister() @@ -248,8 +248,8 @@ public class UnversionedCascadeDereferencedCollectionTest extends AbstractDerefe CollectionEntry ceManiesOrig = getCollectionEntry( session, maniesEEOneStateOrig ); assertNotNull( ceManiesOrig ); assertEquals( role, ceManiesOrig.getRole() ); - assertSame( - scope.getSessionFactory().getRuntimeMetamodels() + assertSame( + scope.getSessionFactory().getRuntimeMetamodels() .getMappingMetamodel() .getCollectionDescriptor(role), ceManiesOrig.getLoadedPersister() @@ -293,8 +293,8 @@ public class UnversionedCascadeDereferencedCollectionTest extends AbstractDerefe ); assertNotNull( ceManiesAfterReplace ); assertEquals( role, ceManiesAfterReplace.getRole() ); - assertSame( - scope.getSessionFactory().getRuntimeMetamodels() + assertSame( + scope.getSessionFactory().getRuntimeMetamodels() .getMappingMetamodel() .getCollectionDescriptor(role), ceManiesAfterReplace.getLoadedPersister() diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/collection/dereferenced/UnversionedNoCascadeDereferencedCollectionTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/collection/dereferenced/UnversionedNoCascadeDereferencedCollectionTest.java index dfac470265..7603aaffb1 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/collection/dereferenced/UnversionedNoCascadeDereferencedCollectionTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/collection/dereferenced/UnversionedNoCascadeDereferencedCollectionTest.java @@ -77,8 +77,8 @@ public class UnversionedNoCascadeDereferencedCollectionTest extends AbstractDere CollectionEntry ceManiesOrig = getCollectionEntry( session, maniesEEOneStateOrig ); assertNotNull( ceManiesOrig ); assertEquals( role, ceManiesOrig.getRole() ); - assertSame( - scope.getSessionFactory().getRuntimeMetamodels() + assertSame( + scope.getSessionFactory().getRuntimeMetamodels() .getMappingMetamodel() .getCollectionDescriptor(role), ceManiesOrig.getLoadedPersister() @@ -159,8 +159,8 @@ public class UnversionedNoCascadeDereferencedCollectionTest extends AbstractDere CollectionEntry ceManies = getCollectionEntry( session, maniesEEOneStateOrig ); assertNotNull( ceManies ); assertEquals( role, ceManies.getRole() ); - assertSame( - scope.getSessionFactory().getRuntimeMetamodels() + assertSame( + scope.getSessionFactory().getRuntimeMetamodels() .getMappingMetamodel() .getCollectionDescriptor(role), ceManies.getLoadedPersister() @@ -244,8 +244,8 @@ public class UnversionedNoCascadeDereferencedCollectionTest extends AbstractDere CollectionEntry ceManiesOrig = getCollectionEntry( session, maniesEEOneStateOrig ); assertNotNull( ceManiesOrig ); assertEquals( role, ceManiesOrig.getRole() ); - assertSame( - scope.getSessionFactory().getRuntimeMetamodels() + assertSame( + scope.getSessionFactory().getRuntimeMetamodels() .getMappingMetamodel() .getCollectionDescriptor(role), ceManiesOrig.getLoadedPersister() @@ -289,8 +289,8 @@ public class UnversionedNoCascadeDereferencedCollectionTest extends AbstractDere ); assertNotNull( ceManiesAfterReplace ); assertEquals( role, ceManiesAfterReplace.getRole() ); - assertSame( - scope.getSessionFactory().getRuntimeMetamodels() + assertSame( + scope.getSessionFactory().getRuntimeMetamodels() .getMappingMetamodel() .getCollectionDescriptor(role), ceManiesAfterReplace.getLoadedPersister() diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/collection/dereferenced/VersionedCascadeDereferencedCollectionTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/collection/dereferenced/VersionedCascadeDereferencedCollectionTest.java index 458af9e448..181c402c19 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/collection/dereferenced/VersionedCascadeDereferencedCollectionTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/collection/dereferenced/VersionedCascadeDereferencedCollectionTest.java @@ -79,8 +79,8 @@ public class VersionedCascadeDereferencedCollectionTest extends AbstractDerefere CollectionEntry ceManiesOrig = getCollectionEntry( session, maniesEEOneStateOrig ); assertNotNull( ceManiesOrig ); assertEquals( role, ceManiesOrig.getRole() ); - assertSame( - scope.getSessionFactory().getRuntimeMetamodels() + assertSame( + scope.getSessionFactory().getRuntimeMetamodels() .getMappingMetamodel() .getCollectionDescriptor(role), ceManiesOrig.getLoadedPersister() @@ -159,8 +159,8 @@ public class VersionedCascadeDereferencedCollectionTest extends AbstractDerefere CollectionEntry ceManies = getCollectionEntry( session, maniesEEOneStateOrig ); assertNotNull( ceManies ); assertEquals( role, ceManies.getRole() ); - assertSame( - scope.getSessionFactory().getRuntimeMetamodels() + assertSame( + scope.getSessionFactory().getRuntimeMetamodels() .getMappingMetamodel() .getCollectionDescriptor(role), ceManies.getLoadedPersister() @@ -241,8 +241,8 @@ public class VersionedCascadeDereferencedCollectionTest extends AbstractDerefere CollectionEntry ceManiesOrig = getCollectionEntry( session, maniesEEOneStateOrig ); assertNotNull( ceManiesOrig ); assertEquals( role, ceManiesOrig.getRole() ); - assertSame( - scope.getSessionFactory().getRuntimeMetamodels() + assertSame( + scope.getSessionFactory().getRuntimeMetamodels() .getMappingMetamodel() .getCollectionDescriptor(role), ceManiesOrig.getLoadedPersister() @@ -286,8 +286,8 @@ public class VersionedCascadeDereferencedCollectionTest extends AbstractDerefere ); assertNotNull( ceManiesAfterReplace ); assertEquals( role, ceManiesAfterReplace.getRole() ); - assertSame( - scope.getSessionFactory().getRuntimeMetamodels() + assertSame( + scope.getSessionFactory().getRuntimeMetamodels() .getMappingMetamodel() .getCollectionDescriptor(role), ceManiesAfterReplace.getLoadedPersister() diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/collection/dereferenced/VersionedNoCascadeDereferencedCollectionTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/collection/dereferenced/VersionedNoCascadeDereferencedCollectionTest.java index af3e69a46e..9bf14ca0b7 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/collection/dereferenced/VersionedNoCascadeDereferencedCollectionTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/collection/dereferenced/VersionedNoCascadeDereferencedCollectionTest.java @@ -79,8 +79,8 @@ public class VersionedNoCascadeDereferencedCollectionTest extends AbstractDerefe CollectionEntry ceManiesOrig = getCollectionEntry( session, maniesEEOneStateOrig ); assertNotNull( ceManiesOrig ); assertEquals( role, ceManiesOrig.getRole() ); - assertSame( - scope.getSessionFactory().getRuntimeMetamodels() + assertSame( + scope.getSessionFactory().getRuntimeMetamodels() .getMappingMetamodel() .getCollectionDescriptor(role), ceManiesOrig.getLoadedPersister() @@ -161,8 +161,8 @@ public class VersionedNoCascadeDereferencedCollectionTest extends AbstractDerefe CollectionEntry ceManies = getCollectionEntry( session, maniesEEOneStateOrig ); assertNotNull( ceManies ); assertEquals( role, ceManies.getRole() ); - assertSame( - scope.getSessionFactory().getRuntimeMetamodels() + assertSame( + scope.getSessionFactory().getRuntimeMetamodels() .getMappingMetamodel() .getCollectionDescriptor(role), ceManies.getLoadedPersister() @@ -247,8 +247,8 @@ public class VersionedNoCascadeDereferencedCollectionTest extends AbstractDerefe CollectionEntry ceManiesOrig = getCollectionEntry( session, maniesEEOneStateOrig ); assertNotNull( ceManiesOrig ); assertEquals( role, ceManiesOrig.getRole() ); - assertSame( - scope.getSessionFactory().getRuntimeMetamodels() + assertSame( + scope.getSessionFactory().getRuntimeMetamodels() .getMappingMetamodel() .getCollectionDescriptor(role), ceManiesOrig.getLoadedPersister() @@ -292,8 +292,8 @@ public class VersionedNoCascadeDereferencedCollectionTest extends AbstractDerefe ); assertNotNull( ceManiesAfterReplace ); assertEquals( role, ceManiesAfterReplace.getRole() ); - assertSame( - scope.getSessionFactory().getRuntimeMetamodels() + assertSame( + scope.getSessionFactory().getRuntimeMetamodels() .getMappingMetamodel() .getCollectionDescriptor(role), ceManiesAfterReplace.getLoadedPersister() diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/collection/detached/DetachedCollectionTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/collection/detached/DetachedCollectionTest.java index 19b32ce4e8..667cbd9742 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/collection/detached/DetachedCollectionTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/collection/detached/DetachedCollectionTest.java @@ -21,81 +21,81 @@ import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; @DomainModel( - annotatedClasses = {One.class, Many.class, Several.class} + annotatedClasses = {One.class, Many.class, Several.class} ) @SessionFactory public class DetachedCollectionTest { - @Test - public void testToOne(SessionFactoryScope scope) { - One one = new One(); - scope.inTransaction( session -> session.persist(one) ); - One two = Hibernate.createDetachedProxy( scope.getSessionFactory(), One.class, one.id ); - assertEquals( one.id, two.getId() ); - Many many = new Many(); - many.one = two; - scope.inTransaction( session -> session.persist(many) ); - scope.inTransaction( session -> { - Many m = session.find(Many.class, many.id); - assertNotNull(m.one); - assertEquals( one.id, m.one.id ); - }); - } + @Test + public void testToOne(SessionFactoryScope scope) { + One one = new One(); + scope.inTransaction( session -> session.persist(one) ); + One two = Hibernate.createDetachedProxy( scope.getSessionFactory(), One.class, one.id ); + assertEquals( one.id, two.getId() ); + Many many = new Many(); + many.one = two; + scope.inTransaction( session -> session.persist(many) ); + scope.inTransaction( session -> { + Many m = session.find(Many.class, many.id); + assertNotNull(m.one); + assertEquals( one.id, m.one.id ); + }); + } - @Test - public void testOwned(SessionFactoryScope scope) { - Several several = new Several(); - several.many = new HashSet<>(); - Many many = new Many(); - several.many.add(many); - assertNotNull(several.many); - scope.inTransaction(session -> { - session.persist(several); - session.persist(many); - }); - assertNotNull(several.many); - several.many = Hibernate.set().createDetachedInstance(); - assertFalse(Hibernate.isInitialized(several.many)); - scope.inTransaction(session -> { - Several merged = (Several) session.merge(several); - assertNotNull(merged.many); - assertTrue(Hibernate.isInitialized(merged.many)); - assertEquals(1, merged.many.size()); - }); - scope.inTransaction(session -> { - Several found = session.find(Several.class, several.id); - Hibernate.initialize(found.many); - assertNotNull(found.many); - assertEquals(1, found.many.size()); - }); - } + @Test + public void testOwned(SessionFactoryScope scope) { + Several several = new Several(); + several.many = new HashSet<>(); + Many many = new Many(); + several.many.add(many); + assertNotNull(several.many); + scope.inTransaction(session -> { + session.persist(several); + session.persist(many); + }); + assertNotNull(several.many); + several.many = Hibernate.set().createDetachedInstance(); + assertFalse(Hibernate.isInitialized(several.many)); + scope.inTransaction(session -> { + Several merged = (Several) session.merge(several); + assertNotNull(merged.many); + assertTrue(Hibernate.isInitialized(merged.many)); + assertEquals(1, merged.many.size()); + }); + scope.inTransaction(session -> { + Several found = session.find(Several.class, several.id); + Hibernate.initialize(found.many); + assertNotNull(found.many); + assertEquals(1, found.many.size()); + }); + } - @Test - public void testUnowned(SessionFactoryScope scope) { - One one = new One(); - one.many = new ArrayList<>(); - Many many = new Many(); - many.one = one; - one.many.add(many); - assertNotNull(one.many); - scope.inTransaction(session -> { - session.persist(one); - session.persist(many); - }); - assertNotNull(one.many); - one.many = Hibernate.list().createDetachedInstance(); - assertFalse(Hibernate.isInitialized(one.many)); - scope.inTransaction(session -> { - One merged = (One) session.merge(one); - assertNotNull(merged.many); - assertTrue(Hibernate.isInitialized(merged.many)); - assertEquals(1, merged.many.size()); - }); - scope.inTransaction(session -> { - One found = session.find(One.class, one.id); - Hibernate.initialize(found.many); - assertNotNull(found.many); - assertEquals(1, found.many.size()); - }); - } + @Test + public void testUnowned(SessionFactoryScope scope) { + One one = new One(); + one.many = new ArrayList<>(); + Many many = new Many(); + many.one = one; + one.many.add(many); + assertNotNull(one.many); + scope.inTransaction(session -> { + session.persist(one); + session.persist(many); + }); + assertNotNull(one.many); + one.many = Hibernate.list().createDetachedInstance(); + assertFalse(Hibernate.isInitialized(one.many)); + scope.inTransaction(session -> { + One merged = (One) session.merge(one); + assertNotNull(merged.many); + assertTrue(Hibernate.isInitialized(merged.many)); + assertEquals(1, merged.many.size()); + }); + scope.inTransaction(session -> { + One found = session.find(One.class, one.id); + Hibernate.initialize(found.many); + assertNotNull(found.many); + assertEquals(1, found.many.size()); + }); + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/collection/detached/Many.java b/hibernate-core/src/test/java/org/hibernate/orm/test/collection/detached/Many.java index b176cc5cc9..6c24cf98cb 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/collection/detached/Many.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/collection/detached/Many.java @@ -14,10 +14,10 @@ import jakarta.persistence.Table; @Entity @Table(name="DCMany") public class Many { - @GeneratedValue - @Id - long id; + @GeneratedValue + @Id + long id; - @ManyToOne - One one; + @ManyToOne + One one; } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/collection/detached/One.java b/hibernate-core/src/test/java/org/hibernate/orm/test/collection/detached/One.java index 4f801795b3..db2fe83572 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/collection/detached/One.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/collection/detached/One.java @@ -17,15 +17,15 @@ import java.util.List; @Entity @Table(name="DCOne") public class One { - @GeneratedValue - @Id - long id; + @GeneratedValue + @Id + long id; - @OneToMany(mappedBy = "one", - cascade = {CascadeType.PERSIST, CascadeType.MERGE}) - List many; + @OneToMany(mappedBy = "one", + cascade = {CascadeType.PERSIST, CascadeType.MERGE}) + List many; - public long getId() { - return id; - } + public long getId() { + return id; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/collection/detached/Several.java b/hibernate-core/src/test/java/org/hibernate/orm/test/collection/detached/Several.java index 40b610a11b..66cce60aa1 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/collection/detached/Several.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/collection/detached/Several.java @@ -17,10 +17,10 @@ import java.util.Set; @Entity @Table(name="DCSeveral") public class Several { - @GeneratedValue - @Id - long id; + @GeneratedValue + @Id + long id; - @ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE}) - Set many; + @ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE}) + Set many; } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/collection/list/PersistentListTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/collection/list/PersistentListTest.java index 58642b665c..5fb3b25305 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/collection/list/PersistentListTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/collection/list/PersistentListTest.java @@ -45,7 +45,7 @@ public class PersistentListTest { public void testInverseListIndex(SessionFactoryScope scope) { // make sure no one changes the mapping SessionFactoryImplementor sessionFactory = scope.getSessionFactory(); - final CollectionPersister collectionPersister = sessionFactory.getRuntimeMetamodels() + final CollectionPersister collectionPersister = sessionFactory.getRuntimeMetamodels() .getMappingMetamodel() .getCollectionDescriptor(ListOwner.class.getName() + ".children"); assertTrue( collectionPersister.isInverse() ); @@ -110,7 +110,7 @@ public class PersistentListTest { public void testInverseListIndex2(SessionFactoryScope scope) { // make sure no one changes the mapping SessionFactoryImplementor sessionFactory = scope.getSessionFactory(); - final CollectionPersister collectionPersister = sessionFactory.getRuntimeMetamodels() + final CollectionPersister collectionPersister = sessionFactory.getRuntimeMetamodels() .getMappingMetamodel() .getCollectionDescriptor(Order.class.getName() + ".lineItems"); assertTrue( collectionPersister.isInverse() ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/collection/map/MultilingualStringParent.java b/hibernate-core/src/test/java/org/hibernate/orm/test/collection/map/MultilingualStringParent.java index 31d8cb2236..dbc3ac2004 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/collection/map/MultilingualStringParent.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/collection/map/MultilingualStringParent.java @@ -12,35 +12,35 @@ import jakarta.persistence.*; @Table(name = "multilingual_parent") public class MultilingualStringParent { - @Id - @GeneratedValue - private long id; - @ManyToOne(fetch = FetchType.LAZY) - private MultilingualStringParent parent; - @ManyToOne(fetch = FetchType.LAZY) - private MultilingualString string; + @Id + @GeneratedValue + private long id; + @ManyToOne(fetch = FetchType.LAZY) + private MultilingualStringParent parent; + @ManyToOne(fetch = FetchType.LAZY) + private MultilingualString string; - public long getId() { - return id; - } + public long getId() { + return id; + } - public void setId(long id) { - this.id = id; - } + public void setId(long id) { + this.id = id; + } - public MultilingualStringParent getParent() { - return parent; - } + public MultilingualStringParent getParent() { + return parent; + } - public void setParent(MultilingualStringParent parent) { - this.parent = parent; - } + public void setParent(MultilingualStringParent parent) { + this.parent = parent; + } - public MultilingualString getString() { - return string; - } + public MultilingualString getString() { + return string; + } - public void setString(MultilingualString string) { - this.string = string; - } + public void setString(MultilingualString string) { + this.string = string; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/collection/map/PersistentMapTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/collection/map/PersistentMapTest.java index 54789abd60..6a8958e36a 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/collection/map/PersistentMapTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/collection/map/PersistentMapTest.java @@ -223,15 +223,15 @@ public class PersistentMapTest { session.getTransaction().begin(); /* select - userdatas0_.userId as userid2_8_0_, - userdatas0_.id as id1_8_0_, - userdatas0_.name as name3_0_, - userdatas0_.id as id1_8_1_, - userdatas0_.userId as userid2_8_1_ - from - UserData userdatas0_ - where - userdatas0_.userId=1 + userdatas0_.userId as userid2_8_0_, + userdatas0_.id as id1_8_0_, + userdatas0_.name as name3_0_, + userdatas0_.id as id1_8_1_, + userdatas0_.userId as userid2_8_1_ + from + UserData userdatas0_ + where + userdatas0_.userId=1 */ assertEquals( 0, session.get( User.class, user.id ).userDatas.size() ); assertEquals( 0, session.createQuery( "FROM " + UserData.class.getName() ).list().size() ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/collection/original/Animal.java b/hibernate-core/src/test/java/org/hibernate/orm/test/collection/original/Animal.java index 11ce1c708d..a910fec50b 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/collection/original/Animal.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/collection/original/Animal.java @@ -8,24 +8,24 @@ package org.hibernate.orm.test.collection.original; public class Animal { - long id; - String name; - boolean boolvar; - Zoo zoo; + long id; + String name; + boolean boolvar; + Zoo zoo; - public long getId() { - return id; - } - public void setId( long id ) { - this.id = id; - } - public String getName() { - return name; - } - public void setName( String name ) { - this.name = name; - } - public boolean isBoolvar() { + public long getId() { + return id; + } + public void setId( long id ) { + this.id = id; + } + public String getName() { + return name; + } + public void setName( String name ) { + this.name = name; + } + public boolean isBoolvar() { return boolvar; } public void setBoolvar(boolean boolvar) { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/collection/original/Mammal.java b/hibernate-core/src/test/java/org/hibernate/orm/test/collection/original/Mammal.java index 353111654e..60360ca95d 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/collection/original/Mammal.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/collection/original/Mammal.java @@ -8,9 +8,9 @@ package org.hibernate.orm.test.collection.original; public class Mammal extends Animal { - private String mammalName; - private String mammalName2; - private String mammalName3; + private String mammalName; + private String mammalName2; + private String mammalName3; public String getMammalName() { return mammalName; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/collection/original/Zoo.java b/hibernate-core/src/test/java/org/hibernate/orm/test/collection/original/Zoo.java index 8150e19d55..294afdd7e7 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/collection/original/Zoo.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/collection/original/Zoo.java @@ -9,15 +9,15 @@ import java.util.ArrayList; import java.util.List; public class Zoo { - long id; - List animals = new ArrayList(); + long id; + List animals = new ArrayList(); - public long getId() { - return id; - } - public void setId( long id ) { - this.id = id; - } + public long getId() { + return id; + } + public void setId( long id ) { + this.id = id; + } public List getAnimals() { return animals; } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/component/basic2/Component.java b/hibernate-core/src/test/java/org/hibernate/orm/test/component/basic2/Component.java index a5ecba0642..fe0e13386f 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/component/basic2/Component.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/component/basic2/Component.java @@ -19,26 +19,26 @@ import java.util.Set; @Entity public class Component { - @Id + @Id private Long id; - @Embedded + @Embedded private Component.Emb emb; - @Access(AccessType.FIELD) - @Embeddable - public static class Emb { + @Access(AccessType.FIELD) + @Embeddable + public static class Emb { - @OneToMany(targetEntity = Stuff.class) - Set stuffs = new HashSet(); + @OneToMany(targetEntity = Stuff.class) + Set stuffs = new HashSet(); - @Entity - @Table(name = "stuff") - public static class Stuff { - @Id - private Long id; - } - } + @Entity + @Table(name = "stuff") + public static class Stuff { + @Id + private Long id; + } + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/component/basic2/Name.java b/hibernate-core/src/test/java/org/hibernate/orm/test/component/basic2/Name.java index 2cd9723bf3..7a01176582 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/component/basic2/Name.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/component/basic2/Name.java @@ -15,8 +15,8 @@ import jakarta.persistence.Embeddable; */ @Embeddable public class Name implements Serializable { - private String firstName; - private String lastName; + private String firstName; + private String lastName; public Name() { } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/component/cascading/collection/Definition.java b/hibernate-core/src/test/java/org/hibernate/orm/test/component/cascading/collection/Definition.java index 8e5aa097a5..381d7db88d 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/component/cascading/collection/Definition.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/component/cascading/collection/Definition.java @@ -14,7 +14,7 @@ import java.util.Set; * @author Steve Ebersole */ public class Definition { - private Long id; + private Long id; private Set values = new HashSet(); public Long getId() { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/connection/PropertiesTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/connection/PropertiesTest.java index 489c3feb08..c81e9502c6 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/connection/PropertiesTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/connection/PropertiesTest.java @@ -86,8 +86,8 @@ public class PropertiesTest { /* All the StandardServiceRegistryBuilder public constructors populate the settings reading from hibernate.properties file, that sets the deprecated property AvailableSettings.URL - MyStandardServiceRegistryBuilder gives access to the StandardServiceRegistryBuilder protected constructor - that does not read the hibernate.properties, + MyStandardServiceRegistryBuilder gives access to the StandardServiceRegistryBuilder protected constructor + that does not read the hibernate.properties, */ public static class MyStandardServiceRegistryBuilder extends StandardServiceRegistryBuilder { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/connections/AggressiveReleaseTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/connections/AggressiveReleaseTest.java index 2f6a109cee..938c9cf63f 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/connections/AggressiveReleaseTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/connections/AggressiveReleaseTest.java @@ -151,7 +151,7 @@ public class AggressiveReleaseTest extends ConnectionManagementTestCase { } try (ScrollableResults sr = s.createQuery( "from Silly" ).scroll(); - ScrollableResults sr2 = s.createQuery( "from Silly where name = 'silly'" ).scroll()) { + ScrollableResults sr2 = s.createQuery( "from Silly where name = 'silly'" ).scroll()) { assertTrue( sr.next() ); assertEquals( silly, sr.get() ); assertTrue( sr2.next() ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/connections/BeforeCompletionReleaseTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/connections/BeforeCompletionReleaseTest.java index ae0ca26b41..b2123c16a4 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/connections/BeforeCompletionReleaseTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/connections/BeforeCompletionReleaseTest.java @@ -62,166 +62,166 @@ import static org.mockito.Mockito.spy; @RunWith(CustomParameterized.class) public class BeforeCompletionReleaseTest extends BaseEntityManagerFunctionalTestCase { - @Parameterized.Parameters(name = "{0}") - public static List params() { - return Arrays.asList( new Object[][] { - { - "Setting connection handling mode from properties", - PhysicalConnectionHandlingMode.DELAYED_ACQUISITION_AND_RELEASE_BEFORE_TRANSACTION_COMPLETION, - null - }, - { - "Setting connection handling mode through SessionBuilder", - PhysicalConnectionHandlingMode.DELAYED_ACQUISITION_AND_RELEASE_AFTER_STATEMENT, - PhysicalConnectionHandlingMode.DELAYED_ACQUISITION_AND_RELEASE_BEFORE_TRANSACTION_COMPLETION - } - } ); - } + @Parameterized.Parameters(name = "{0}") + public static List params() { + return Arrays.asList( new Object[][] { + { + "Setting connection handling mode from properties", + PhysicalConnectionHandlingMode.DELAYED_ACQUISITION_AND_RELEASE_BEFORE_TRANSACTION_COMPLETION, + null + }, + { + "Setting connection handling mode through SessionBuilder", + PhysicalConnectionHandlingMode.DELAYED_ACQUISITION_AND_RELEASE_AFTER_STATEMENT, + PhysicalConnectionHandlingMode.DELAYED_ACQUISITION_AND_RELEASE_BEFORE_TRANSACTION_COMPLETION + } + } ); + } - @Rule - public MockitoRule mockito = MockitoJUnit.rule().strictness( Strictness.STRICT_STUBS ); - private final ConnectionProvider connectionProvider = spy( - new ConnectionProviderDelegate( ConnectionProviderBuilder.buildConnectionProvider() ) - ); + @Rule + public MockitoRule mockito = MockitoJUnit.rule().strictness( Strictness.STRICT_STUBS ); + private final ConnectionProvider connectionProvider = spy( + new ConnectionProviderDelegate( ConnectionProviderBuilder.buildConnectionProvider() ) + ); - private final PhysicalConnectionHandlingMode connectionHandlingModeInProperties; - private final PhysicalConnectionHandlingMode connectionHandlingModeInSessionBuilder; + private final PhysicalConnectionHandlingMode connectionHandlingModeInProperties; + private final PhysicalConnectionHandlingMode connectionHandlingModeInSessionBuilder; - public BeforeCompletionReleaseTest( - String ignoredTestLabel, PhysicalConnectionHandlingMode connectionHandlingModeInProperties, - PhysicalConnectionHandlingMode connectionHandlingModeInSessionBuilder) { - this.connectionHandlingModeInProperties = connectionHandlingModeInProperties; - this.connectionHandlingModeInSessionBuilder = connectionHandlingModeInSessionBuilder; - } + public BeforeCompletionReleaseTest( + String ignoredTestLabel, PhysicalConnectionHandlingMode connectionHandlingModeInProperties, + PhysicalConnectionHandlingMode connectionHandlingModeInSessionBuilder) { + this.connectionHandlingModeInProperties = connectionHandlingModeInProperties; + this.connectionHandlingModeInSessionBuilder = connectionHandlingModeInSessionBuilder; + } - @Override - protected Map getConfig() { - Map config = super.getConfig(); - TestingJtaBootstrap.prepare( config ); - config.put( AvailableSettings.CONNECTION_PROVIDER, connectionProvider ); - if ( connectionHandlingModeInProperties != null ) { - config.put( AvailableSettings.CONNECTION_HANDLING, connectionHandlingModeInProperties ); - } - return config; - } + @Override + protected Map getConfig() { + Map config = super.getConfig(); + TestingJtaBootstrap.prepare( config ); + config.put( AvailableSettings.CONNECTION_PROVIDER, connectionProvider ); + if ( connectionHandlingModeInProperties != null ) { + config.put( AvailableSettings.CONNECTION_HANDLING, connectionHandlingModeInProperties ); + } + return config; + } - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { Thing.class }; - } + @Override + protected Class[] getAnnotatedClasses() { + return new Class[] { Thing.class }; + } - @Test - @JiraKeyGroup( value = { - @JiraKey( value = "HHH-13976" ), - @JiraKey( value = "HHH-14326" ) - } ) - public void testResourcesReleasedThenConnectionClosedThenCommit() throws SQLException, XAException { - try (SessionImplementor s = (SessionImplementor) openSession()) { - XAResource transactionSpy = mock( XAResource.class ); - Connection[] connections = new Connection[1]; - Statement statementMock = Mockito.mock( Statement.class ); + @Test + @JiraKeyGroup( value = { + @JiraKey( value = "HHH-13976" ), + @JiraKey( value = "HHH-14326" ) + } ) + public void testResourcesReleasedThenConnectionClosedThenCommit() throws SQLException, XAException { + try (SessionImplementor s = (SessionImplementor) openSession()) { + XAResource transactionSpy = mock( XAResource.class ); + Connection[] connections = new Connection[1]; + Statement statementMock = Mockito.mock( Statement.class ); - TransactionUtil2.inTransaction( s, session -> { - spyOnTransaction( transactionSpy ); + TransactionUtil2.inTransaction( s, session -> { + spyOnTransaction( transactionSpy ); - Thing thing = new Thing(); - thing.setId( 1 ); - session.persist( thing ); + Thing thing = new Thing(); + thing.setId( 1 ); + session.persist( thing ); - LogicalConnectionImplementor logicalConnection = session.getJdbcCoordinator().getLogicalConnection(); - logicalConnection.getResourceRegistry().register( statementMock, true ); - connections[0] = logicalConnection.getPhysicalConnection(); - } ); + LogicalConnectionImplementor logicalConnection = session.getJdbcCoordinator().getLogicalConnection(); + logicalConnection.getResourceRegistry().register( statementMock, true ); + connections[0] = logicalConnection.getPhysicalConnection(); + } ); - // Note: all this must happen BEFORE the session is closed; - // it's particularly important when reusing the session. + // Note: all this must happen BEFORE the session is closed; + // it's particularly important when reusing the session. - Connection connection = connections[0]; + Connection connection = connections[0]; - // Must close the resources, then the connection, then commit - InOrder inOrder = inOrder( statementMock, connectionProvider, transactionSpy ); - inOrder.verify( statementMock ).close(); - inOrder.verify( connectionProvider ).closeConnection( connection ); - inOrder.verify( transactionSpy ).commit( any(), anyBoolean() ); - } - } + // Must close the resources, then the connection, then commit + InOrder inOrder = inOrder( statementMock, connectionProvider, transactionSpy ); + inOrder.verify( statementMock ).close(); + inOrder.verify( connectionProvider ).closeConnection( connection ); + inOrder.verify( transactionSpy ).commit( any(), anyBoolean() ); + } + } - @Test - @JiraKey(value = "HHH-14557") - public void testResourcesReleasedThenConnectionClosedOnEachRollback() throws SQLException { - try (SessionImplementor s = (SessionImplementor) openSession()) { - Connection[] connections = new Connection[1]; - Statement statementMock = Mockito.mock( Statement.class ); - RuntimeException rollbackException = new RuntimeException("Rollback"); + @Test + @JiraKey(value = "HHH-14557") + public void testResourcesReleasedThenConnectionClosedOnEachRollback() throws SQLException { + try (SessionImplementor s = (SessionImplementor) openSession()) { + Connection[] connections = new Connection[1]; + Statement statementMock = Mockito.mock( Statement.class ); + RuntimeException rollbackException = new RuntimeException("Rollback"); - try { - TransactionUtil2.inTransaction( s, session -> { - Thing thing = new Thing(); - thing.setId( 1 ); - session.persist( thing ); + try { + TransactionUtil2.inTransaction( s, session -> { + Thing thing = new Thing(); + thing.setId( 1 ); + session.persist( thing ); - LogicalConnectionImplementor logicalConnection = session.getJdbcCoordinator().getLogicalConnection(); - logicalConnection.getResourceRegistry().register( statementMock, true ); - connections[0] = logicalConnection.getPhysicalConnection(); + LogicalConnectionImplementor logicalConnection = session.getJdbcCoordinator().getLogicalConnection(); + logicalConnection.getResourceRegistry().register( statementMock, true ); + connections[0] = logicalConnection.getPhysicalConnection(); - throw rollbackException; - } ); - } - catch (RuntimeException e) { - if ( e != rollbackException ) { - throw e; - } - // Else: ignore, that was expected. - } + throw rollbackException; + } ); + } + catch (RuntimeException e) { + if ( e != rollbackException ) { + throw e; + } + // Else: ignore, that was expected. + } - // Note: all this must happen BEFORE the session is closed; - // it's particularly important when reusing the session. + // Note: all this must happen BEFORE the session is closed; + // it's particularly important when reusing the session. - Connection connection = connections[0]; + Connection connection = connections[0]; - // Must close the resources, then the connection - InOrder inOrder = inOrder( statementMock, connectionProvider ); - inOrder.verify( statementMock ).close(); - inOrder.verify( connectionProvider ).closeConnection( connection ); - // We don't check the relative ordering of the rollback here, - // because unfortunately we know it's wrong: - // we don't get a "before transaction completion" event for rollbacks, - // so in the case of rollbacks the closing always happen after transaction completion. - } - } + // Must close the resources, then the connection + InOrder inOrder = inOrder( statementMock, connectionProvider ); + inOrder.verify( statementMock ).close(); + inOrder.verify( connectionProvider ).closeConnection( connection ); + // We don't check the relative ordering of the rollback here, + // because unfortunately we know it's wrong: + // we don't get a "before transaction completion" event for rollbacks, + // so in the case of rollbacks the closing always happen after transaction completion. + } + } - private void spyOnTransaction(XAResource xaResource) { - try { - TestingJtaPlatformImpl.transactionManager().getTransaction().enlistResource( xaResource ); - } - catch (RollbackException | SystemException e) { - throw new IllegalStateException( e ); - } - } + private void spyOnTransaction(XAResource xaResource) { + try { + TestingJtaPlatformImpl.transactionManager().getTransaction().enlistResource( xaResource ); + } + catch (RollbackException | SystemException e) { + throw new IllegalStateException( e ); + } + } - private Session openSession() { - return connectionHandlingModeInSessionBuilder == null - ? entityManagerFactory().openSession() - : entityManagerFactory().withOptions().connectionHandlingMode( connectionHandlingModeInSessionBuilder ) - .openSession(); - } + private Session openSession() { + return connectionHandlingModeInSessionBuilder == null + ? entityManagerFactory().openSession() + : entityManagerFactory().withOptions().connectionHandlingMode( connectionHandlingModeInSessionBuilder ) + .openSession(); + } - // --- // + // --- // - @Entity(name = "Thing") - @Table(name = "Thing") - public static class Thing { + @Entity(name = "Thing") + @Table(name = "Thing") + public static class Thing { - @Id - public Integer id; + @Id + public Integer id; - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } - } + public void setId(Integer id) { + this.id = id; + } + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/constraint/ConstraintTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/constraint/ConstraintTest.java index e479314a6d..2f8713c6c4 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/constraint/ConstraintTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/constraint/ConstraintTest.java @@ -71,7 +71,7 @@ public class ConstraintTest extends BaseNonConfigCoreFunctionalTestCase { int foundCount = 0; for ( Namespace namespace : metadata().getDatabase().getNamespaces() ) { for ( org.hibernate.mapping.Table table : namespace.getTables() ) { - Iterator fkItr = table.getForeignKeys().values().iterator(); + Iterator fkItr = table.getForeignKeys().values().iterator(); while (fkItr.hasNext()) { ForeignKey fk = (ForeignKey) fkItr.next(); assertTrue( fk.getName().length() <= MAX_NAME_LENGTH ); @@ -89,7 +89,7 @@ public class ConstraintTest extends BaseNonConfigCoreFunctionalTestCase { } } - Iterator ukItr = table.getUniqueKeys().values().iterator(); + Iterator ukItr = table.getUniqueKeys().values().iterator(); while (ukItr.hasNext()) { UniqueKey uk = (UniqueKey) ukItr.next(); assertTrue( uk.getName().length() <= MAX_NAME_LENGTH ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/constraint/ForeignKeyConstraintMapsIdTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/constraint/ForeignKeyConstraintMapsIdTest.java index 58e3834c1d..3910b74cfe 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/constraint/ForeignKeyConstraintMapsIdTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/constraint/ForeignKeyConstraintMapsIdTest.java @@ -90,7 +90,7 @@ public class ForeignKeyConstraintMapsIdTest extends BaseNonConfigCoreFunctionalT for ( Namespace namespace : metadata().getDatabase().getNamespaces() ) { for ( Table table : namespace.getTables() ) { if ( table.getName().equals( "Post" ) ) { - Iterator foreignKeyIterator = table.getForeignKeys().values().iterator(); + Iterator foreignKeyIterator = table.getForeignKeys().values().iterator(); while ( foreignKeyIterator.hasNext() ) { org.hibernate.mapping.ForeignKey foreignKey = foreignKeyIterator.next(); if ( foreignKey.getColumn( 0 ).getName().equals( "PD_ID" ) ) { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/constraint/ForeignKeyConstraintTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/constraint/ForeignKeyConstraintTest.java index bb88654460..7c3195e066 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/constraint/ForeignKeyConstraintTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/constraint/ForeignKeyConstraintTest.java @@ -180,7 +180,7 @@ public class ForeignKeyConstraintTest { Set columnSet = new LinkedHashSet<>( Arrays.asList( columns ) ); for ( Namespace namespace : scope.getDomainModel().getDatabase().getNamespaces() ) { for ( org.hibernate.mapping.Table table : namespace.getTables() ) { - Iterator fkItr = table.getForeignKeys().values().iterator(); + Iterator fkItr = table.getForeignKeys().values().iterator(); while ( fkItr.hasNext() ) { org.hibernate.mapping.ForeignKey fk = fkItr.next(); @@ -202,7 +202,7 @@ public class ForeignKeyConstraintTest { private void assertNoForeignKey(DomainModelScope scope, String foreignKeyName, String... columns) { for ( Namespace namespace : scope.getDomainModel().getDatabase().getNamespaces() ) { for ( org.hibernate.mapping.Table table : namespace.getTables() ) { - Iterator fkItr = table.getForeignKeys().values().iterator(); + Iterator fkItr = table.getForeignKeys().values().iterator(); while ( fkItr.hasNext() ) { org.hibernate.mapping.ForeignKey fk = fkItr.next(); assertFalse( diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/cuk/JoinColumnOccursOutOfOrderTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/cuk/JoinColumnOccursOutOfOrderTest.java index 7cffc022b1..ffe439676d 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/cuk/JoinColumnOccursOutOfOrderTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/cuk/JoinColumnOccursOutOfOrderTest.java @@ -24,185 +24,185 @@ import java.util.List; @SessionFactory @DomainModel(annotatedClasses = { - JoinColumnOccursOutOfOrderTest.MasterEntity.class, - JoinColumnOccursOutOfOrderTest.ChildTwoEntity.class, - JoinColumnOccursOutOfOrderTest.ChildEntityOne.class, - JoinColumnOccursOutOfOrderTest.ChildEntityFour.class, - JoinColumnOccursOutOfOrderTest.ChildEntityThree.class, + JoinColumnOccursOutOfOrderTest.MasterEntity.class, + JoinColumnOccursOutOfOrderTest.ChildTwoEntity.class, + JoinColumnOccursOutOfOrderTest.ChildEntityOne.class, + JoinColumnOccursOutOfOrderTest.ChildEntityFour.class, + JoinColumnOccursOutOfOrderTest.ChildEntityThree.class, }) @JiraKey("HHH-16263") public class JoinColumnOccursOutOfOrderTest { - @BeforeAll - public void setUp(SessionFactoryScope scope) { - scope.inTransaction( session -> { - var meta = new MasterEntity(); - meta.setId(1l); - meta.column1 = "1"; - meta.column2 = "2"; - meta.column3 = "3"; - session.persist( meta ); - } ); - } + @BeforeAll + public void setUp(SessionFactoryScope scope) { + scope.inTransaction( session -> { + var meta = new MasterEntity(); + meta.setId(1l); + meta.column1 = "1"; + meta.column2 = "2"; + meta.column3 = "3"; + session.persist( meta ); + } ); + } - @AfterAll - public void tearDown(SessionFactoryScope scope) { - scope.inTransaction( session -> { - } ); - } + @AfterAll + public void tearDown(SessionFactoryScope scope) { + scope.inTransaction( session -> { + } ); + } - @Test - public void testOutOffOrder(SessionFactoryScope scope) { - scope.inTransaction( session -> { - final var container = session.createQuery( - "from MasterEntity container where container.id = :param ", - MasterEntity.class - ).setParameter("param", 1).getSingleResult(); - } ); - } + @Test + public void testOutOffOrder(SessionFactoryScope scope) { + scope.inTransaction( session -> { + final var container = session.createQuery( + "from MasterEntity container where container.id = :param ", + MasterEntity.class + ).setParameter("param", 1).getSingleResult(); + } ); + } - @Embeddable - public static class ChildOneId implements Serializable { + @Embeddable + public static class ChildOneId implements Serializable { - @Column(name = "COLUMN_1", nullable = false, length = 7) - private String column1; + @Column(name = "COLUMN_1", nullable = false, length = 7) + private String column1; - @Column(name = "COLUMN_2", nullable = false, length = 4) - private String column2; + @Column(name = "COLUMN_2", nullable = false, length = 4) + private String column2; - @Column(name = "COLUMN_3", nullable = false, length = 2) - private String column3; - } + @Column(name = "COLUMN_3", nullable = false, length = 2) + private String column3; + } - @Embeddable - public static class ChildTwoId implements Serializable { + @Embeddable + public static class ChildTwoId implements Serializable { - @Column(name = "COLUMN_1", length = 7, nullable = false) - private String column1; - @Column(name = "COLUMN_2", length = 4, nullable = false) - private String column2; - @Column(name = "COLUMN_3", length = 2, nullable = false) - private String column3; + @Column(name = "COLUMN_1", length = 7, nullable = false) + private String column1; + @Column(name = "COLUMN_2", length = 4, nullable = false) + private String column2; + @Column(name = "COLUMN_3", length = 2, nullable = false) + private String column3; - } + } - @Embeddable - public static class ChildThreeId implements Serializable { + @Embeddable + public static class ChildThreeId implements Serializable { - @Column(name = "COLUMN_1", nullable = false, length = 7) - private String column1; + @Column(name = "COLUMN_1", nullable = false, length = 7) + private String column1; - @Column(name = "COLUMN_2", nullable = false, length = 4) - private String column2; + @Column(name = "COLUMN_2", nullable = false, length = 4) + private String column2; - @Column(name = "COLUMN_3", nullable = false, length = 2) - private String column3; + @Column(name = "COLUMN_3", nullable = false, length = 2) + private String column3; - @Column(name = "COLUMN_4", nullable = false) - private LocalDateTime creation; + @Column(name = "COLUMN_4", nullable = false) + private LocalDateTime creation; - } + } - @Embeddable - public static class ChildFourId implements Serializable { + @Embeddable + public static class ChildFourId implements Serializable { - @Column(name = "COLUMN_1", length = 7, nullable = false) - private String column1; + @Column(name = "COLUMN_1", length = 7, nullable = false) + private String column1; - @Column(name = "COLUMN_2", length = 4, nullable = false) - private String colum2; + @Column(name = "COLUMN_2", length = 4, nullable = false) + private String colum2; - @Column(name = "COLUMN_3", length = 2, nullable = false) - private String column3; + @Column(name = "COLUMN_3", length = 2, nullable = false) + private String column3; - @Column(name = "NON_UNIQUE_ID", nullable = false) - private Long nonUNiqueId; + @Column(name = "NON_UNIQUE_ID", nullable = false) + private Long nonUNiqueId; - @Column(name = "COLUMN_4", nullable = false) - private LocalDateTime creation; + @Column(name = "COLUMN_4", nullable = false) + private LocalDateTime creation; - } + } - @Entity(name = "ChildEntityFour") - public static class ChildEntityFour { - @EmbeddedId - private ChildFourId id; - } + @Entity(name = "ChildEntityFour") + public static class ChildEntityFour { + @EmbeddedId + private ChildFourId id; + } - @Entity(name = "ChildEntityOne") - public static class ChildEntityOne { - @EmbeddedId - private ChildOneId id; - } + @Entity(name = "ChildEntityOne") + public static class ChildEntityOne { + @EmbeddedId + private ChildOneId id; + } - @Entity(name = "ChildTwoEntity") - @DynamicUpdate - public static class ChildTwoEntity { - @EmbeddedId - private ChildTwoId id; - } + @Entity(name = "ChildTwoEntity") + @DynamicUpdate + public static class ChildTwoEntity { + @EmbeddedId + private ChildTwoId id; + } - @Entity(name = "ChildEntityThree") - public static class ChildEntityThree { - @EmbeddedId - private ChildThreeId id; - } + @Entity(name = "ChildEntityThree") + public static class ChildEntityThree { + @EmbeddedId + private ChildThreeId id; + } - @Entity(name = "MasterEntity") - public static class MasterEntity { + @Entity(name = "MasterEntity") + public static class MasterEntity { - @Id - @Column(name = "ID", unique = true, nullable = false) - private Long id; + @Id + @Column(name = "ID", unique = true, nullable = false) + private Long id; - @Column(name = "COLUMN_1", nullable = false, length = 7) - private String column1; + @Column(name = "COLUMN_1", nullable = false, length = 7) + private String column1; - @Column(name = "COLUMN_2", nullable = false, length = 4) - private String column2; + @Column(name = "COLUMN_2", nullable = false, length = 4) + private String column2; - @Column(name = "COLUMN_3", nullable = false, length = 2) - private String column3; + @Column(name = "COLUMN_3", nullable = false, length = 2) + private String column3; - @OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true) - @JoinColumns(foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT), value = { - @JoinColumn(name = "COLUMN_1", referencedColumnName = "COLUMN_1", insertable = false, updatable = false), - @JoinColumn(name = "COLUMN_2", referencedColumnName = "COLUMN_2", insertable = false, updatable = false), - @JoinColumn(name = "COLUMN_3", referencedColumnName = "COLUMN_3", insertable = false, updatable = false) - }) - @NotFound(action = NotFoundAction.IGNORE) - private ChildEntityOne childEntityOne; + @OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true) + @JoinColumns(foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT), value = { + @JoinColumn(name = "COLUMN_1", referencedColumnName = "COLUMN_1", insertable = false, updatable = false), + @JoinColumn(name = "COLUMN_2", referencedColumnName = "COLUMN_2", insertable = false, updatable = false), + @JoinColumn(name = "COLUMN_3", referencedColumnName = "COLUMN_3", insertable = false, updatable = false) + }) + @NotFound(action = NotFoundAction.IGNORE) + private ChildEntityOne childEntityOne; - @OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true) - @JoinColumns(foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT), value = { - @JoinColumn(name = "COLUMN_1", referencedColumnName = "COLUMN_1", insertable = false, updatable = false), - @JoinColumn(name = "COLUMN_2", referencedColumnName = "COLUMN_2", insertable = false, updatable = false), - @JoinColumn(name = "COLUMN_3", referencedColumnName = "COLUMN_3", insertable = false, updatable = false) - }) - @NotFound(action = NotFoundAction.IGNORE) - private ChildTwoEntity childEntityTwo; + @OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true) + @JoinColumns(foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT), value = { + @JoinColumn(name = "COLUMN_1", referencedColumnName = "COLUMN_1", insertable = false, updatable = false), + @JoinColumn(name = "COLUMN_2", referencedColumnName = "COLUMN_2", insertable = false, updatable = false), + @JoinColumn(name = "COLUMN_3", referencedColumnName = "COLUMN_3", insertable = false, updatable = false) + }) + @NotFound(action = NotFoundAction.IGNORE) + private ChildTwoEntity childEntityTwo; - @OneToMany(fetch = FetchType.LAZY) - @JoinColumn(name = "COLUMN_1", referencedColumnName = "COLUMN_1", insertable = false, updatable = false) - @JoinColumn(name = "COLUMN_2", referencedColumnName = "COLUMN_2", insertable = false, updatable = false) - @JoinColumn(name = "COLUMN_3", referencedColumnName = "COLUMN_3", insertable = false, updatable = false) - private List childEntityThree; + @OneToMany(fetch = FetchType.LAZY) + @JoinColumn(name = "COLUMN_1", referencedColumnName = "COLUMN_1", insertable = false, updatable = false) + @JoinColumn(name = "COLUMN_2", referencedColumnName = "COLUMN_2", insertable = false, updatable = false) + @JoinColumn(name = "COLUMN_3", referencedColumnName = "COLUMN_3", insertable = false, updatable = false) + private List childEntityThree; - @OneToMany(fetch = FetchType.LAZY) - @JoinColumn(name = "COLUMN_1", referencedColumnName = "COLUMN_1", insertable = false, updatable = false) - @JoinColumn(name = "COLUMN_2", referencedColumnName = "COLUMN_2", insertable = false, updatable = false) - @JoinColumn(name = "COLUMN_3", referencedColumnName = "COLUMN_3", insertable = false, updatable = false) - private List childEntityFour; + @OneToMany(fetch = FetchType.LAZY) + @JoinColumn(name = "COLUMN_1", referencedColumnName = "COLUMN_1", insertable = false, updatable = false) + @JoinColumn(name = "COLUMN_2", referencedColumnName = "COLUMN_2", insertable = false, updatable = false) + @JoinColumn(name = "COLUMN_3", referencedColumnName = "COLUMN_3", insertable = false, updatable = false) + private List childEntityFour; - public Long getId() { - return id; - } + public Long getId() { + return id; + } - public void setId(Long id) { - this.id = id; - } + public void setId(Long id) { + this.id = id; + } - } + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/customsql/CustomSqlGeneratedTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/customsql/CustomSqlGeneratedTest.java index a52abf6726..94e4981f38 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/customsql/CustomSqlGeneratedTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/customsql/CustomSqlGeneratedTest.java @@ -32,48 +32,48 @@ import static org.junit.jupiter.api.Assertions.assertEquals; @SessionFactory @DomainModel(annotatedClasses = CustomSqlGeneratedTest.Custom.class) public class CustomSqlGeneratedTest { - @Test - public void testCustomSqlWithGenerated(SessionFactoryScope scope) { - Custom c = new Custom(); - c.name = "name"; - c.text = "text"; - scope.inTransaction(s->{ - s.persist(c); - s.flush(); - Custom cc = s.find(Custom.class, c.id); - assertEquals(cc.text, "TEXT"); - assertEquals(cc.name, "NAME"); - cc.name = "eman"; - cc.text = "more text"; - s.flush(); - cc = s.find(Custom.class, c.id); - assertThat(cc.text ).isEqualTo( "MORE TEXT"); - assertThat( cc.name ).isEqualTo( "EMAN" ); - s.remove(cc); - s.flush(); - cc = s.find(Custom.class, c.id); - assertEquals(cc.text, "DELETED"); - assertEquals(cc.name, "DELETED"); - }); - } - @Entity - @Table(name = "CustomPrimary") - @SecondaryTable(name = "CustomSecondary") - @SQLInsert(sql="insert into CustomPrimary (name, revision, id) values (upper(?),?,?)") - @SQLInsert(table = "CustomSecondary", sql="insert into CustomSecondary (text, id) values (upper(?),?)") - @SQLUpdate(sql="update CustomPrimary set name = upper(?), revision = ? where id = ? and revision = ?") - @SQLUpdate(table = "CustomSecondary", sql="update CustomSecondary set text = upper(?) where id = ?") - @SQLDelete(sql="update CustomPrimary set name = 'DELETED' where id = ? and revision = ?") - @SQLDelete(table = "CustomSecondary", sql="update CustomSecondary set text = 'DELETED' where id = ?") - static class Custom { - @Id @GeneratedValue - Long id; - @Version @Column(name = "revision") - int version; - @Generated(event = { EventType.INSERT, EventType.UPDATE}, writable = true) - String name; - @Generated(event = { EventType.INSERT, EventType.UPDATE}, writable = true) - @Column(table = "CustomSecondary") - String text; - } + @Test + public void testCustomSqlWithGenerated(SessionFactoryScope scope) { + Custom c = new Custom(); + c.name = "name"; + c.text = "text"; + scope.inTransaction(s->{ + s.persist(c); + s.flush(); + Custom cc = s.find(Custom.class, c.id); + assertEquals(cc.text, "TEXT"); + assertEquals(cc.name, "NAME"); + cc.name = "eman"; + cc.text = "more text"; + s.flush(); + cc = s.find(Custom.class, c.id); + assertThat(cc.text ).isEqualTo( "MORE TEXT"); + assertThat( cc.name ).isEqualTo( "EMAN" ); + s.remove(cc); + s.flush(); + cc = s.find(Custom.class, c.id); + assertEquals(cc.text, "DELETED"); + assertEquals(cc.name, "DELETED"); + }); + } + @Entity + @Table(name = "CustomPrimary") + @SecondaryTable(name = "CustomSecondary") + @SQLInsert(sql="insert into CustomPrimary (name, revision, id) values (upper(?),?,?)") + @SQLInsert(table = "CustomSecondary", sql="insert into CustomSecondary (text, id) values (upper(?),?)") + @SQLUpdate(sql="update CustomPrimary set name = upper(?), revision = ? where id = ? and revision = ?") + @SQLUpdate(table = "CustomSecondary", sql="update CustomSecondary set text = upper(?) where id = ?") + @SQLDelete(sql="update CustomPrimary set name = 'DELETED' where id = ? and revision = ?") + @SQLDelete(table = "CustomSecondary", sql="update CustomSecondary set text = 'DELETED' where id = ?") + static class Custom { + @Id @GeneratedValue + Long id; + @Version @Column(name = "revision") + int version; + @Generated(event = { EventType.INSERT, EventType.UPDATE}, writable = true) + String name; + @Generated(event = { EventType.INSERT, EventType.UPDATE}, writable = true) + @Column(table = "CustomSecondary") + String text; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/customsql/CustomSqlOverrideTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/customsql/CustomSqlOverrideTest.java index 3d5fab4d02..dfbb59df59 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/customsql/CustomSqlOverrideTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/customsql/CustomSqlOverrideTest.java @@ -36,56 +36,56 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; @RequiresDialect(value = PostgreSQLDialect.class, majorVersion = 13) @RequiresDialect(SQLServerDialect.class) public class CustomSqlOverrideTest { - @Test - public void testCustomSql(SessionFactoryScope scope) { - Custom c = new Custom(); - scope.inTransaction(s->{ - s.persist(c); - c.whatever = "old value"; - s.flush(); - assertNotNull(c.id); - assertNotNull(c.uid); - s.clear(); - Custom cc = s.find(Custom.class, c.id); - assertNotNull(cc.id); - assertNotNull(cc.uid); - assertEquals("old value", cc.whatever); - cc.whatever = "new value"; - s.flush(); - s.clear(); - Custom ccc = s.find(Custom.class, c.id); - assertNotNull(cc.id); - assertNotNull(cc.uid); - assertEquals("new value", ccc.whatever); - assertEquals(cc.id, ccc.id); - assertNotEquals(cc.uid, ccc.uid); - }); - } - @Entity - @Table(name = "CustomTable") + @Test + public void testCustomSql(SessionFactoryScope scope) { + Custom c = new Custom(); + scope.inTransaction(s->{ + s.persist(c); + c.whatever = "old value"; + s.flush(); + assertNotNull(c.id); + assertNotNull(c.uid); + s.clear(); + Custom cc = s.find(Custom.class, c.id); + assertNotNull(cc.id); + assertNotNull(cc.uid); + assertEquals("old value", cc.whatever); + cc.whatever = "new value"; + s.flush(); + s.clear(); + Custom ccc = s.find(Custom.class, c.id); + assertNotNull(cc.id); + assertNotNull(cc.uid); + assertEquals("new value", ccc.whatever); + assertEquals(cc.id, ccc.id); + assertNotEquals(cc.uid, ccc.uid); + }); + } + @Entity + @Table(name = "CustomTable") // @SQLInsert(sql="") - @DialectOverride.SQLInsert(dialect = H2Dialect.class, - override = @SQLInsert(sql="insert into CustomTable (uid,whatever) values (random_uuid(),?)")) - @DialectOverride.SQLInsert(dialect = MySQLDialect.class, - override = @SQLInsert(sql="insert into CustomTable (uid,whatever) values (uuid(),?)")) - @DialectOverride.SQLInsert(dialect = PostgreSQLDialect.class, - override = @SQLInsert(sql="insert into CustomTable (uid,whatever) values (gen_random_uuid(),?)")) - @DialectOverride.SQLInsert(dialect = SQLServerDialect.class, - override = @SQLInsert(sql="insert into CustomTable (uid,whatever) values (newid(),?)")) + @DialectOverride.SQLInsert(dialect = H2Dialect.class, + override = @SQLInsert(sql="insert into CustomTable (uid,whatever) values (random_uuid(),?)")) + @DialectOverride.SQLInsert(dialect = MySQLDialect.class, + override = @SQLInsert(sql="insert into CustomTable (uid,whatever) values (uuid(),?)")) + @DialectOverride.SQLInsert(dialect = PostgreSQLDialect.class, + override = @SQLInsert(sql="insert into CustomTable (uid,whatever) values (gen_random_uuid(),?)")) + @DialectOverride.SQLInsert(dialect = SQLServerDialect.class, + override = @SQLInsert(sql="insert into CustomTable (uid,whatever) values (newid(),?)")) // @SQLUpdate(sql="") - @DialectOverride.SQLUpdate(dialect = H2Dialect.class, - override = @SQLUpdate(sql="update CustomTable set uid = random_uuid(), whatever = ? where id = ?")) - @DialectOverride.SQLUpdate(dialect = MySQLDialect.class, - override = @SQLUpdate(sql="update CustomTable set uid = uuid(), whatever = ? where id = ?")) - @DialectOverride.SQLUpdate(dialect = PostgreSQLDialect.class, - override = @SQLUpdate(sql="update CustomTable set uid = gen_random_uuid(), whatever = ? where id = ?")) - @DialectOverride.SQLUpdate(dialect = SQLServerDialect.class, - override = @SQLUpdate(sql="update CustomTable set uid = newid(), whatever = ? where id = ?")) - static class Custom { - @Id @GeneratedValue(strategy = GenerationType.IDENTITY) - Long id; - @Generated - String uid; - String whatever; - } + @DialectOverride.SQLUpdate(dialect = H2Dialect.class, + override = @SQLUpdate(sql="update CustomTable set uid = random_uuid(), whatever = ? where id = ?")) + @DialectOverride.SQLUpdate(dialect = MySQLDialect.class, + override = @SQLUpdate(sql="update CustomTable set uid = uuid(), whatever = ? where id = ?")) + @DialectOverride.SQLUpdate(dialect = PostgreSQLDialect.class, + override = @SQLUpdate(sql="update CustomTable set uid = gen_random_uuid(), whatever = ? where id = ?")) + @DialectOverride.SQLUpdate(dialect = SQLServerDialect.class, + override = @SQLUpdate(sql="update CustomTable set uid = newid(), whatever = ? where id = ?")) + static class Custom { + @Id @GeneratedValue(strategy = GenerationType.IDENTITY) + Long id; + @Generated + String uid; + String whatever; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/customsql/CustomSqlPrimaryTableExplicitTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/customsql/CustomSqlPrimaryTableExplicitTest.java index ebed5791e2..9db4a113c5 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/customsql/CustomSqlPrimaryTableExplicitTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/customsql/CustomSqlPrimaryTableExplicitTest.java @@ -27,61 +27,61 @@ import static org.junit.jupiter.api.Assertions.assertEquals; @SessionFactory @DomainModel(annotatedClasses = CustomSqlPrimaryTableExplicitTest.Custom.class) public class CustomSqlPrimaryTableExplicitTest { - @Test - public void testCustomSql(SessionFactoryScope scope) { - Custom c = new Custom(); - c.name = "name"; - c.text = "text"; - scope.inTransaction(s->{ - s.persist(c); - s.flush(); - s.clear(); - Custom cc = s.find(Custom.class, c.id); - assertEquals(cc.text, "TEXT"); - assertEquals(cc.name, "NAME"); - cc.name = "eman"; - cc.text = "more text"; - s.flush(); - s.clear(); - cc = s.find(Custom.class, c.id); - assertEquals(cc.text, "MORE TEXT"); - assertEquals(cc.name, "EMAN"); - s.remove(cc); - s.flush(); - s.clear(); - cc = s.find(Custom.class, c.id); - assertEquals(cc.text, "DELETED"); - assertEquals(cc.name, "DELETED"); - }); - } - @Entity - @Table(name = "CustomPrimary") - @SecondaryTable(name = "CustomSecondary") - @SQLInsert(table = "CustomPrimary", - sql="insert into CustomPrimary (name, revision, id) values (upper(?),?,?)", - verify = Expectation.RowCount.class) - @SQLInsert(table = "CustomSecondary", - sql="insert into CustomSecondary (text, id) values (upper(?),?)", - verify = Expectation.None.class) - @SQLUpdate(table = "CustomPrimary", - sql="update CustomPrimary set name = upper(?), revision = ? where id = ? and revision = ?", - verify = Expectation.RowCount.class) - @SQLUpdate(table = "CustomSecondary", - sql="update CustomSecondary set text = upper(?) where id = ?", - verify = Expectation.None.class) - @SQLDelete(table = "CustomPrimary", - sql="update CustomPrimary set name = 'DELETED' where id = ? and revision = ?", - verify = Expectation.RowCount.class) - @SQLDelete(table = "CustomSecondary", - sql="update CustomSecondary set text = 'DELETED' where id = ?", - verify = Expectation.None.class) - static class Custom { - @Id @GeneratedValue - Long id; - @Version @Column(name = "revision") - int version; - String name; - @Column(table = "CustomSecondary") - String text; - } + @Test + public void testCustomSql(SessionFactoryScope scope) { + Custom c = new Custom(); + c.name = "name"; + c.text = "text"; + scope.inTransaction(s->{ + s.persist(c); + s.flush(); + s.clear(); + Custom cc = s.find(Custom.class, c.id); + assertEquals(cc.text, "TEXT"); + assertEquals(cc.name, "NAME"); + cc.name = "eman"; + cc.text = "more text"; + s.flush(); + s.clear(); + cc = s.find(Custom.class, c.id); + assertEquals(cc.text, "MORE TEXT"); + assertEquals(cc.name, "EMAN"); + s.remove(cc); + s.flush(); + s.clear(); + cc = s.find(Custom.class, c.id); + assertEquals(cc.text, "DELETED"); + assertEquals(cc.name, "DELETED"); + }); + } + @Entity + @Table(name = "CustomPrimary") + @SecondaryTable(name = "CustomSecondary") + @SQLInsert(table = "CustomPrimary", + sql="insert into CustomPrimary (name, revision, id) values (upper(?),?,?)", + verify = Expectation.RowCount.class) + @SQLInsert(table = "CustomSecondary", + sql="insert into CustomSecondary (text, id) values (upper(?),?)", + verify = Expectation.None.class) + @SQLUpdate(table = "CustomPrimary", + sql="update CustomPrimary set name = upper(?), revision = ? where id = ? and revision = ?", + verify = Expectation.RowCount.class) + @SQLUpdate(table = "CustomSecondary", + sql="update CustomSecondary set text = upper(?) where id = ?", + verify = Expectation.None.class) + @SQLDelete(table = "CustomPrimary", + sql="update CustomPrimary set name = 'DELETED' where id = ? and revision = ?", + verify = Expectation.RowCount.class) + @SQLDelete(table = "CustomSecondary", + sql="update CustomSecondary set text = 'DELETED' where id = ?", + verify = Expectation.None.class) + static class Custom { + @Id @GeneratedValue + Long id; + @Version @Column(name = "revision") + int version; + String name; + @Column(table = "CustomSecondary") + String text; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/customsql/CustomSqlTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/customsql/CustomSqlTest.java index 1960d2bcf2..2a3ff36873 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/customsql/CustomSqlTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/customsql/CustomSqlTest.java @@ -28,49 +28,49 @@ import static org.junit.jupiter.api.Assertions.assertEquals; @SessionFactory @DomainModel(annotatedClasses = CustomSqlTest.Custom.class) public class CustomSqlTest { - @Test - public void testCustomSql(SessionFactoryScope scope) { - Custom c = new Custom(); - c.name = "name"; - c.text = "text"; - scope.inTransaction(s->{ - s.persist(c); - s.flush(); - s.clear(); - Custom cc = s.find(Custom.class, c.id); - assertEquals(cc.text, "TEXT"); - assertEquals(cc.name, "NAME"); - cc.name = "eman"; - cc.text = "more text"; - s.flush(); - s.clear(); - cc = s.find(Custom.class, c.id); - assertEquals(cc.text, "MORE TEXT"); - assertEquals(cc.name, "EMAN"); - s.remove(cc); - s.flush(); - s.clear(); - cc = s.find(Custom.class, c.id); - assertEquals(cc.text, "DELETED"); - assertEquals(cc.name, "DELETED"); - }); - } - @Entity - @Table(name = "CustomPrimary") - @SecondaryTable(name = "CustomSecondary") - @SQLInsert(sql="insert into CustomPrimary (name, revision, id) values (upper(?),?,?)") - @SQLInsert(table = "CustomSecondary", sql="insert into CustomSecondary (text, id) values (upper(?),?)") - @SQLUpdate(sql="update CustomPrimary set name = upper(?), revision = ? where id = ? and revision = ?") - @SQLUpdate(table = "CustomSecondary", sql="update CustomSecondary set text = upper(?) where id = ?") - @SQLDelete(sql="update CustomPrimary set name = 'DELETED' where id = ? and revision = ?") - @SQLDelete(table = "CustomSecondary", sql="update CustomSecondary set text = 'DELETED' where id = ?") - static class Custom { - @Id @GeneratedValue - Long id; - @Version @Column(name = "revision") - int version; - String name; - @Column(table = "CustomSecondary") - String text; - } + @Test + public void testCustomSql(SessionFactoryScope scope) { + Custom c = new Custom(); + c.name = "name"; + c.text = "text"; + scope.inTransaction(s->{ + s.persist(c); + s.flush(); + s.clear(); + Custom cc = s.find(Custom.class, c.id); + assertEquals(cc.text, "TEXT"); + assertEquals(cc.name, "NAME"); + cc.name = "eman"; + cc.text = "more text"; + s.flush(); + s.clear(); + cc = s.find(Custom.class, c.id); + assertEquals(cc.text, "MORE TEXT"); + assertEquals(cc.name, "EMAN"); + s.remove(cc); + s.flush(); + s.clear(); + cc = s.find(Custom.class, c.id); + assertEquals(cc.text, "DELETED"); + assertEquals(cc.name, "DELETED"); + }); + } + @Entity + @Table(name = "CustomPrimary") + @SecondaryTable(name = "CustomSecondary") + @SQLInsert(sql="insert into CustomPrimary (name, revision, id) values (upper(?),?,?)") + @SQLInsert(table = "CustomSecondary", sql="insert into CustomSecondary (text, id) values (upper(?),?)") + @SQLUpdate(sql="update CustomPrimary set name = upper(?), revision = ? where id = ? and revision = ?") + @SQLUpdate(table = "CustomSecondary", sql="update CustomSecondary set text = upper(?) where id = ?") + @SQLDelete(sql="update CustomPrimary set name = 'DELETED' where id = ? and revision = ?") + @SQLDelete(table = "CustomSecondary", sql="update CustomSecondary set text = 'DELETED' where id = ?") + static class Custom { + @Id @GeneratedValue + Long id; + @Version @Column(name = "revision") + int version; + String name; + @Column(table = "CustomSecondary") + String text; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/customstructures/IdentityMapTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/customstructures/IdentityMapTest.java index ef79232c74..4383b6e092 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/customstructures/IdentityMapTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/customstructures/IdentityMapTest.java @@ -16,62 +16,62 @@ import org.junit.Test; public class IdentityMapTest { - @Test - public void basicIdentityMapFunctionality() { - final IdentityMap map = IdentityMap.instantiateSequenced( 10 ); - Holder k1 = new Holder( "k", 1 ); - Holder s2 = new Holder( "s", 2 ); - map.put( k1, "k1" ); - map.put( s2, "s2" ); - map.put( k1, "K1!" ); - Assert.assertEquals( 2, map.size() ); - k1.name = "p"; - Assert.assertEquals( 2, map.size() ); - Assert.assertEquals( "K1!", map.get( k1 ) ); - Holder k1similar = new Holder( "p", 1 ); - map.put( k1similar, "notk1" ); - Assert.assertEquals( "K1!", map.get( k1 ) ); + @Test + public void basicIdentityMapFunctionality() { + final IdentityMap map = IdentityMap.instantiateSequenced( 10 ); + Holder k1 = new Holder( "k", 1 ); + Holder s2 = new Holder( "s", 2 ); + map.put( k1, "k1" ); + map.put( s2, "s2" ); + map.put( k1, "K1!" ); + Assert.assertEquals( 2, map.size() ); + k1.name = "p"; + Assert.assertEquals( 2, map.size() ); + Assert.assertEquals( "K1!", map.get( k1 ) ); + Holder k1similar = new Holder( "p", 1 ); + map.put( k1similar, "notk1" ); + Assert.assertEquals( "K1!", map.get( k1 ) ); - IdentityMap.onEachKey( map, k -> k.value = 10 ); + IdentityMap.onEachKey( map, k -> k.value = 10 ); - final Iterator keyIterator = map.keyIterator(); - int count = 0; - while ( keyIterator.hasNext() ) { - final Holder key = keyIterator.next(); - Assert.assertNotNull( key ); - count++; - Assert.assertEquals( 10, key.value ); - } - Assert.assertEquals( 3, count ); - } + final Iterator keyIterator = map.keyIterator(); + int count = 0; + while ( keyIterator.hasNext() ) { + final Holder key = keyIterator.next(); + Assert.assertNotNull( key ); + count++; + Assert.assertEquals( 10, key.value ); + } + Assert.assertEquals( 3, count ); + } - private static class Holder { + private static class Holder { - //Evil: mutable keys! - private String name; - private int value; + //Evil: mutable keys! + private String name; + private int value; - public Holder(String name, int value) { - this.name = name; - this.value = value; - } + public Holder(String name, int value) { + this.name = name; + this.value = value; + } - @Override - public boolean equals(Object o) { - if ( this == o ) { - return true; - } - if ( o == null || getClass() != o.getClass() ) { - return false; - } - Holder holder = (Holder) o; - return value == holder.value && - name.equals( holder.name ); - } + @Override + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( o == null || getClass() != o.getClass() ) { + return false; + } + Holder holder = (Holder) o; + return value == holder.value && + name.equals( holder.name ); + } - @Override - public int hashCode() { - return Objects.hash( name, value ); - } - } + @Override + public int hashCode() { + return Objects.hash( name, value ); + } + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/cut/generic/EnumPlaceholderUserType.java b/hibernate-core/src/test/java/org/hibernate/orm/test/cut/generic/EnumPlaceholderUserType.java index d7d0ff4190..e7b399ef3c 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/cut/generic/EnumPlaceholderUserType.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/cut/generic/EnumPlaceholderUserType.java @@ -16,88 +16,88 @@ import org.hibernate.usertype.CompositeUserType; public class EnumPlaceholderUserType implements CompositeUserType { - @Override - public Object getPropertyValue(EnumPlaceholder component, int property) throws HibernateException { - switch ( property ) { - case 0: - return component.getFirstEnum().getClass(); - case 1: - return component.getFirstEnum().name(); - case 2: - return component.getSecondEnum().getClass(); - case 3: - return component.getSecondEnum().name(); - default: - throw new RuntimeException(); - } - } + @Override + public Object getPropertyValue(EnumPlaceholder component, int property) throws HibernateException { + switch ( property ) { + case 0: + return component.getFirstEnum().getClass(); + case 1: + return component.getFirstEnum().name(); + case 2: + return component.getSecondEnum().getClass(); + case 3: + return component.getSecondEnum().name(); + default: + throw new RuntimeException(); + } + } - @Override - public EnumPlaceholder instantiate(ValueAccess values, SessionFactoryImplementor sessionFactory) { - Class firstEnumClass = values.getValue( 0, Class.class ); - String firstEnumValue = values.getValue( 1, String.class ); - Class secondEnumClass = values.getValue( 2, Class.class ); - String secondEnumValue = values.getValue( 3, String.class ); + @Override + public EnumPlaceholder instantiate(ValueAccess values, SessionFactoryImplementor sessionFactory) { + Class firstEnumClass = values.getValue( 0, Class.class ); + String firstEnumValue = values.getValue( 1, String.class ); + Class secondEnumClass = values.getValue( 2, Class.class ); + String secondEnumValue = values.getValue( 3, String.class ); - Enum firstEnum = Enum.valueOf( firstEnumClass, firstEnumValue ); - Enum secondEnum = Enum.valueOf( secondEnumClass, secondEnumValue ); + Enum firstEnum = Enum.valueOf( firstEnumClass, firstEnumValue ); + Enum secondEnum = Enum.valueOf( secondEnumClass, secondEnumValue ); - return new EnumPlaceholder( firstEnum, secondEnum ); - } + return new EnumPlaceholder( firstEnum, secondEnum ); + } - @Override - public Class embeddable() { - return EmbeddableMapper.class; - } + @Override + public Class embeddable() { + return EmbeddableMapper.class; + } - @Override - public Class returnedClass() { - return EnumPlaceholder.class; - } + @Override + public Class returnedClass() { + return EnumPlaceholder.class; + } - @Override - public boolean equals(EnumPlaceholder x, EnumPlaceholder y) { - return Objects.equals( x, y ); - } + @Override + public boolean equals(EnumPlaceholder x, EnumPlaceholder y) { + return Objects.equals( x, y ); + } - @Override - public int hashCode(EnumPlaceholder x) { - return Objects.hashCode( x ); - } + @Override + public int hashCode(EnumPlaceholder x) { + return Objects.hashCode( x ); + } - @Override - public EnumPlaceholder deepCopy(EnumPlaceholder value) { - return new EnumPlaceholder<>( value.getFirstEnum(), value.getSecondEnum() ); - } + @Override + public EnumPlaceholder deepCopy(EnumPlaceholder value) { + return new EnumPlaceholder<>( value.getFirstEnum(), value.getSecondEnum() ); + } - @Override - public boolean isMutable() { - return false; - } + @Override + public boolean isMutable() { + return false; + } - @Override - public Serializable disassemble(EnumPlaceholder value) { - return (Serializable) value; - } + @Override + public Serializable disassemble(EnumPlaceholder value) { + return (Serializable) value; + } - @Override - public EnumPlaceholder assemble(Serializable cached, Object owner) { - return (EnumPlaceholder) cached; - } + @Override + public EnumPlaceholder assemble(Serializable cached, Object owner) { + return (EnumPlaceholder) cached; + } - @Override - public EnumPlaceholder replace(EnumPlaceholder detached, EnumPlaceholder managed, Object owner) { - return detached; - } + @Override + public EnumPlaceholder replace(EnumPlaceholder detached, EnumPlaceholder managed, Object owner) { + return detached; + } - public static class EmbeddableMapper { - Class firstEnumClass; + public static class EmbeddableMapper { + Class firstEnumClass; - String firstEnumValue; + String firstEnumValue; - Class secondEnumClass; + Class secondEnumClass; - String secondEnumValue; - } + String secondEnumValue; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/cut/generic/Weekdays.java b/hibernate-core/src/test/java/org/hibernate/orm/test/cut/generic/Weekdays.java index bd5eab92dd..7f0d86a6e7 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/cut/generic/Weekdays.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/cut/generic/Weekdays.java @@ -7,10 +7,10 @@ package org.hibernate.orm.test.cut.generic; public enum Weekdays { - MONDAY, - TUESDAY, - WEDNESDAY, - THURSDAY, - SATURDAY, - SUNDAY + MONDAY, + TUESDAY, + WEDNESDAY, + THURSDAY, + SATURDAY, + SUNDAY } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/deleteunloaded/Child.java b/hibernate-core/src/test/java/org/hibernate/orm/test/deleteunloaded/Child.java index 5b74e9fe94..eb634f4fa9 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/deleteunloaded/Child.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/deleteunloaded/Child.java @@ -13,21 +13,21 @@ import jakarta.persistence.ManyToOne; @Entity public class Child { - @GeneratedValue - @Id - private long id; - @ManyToOne - private Parent parent; + @GeneratedValue + @Id + private long id; + @ManyToOne + private Parent parent; - public long getId() { - return id; - } + public long getId() { + return id; + } - public Parent getParent() { - return parent; - } + public Parent getParent() { + return parent; + } - public void setParent(Parent parent) { - this.parent = parent; - } + public void setParent(Parent parent) { + this.parent = parent; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/deleteunloaded/DeleteUnloadedProxyTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/deleteunloaded/DeleteUnloadedProxyTest.java index 0512794526..78eedf96a6 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/deleteunloaded/DeleteUnloadedProxyTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/deleteunloaded/DeleteUnloadedProxyTest.java @@ -29,124 +29,124 @@ import static org.junit.jupiter.api.Assertions.assertNull; //) public class DeleteUnloadedProxyTest { - @AfterEach - public void cleanup(SessionFactoryScope scope) { - scope.inTransaction( session -> { - session.createMutationQuery( "delete from ParentSub" ).executeUpdate(); - session.createMutationQuery( "delete from Child" ).executeUpdate(); - session.createMutationQuery( "delete from Parent" ).executeUpdate(); - } ); - } - @Test - public void testAttached(SessionFactoryScope scope) { - Parent p = new Parent(); - Child c = new Child(); - scope.inSession( em -> { - Transaction tx = em.beginTransaction(); - c.setParent(p); - p.getChildren().add(c); - p.getWords().add("hello"); - p.getWords().add("world"); - em.persist(p); - tx.commit(); - } ); - scope.inSession( em -> { - Transaction tx = em.beginTransaction(); - Child child = em.getReference( Child.class, c.getId() ); - assertFalse( isInitialized(child) ); - em.remove(child); - Parent parent = em.getReference( Parent.class, p.getId() ); - assertFalse( isInitialized(parent) ); - em.remove(parent); - tx.commit(); - assertFalse( isInitialized(child) ); - assertFalse( isInitialized(parent) ); - } ); - scope.inSession( em -> { - assertNull( em.find( Parent.class, p.getId() ) ); - assertNull( em.find( Child.class, c.getId() ) ); - } ); - } - @Test - public void testDetached(SessionFactoryScope scope) { - Parent p = new Parent(); - Child c = new Child(); - scope.inSession( em -> { - Transaction tx = em.beginTransaction(); - c.setParent(p); - p.getChildren().add(c); - p.getWords().add("hello"); - p.getWords().add("world"); - em.persist(p); - tx.commit(); - } ); - Child cc = scope.fromSession( em -> { - Transaction tx = em.beginTransaction(); - Child child = em.getReference( Child.class, c.getId() ); - assertFalse( isInitialized(child) ); - return child; - } ); - Parent pp = scope.fromSession( em -> { - Transaction tx = em.beginTransaction(); - Parent parent = em.getReference( Parent.class, p.getId() ); - assertFalse( isInitialized(parent) ); - return parent; - } ); - scope.inSession( em -> { - Transaction tx = em.beginTransaction(); - em.remove(cc); - em.remove(pp); - tx.commit(); - assertFalse( isInitialized(cc) ); - assertFalse( isInitialized(pp) ); - } ); - scope.inSession( em -> { - assertNull( em.find( Parent.class, p.getId() ) ); - assertNull( em.find( Child.class, c.getId() ) ); - } ); - } + @AfterEach + public void cleanup(SessionFactoryScope scope) { + scope.inTransaction( session -> { + session.createMutationQuery( "delete from ParentSub" ).executeUpdate(); + session.createMutationQuery( "delete from Child" ).executeUpdate(); + session.createMutationQuery( "delete from Parent" ).executeUpdate(); + } ); + } + @Test + public void testAttached(SessionFactoryScope scope) { + Parent p = new Parent(); + Child c = new Child(); + scope.inSession( em -> { + Transaction tx = em.beginTransaction(); + c.setParent(p); + p.getChildren().add(c); + p.getWords().add("hello"); + p.getWords().add("world"); + em.persist(p); + tx.commit(); + } ); + scope.inSession( em -> { + Transaction tx = em.beginTransaction(); + Child child = em.getReference( Child.class, c.getId() ); + assertFalse( isInitialized(child) ); + em.remove(child); + Parent parent = em.getReference( Parent.class, p.getId() ); + assertFalse( isInitialized(parent) ); + em.remove(parent); + tx.commit(); + assertFalse( isInitialized(child) ); + assertFalse( isInitialized(parent) ); + } ); + scope.inSession( em -> { + assertNull( em.find( Parent.class, p.getId() ) ); + assertNull( em.find( Child.class, c.getId() ) ); + } ); + } + @Test + public void testDetached(SessionFactoryScope scope) { + Parent p = new Parent(); + Child c = new Child(); + scope.inSession( em -> { + Transaction tx = em.beginTransaction(); + c.setParent(p); + p.getChildren().add(c); + p.getWords().add("hello"); + p.getWords().add("world"); + em.persist(p); + tx.commit(); + } ); + Child cc = scope.fromSession( em -> { + Transaction tx = em.beginTransaction(); + Child child = em.getReference( Child.class, c.getId() ); + assertFalse( isInitialized(child) ); + return child; + } ); + Parent pp = scope.fromSession( em -> { + Transaction tx = em.beginTransaction(); + Parent parent = em.getReference( Parent.class, p.getId() ); + assertFalse( isInitialized(parent) ); + return parent; + } ); + scope.inSession( em -> { + Transaction tx = em.beginTransaction(); + em.remove(cc); + em.remove(pp); + tx.commit(); + assertFalse( isInitialized(cc) ); + assertFalse( isInitialized(pp) ); + } ); + scope.inSession( em -> { + assertNull( em.find( Parent.class, p.getId() ) ); + assertNull( em.find( Child.class, c.getId() ) ); + } ); + } - @Test - @JiraKey( "HHH-16690" ) - public void testRePersist(SessionFactoryScope scope) { - Parent p = new Parent(); - ParentSub ps = new ParentSub( 1L, "abc", p ); - scope.inTransaction( em -> { - em.persist( p ); - em.persist( ps ); - } ); - scope.inTransaction( em -> { - ParentSub sub = em.getReference( ParentSub.class, 1L ); - assertFalse( isInitialized( sub ) ); - em.remove( sub ); - em.persist( new ParentSub( 1L, "def", p ) ); - } ); - scope.inSession( em -> { - ParentSub sub = em.find( ParentSub.class, 1L ); - assertNotNull( sub ); - assertEquals( "def", sub.getData() ); - } ); - } + @Test + @JiraKey( "HHH-16690" ) + public void testRePersist(SessionFactoryScope scope) { + Parent p = new Parent(); + ParentSub ps = new ParentSub( 1L, "abc", p ); + scope.inTransaction( em -> { + em.persist( p ); + em.persist( ps ); + } ); + scope.inTransaction( em -> { + ParentSub sub = em.getReference( ParentSub.class, 1L ); + assertFalse( isInitialized( sub ) ); + em.remove( sub ); + em.persist( new ParentSub( 1L, "def", p ) ); + } ); + scope.inSession( em -> { + ParentSub sub = em.find( ParentSub.class, 1L ); + assertNotNull( sub ); + assertEquals( "def", sub.getData() ); + } ); + } - @Test - @JiraKey( "HHH-16690" ) - public void testReMerge(SessionFactoryScope scope) { - Parent p = new Parent(); - ParentSub ps = new ParentSub( 1L, "abc", p ); - scope.inTransaction( em -> { - em.persist( p ); - em.persist( ps ); - } ); - scope.inTransaction( em -> { - ParentSub sub = em.getReference( ParentSub.class, 1L ); - assertFalse( isInitialized( sub ) ); - em.remove( sub ); - em.merge( new ParentSub( 1L, "def", p ) ); - } ); - scope.inSession( em -> { - ParentSub sub = em.find( ParentSub.class, 1L ); - assertNotNull( sub ); - assertEquals( "def", sub.getData() ); - } ); - } + @Test + @JiraKey( "HHH-16690" ) + public void testReMerge(SessionFactoryScope scope) { + Parent p = new Parent(); + ParentSub ps = new ParentSub( 1L, "abc", p ); + scope.inTransaction( em -> { + em.persist( p ); + em.persist( ps ); + } ); + scope.inTransaction( em -> { + ParentSub sub = em.getReference( ParentSub.class, 1L ); + assertFalse( isInitialized( sub ) ); + em.remove( sub ); + em.merge( new ParentSub( 1L, "def", p ) ); + } ); + scope.inSession( em -> { + ParentSub sub = em.find( ParentSub.class, 1L ); + assertNotNull( sub ); + assertEquals( "def", sub.getData() ); + } ); + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/deleteunloaded/Parent.java b/hibernate-core/src/test/java/org/hibernate/orm/test/deleteunloaded/Parent.java index 1229abe686..85d1bc5a81 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/deleteunloaded/Parent.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/deleteunloaded/Parent.java @@ -21,27 +21,27 @@ import java.util.Set; @Entity public class Parent { - @GeneratedValue - @Id - private long id; - @Version - private int version; + @GeneratedValue + @Id + private long id; + @Version + private int version; - @OneToMany(mappedBy = "parent", cascade = CascadeType.PERSIST) - private Set children = new HashSet<>(); + @OneToMany(mappedBy = "parent", cascade = CascadeType.PERSIST) + private Set children = new HashSet<>(); - @ElementCollection - private List words = new ArrayList<>(); + @ElementCollection + private List words = new ArrayList<>(); - public Set getChildren() { - return children; - } + public Set getChildren() { + return children; + } - public List getWords() { - return words; - } + public List getWords() { + return words; + } - public long getId() { - return id; - } + public long getId() { + return id; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/deleteunloaded/ParentSub.java b/hibernate-core/src/test/java/org/hibernate/orm/test/deleteunloaded/ParentSub.java index 399f8ad113..b942ac8fa1 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/deleteunloaded/ParentSub.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/deleteunloaded/ParentSub.java @@ -13,42 +13,42 @@ import jakarta.persistence.OneToOne; @Entity public class ParentSub { - @Id - private long id; - private String data; - @OneToOne(fetch = FetchType.LAZY) - private Parent parent; + @Id + private long id; + private String data; + @OneToOne(fetch = FetchType.LAZY) + private Parent parent; - public ParentSub() { - } + public ParentSub() { + } - public ParentSub(long id, String data, Parent parent) { - this.id = id; - this.data = data; - this.parent = parent; - } + public ParentSub(long id, String data, Parent parent) { + this.id = id; + this.data = data; + this.parent = parent; + } - public long getId() { - return id; - } + public long getId() { + return id; + } - public void setId(long id) { - this.id = id; - } + public void setId(long id) { + this.id = id; + } - public String getData() { - return data; - } + public String getData() { + return data; + } - public void setData(String data) { - this.data = data; - } + public void setData(String data) { + this.data = data; + } - public Parent getParent() { - return parent; - } + public Parent getParent() { + return parent; + } - public void setParent(Parent parent) { - this.parent = parent; - } + public void setParent(Parent parent) { + this.parent = parent; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/DB2iDialectInitTestCase.java b/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/DB2iDialectInitTestCase.java index 0db9662153..62a36ba465 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/DB2iDialectInitTestCase.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/DB2iDialectInitTestCase.java @@ -20,10 +20,10 @@ import static org.junit.Assert.assertNotNull; @RequiresDialect(DB2iDialect.class) public class DB2iDialectInitTestCase { - @Test - public void testInitUniqueDelegate() { - final var db2iDialect = new DB2iDialect(); - assertNotNull(db2iDialect); - } + @Test + public void testInitUniqueDelegate() { + final var db2iDialect = new DB2iDialect(); + assertNotNull(db2iDialect); + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/DB2zDialectInitTestCase.java b/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/DB2zDialectInitTestCase.java index 1ed180f109..b47edf23e6 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/DB2zDialectInitTestCase.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/DB2zDialectInitTestCase.java @@ -20,12 +20,12 @@ import static org.junit.Assert.assertNotNull; @RequiresDialect(DB2zDialect.class) public class DB2zDialectInitTestCase { - static class DB2zDialectWithExplicitTimezoneSupport extends DB2zDialect { + static class DB2zDialectWithExplicitTimezoneSupport extends DB2zDialect { } - @Test - public void testInitWithTimezoneSupport() { - final var db2zDialect = new DB2zDialectWithExplicitTimezoneSupport(); - assertNotNull(db2zDialect); - } + @Test + public void testInitWithTimezoneSupport() { + final var db2zDialect = new DB2zDialectWithExplicitTimezoneSupport(); + assertNotNull(db2zDialect); + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/HANADialectTestCase.java b/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/HANADialectTestCase.java index 79d5a627b4..f03b7fdf47 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/HANADialectTestCase.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/HANADialectTestCase.java @@ -64,8 +64,8 @@ public class HANADialectTestCase extends BaseUnitTestCase { @Entity( name = "EntityWithIdentity" ) @Table( name = "EntityWithIdentity" ) public static class EntityWithIdentity { - @Id @GeneratedValue( strategy = GenerationType.IDENTITY ) - private Integer id; + @Id @GeneratedValue( strategy = GenerationType.IDENTITY ) + private Integer id; private EntityWithIdentity() { // for use by Hibernate diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/function/AnsiTrimEmulationFunctionTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/function/AnsiTrimEmulationFunctionTest.java index fff287a986..f077df651b 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/function/AnsiTrimEmulationFunctionTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/function/AnsiTrimEmulationFunctionTest.java @@ -52,7 +52,7 @@ public class AnsiTrimEmulationFunctionTest { private static final String TRAILING = "substring(?1,1,len(?1+'x')-1-patindex('%[^'+?2+']%',reverse(?1))+1)"; private static final String BOTH = "substring(?1,patindex('%[^'+?2+']%',?1),len(?1+'x')-1-patindex('%[^'+?2+']%',?1)-patindex('%[^'+?2+']%',reverse(?1))+2)"; - @Test + @Test // @RequiresDialect( SQLServerDialect.class ) public void testBasicSqlServerProcessing(ServiceRegistryScope scope) { Dialect dialect = new SQLServerDialect(); @@ -76,7 +76,7 @@ public class AnsiTrimEmulationFunctionTest { assertEquals( expected, rendered ); } - @Test + @Test // @RequiresDialect( SybaseDialect.class ) public void testBasicSybaseProcessing(ServiceRegistryScope scope) { Dialect dialect = new SybaseDialect(); @@ -145,7 +145,7 @@ public class AnsiTrimEmulationFunctionTest { return null; } } ); - function.render( walker, sqlAstArguments, (ReturnableType) null, walker ); + function.render( walker, sqlAstArguments, (ReturnableType) null, walker ); return walker.getSql(); } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/function/HSQLTruncFunctionTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/function/HSQLTruncFunctionTest.java index 1cb0649201..10efb37e7b 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/function/HSQLTruncFunctionTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/function/HSQLTruncFunctionTest.java @@ -19,7 +19,7 @@ import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; import static org.junit.Assert.assertEquals; /** - @author Vlad Mihalcea +@author Vlad Mihalcea */ @RequiresDialect( HSQLDialect.class ) public class HSQLTruncFunctionTest extends BaseEntityManagerFunctionalTestCase { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/function/MySQLRoundFunctionTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/function/MySQLRoundFunctionTest.java index b54dfe1608..b68d334266 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/function/MySQLRoundFunctionTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/function/MySQLRoundFunctionTest.java @@ -19,7 +19,7 @@ import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; import static org.junit.Assert.assertEquals; /** - @author Strong Liu +@author Strong Liu */ @RequiresDialect( MySQLDialect.class ) public class MySQLRoundFunctionTest extends BaseCoreFunctionalTestCase { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/functional/HANASearchTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/functional/HANASearchTest.java index aedb122580..eda8928eb9 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/functional/HANASearchTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/functional/HANASearchTest.java @@ -50,7 +50,7 @@ public class HANASearchTest { session -> session.doWork( connection -> { try (PreparedStatement ps = connection.prepareStatement( "CREATE COLUMN TABLE " + ENTITY_NAME - + " (key INTEGER, t TEXT, c NVARCHAR(255), PRIMARY KEY (key))" )) { + + " (key INTEGER, t TEXT, c NVARCHAR(255), PRIMARY KEY (key))" )) { ps.execute(); } try (PreparedStatement ps = connection @@ -99,7 +99,7 @@ public class HANASearchTest { session.flush(); Query legacyQuery = session.createQuery( "select b, snippets(t), highlighted(t), score() from " - + ENTITY_NAME + " b where contains(b.t, 'text')", Object[].class ); + + ENTITY_NAME + " b where contains(b.t, 'text')", Object[].class ); Object[] result = legacyQuery.getSingleResult(); SearchEntity retrievedEntity = (SearchEntity) result[0]; @@ -131,7 +131,7 @@ public class HANASearchTest { session.flush(); Query legacyQuery = session.createQuery( "select b, snippets(t), highlighted(t), score() from " + ENTITY_NAME - + " b where not contains(b.t, 'string')", Object[].class ); + + " b where not contains(b.t, 'string')", Object[].class ); Object[] result = legacyQuery.getSingleResult(); SearchEntity retrievedEntity = (SearchEntity) result[0]; @@ -241,7 +241,7 @@ public class HANASearchTest { session.beginTransaction(); Query legacyQuery = session.createQuery( "select b, snippets(c), highlighted(c), score() from " + ENTITY_NAME - + " b where contains(b.c, 'string', FUZZY(0.7))", Object[].class ); + + " b where contains(b.c, 'string', FUZZY(0.7))", Object[].class ); Object[] result = legacyQuery.getSingleResult(); SearchEntity retrievedEntity = (SearchEntity) result[0]; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/functional/OracleFollowOnLockingTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/functional/OracleFollowOnLockingTest.java index 50f6d26264..2c9587731a 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/functional/OracleFollowOnLockingTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/functional/OracleFollowOnLockingTest.java @@ -209,7 +209,7 @@ public class OracleFollowOnLockingTest extends List products = session.createQuery( "select p from Product p", Product.class ) .setLockOptions( new LockOptions( LockMode.PESSIMISTIC_WRITE ) - .setFollowOnLocking( false ) ) + .setFollowOnLocking( false ) ) .setFirstResult( 40 ) .setMaxResults( 10 ) .getResultList(); @@ -234,7 +234,7 @@ public class OracleFollowOnLockingTest extends session.createQuery( "select p from Product p left join p.vehicle v on v.id is null", Product.class ) .setLockOptions( new LockOptions( LockMode.PESSIMISTIC_WRITE ) - .setFollowOnLocking( false ) ) + .setFollowOnLocking( false ) ) .setFirstResult( 40 ) .setMaxResults( 10 ) .getResultList(); @@ -264,7 +264,7 @@ public class OracleFollowOnLockingTest extends session.createQuery( "select p from Product p", Product.class ) .setLockOptions( new LockOptions( LockMode.PESSIMISTIC_WRITE ) - .setFollowOnLocking( true ) ) + .setFollowOnLocking( true ) ) .setFirstResult( 40 ) .setMaxResults( 10 ) .getResultList(); @@ -335,7 +335,7 @@ public class OracleFollowOnLockingTest extends Product.class ) .setLockOptions( new LockOptions( LockMode.PESSIMISTIC_WRITE ) - .setFollowOnLocking( false ) ) + .setFollowOnLocking( false ) ) .setMaxResults( 10 ) .getResultList(); assertEquals( 10, products.size() ); @@ -354,7 +354,7 @@ public class OracleFollowOnLockingTest extends session.createQuery( "select p from Product p order by p.id", Product.class ) .setLockOptions( new LockOptions( LockMode.PESSIMISTIC_WRITE ) - .setFollowOnLocking( true ) ) + .setFollowOnLocking( true ) ) .setMaxResults( 10 ) .getResultList(); @@ -403,7 +403,7 @@ public class OracleFollowOnLockingTest extends Product.class ) .setLockOptions( new LockOptions( LockMode.PESSIMISTIC_WRITE ) - .setFollowOnLocking( false ) ) + .setFollowOnLocking( false ) ) .getResultList(); fail( "Should throw exception since Oracle does not support DISTINCT if follow on locking is disabled" ); } @@ -432,7 +432,7 @@ public class OracleFollowOnLockingTest extends session.createQuery( "select distinct p from Product p where p.id > 40" ) .setLockOptions( new LockOptions( LockMode.PESSIMISTIC_WRITE ) - .setFollowOnLocking( true ) ) + .setFollowOnLocking( true ) ) .setMaxResults( 10 ) .getResultList(); @@ -481,7 +481,7 @@ public class OracleFollowOnLockingTest extends "from Product p " + "group by p.id, p.name, p.vehicle.id " ) .setLockOptions( new LockOptions( LockMode.PESSIMISTIC_WRITE ) - .setFollowOnLocking( false ) ) + .setFollowOnLocking( false ) ) .getResultList(); fail( "Should throw exception since Oracle does not support GROUP BY if follow on locking is disabled" ); } @@ -512,7 +512,7 @@ public class OracleFollowOnLockingTest extends "from Product p " + "group by p.id, p.name, p.vehicle.id " ) .setLockOptions( new LockOptions( LockMode.PESSIMISTIC_WRITE ) - .setFollowOnLocking( true ) ) + .setFollowOnLocking( true ) ) .getResultList(); assertEquals( 50, products.size() ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/functional/SequenceInformationMariaDBTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/functional/SequenceInformationMariaDBTest.java index c1b8514662..36d4ce329d 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/functional/SequenceInformationMariaDBTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/functional/SequenceInformationMariaDBTest.java @@ -73,31 +73,31 @@ public class SequenceInformationMariaDBTest { catch (SQLException e) { } statement.execute( "CREATE TABLE `TBL_BOOK` ( " + - " `ID` int(11) NOT NULL, " + - " `TITLE` varchar(255) DEFAULT NULL, " + - " PRIMARY KEY (`ID`) " + - ") ENGINE=InnoDB" ); + " `ID` int(11) NOT NULL, " + + " `TITLE` varchar(255) DEFAULT NULL, " + + " PRIMARY KEY (`ID`) " + + ") ENGINE=InnoDB" ); statement.execute( "CREATE TABLE `TBL_AUTHOR` ( " + - " `ID` int(11) NOT NULL, " + - " `firstName` varchar(255) DEFAULT NULL, " + - " `lastName` varchar(255) DEFAULT NULL, " + - " PRIMARY KEY (`ID`) " + - ") ENGINE=InnoDB" ); + " `ID` int(11) NOT NULL, " + + " `firstName` varchar(255) DEFAULT NULL, " + + " `lastName` varchar(255) DEFAULT NULL, " + + " PRIMARY KEY (`ID`) " + + ") ENGINE=InnoDB" ); statement.execute( "CREATE SEQUENCE book_sequence " + - " START WITH 1 " + - " INCREMENT BY 1 " + - " MAXVALUE 2999999999 " + - " MINVALUE 0 " + - " CACHE 10" ); + " START WITH 1 " + + " INCREMENT BY 1 " + + " MAXVALUE 2999999999 " + + " MINVALUE 0 " + + " CACHE 10" ); statement.execute( "CREATE SEQUENCE author_sequence " + - " START WITH 1 " + - " INCREMENT BY 1 " + - " MAXVALUE 2999999999 " + - " MINVALUE 0 " + - " CACHE 10" ); + " START WITH 1 " + + " INCREMENT BY 1 " + + " MAXVALUE 2999999999 " + + " MINVALUE 0 " + + " CACHE 10" ); } catch (SQLException e) { fail(e.getMessage()); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/resolver/StandardDialectResolverTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/resolver/StandardDialectResolverTest.java index 25cc7ba5bc..163a22026e 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/resolver/StandardDialectResolverTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/resolver/StandardDialectResolverTest.java @@ -189,8 +189,8 @@ public class StandardDialectResolverTest extends BaseUnitTestCase { // Make sure to test that the actual dialect class is as expected // (not just an instance of the expected dialect. assertEquals( "Dialect for " + dbms + " should be " + expectedDialect.getSimpleName(), - expectedDialect, - dialect.getClass() + expectedDialect, + dialect.getClass() ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/discriminatedcollections/Account.java b/hibernate-core/src/test/java/org/hibernate/orm/test/discriminatedcollections/Account.java index e6a58c326d..ea55251877 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/discriminatedcollections/Account.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/discriminatedcollections/Account.java @@ -17,94 +17,94 @@ import jakarta.persistence.ManyToOne; @DiscriminatorColumn(name = "account_type") abstract class Account { - @Id - private Integer id; - private double amount; - private Double rate; + @Id + private Integer id; + private double amount; + private Double rate; - @ManyToOne(fetch = FetchType.LAZY) - private Client client; + @ManyToOne(fetch = FetchType.LAZY) + private Client client; - Account() {} + Account() {} - public Account(Integer id, double amount, Double rate, Client client) { - this.id = id; - this.amount = amount; - this.rate = rate; - this.client = client; - } + public Account(Integer id, double amount, Double rate, Client client) { + this.id = id; + this.amount = amount; + this.rate = rate; + this.client = client; + } - public Account(Integer id, Client client) { - this( id, 0.0, 12.0, client ); - } + public Account(Integer id, Client client) { + this( id, 0.0, 12.0, client ); + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public Client getClient() { - return client; - } + public Client getClient() { + return client; + } - public double getAmount() { - return amount; - } + public double getAmount() { + return amount; + } - public void setAmount(double amount) { - this.amount = amount; - } + public void setAmount(double amount) { + this.amount = amount; + } - public Double getRate() { - return rate; - } + public Double getRate() { + return rate; + } - public void setRate(Double rate) { - this.rate = rate; - } + public void setRate(Double rate) { + this.rate = rate; + } - public abstract AccountType getType(); + public abstract AccountType getType(); } @Entity @DiscriminatorValue("D") class DebitAccount extends Account { - DebitAccount() { - } + DebitAccount() { + } - public DebitAccount(Integer id, double amount, Double rate, Client client) { - super( id, amount, rate, client ); - } + public DebitAccount(Integer id, double amount, Double rate, Client client) { + super( id, amount, rate, client ); + } - public DebitAccount(Integer id, Client client) { - super( id, client ); - } + public DebitAccount(Integer id, Client client) { + super( id, client ); + } - @Override - public AccountType getType() { - return AccountType.DEBIT; - } + @Override + public AccountType getType() { + return AccountType.DEBIT; + } } @Entity @DiscriminatorValue("C") class CreditAccount extends Account { - CreditAccount() { - } + CreditAccount() { + } - public CreditAccount(Integer id, double amount, Double rate, Client client) { - super( id, amount, rate, client ); - } + public CreditAccount(Integer id, double amount, Double rate, Client client) { + super( id, amount, rate, client ); + } - public CreditAccount(Integer id, Client client) { - super( id, client ); - } + public CreditAccount(Integer id, Client client) { + super( id, client ); + } - @Override - public AccountType getType() { - return AccountType.CREDIT; - } + @Override + public AccountType getType() { + return AccountType.CREDIT; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/discriminatedcollections/AccountType.java b/hibernate-core/src/test/java/org/hibernate/orm/test/discriminatedcollections/AccountType.java index b5b192fa60..38b3428f84 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/discriminatedcollections/AccountType.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/discriminatedcollections/AccountType.java @@ -7,6 +7,6 @@ package org.hibernate.orm.test.discriminatedcollections; public enum AccountType { - DEBIT, - CREDIT + DEBIT, + CREDIT } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/discriminatedcollections/Client.java b/hibernate-core/src/test/java/org/hibernate/orm/test/discriminatedcollections/Client.java index 7b76615578..c8a18fd17b 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/discriminatedcollections/Client.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/discriminatedcollections/Client.java @@ -16,37 +16,37 @@ import java.util.Set; @Entity class Client { - @Id - private Integer id; - private String name; + @Id + private Integer id; + private String name; - @OneToMany(cascade = CascadeType.ALL, mappedBy = "client", fetch = FetchType.LAZY) - private Set debitAccounts = new HashSet<>(); + @OneToMany(cascade = CascadeType.ALL, mappedBy = "client", fetch = FetchType.LAZY) + private Set debitAccounts = new HashSet<>(); - @OneToMany(cascade = CascadeType.ALL, mappedBy = "client", fetch = FetchType.LAZY) - private Set creditAccounts = new HashSet<>(); + @OneToMany(cascade = CascadeType.ALL, mappedBy = "client", fetch = FetchType.LAZY) + private Set creditAccounts = new HashSet<>(); - Client() {} + Client() {} - public Client(Integer id, String name) { - this.id = id; - this.name = name; - } + public Client(Integer id, String name) { + this.id = id; + this.name = name; + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public Set getCreditAccounts() { - return creditAccounts; - } + public Set getCreditAccounts() { + return creditAccounts; + } - public Set getDebitAccounts() { - return debitAccounts; - } + public Set getDebitAccounts() { + return debitAccounts; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/entitygraph/EntityGraphNativeQueryTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/entitygraph/EntityGraphNativeQueryTest.java index d2e0eb0a49..ddbcb06e95 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/entitygraph/EntityGraphNativeQueryTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/entitygraph/EntityGraphNativeQueryTest.java @@ -142,8 +142,8 @@ public class EntityGraphNativeQueryTest { ); } - @Entity(name = "Foo") - public static class Foo { + @Entity(name = "Foo") + public static class Foo { @Id @GeneratedValue @@ -163,19 +163,19 @@ public class EntityGraphNativeQueryTest { @GeneratedValue public Integer id; - @OneToMany(mappedBy = "bar") - public Set foos = new HashSet<>(); + @OneToMany(mappedBy = "bar") + public Set foos = new HashSet<>(); } @Entity(name = "Baz") - public static class Baz { + public static class Baz { @Id @GeneratedValue - public Integer id; + public Integer id; - @OneToMany(mappedBy = "baz") - public Set foos = new HashSet<>(); + @OneToMany(mappedBy = "baz") + public Set foos = new HashSet<>(); } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/entitygraph/InheritedEntityGraphTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/entitygraph/InheritedEntityGraphTest.java index 0e433181ba..ec754fb864 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/entitygraph/InheritedEntityGraphTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/entitygraph/InheritedEntityGraphTest.java @@ -37,209 +37,209 @@ import static org.hibernate.testing.hamcrest.InitializationCheckMatcher.isInitia * @author Oliver Breidenbach */ @DomainModel( - annotatedClasses = { - InheritedEntityGraphTest.Foo2.class, - InheritedEntityGraphTest.Foo.class, - InheritedEntityGraphTest.Bar.class - } + annotatedClasses = { + InheritedEntityGraphTest.Foo2.class, + InheritedEntityGraphTest.Foo.class, + InheritedEntityGraphTest.Bar.class + } ) @SessionFactory public class InheritedEntityGraphTest { @Test - @JiraKey(value = "HHH-10261") - void singleAttributeNodeInheritanceTest(SessionFactoryScope scope) { + @JiraKey(value = "HHH-10261") + void singleAttributeNodeInheritanceTest(SessionFactoryScope scope) { - MutableLong fooId = new MutableLong(); + MutableLong fooId = new MutableLong(); - scope.inTransaction( - session -> { - Bar bar = new Bar(); - session.persist(bar); + scope.inTransaction( + session -> { + Bar bar = new Bar(); + session.persist(bar); - Foo foo = new Foo(); - foo.bar = bar; - session.persist( foo ); + Foo foo = new Foo(); + foo.bar = bar; + session.persist( foo ); - fooId.set( foo.id ); - } - ); + fooId.set( foo.id ); + } + ); - scope.inTransaction( - session -> { - EntityManager em = session.unwrap( EntityManager.class ); - EntityGraph entityGraph = em.createEntityGraph( Foo.class ); - entityGraph.addSubgraph( "bar" ); + scope.inTransaction( + session -> { + EntityManager em = session.unwrap( EntityManager.class ); + EntityGraph entityGraph = em.createEntityGraph( Foo.class ); + entityGraph.addSubgraph( "bar" ); - Map properties = Collections.singletonMap( - GraphSemantic.LOAD.getJpaHintName(), entityGraph - ); + Map properties = Collections.singletonMap( + GraphSemantic.LOAD.getJpaHintName(), entityGraph + ); - Foo result = em.find( Foo.class, fooId.get(), properties ); + Foo result = em.find( Foo.class, fooId.get(), properties ); - assertThat( result, isInitialized() ); - assertThat( result.bar, isInitialized() ); - } - ); - } + assertThat( result, isInitialized() ); + assertThat( result.bar, isInitialized() ); + } + ); + } - @Test - @JiraKey(value = "HHH-10261") - void collectionAttributeNodeInheritanceTest(SessionFactoryScope scope) { + @Test + @JiraKey(value = "HHH-10261") + void collectionAttributeNodeInheritanceTest(SessionFactoryScope scope) { - MutableLong fooId = new MutableLong(); + MutableLong fooId = new MutableLong(); - scope.inTransaction( - session -> { - Bar bar = new Bar(); - session.persist(bar); + scope.inTransaction( + session -> { + Bar bar = new Bar(); + session.persist(bar); - Foo foo = new Foo(); - foo.bar = bar; - session.persist( foo ); + Foo foo = new Foo(); + foo.bar = bar; + session.persist( foo ); - fooId.set( foo.id ); - } - ); + fooId.set( foo.id ); + } + ); - scope.inTransaction( - session -> { - EntityManager em = session.unwrap( EntityManager.class ); - EntityGraph entityGraph = em.createEntityGraph( Foo.class ); - entityGraph.addSubgraph( "bars" ); + scope.inTransaction( + session -> { + EntityManager em = session.unwrap( EntityManager.class ); + EntityGraph entityGraph = em.createEntityGraph( Foo.class ); + entityGraph.addSubgraph( "bars" ); - Map properties = Collections.singletonMap( - GraphSemantic.LOAD.getJpaHintName(), entityGraph - ); + Map properties = Collections.singletonMap( + GraphSemantic.LOAD.getJpaHintName(), entityGraph + ); - Foo result = em.find( Foo.class, fooId.get(), properties ); + Foo result = em.find( Foo.class, fooId.get(), properties ); - assertThat( result, isInitialized() ); - assertThat( result.bars, isInitialized() ); - } - ); - } + assertThat( result, isInitialized() ); + assertThat( result.bars, isInitialized() ); + } + ); + } - @Test - @JiraKey(value = "HHH-10261") - void singleAttributeSubgraphInheritanceTest(SessionFactoryScope scope) { + @Test + @JiraKey(value = "HHH-10261") + void singleAttributeSubgraphInheritanceTest(SessionFactoryScope scope) { - MutableLong foo2Id = new MutableLong(); + MutableLong foo2Id = new MutableLong(); - scope.inTransaction( - session -> { - Bar bar = new Bar(); - session.persist(bar); + scope.inTransaction( + session -> { + Bar bar = new Bar(); + session.persist(bar); - Foo foo = new Foo(); - foo.bar = bar; - session.persist( foo ); + Foo foo = new Foo(); + foo.bar = bar; + session.persist( foo ); - Foo2 foo2 = new Foo2(); - foo2.foo = foo; - session.persist( foo2 ); + Foo2 foo2 = new Foo2(); + foo2.foo = foo; + session.persist( foo2 ); - foo2Id.set( foo2.id ); - } - ); + foo2Id.set( foo2.id ); + } + ); - scope.inTransaction( - session -> { - EntityManager em = session.unwrap( EntityManager.class ); - EntityGraph entityGraph = em.createEntityGraph( Foo2.class ); - Subgraph subgraphFoo = entityGraph.addSubgraph( "foo" ); - subgraphFoo.addSubgraph( "bar" ); + scope.inTransaction( + session -> { + EntityManager em = session.unwrap( EntityManager.class ); + EntityGraph entityGraph = em.createEntityGraph( Foo2.class ); + Subgraph subgraphFoo = entityGraph.addSubgraph( "foo" ); + subgraphFoo.addSubgraph( "bar" ); - Map properties = Collections.singletonMap( - GraphSemantic.LOAD.getJpaHintName(), entityGraph - ); + Map properties = Collections.singletonMap( + GraphSemantic.LOAD.getJpaHintName(), entityGraph + ); - Foo2 result = em.find( Foo2.class, foo2Id.get(), properties ); + Foo2 result = em.find( Foo2.class, foo2Id.get(), properties ); - assertThat( result, isInitialized() ); - assertThat( result.foo, isInitialized() ); - assertThat( result.foo.bar, isInitialized() ); - } - ); - } + assertThat( result, isInitialized() ); + assertThat( result.foo, isInitialized() ); + assertThat( result.foo.bar, isInitialized() ); + } + ); + } - @Test - @JiraKey(value = "HHH-10261") - void collectionAttributeSubgraphInheritanceTest(SessionFactoryScope scope) { + @Test + @JiraKey(value = "HHH-10261") + void collectionAttributeSubgraphInheritanceTest(SessionFactoryScope scope) { - MutableLong foo2Id = new MutableLong(); + MutableLong foo2Id = new MutableLong(); - scope.inTransaction( - session -> { - Bar bar = new Bar(); - session.persist(bar); + scope.inTransaction( + session -> { + Bar bar = new Bar(); + session.persist(bar); - Foo foo = new Foo(); - foo.bar = bar; - session.persist( foo ); + Foo foo = new Foo(); + foo.bar = bar; + session.persist( foo ); - Foo2 foo2 = new Foo2(); - foo2.foo = foo; - session.persist( foo2 ); + Foo2 foo2 = new Foo2(); + foo2.foo = foo; + session.persist( foo2 ); - foo2Id.set( foo2.id ); - } - ); + foo2Id.set( foo2.id ); + } + ); - scope.inTransaction( - session -> { - EntityManager em = session.unwrap( EntityManager.class ); - EntityGraph entityGraph = em.createEntityGraph( Foo2.class ); - Subgraph subgraphFoo = entityGraph.addSubgraph( "foo" ); - subgraphFoo.addSubgraph( "bars" ); + scope.inTransaction( + session -> { + EntityManager em = session.unwrap( EntityManager.class ); + EntityGraph entityGraph = em.createEntityGraph( Foo2.class ); + Subgraph subgraphFoo = entityGraph.addSubgraph( "foo" ); + subgraphFoo.addSubgraph( "bars" ); - Map properties = Collections.singletonMap( - GraphSemantic.LOAD.getJpaHintName(), entityGraph - ); + Map properties = Collections.singletonMap( + GraphSemantic.LOAD.getJpaHintName(), entityGraph + ); - Foo2 result = em.find( Foo2.class, foo2Id.get(), properties ); + Foo2 result = em.find( Foo2.class, foo2Id.get(), properties ); - assertThat( result, isInitialized() ); - assertThat( result.foo, isInitialized() ); - assertThat( result.foo.bars, isInitialized() ); - } - ); - } + assertThat( result, isInitialized() ); + assertThat( result.foo, isInitialized() ); + assertThat( result.foo.bars, isInitialized() ); + } + ); + } - @MappedSuperclass - public static class MappedSupperclass { - @Id - @GeneratedValue - public long id; + @MappedSuperclass + public static class MappedSupperclass { + @Id + @GeneratedValue + public long id; - @OneToOne(fetch = FetchType.LAZY) - public Bar bar; + @OneToOne(fetch = FetchType.LAZY) + public Bar bar; - @OneToMany - public Set bars = new HashSet(); + @OneToMany + public Set bars = new HashSet(); - } + } - @Entity(name = "Bar") - public static class Bar { - @Id @GeneratedValue - public long id; + @Entity(name = "Bar") + public static class Bar { + @Id @GeneratedValue + public long id; - } + } - @Entity(name = "Foo") - public static class Foo extends MappedSupperclass { + @Entity(name = "Foo") + public static class Foo extends MappedSupperclass { - } + } - @Entity(name = "Foo2") - public static class Foo2 { - @Id @GeneratedValue - public long id; + @Entity(name = "Foo2") + public static class Foo2 { + @Id @GeneratedValue + public long id; - @OneToOne(fetch = FetchType.LAZY) - public Foo foo; + @OneToOne(fetch = FetchType.LAZY) + public Foo foo; - } + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/entitygraph/ast/CriteriaEntityGraphTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/entitygraph/ast/CriteriaEntityGraphTest.java index 1047c6038c..ceb08c29fd 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/entitygraph/ast/CriteriaEntityGraphTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/entitygraph/ast/CriteriaEntityGraphTest.java @@ -114,7 +114,7 @@ public class CriteriaEntityGraphTest implements SessionFactoryScopeAware { // Check the domain-result graph assertDomainResult( sqlAst, Cat.class, fetch -> { - if (graphSemantic == GraphSemantic.LOAD) { + if (graphSemantic == GraphSemantic.LOAD) { assertThat( fetch, instanceOf( BiDirectionalFetch.class ) ); } else { assertThat( fetch, instanceOf( EntityFetch.class ) ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/event/MergeContextTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/event/MergeContextTest.java index 5bdb9f1e54..82320d652d 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/event/MergeContextTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/event/MergeContextTest.java @@ -54,22 +54,22 @@ public class MergeContextTest extends BaseCoreFunctionalTestCase { } @Test - public void testMergeToManagedEntityFillFollowedByInvertMapping() { + public void testMergeToManagedEntityFillFollowedByInvertMapping() { MergeContext cache = new MergeContext( session, new DoNothingEntityCopyObserver() ); - Object mergeEntity = new Simple( 1 ); - Object managedEntity = new Simple( 2 ); + Object mergeEntity = new Simple( 1 ); + Object managedEntity = new Simple( 2 ); - cache.put(mergeEntity, managedEntity); + cache.put(mergeEntity, managedEntity); checkCacheConsistency( cache, 1 ); assertTrue( cache.containsKey( mergeEntity ) ); - assertFalse( cache.containsKey( managedEntity ) ); + assertFalse( cache.containsKey( managedEntity ) ); assertTrue( cache.containsValue( managedEntity ) ); assertTrue( cache.invertMap().containsKey( managedEntity ) ); - assertFalse( cache.invertMap().containsKey( mergeEntity ) ); + assertFalse( cache.invertMap().containsKey( mergeEntity ) ); assertTrue( cache.invertMap().containsValue( mergeEntity ) ); cache.clear(); @@ -77,73 +77,73 @@ public class MergeContextTest extends BaseCoreFunctionalTestCase { checkCacheConsistency( cache, 0 ); assertFalse(cache.containsKey(mergeEntity)); - assertFalse(cache.invertMap().containsKey(managedEntity)); + assertFalse(cache.invertMap().containsKey(managedEntity)); } @Test - public void testMergeToManagedEntityFillFollowedByInvert() { + public void testMergeToManagedEntityFillFollowedByInvert() { MergeContext cache = new MergeContext( session, new DoNothingEntityCopyObserver() ); - Object mergeEntity = new Simple( 1 ); - Object managedEntity = new Simple( 2 ); + Object mergeEntity = new Simple( 1 ); + Object managedEntity = new Simple( 2 ); - cache.put(mergeEntity, managedEntity); + cache.put(mergeEntity, managedEntity); checkCacheConsistency( cache, 1 ); assertTrue(cache.containsKey(mergeEntity)); - assertFalse( cache.containsKey( managedEntity ) ); + assertFalse( cache.containsKey( managedEntity ) ); - assertTrue( cache.invertMap().containsKey( managedEntity ) ); - assertFalse( cache.invertMap().containsKey( mergeEntity ) ); - } + assertTrue( cache.invertMap().containsKey( managedEntity ) ); + assertFalse( cache.invertMap().containsKey( mergeEntity ) ); + } @Test - public void testMergeToManagedEntityFillFollowedByInvertUsingPutAll() { + public void testMergeToManagedEntityFillFollowedByInvertUsingPutAll() { MergeContext cache = new MergeContext( session, new DoNothingEntityCopyObserver() ); - Map input = new HashMap(); - Object mergeEntity1 = new Simple( 1 ); + Map input = new HashMap(); + Object mergeEntity1 = new Simple( 1 ); // - Object managedEntity1 = 1; - input.put(mergeEntity1, managedEntity1); - Object mergeEntity2 = new Simple( 3 ); - Object managedEntity2 = 2; - input.put(mergeEntity2, managedEntity2); - cache.putAll(input); + Object managedEntity1 = 1; + input.put(mergeEntity1, managedEntity1); + Object mergeEntity2 = new Simple( 3 ); + Object managedEntity2 = 2; + input.put(mergeEntity2, managedEntity2); + cache.putAll(input); checkCacheConsistency( cache, 2 ); assertTrue(cache.containsKey(mergeEntity1)); - assertFalse(cache.containsKey(managedEntity1)); - assertTrue(cache.containsKey(mergeEntity2)); - assertFalse(cache.containsKey(managedEntity2)); + assertFalse(cache.containsKey(managedEntity1)); + assertTrue(cache.containsKey(mergeEntity2)); + assertFalse(cache.containsKey(managedEntity2)); - assertTrue(cache.invertMap().containsKey(managedEntity1)); - assertFalse(cache.invertMap().containsKey(mergeEntity1)); + assertTrue(cache.invertMap().containsKey(managedEntity1)); + assertFalse(cache.invertMap().containsKey(mergeEntity1)); - assertTrue(cache.invertMap().containsKey(managedEntity2)); - assertFalse(cache.invertMap().containsKey(mergeEntity2)); - } + assertTrue(cache.invertMap().containsKey(managedEntity2)); + assertFalse(cache.invertMap().containsKey(mergeEntity2)); + } @Test - public void testMergeToManagedEntityFillFollowedByInvertUsingPutWithSetOperatedOnArg() { + public void testMergeToManagedEntityFillFollowedByInvertUsingPutWithSetOperatedOnArg() { MergeContext cache = new MergeContext( session, new DoNothingEntityCopyObserver() ); - Object mergeEntity = new Simple( 1 ); - Object managedEntity = new Simple( 2 ); + Object mergeEntity = new Simple( 1 ); + Object managedEntity = new Simple( 2 ); - cache.put(mergeEntity, managedEntity, true); + cache.put(mergeEntity, managedEntity, true); checkCacheConsistency( cache, 1 ); assertTrue(cache.containsKey(mergeEntity)); - assertFalse( cache.containsKey( managedEntity ) ); + assertFalse( cache.containsKey( managedEntity ) ); - assertTrue( cache.invertMap().containsKey( managedEntity ) ); - assertFalse( cache.invertMap().containsKey( mergeEntity ) ); + assertTrue( cache.invertMap().containsKey( managedEntity ) ); + assertFalse( cache.invertMap().containsKey( mergeEntity ) ); - cache.clear(); + cache.clear(); checkCacheConsistency( cache, 0 ); @@ -153,8 +153,8 @@ public class MergeContextTest extends BaseCoreFunctionalTestCase { checkCacheConsistency( cache, 1 ); assertTrue(cache.containsKey(mergeEntity)); - assertFalse(cache.containsKey(managedEntity)); - } + assertFalse(cache.containsKey(managedEntity)); + } @Test public void testMergeToManagedEntityFillFollowedByIterateEntrySet() { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/event/PreInsertEventListenerVetoUnidirectionalTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/event/PreInsertEventListenerVetoUnidirectionalTest.java index 4bf4f7ae1f..785efb39de 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/event/PreInsertEventListenerVetoUnidirectionalTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/event/PreInsertEventListenerVetoUnidirectionalTest.java @@ -33,93 +33,93 @@ import static org.junit.Assert.fail; @RequiresDialectFeature(DialectChecks.SupportsIdentityColumns.class) @JiraKey( value = "HHH-11721" ) public class PreInsertEventListenerVetoUnidirectionalTest extends BaseCoreFunctionalTestCase { - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { Child.class, Parent.class }; - } + @Override + protected Class[] getAnnotatedClasses() { + return new Class[] { Child.class, Parent.class }; + } - @Override - protected void afterSessionFactoryBuilt() { - super.afterSessionFactoryBuilt(); - EventListenerRegistry registry = sessionFactory().getServiceRegistry().getService( EventListenerRegistry.class ); - registry.appendListeners( - EventType.PRE_INSERT, - (PreInsertEventListener) event -> event.getEntity() instanceof Parent - ); - } + @Override + protected void afterSessionFactoryBuilt() { + super.afterSessionFactoryBuilt(); + EventListenerRegistry registry = sessionFactory().getServiceRegistry().getService( EventListenerRegistry.class ); + registry.appendListeners( + EventType.PRE_INSERT, + (PreInsertEventListener) event -> event.getEntity() instanceof Parent + ); + } - @Test(expected = EntityActionVetoException.class) - public void testVeto() { - doInHibernate( this::sessionFactory, session -> { - Parent parent = new Parent(); - parent.setField1( "f1" ); - parent.setfield2( "f2" ); + @Test(expected = EntityActionVetoException.class) + public void testVeto() { + doInHibernate( this::sessionFactory, session -> { + Parent parent = new Parent(); + parent.setField1( "f1" ); + parent.setfield2( "f2" ); - Child child = new Child(); - child.setParent( parent ); + Child child = new Child(); + child.setParent( parent ); - session.persist( child ); - } ); + session.persist( child ); + } ); - fail( "Should have thrown EntityActionVetoException!" ); - } + fail( "Should have thrown EntityActionVetoException!" ); + } - @Entity(name = "Child") - public static class Child { - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - private Integer id; + @Entity(name = "Child") + public static class Child { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Integer id; - @OneToOne(cascade = CascadeType.ALL) - private Parent parent; + @OneToOne(cascade = CascadeType.ALL) + private Parent parent; - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public Parent getParent() { - return parent; - } + public Parent getParent() { + return parent; + } - public void setParent(Parent parent) { - this.parent = parent; - } - } + public void setParent(Parent parent) { + this.parent = parent; + } + } - @Entity(name = "Parent") - public static class Parent { - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - private Integer id; - private String field1; - private String field2; + @Entity(name = "Parent") + public static class Parent { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Integer id; + private String field1; + private String field2; - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public String getField1() { - return field1; - } + public String getField1() { + return field1; + } - public void setField1(String field1) { - this.field1 = field1; - } + public void setField1(String field1) { + this.field1 = field1; + } - public String getField2() { - return field2; - } + public String getField2() { + return field2; + } - public void setfield2(String field2) { - this.field2 = field2; - } - } + public void setfield2(String field2) { + this.field2 = field2; + } + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/event/collection/AbstractCollectionEventTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/event/collection/AbstractCollectionEventTest.java index 4fce431a55..5b0c248494 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/event/collection/AbstractCollectionEventTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/event/collection/AbstractCollectionEventTest.java @@ -791,23 +791,23 @@ public abstract class AbstractCollectionEventTest extends BaseCoreFunctionalTest } protected void checkResult(CollectionListeners listeners, - CollectionListeners.Listener listenerExpected, - ParentWithCollection parent, - int index) { + CollectionListeners.Listener listenerExpected, + ParentWithCollection parent, + int index) { checkResult( listeners, listenerExpected, parent, parent.getChildren(), index ); } protected void checkResult(CollectionListeners listeners, - CollectionListeners.Listener listenerExpected, - ChildWithBidirectionalManyToMany child, - int index) { + CollectionListeners.Listener listenerExpected, + ChildWithBidirectionalManyToMany child, + int index) { checkResult( listeners, listenerExpected, child, child.getParents(), index ); } protected void checkResult(CollectionListeners listeners, - CollectionListeners.Listener listenerExpected, - Entity ownerExpected, - Collection collExpected, - int index) { + CollectionListeners.Listener listenerExpected, + Entity ownerExpected, + Collection collExpected, + int index) { assertSame( listenerExpected, listeners.getListenersCalled().get( index ) ); assertSame( ownerExpected, diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/event/collection/BrokenCollectionEventTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/event/collection/BrokenCollectionEventTest.java index 2e0f620d24..482600906d 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/event/collection/BrokenCollectionEventTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/event/collection/BrokenCollectionEventTest.java @@ -301,23 +301,23 @@ public class BrokenCollectionEventTest extends BaseCoreFunctionalTestCase { } protected void checkResult(CollectionListeners listeners, - CollectionListeners.Listener listenerExpected, - ParentWithCollection parent, - int index) { + CollectionListeners.Listener listenerExpected, + ParentWithCollection parent, + int index) { checkResult( listeners, listenerExpected, parent, parent.getChildren(), index ); } protected void checkResult(CollectionListeners listeners, - CollectionListeners.Listener listenerExpected, - ChildWithBidirectionalManyToMany child, - int index) { + CollectionListeners.Listener listenerExpected, + ChildWithBidirectionalManyToMany child, + int index) { checkResult( listeners, listenerExpected, child, child.getParents(), index ); } protected void checkResult(CollectionListeners listeners, - CollectionListeners.Listener listenerExpected, - Entity ownerExpected, - Collection collExpected, - int index) { + CollectionListeners.Listener listenerExpected, + Entity ownerExpected, + Collection collExpected, + int index) { assertSame( listenerExpected, listeners.getListenersCalled().get( index ) ); assertSame( ownerExpected, diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/event/collection/detached/AggregatedCollectionEventListener.java b/hibernate-core/src/test/java/org/hibernate/orm/test/event/collection/detached/AggregatedCollectionEventListener.java index 1b3b4a8f40..ce73717813 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/event/collection/detached/AggregatedCollectionEventListener.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/event/collection/detached/AggregatedCollectionEventListener.java @@ -42,12 +42,12 @@ import org.jboss.logging.Logger; */ public class AggregatedCollectionEventListener implements InitializeCollectionEventListener, - PreCollectionRecreateEventListener, - PostCollectionRecreateEventListener, - PreCollectionRemoveEventListener, - PostCollectionRemoveEventListener, - PreCollectionUpdateEventListener, - PostCollectionUpdateEventListener { + PreCollectionRecreateEventListener, + PostCollectionRecreateEventListener, + PreCollectionRemoveEventListener, + PostCollectionRemoveEventListener, + PreCollectionUpdateEventListener, + PostCollectionUpdateEventListener { private static final Logger log = Logger.getLogger( AggregatedCollectionEventListener.class ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/events/BaseEntity.java b/hibernate-core/src/test/java/org/hibernate/orm/test/events/BaseEntity.java index d463bf5f63..3b1228491d 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/events/BaseEntity.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/events/BaseEntity.java @@ -16,29 +16,29 @@ import jakarta.persistence.MappedSuperclass; @MappedSuperclass public abstract class BaseEntity { - private Timestamp createdOn; + private Timestamp createdOn; - private Timestamp updatedOn; + private Timestamp updatedOn; - //Getters and setters are omitted for brevity + //Getters and setters are omitted for brevity //end::events-default-listener-mapping-example[] - public Timestamp getCreatedOn() { - return createdOn; - } + public Timestamp getCreatedOn() { + return createdOn; + } - void setCreatedOn(Timestamp createdOn) { - this.createdOn = createdOn; - } + void setCreatedOn(Timestamp createdOn) { + this.createdOn = createdOn; + } - public Timestamp getUpdatedOn() { - return updatedOn; - } + public Timestamp getUpdatedOn() { + return updatedOn; + } - void setUpdatedOn(Timestamp updatedOn) { - this.updatedOn = updatedOn; - } + void setUpdatedOn(Timestamp updatedOn) { + this.updatedOn = updatedOn; + } //tag::events-default-listener-mapping-example[] } //end::events-default-listener-mapping-example[] diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/events/CallbackTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/events/CallbackTest.java index 12c1dc97a7..b8b6233200 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/events/CallbackTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/events/CallbackTest.java @@ -46,12 +46,12 @@ public class CallbackTest extends BaseCoreFunctionalTestCase { private TestingListener listener = new TestingListener(); @Override - public String[] getMappings() { + public String[] getMappings() { return NO_MAPPINGS; } @Override - public void configure(Configuration cfg) { + public void configure(Configuration cfg) { cfg.setSessionFactoryObserver( observer ); } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/events/DefaultEntityListener.java b/hibernate-core/src/test/java/org/hibernate/orm/test/events/DefaultEntityListener.java index 8c57c56b94..92873d40d1 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/events/DefaultEntityListener.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/events/DefaultEntityListener.java @@ -16,24 +16,24 @@ import java.time.ZoneOffset; //tag::events-default-listener-mapping-example[] public class DefaultEntityListener { - public void onPersist(Object entity) { - if (entity instanceof BaseEntity) { - BaseEntity baseEntity = (BaseEntity) entity; - baseEntity.setCreatedOn(now()); - } - } + public void onPersist(Object entity) { + if (entity instanceof BaseEntity) { + BaseEntity baseEntity = (BaseEntity) entity; + baseEntity.setCreatedOn(now()); + } + } - public void onUpdate(Object entity) { - if (entity instanceof BaseEntity) { - BaseEntity baseEntity = (BaseEntity) entity; - baseEntity.setUpdatedOn(now()); - } - } + public void onUpdate(Object entity) { + if (entity instanceof BaseEntity) { + BaseEntity baseEntity = (BaseEntity) entity; + baseEntity.setUpdatedOn(now()); + } + } - private Timestamp now() { - return Timestamp.from( - LocalDateTime.now().toInstant(ZoneOffset.UTC) - ); - } + private Timestamp now() { + return Timestamp.from( + LocalDateTime.now().toInstant(ZoneOffset.UTC) + ); + } } //end::events-default-listener-mapping-example[] diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/exception/SQLExceptionConversionTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/exception/SQLExceptionConversionTest.java index 88c11a78cd..8a564128dc 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/exception/SQLExceptionConversionTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/exception/SQLExceptionConversionTest.java @@ -151,7 +151,7 @@ public class SQLExceptionConversionTest extends BaseCoreFunctionalTestCase { private void releaseStatement(Session session, PreparedStatement ps) { if ( ps != null ) { try { - ((SessionImplementor) session).getJdbcCoordinator().getLogicalConnection().getResourceRegistry().release( ps ); + ((SessionImplementor) session).getJdbcCoordinator().getLogicalConnection().getResourceRegistry().release( ps ); } catch ( Throwable ignore ) { // ignore... diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/fetchprofiles/join/JoinFetchProfileTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/fetchprofiles/join/JoinFetchProfileTest.java index 0168f9f48d..0353143395 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/fetchprofiles/join/JoinFetchProfileTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/fetchprofiles/join/JoinFetchProfileTest.java @@ -134,8 +134,8 @@ public class JoinFetchProfileTest extends BaseCoreFunctionalTestCase { assertFalse( Hibernate.isInitialized( section.getCourse() ) ); assertFalse( Hibernate.isInitialized( section.getEnrollments() ) ); assertFalse( Hibernate.isInitialized( section.getCourse() - .getCode() - .getDepartment() ) ); + .getCode() + .getDepartment() ) ); assertTrue( Hibernate.isInitialized( section.getCourse() ) ); assertEquals( 1, sessionFactory().getStatistics().getEntityFetchCount() ); } @@ -160,8 +160,8 @@ public class JoinFetchProfileTest extends BaseCoreFunctionalTestCase { assertFalse( Hibernate.isInitialized( section.getCourse() ) ); assertFalse( Hibernate.isInitialized( section.getEnrollments() ) ); assertFalse( Hibernate.isInitialized( section.getCourse() - .getCode() - .getDepartment() ) ); + .getCode() + .getDepartment() ) ); assertTrue( Hibernate.isInitialized( section.getCourse() ) ); assertEquals( 1, sessionFactory().getStatistics().getEntityFetchCount() ); } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/filter/CriteriaQueryWithAppliedFilterTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/filter/CriteriaQueryWithAppliedFilterTest.java index 74b73a188f..23c98f218b 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/filter/CriteriaQueryWithAppliedFilterTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/filter/CriteriaQueryWithAppliedFilterTest.java @@ -71,7 +71,7 @@ public class CriteriaQueryWithAppliedFilterTest extends AbstractStatefulStateles student2.setAge( 27 ); student2.setAddress( new Address( "London", "Oxford St" ) ); session.persist( student2 ); - }); + }); } @AfterEach @@ -108,7 +108,7 @@ public class CriteriaQueryWithAppliedFilterTest extends AbstractStatefulStateles // query.add( Property.forName( "age" ).eq( inner ) ); assertThat( list.size(), is( 1 ) ); - }); + }); scope.inTransaction( session -> { session.enableFilter( "statusFilter" ).setParameter( "status", "deleted" ); @@ -133,7 +133,7 @@ public class CriteriaQueryWithAppliedFilterTest extends AbstractStatefulStateles final List list = session.createQuery( query ).getResultList(); assertThat( list.size(), is( 0 ) ); - }); + }); } @ParameterizedTest diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/filter/DynamicFilterTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/filter/DynamicFilterTest.java index e1ba453a22..6254cb71c8 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/filter/DynamicFilterTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/filter/DynamicFilterTest.java @@ -105,7 +105,7 @@ public class DynamicFilterTest extends BaseNonConfigCoreFunctionalTestCase { @Test public void testSecondLevelCachedCollectionsFiltering() { - CollectionPersister persister = sessionFactory().getRuntimeMetamodels() + CollectionPersister persister = sessionFactory().getRuntimeMetamodels() .getMappingMetamodel() .getCollectionDescriptor(Salesperson.class.getName() + ".orders"); CollectionDataAccess cache = persister.getCacheAccessStrategy(); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/filter/FilterParameterTests.java b/hibernate-core/src/test/java/org/hibernate/orm/test/filter/FilterParameterTests.java index 327cafc549..9e6eff8cf3 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/filter/FilterParameterTests.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/filter/FilterParameterTests.java @@ -309,9 +309,9 @@ public class FilterParameterTests extends AbstractStatefulStatelessFilterTest { @Entity( name = "EntityOne" ) @Table( name = "EntityOne" ) public static class EntityOne { - @Id - private Integer id; - @Basic + @Id + private Integer id; + @Basic private String name; @Column( name = "yes_no" ) @JdbcTypeCode( Types.CHAR ) @@ -364,9 +364,9 @@ public class FilterParameterTests extends AbstractStatefulStatelessFilterTest { @Entity( name = "EntityTwo" ) @Table( name = "EntityTwo" ) public static class EntityTwo { - @Id - private Integer id; - @Basic + @Id + private Integer id; + @Basic private String name; @Column( name = "zero_one" ) @JdbcTypeCode( Types.TINYINT ) @@ -412,9 +412,9 @@ public class FilterParameterTests extends AbstractStatefulStatelessFilterTest { @Entity( name = "EntityThree" ) @Table( name = "EntityThree" ) public static class EntityThree { - @Id - private Integer id; - @Basic + @Id + private Integer id; + @Basic private String name; @Column( name = "mismatch" ) @JdbcTypeCode( Types.TINYINT ) diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/filter/OneToManyWithDynamicFilterTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/filter/OneToManyWithDynamicFilterTest.java index 9c35aa704d..029e225083 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/filter/OneToManyWithDynamicFilterTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/filter/OneToManyWithDynamicFilterTest.java @@ -90,8 +90,8 @@ public class OneToManyWithDynamicFilterTest extends AbstractStatefulStatelessFil enableFilter.validate(); final Query query = session.createQuery( "select a.id from ArticleRevision as a " + - "left join a.articleTradings as t " + - "with ( (t.partyId = :p_0) and (t.classifier = :p_1) )", Long.class ); + "left join a.articleTradings as t " + + "with ( (t.partyId = :p_0) and (t.classifier = :p_1) )", Long.class ); query.setParameter( "p_0", 1L ); query.setParameter( "p_1", "no_classification" ); final List list = query.getResultList(); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/filter/subclass/joined2/Animal.java b/hibernate-core/src/test/java/org/hibernate/orm/test/filter/subclass/joined2/Animal.java index e175049626..d58625aded 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/filter/subclass/joined2/Animal.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/filter/subclass/joined2/Animal.java @@ -22,10 +22,10 @@ import static jakarta.persistence.InheritanceType.JOINED; public class Animal { @Id @Column(name = "id_animal") - private int id; + private int id; - private String name; + private String name; @Column(name = "id_company") - private long company; + private long company; } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/filter/subclass/joined2/Dog.java b/hibernate-core/src/test/java/org/hibernate/orm/test/filter/subclass/joined2/Dog.java index 2d833b0ce9..4897f3b4a1 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/filter/subclass/joined2/Dog.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/filter/subclass/joined2/Dog.java @@ -16,7 +16,7 @@ import jakarta.persistence.Table; @Table(name = "dogs") @PrimaryKeyJoinColumn(name = "id_dog", referencedColumnName = "id_animal") public class Dog extends Animal { - private String breed; + private String breed; @ManyToOne @JoinColumn(name = "id_owner") - private Owner owner; + private Owner owner; } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/flush/AlwaysFlushTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/flush/AlwaysFlushTest.java index 871cd4cea2..1f83b1c849 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/flush/AlwaysFlushTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/flush/AlwaysFlushTest.java @@ -34,128 +34,128 @@ public class AlwaysFlushTest extends BaseEntityManagerFunctionalTestCase { protected Class[] getAnnotatedClasses() { return new Class[] { Person.class, - Phone.class, + Phone.class, Advertisement.class }; } - @Test - public void testFlushSQL() { - doInJPA(this::entityManagerFactory, entityManager -> { - entityManager.createNativeQuery("delete from Person").executeUpdate(); - }); - doInJPA(this::entityManagerFactory, entityManager -> { - log.info("testFlushSQL"); - //tag::flushing-always-flush-sql-example[] - Person person = new Person("John Doe"); - entityManager.persist(person); + @Test + public void testFlushSQL() { + doInJPA(this::entityManagerFactory, entityManager -> { + entityManager.createNativeQuery("delete from Person").executeUpdate(); + }); + doInJPA(this::entityManagerFactory, entityManager -> { + log.info("testFlushSQL"); + //tag::flushing-always-flush-sql-example[] + Person person = new Person("John Doe"); + entityManager.persist(person); - Session session = entityManager.unwrap(Session.class); - assertTrue(((Number) session - .createNativeQuery("select count(*) from Person", Integer.class) - .setHibernateFlushMode(FlushMode.ALWAYS) - .uniqueResult()).intValue() == 1); - //end::flushing-always-flush-sql-example[] - }); - } + Session session = entityManager.unwrap(Session.class); + assertTrue(((Number) session + .createNativeQuery("select count(*) from Person", Integer.class) + .setHibernateFlushMode(FlushMode.ALWAYS) + .uniqueResult()).intValue() == 1); + //end::flushing-always-flush-sql-example[] + }); + } - @Entity(name = "Person") - public static class Person { + @Entity(name = "Person") + public static class Person { - @Id - @GeneratedValue - private Long id; + @Id + @GeneratedValue + private Long id; - private String name; + private String name; - @OneToMany(mappedBy = "person", cascade = CascadeType.ALL) - private List phones = new ArrayList<>(); + @OneToMany(mappedBy = "person", cascade = CascadeType.ALL) + private List phones = new ArrayList<>(); - public Person() { - } + public Person() { + } - public Person(String name) { - this.name = name; - } + public Person(String name) { + this.name = name; + } - public Long getId() { - return id; - } + public Long getId() { + return id; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public List getPhones() { - return phones; - } + public List getPhones() { + return phones; + } - public void addPhone(Phone phone) { - phones.add(phone); - phone.setPerson(this); - } - } + public void addPhone(Phone phone) { + phones.add(phone); + phone.setPerson(this); + } + } - @Entity(name = "Phone") - public static class Phone { + @Entity(name = "Phone") + public static class Phone { - @Id - @GeneratedValue - private Long id; + @Id + @GeneratedValue + private Long id; - @ManyToOne - private Person person; + @ManyToOne + private Person person; - @Column(name = "`number`") - private String number; + @Column(name = "`number`") + private String number; - public Phone() { - } + public Phone() { + } - public Phone(String number) { - this.number = number; - } + public Phone(String number) { + this.number = number; + } - public Long getId() { - return id; - } + public Long getId() { + return id; + } - public String getNumber() { - return number; - } + public String getNumber() { + return number; + } - public Person getPerson() { - return person; - } + public Person getPerson() { + return person; + } - public void setPerson(Person person) { - this.person = person; - } - } + public void setPerson(Person person) { + this.person = person; + } + } - @Entity(name = "Advertisement") - public static class Advertisement { + @Entity(name = "Advertisement") + public static class Advertisement { - @Id - @GeneratedValue - private Long id; + @Id + @GeneratedValue + private Long id; - private String title; + private String title; - public Long getId() { - return id; - } + public Long getId() { + return id; + } - public void setId(Long id) { - this.id = id; - } + public void setId(Long id) { + this.id = id; + } - public String getTitle() { - return title; - } + public String getTitle() { + return title; + } - public void setTitle(String title) { - this.title = title; - } - } + public void setTitle(String title) { + this.title = title; + } + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/flush/CommitFlushTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/flush/CommitFlushTest.java index b9db5a9eb0..202a65d67c 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/flush/CommitFlushTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/flush/CommitFlushTest.java @@ -30,150 +30,150 @@ import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; */ public class CommitFlushTest extends BaseEntityManagerFunctionalTestCase { - @Override - protected Class[] getAnnotatedClasses() { - return new Class[]{ - Person.class, - Phone.class, - Advertisement.class, - }; - } + @Override + protected Class[] getAnnotatedClasses() { + return new Class[]{ + Person.class, + Phone.class, + Advertisement.class, + }; + } - @Test - public void testFlushJPQL() { - doInJPA(this::entityManagerFactory, entityManager -> { - log.info("testFlushJPQL"); - //tag::flushing-commit-flush-jpql-example[] - Person person = new Person("John Doe"); - entityManager.persist(person); + @Test + public void testFlushJPQL() { + doInJPA(this::entityManagerFactory, entityManager -> { + log.info("testFlushJPQL"); + //tag::flushing-commit-flush-jpql-example[] + Person person = new Person("John Doe"); + entityManager.persist(person); - entityManager.createQuery("select p from Advertisement p") - .setFlushMode(FlushModeType.COMMIT) - .getResultList(); + entityManager.createQuery("select p from Advertisement p") + .setFlushMode(FlushModeType.COMMIT) + .getResultList(); - entityManager.createQuery("select p from Person p") - .setFlushMode(FlushModeType.COMMIT) - .getResultList(); - //end::flushing-commit-flush-jpql-example[] - }); - } + entityManager.createQuery("select p from Person p") + .setFlushMode(FlushModeType.COMMIT) + .getResultList(); + //end::flushing-commit-flush-jpql-example[] + }); + } - @Test - public void testFlushSQL() { - doInJPA(this::entityManagerFactory, entityManager -> { - entityManager.createNativeQuery("delete from Person") - .executeUpdate(); - }); - doInJPA(this::entityManagerFactory, entityManager -> { - log.info("testFlushSQL"); - //tag::flushing-commit-flush-sql-example[] - Person person = new Person("John Doe"); - entityManager.persist(person); + @Test + public void testFlushSQL() { + doInJPA(this::entityManagerFactory, entityManager -> { + entityManager.createNativeQuery("delete from Person") + .executeUpdate(); + }); + doInJPA(this::entityManagerFactory, entityManager -> { + log.info("testFlushSQL"); + //tag::flushing-commit-flush-sql-example[] + Person person = new Person("John Doe"); + entityManager.persist(person); - assertTrue(((Number) entityManager - .createNativeQuery("select count(*) from Person") - .getSingleResult()).intValue() == 1); - //end::flushing-commit-flush-sql-example[] - }); - } + assertTrue(((Number) entityManager + .createNativeQuery("select count(*) from Person") + .getSingleResult()).intValue() == 1); + //end::flushing-commit-flush-sql-example[] + }); + } - @Entity(name = "Person") - public static class Person { + @Entity(name = "Person") + public static class Person { - @Id - @GeneratedValue - private Long id; + @Id + @GeneratedValue + private Long id; - private String name; + private String name; - @OneToMany(mappedBy = "person", cascade = CascadeType.ALL) - private List phones = new ArrayList<>(); + @OneToMany(mappedBy = "person", cascade = CascadeType.ALL) + private List phones = new ArrayList<>(); - public Person() { - } + public Person() { + } - public Person(String name) { - this.name = name; - } + public Person(String name) { + this.name = name; + } - public Long getId() { - return id; - } + public Long getId() { + return id; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public List getPhones() { - return phones; - } + public List getPhones() { + return phones; + } - public void addPhone(Phone phone) { - phones.add(phone); - phone.setPerson(this); - } - } + public void addPhone(Phone phone) { + phones.add(phone); + phone.setPerson(this); + } + } - @Entity(name = "Phone") - public static class Phone { + @Entity(name = "Phone") + public static class Phone { - @Id - @GeneratedValue - private Long id; + @Id + @GeneratedValue + private Long id; - @ManyToOne - private Person person; + @ManyToOne + private Person person; - @Column(name = "`number`") - private String number; + @Column(name = "`number`") + private String number; - public Phone() { - } + public Phone() { + } - public Phone(String number) { - this.number = number; - } + public Phone(String number) { + this.number = number; + } - public Long getId() { - return id; - } + public Long getId() { + return id; + } - public String getNumber() { - return number; - } + public String getNumber() { + return number; + } - public Person getPerson() { - return person; - } + public Person getPerson() { + return person; + } - public void setPerson(Person person) { - this.person = person; - } - } + public void setPerson(Person person) { + this.person = person; + } + } - @Entity(name = "Advertisement") - public static class Advertisement { + @Entity(name = "Advertisement") + public static class Advertisement { - @Id - @GeneratedValue - private Long id; + @Id + @GeneratedValue + private Long id; - private String title; + private String title; - public Long getId() { - return id; - } + public Long getId() { + return id; + } - public void setId(Long id) { - this.id = id; - } + public void setId(Long id) { + this.id = id; + } - public String getTitle() { - return title; - } + public String getTitle() { + return title; + } - public void setTitle(String title) { - this.title = title; - } - } + public void setTitle(String title) { + this.title = title; + } + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/flush/FlushOrderTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/flush/FlushOrderTest.java index b80ab64879..f8ee47dd27 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/flush/FlushOrderTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/flush/FlushOrderTest.java @@ -20,66 +20,66 @@ import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; */ public class FlushOrderTest extends BaseEntityManagerFunctionalTestCase { - @Override - protected Class[] getAnnotatedClasses() { - return new Class[]{ - Person.class - }; - } + @Override + protected Class[] getAnnotatedClasses() { + return new Class[]{ + Person.class + }; + } - @Test - public void testOrder() { - doInJPA(this::entityManagerFactory, entityManager -> { - entityManager.createNativeQuery("delete from Person").executeUpdate(); - }); - doInJPA(this::entityManagerFactory, entityManager -> { - Person person = new Person("John Doe"); - person.id = 1L; - entityManager.persist(person); - }); - doInJPA(this::entityManagerFactory, entityManager -> { - log.info("testFlushSQL"); - //tag::flushing-order-example[] - Person person = entityManager.find(Person.class, 1L); - entityManager.remove(person); + @Test + public void testOrder() { + doInJPA(this::entityManagerFactory, entityManager -> { + entityManager.createNativeQuery("delete from Person").executeUpdate(); + }); + doInJPA(this::entityManagerFactory, entityManager -> { + Person person = new Person("John Doe"); + person.id = 1L; + entityManager.persist(person); + }); + doInJPA(this::entityManagerFactory, entityManager -> { + log.info("testFlushSQL"); + //tag::flushing-order-example[] + Person person = entityManager.find(Person.class, 1L); + entityManager.remove(person); - Person newPerson = new Person(); - newPerson.setId(2L); - newPerson.setName("John Doe"); - entityManager.persist(newPerson); - //end::flushing-order-example[] - }); - } + Person newPerson = new Person(); + newPerson.setId(2L); + newPerson.setName("John Doe"); + entityManager.persist(newPerson); + //end::flushing-order-example[] + }); + } - @Entity(name = "Person") - public static class Person { + @Entity(name = "Person") + public static class Person { - @Id - private Long id; + @Id + private Long id; - private String name; + private String name; - public Person() { - } + public Person() { + } - public Person(String name) { - this.name = name; - } + public Person(String name) { + this.name = name; + } - public Long getId() { - return id; - } + public Long getId() { + return id; + } - public void setId(Long id) { - this.id = id; - } + public void setId(Long id) { + this.id = id; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } - } + public void setName(String name) { + this.name = name; + } + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/flush/ManualFlushTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/flush/ManualFlushTest.java index 466d2c562f..db088c3fbf 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/flush/ManualFlushTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/flush/ManualFlushTest.java @@ -30,137 +30,137 @@ import static org.junit.Assert.assertTrue; */ public class ManualFlushTest extends BaseEntityManagerFunctionalTestCase { - @Override - protected Class[] getAnnotatedClasses() { - return new Class[]{ - Person.class, - Phone.class, - Advertisement.class, - }; - } + @Override + protected Class[] getAnnotatedClasses() { + return new Class[]{ + Person.class, + Phone.class, + Advertisement.class, + }; + } - @Test - public void testFlushSQL() { - doInJPA(this::entityManagerFactory, entityManager -> { - entityManager.createNativeQuery("delete from Person").executeUpdate(); - }); - doInJPA(this::entityManagerFactory, entityManager -> { - log.info("testFlushSQL"); - //tag::flushing-manual-flush-example[] - Person person = new Person("John Doe"); - entityManager.persist(person); + @Test + public void testFlushSQL() { + doInJPA(this::entityManagerFactory, entityManager -> { + entityManager.createNativeQuery("delete from Person").executeUpdate(); + }); + doInJPA(this::entityManagerFactory, entityManager -> { + log.info("testFlushSQL"); + //tag::flushing-manual-flush-example[] + Person person = new Person("John Doe"); + entityManager.persist(person); - Session session = entityManager.unwrap(Session.class); - session.setHibernateFlushMode(FlushMode.MANUAL); + Session session = entityManager.unwrap(Session.class); + session.setHibernateFlushMode(FlushMode.MANUAL); - assertTrue(((Number) entityManager - .createQuery("select count(id) from Person") - .getSingleResult()).intValue() == 0); + assertTrue(((Number) entityManager + .createQuery("select count(id) from Person") + .getSingleResult()).intValue() == 0); - assertTrue(((Number) session - .createNativeQuery("select count(*) from Person", Integer.class) - .uniqueResult()).intValue() == 0); - //end::flushing-manual-flush-example[] - }); - } + assertTrue(((Number) session + .createNativeQuery("select count(*) from Person", Integer.class) + .uniqueResult()).intValue() == 0); + //end::flushing-manual-flush-example[] + }); + } - @Entity(name = "Person") - public static class Person { + @Entity(name = "Person") + public static class Person { - @Id - @GeneratedValue - private Long id; + @Id + @GeneratedValue + private Long id; - private String name; + private String name; - @OneToMany(mappedBy = "person", cascade = CascadeType.ALL) - private List phones = new ArrayList<>(); + @OneToMany(mappedBy = "person", cascade = CascadeType.ALL) + private List phones = new ArrayList<>(); - public Person() { - } + public Person() { + } - public Person(String name) { - this.name = name; - } + public Person(String name) { + this.name = name; + } - public Long getId() { - return id; - } + public Long getId() { + return id; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public List getPhones() { - return phones; - } + public List getPhones() { + return phones; + } - public void addPhone(Phone phone) { - phones.add(phone); - phone.setPerson(this); - } - } + public void addPhone(Phone phone) { + phones.add(phone); + phone.setPerson(this); + } + } - @Entity(name = "Phone") - public static class Phone { + @Entity(name = "Phone") + public static class Phone { - @Id - @GeneratedValue - private Long id; + @Id + @GeneratedValue + private Long id; - @ManyToOne - private Person person; + @ManyToOne + private Person person; - @Column(name = "`number`") - private String number; + @Column(name = "`number`") + private String number; - public Phone() { - } + public Phone() { + } - public Phone(String number) { - this.number = number; - } + public Phone(String number) { + this.number = number; + } - public Long getId() { - return id; - } + public Long getId() { + return id; + } - public String getNumber() { - return number; - } + public String getNumber() { + return number; + } - public Person getPerson() { - return person; - } + public Person getPerson() { + return person; + } - public void setPerson(Person person) { - this.person = person; - } - } + public void setPerson(Person person) { + this.person = person; + } + } - @Entity(name = "Advertisement") - public static class Advertisement { + @Entity(name = "Advertisement") + public static class Advertisement { - @Id - @GeneratedValue - private Long id; + @Id + @GeneratedValue + private Long id; - private String title; + private String title; - public Long getId() { - return id; - } + public Long getId() { + return id; + } - public void setId(Long id) { - this.id = id; - } + public void setId(Long id) { + this.id = id; + } - public String getTitle() { - return title; - } + public String getTitle() { + return title; + } - public void setTitle(String title) { - this.title = title; - } - } + public void setTitle(String title) { + this.title = title; + } + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/graph/HHH15065Test.java b/hibernate-core/src/test/java/org/hibernate/orm/test/graph/HHH15065Test.java index 96f1684bf8..09244a034a 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/graph/HHH15065Test.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/graph/HHH15065Test.java @@ -47,11 +47,11 @@ class HHH15065Test { List sqlQueries = statementInspector.getSqlQueries(); assertEquals( 1, sqlQueries.size() ); assertEquals( "select b1_0.id,a1_0.id,a1_0.name,ca1_0.id,ca1_0.name,ce1_0.id,ce1_0.name,e1_0.id,e1_0.name" + - " from Book b1_0" + - " left join Person a1_0 on a1_0.id=b1_0.author_id" + - " left join Person ca1_0 on ca1_0.id=b1_0.coAuthor_id" + - " left join Person ce1_0 on ce1_0.id=b1_0.coEditor_id" + - " left join Person e1_0 on e1_0.id=b1_0.editor_id", sqlQueries.get(0) ); + " from Book b1_0" + + " left join Person a1_0 on a1_0.id=b1_0.author_id" + + " left join Person ca1_0 on ca1_0.id=b1_0.coAuthor_id" + + " left join Person ce1_0 on ce1_0.id=b1_0.coEditor_id" + + " left join Person e1_0 on e1_0.id=b1_0.editor_id", sqlQueries.get(0) ); } @Entity(name = "Book") diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/hbm/inheritance/Animal.java b/hibernate-core/src/test/java/org/hibernate/orm/test/hbm/inheritance/Animal.java index 4e38f2d60c..a39396f203 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/hbm/inheritance/Animal.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/hbm/inheritance/Animal.java @@ -8,15 +8,15 @@ package org.hibernate.orm.test.hbm.inheritance; public abstract class Animal { - private long id; + private long id; - public long getId() { - return id; - } + public long getId() { + return id; + } - public void setId(long id) { - this.id = id; - } + public void setId(long id) { + this.id = id; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/hbm/query/NamedQueryTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/hbm/query/NamedQueryTest.java index 4da904265e..85b341e1a9 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/hbm/query/NamedQueryTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/hbm/query/NamedQueryTest.java @@ -28,15 +28,15 @@ public class NamedQueryTest extends BaseUnitTestCase { private static String NAMED_QUERY_HBM_XML = " "+ - " "+ + " "+ " "+ - " "+ - " "+ + " "+ + " "+ " "+ - " "+ - " "+ - " from NamedQueryTest$Bar where foo like :foo "+ - " "+ + " "+ + " "+ + " from NamedQueryTest$Bar where foo like :foo "+ + " "+ " "+ " "; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/hbm/query/QueryReturnTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/hbm/query/QueryReturnTest.java index 4b314c2448..a438dfbb23 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/hbm/query/QueryReturnTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/hbm/query/QueryReturnTest.java @@ -35,20 +35,20 @@ public class QueryReturnTest extends BaseUnitTestCase { private static String QUERY_RETURN_HBM_XML = " "+ - " "+ + " "+ " "+ - " "+ - " "+ - " "+ + " "+ + " "+ + " "+ " "+ - " "+ + " "+ " "+ - " "+ - " 50]]> "+ - " "+ + " 50]]> "+ + " "+ " "; @Test diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/hql/ASTParserLoadingTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/hql/ASTParserLoadingTest.java index e5d2e2be79..7a67370123 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/hql/ASTParserLoadingTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/hql/ASTParserLoadingTest.java @@ -1138,7 +1138,7 @@ public class ASTParserLoadingTest extends BaseCoreFunctionalTestCase { "implicit-join in select and group-by clauses" ); - s = openSession(); + s = openSession(); s.beginTransaction(); s.remove( e1 ); s.remove( e2 ); @@ -1223,7 +1223,7 @@ public class ASTParserLoadingTest extends BaseCoreFunctionalTestCase { s.getTransaction().commit(); s.close(); - s = openSession(); + s = openSession(); s.beginTransaction(); int count = determineCount( s.createQuery( "select e.id, e.owner from SimpleAssociatedEntity e" ).list().iterator() ); // thing two would be removed from the result due to the inner join @@ -1231,7 +1231,7 @@ public class ASTParserLoadingTest extends BaseCoreFunctionalTestCase { s.getTransaction().commit(); s.close(); - s = openSession(); + s = openSession(); s.beginTransaction(); s.remove( e1 ); s.remove( e2 ); @@ -1249,25 +1249,25 @@ public class ASTParserLoadingTest extends BaseCoreFunctionalTestCase { return count; } - @Test - @JiraKey( value = "HHH-6714" ) - public void testUnaryMinus(){ - Session s = openSession(); - s.beginTransaction(); - Human stliu = new Human(); - stliu.setIntValue( 26 ); + @Test + @JiraKey( value = "HHH-6714" ) + public void testUnaryMinus(){ + Session s = openSession(); + s.beginTransaction(); + Human stliu = new Human(); + stliu.setIntValue( 26 ); - s.persist( stliu ); - s.getTransaction().commit(); - s.clear(); - s.beginTransaction(); - List list =s.createQuery( "from Human h where -(h.intValue - 100)=74" ).list(); - assertEquals( 1, list.size() ); - s.getTransaction().commit(); - s.close(); + s.persist( stliu ); + s.getTransaction().commit(); + s.clear(); + s.beginTransaction(); + List list =s.createQuery( "from Human h where -(h.intValue - 100)=74" ).list(); + assertEquals( 1, list.size() ); + s.getTransaction().commit(); + s.close(); - } + } @Test public void testEntityAndOneToOneReturnedByQuery() { @@ -1738,11 +1738,11 @@ public class ASTParserLoadingTest extends BaseCoreFunctionalTestCase { " select a1 from Animal a1" + " left join a1.offspring o" + " where a1.id=1" + - ")"; + ")"; s.createQuery( qryString ).list(); qryString = "select h.id, h.description" + - " from Human h" + + " from Human h" + " left join h.friends" + " where h in (" + " select h1" + @@ -1753,7 +1753,7 @@ public class ASTParserLoadingTest extends BaseCoreFunctionalTestCase { s.createQuery( qryString ).list(); qryString = "select h.id, h.description" + - " from Human h" + + " from Human h" + " left join h.friends f" + " where f in (" + " select h1" + @@ -3561,7 +3561,7 @@ public class ASTParserLoadingTest extends BaseCoreFunctionalTestCase { t = session.beginTransaction(); try (ScrollableResults sr = session.createQuery( query ) - .setResultTransformer(Transformers.aliasToBean(Animal.class)).scroll()) { + .setResultTransformer(Transformers.aliasToBean(Animal.class)).scroll()) { assertTrue( "Incorrect result size", sr.next() ); assertTrue( "Incorrect return type", sr.get() instanceof Animal ); assertFalse( session.contains( sr.get() ) ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/hql/BooleanPredicateTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/hql/BooleanPredicateTest.java index 1bb9906a09..9b740b4984 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/hql/BooleanPredicateTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/hql/BooleanPredicateTest.java @@ -18,36 +18,36 @@ import static org.junit.jupiter.api.Assertions.assertEquals; @SessionFactory @DomainModel public class BooleanPredicateTest { - @Test void test(SessionFactoryScope scope) { - scope.inSession(session -> { - assertEquals(1, session.createSelectionQuery("select 1 where true is true").getResultList().size()); - assertEquals(0, session.createSelectionQuery("select 1 where false is true").getResultList().size()); - assertEquals(0, session.createSelectionQuery("select 1 where true is not true").getResultList().size()); - assertEquals(1, session.createSelectionQuery("select 1 where false is not true").getResultList().size()); + @Test void test(SessionFactoryScope scope) { + scope.inSession(session -> { + assertEquals(1, session.createSelectionQuery("select 1 where true is true").getResultList().size()); + assertEquals(0, session.createSelectionQuery("select 1 where false is true").getResultList().size()); + assertEquals(0, session.createSelectionQuery("select 1 where true is not true").getResultList().size()); + assertEquals(1, session.createSelectionQuery("select 1 where false is not true").getResultList().size()); - assertEquals(0, session.createSelectionQuery("select 1 where true is false").getResultList().size()); - assertEquals(1, session.createSelectionQuery("select 1 where false is false").getResultList().size()); - assertEquals(1, session.createSelectionQuery("select 1 where true is not false").getResultList().size()); - assertEquals(0, session.createSelectionQuery("select 1 where false is not false").getResultList().size()); - }); - } + assertEquals(0, session.createSelectionQuery("select 1 where true is false").getResultList().size()); + assertEquals(1, session.createSelectionQuery("select 1 where false is false").getResultList().size()); + assertEquals(1, session.createSelectionQuery("select 1 where true is not false").getResultList().size()); + assertEquals(0, session.createSelectionQuery("select 1 where false is not false").getResultList().size()); + }); + } - @SkipForDialect(dialectClass = DerbyDialect.class, reason = "Derby doesn't accept literal null in case") - @Test void testNulls(SessionFactoryScope scope) { - scope.inSession(session -> { - assertEquals(1, session.createSelectionQuery("select 1 where true is true").getResultList().size()); - assertEquals(0, session.createSelectionQuery("select 1 where false is true").getResultList().size()); - assertEquals(0, session.createSelectionQuery("select 1 where null is true").getResultList().size()); - assertEquals(0, session.createSelectionQuery("select 1 where true is not true").getResultList().size()); - assertEquals(1, session.createSelectionQuery("select 1 where false is not true").getResultList().size()); - assertEquals(1, session.createSelectionQuery("select 1 where null is not true").getResultList().size()); + @SkipForDialect(dialectClass = DerbyDialect.class, reason = "Derby doesn't accept literal null in case") + @Test void testNulls(SessionFactoryScope scope) { + scope.inSession(session -> { + assertEquals(1, session.createSelectionQuery("select 1 where true is true").getResultList().size()); + assertEquals(0, session.createSelectionQuery("select 1 where false is true").getResultList().size()); + assertEquals(0, session.createSelectionQuery("select 1 where null is true").getResultList().size()); + assertEquals(0, session.createSelectionQuery("select 1 where true is not true").getResultList().size()); + assertEquals(1, session.createSelectionQuery("select 1 where false is not true").getResultList().size()); + assertEquals(1, session.createSelectionQuery("select 1 where null is not true").getResultList().size()); - assertEquals(0, session.createSelectionQuery("select 1 where true is false").getResultList().size()); - assertEquals(1, session.createSelectionQuery("select 1 where false is false").getResultList().size()); - assertEquals(0, session.createSelectionQuery("select 1 where null is false").getResultList().size()); - assertEquals(1, session.createSelectionQuery("select 1 where true is not false").getResultList().size()); - assertEquals(0, session.createSelectionQuery("select 1 where false is not false").getResultList().size()); - assertEquals(1, session.createSelectionQuery("select 1 where null is not false").getResultList().size()); - }); - } + assertEquals(0, session.createSelectionQuery("select 1 where true is false").getResultList().size()); + assertEquals(1, session.createSelectionQuery("select 1 where false is false").getResultList().size()); + assertEquals(0, session.createSelectionQuery("select 1 where null is false").getResultList().size()); + assertEquals(1, session.createSelectionQuery("select 1 where true is not false").getResultList().size()); + assertEquals(0, session.createSelectionQuery("select 1 where false is not false").getResultList().size()); + assertEquals(1, session.createSelectionQuery("select 1 where null is not false").getResultList().size()); + }); + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/hql/BulkManipulationTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/hql/BulkManipulationTest.java index fb18ff4043..54a904a799 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/hql/BulkManipulationTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/hql/BulkManipulationTest.java @@ -577,7 +577,7 @@ public class BulkManipulationTest extends BaseCoreFunctionalTestCase { } protected boolean supportsBulkInsertIdGeneration(Class entityClass) { - EntityPersister persister = sessionFactory() + EntityPersister persister = sessionFactory() .getMappingMetamodel() .getEntityDescriptor(entityClass.getName()); Generator generator = persister.getGenerator(); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/hql/CallStatistics.java b/hibernate-core/src/test/java/org/hibernate/orm/test/hql/CallStatistics.java index b36297040f..9a97b8b617 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/hql/CallStatistics.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/hql/CallStatistics.java @@ -12,20 +12,20 @@ package org.hibernate.orm.test.hql; //tag::hql-select-clause-dynamic-instantiation-example[] public class CallStatistics { - private final long count; - private final long total; - private final int min; - private final int max; - private final double avg; + private final long count; + private final long total; + private final int min; + private final int max; + private final double avg; - public CallStatistics(long count, long total, int min, int max, double avg) { - this.count = count; - this.total = total; - this.min = min; - this.max = max; - this.avg = avg; - } + public CallStatistics(long count, long total, int min, int max, double avg) { + this.count = count; + this.total = total; + this.min = min; + this.max = max; + this.avg = avg; + } - //Getters and setters omitted for brevity + //Getters and setters omitted for brevity } //end::hql-select-clause-dynamic-instantiation-example[] diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/hql/CoalesceTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/hql/CoalesceTest.java index 845b14587a..5b68b624cf 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/hql/CoalesceTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/hql/CoalesceTest.java @@ -29,108 +29,108 @@ import static org.junit.Assert.assertThat; @JiraKey( value = "HHH-10463") public class CoalesceTest extends BaseCoreFunctionalTestCase { - private Person person; + private Person person; - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Person.class - }; - } + @Override + protected Class[] getAnnotatedClasses() { + return new Class[] { + Person.class + }; + } - @Before - public void setUp() { - doInHibernate( this::sessionFactory, session -> { - person = new Person(); - person.setName("Johannes"); - person.setSurname("Buehler"); - session.persist(person); - } ); - } + @Before + public void setUp() { + doInHibernate( this::sessionFactory, session -> { + person = new Person(); + person.setName("Johannes"); + person.setSurname("Buehler"); + session.persist(person); + } ); + } - @Test - public void HHH_10463_TestCoalesce() { - doInHibernate( this::sessionFactory, session -> { - TypedQuery query = session.createQuery( "from Person p where p.name = coalesce(:name , p.name) ", Person.class ); - query.setParameter("name", "Johannes"); - List resultList = query.getResultList(); - assertThat(resultList, hasItem(person)); - } ); + @Test + public void HHH_10463_TestCoalesce() { + doInHibernate( this::sessionFactory, session -> { + TypedQuery query = session.createQuery( "from Person p where p.name = coalesce(:name , p.name) ", Person.class ); + query.setParameter("name", "Johannes"); + List resultList = query.getResultList(); + assertThat(resultList, hasItem(person)); + } ); - } + } - @Test - public void HHH_10463_NullInCoalesce() { - doInHibernate( this::sessionFactory, session -> { - TypedQuery query = session.createQuery( "from Person p where p.name = coalesce(:name, p.name) ", Person.class ); - query.setParameter("name", null); - List resultList = query.getResultList(); - assertThat(resultList, hasItem(person)); - } ); - } + @Test + public void HHH_10463_NullInCoalesce() { + doInHibernate( this::sessionFactory, session -> { + TypedQuery query = session.createQuery( "from Person p where p.name = coalesce(:name, p.name) ", Person.class ); + query.setParameter("name", null); + List resultList = query.getResultList(); + assertThat(resultList, hasItem(person)); + } ); + } - @Test - public void HHH_10463_NullInCoalesce_PostgreSQL_Workaround() { - doInHibernate( this::sessionFactory, session -> { - TypedQuery query = session.createQuery( "from Person p where p.name = coalesce(cast( :name as string) , p.name) ", Person.class ); - query.setParameter("name", null); - List resultList = query.getResultList(); - assertThat(resultList, hasItem(person)); - } ); - } + @Test + public void HHH_10463_NullInCoalesce_PostgreSQL_Workaround() { + doInHibernate( this::sessionFactory, session -> { + TypedQuery query = session.createQuery( "from Person p where p.name = coalesce(cast( :name as string) , p.name) ", Person.class ); + query.setParameter("name", null); + List resultList = query.getResultList(); + assertThat(resultList, hasItem(person)); + } ); + } - @Entity(name = "Person") - public static class Person { + @Entity(name = "Person") + public static class Person { - @Id - @GeneratedValue - private Integer id; + @Id + @GeneratedValue + private Integer id; - @Column - private String name; + @Column + private String name; - @Column - private String surname; + @Column + private String surname; - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - public String getSurname() { - return surname; - } + public String getSurname() { + return surname; + } - public void setSurname(String surname) { - this.surname = surname; - } + public void setSurname(String surname) { + this.surname = surname; + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof Person )) return false; + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (!(o instanceof Person )) return false; - Person person = (Person) o; + Person person = (Person) o; - return id != null ? id.equals(person.id) : person.id == null; + return id != null ? id.equals(person.id) : person.id == null; - } + } - @Override - public int hashCode() { - return id != null ? id.hashCode() : 0; - } - } + @Override + public int hashCode() { + return id != null ? id.hashCode() : 0; + } + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/hql/DeleteWithSubqueryTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/hql/DeleteWithSubqueryTest.java index 482abcbaed..54f297b2c5 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/hql/DeleteWithSubqueryTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/hql/DeleteWithSubqueryTest.java @@ -54,10 +54,10 @@ public class DeleteWithSubqueryTest extends BaseCoreFunctionalTestCase { public void testDeleteMultipleWhereIns() { Session s = openSession(); s.getTransaction().begin(); - s.createQuery("DELETE FROM Panel panelEntity WHERE " + - " panelEntity.clientId IN ( SELECT trtPanel.clientId FROM TrtPanel trtPanel ) " + - " AND panelEntity.deltaStamp NOT IN ( SELECT trtPanel.deltaStamp FROM TrtPanel trtPanel )").executeUpdate(); - s.getTransaction().commit(); - s.close(); + s.createQuery("DELETE FROM Panel panelEntity WHERE " + + " panelEntity.clientId IN ( SELECT trtPanel.clientId FROM TrtPanel trtPanel ) " + + " AND panelEntity.deltaStamp NOT IN ( SELECT trtPanel.deltaStamp FROM TrtPanel trtPanel )").executeUpdate(); + s.getTransaction().commit(); + s.close(); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/hql/Department.java b/hibernate-core/src/test/java/org/hibernate/orm/test/hql/Department.java index 87413386d1..de973d7bf1 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/hql/Department.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/hql/Department.java @@ -15,26 +15,26 @@ import jakarta.persistence.Table; @Entity @Table(name="department") public class Department implements java.io.Serializable { - private Integer deptNo; - private String deptName; + private Integer deptNo; + private String deptName; - @Id - @GeneratedValue - @Column(name="id_dep") - public Integer getDeptNo() { - return this.deptNo; - } + @Id + @GeneratedValue + @Column(name="id_dep") + public Integer getDeptNo() { + return this.deptNo; + } - public void setDeptNo(Integer deptNo) { - this.deptNo = deptNo; - } + public void setDeptNo(Integer deptNo) { + this.deptNo = deptNo; + } - public String getDeptName() { - return this.deptName; - } + public String getDeptName() { + return this.deptName; + } - public void setDeptName(String deptName) { - this.deptName = deptName; - } + public void setDeptName(String deptName) { + this.deptName = deptName; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/hql/Employee.java b/hibernate-core/src/test/java/org/hibernate/orm/test/hql/Employee.java index 5e55588a8e..5f9ea5a714 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/hql/Employee.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/hql/Employee.java @@ -22,65 +22,65 @@ import jakarta.persistence.Table; @Table(name="employee") public class Employee implements Serializable { - @Id - @GeneratedValue - @Column(name="id_emp") - private Integer id; + @Id + @GeneratedValue + @Column(name="id_emp") + private Integer id; - private String firstName; - private String lastName; + private String firstName; + private String lastName; - @OneToOne - @JoinColumn(name="id_title") - private Title title; + @OneToOne + @JoinColumn(name="id_title") + private Title title; - @ManyToOne(fetch=FetchType.LAZY) - @JoinColumn(name="id_depto") - private Department department; + @ManyToOne(fetch=FetchType.LAZY) + @JoinColumn(name="id_depto") + private Department department; - public Employee() {} + public Employee() {} - public Employee(Integer _id, String _lastName, Integer _idTitle, String _descriptionTitle, Department _dept, String _fname) { - setId(_id); - setLastName(_lastName); - Title _title = new Title(); - _title.setId(_idTitle); - _title.setDescription(_descriptionTitle); - setTitle(_title); - setDepartment(_dept); - setFirstName(_fname); - } + public Employee(Integer _id, String _lastName, Integer _idTitle, String _descriptionTitle, Department _dept, String _fname) { + setId(_id); + setLastName(_lastName); + Title _title = new Title(); + _title.setId(_idTitle); + _title.setDescription(_descriptionTitle); + setTitle(_title); + setDepartment(_dept); + setFirstName(_fname); + } - public Integer getId() { - return id; - } - public void setId(Integer id) { - this.id = id; - } - public String getFirstName() { - return firstName; - } - public void setFirstName(String firstName) { - this.firstName = firstName; - } - public String getLastName() { - return lastName; - } - public void setLastName(String lastName) { - this.lastName = lastName; - } - public Title getTitle() { - return title; - } - public void setTitle(Title title) { - this.title = title; - } - public Department getDepartment() { - return department; - } - public void setDepartment(Department department) { - this.department = department; - } + public Integer getId() { + return id; + } + public void setId(Integer id) { + this.id = id; + } + public String getFirstName() { + return firstName; + } + public void setFirstName(String firstName) { + this.firstName = firstName; + } + public String getLastName() { + return lastName; + } + public void setLastName(String lastName) { + this.lastName = lastName; + } + public Title getTitle() { + return title; + } + public void setTitle(Title title) { + this.title = title; + } + public Department getDepartment() { + return department; + } + public void setDepartment(Department department) { + this.department = department; + } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/hql/FunctionNameAsColumnTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/hql/FunctionNameAsColumnTest.java index ca94a323ad..c86ffb6dd9 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/hql/FunctionNameAsColumnTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/hql/FunctionNameAsColumnTest.java @@ -298,7 +298,7 @@ public class FunctionNameAsColumnTest extends BaseCoreFunctionalTestCase { assertTrue( Hibernate.isInitialized( holder.getEntityWithNoArgFunctionAsColumns() ) ); assertTrue( Hibernate.isInitialized( holder.getNextHolder() ) ); assertTrue( Hibernate.isInitialized( holder.getNextHolder() - .getEntityWithNoArgFunctionAsColumns() ) ); + .getEntityWithNoArgFunctionAsColumns() ) ); assertEquals( 1, holder.getEntityWithNoArgFunctionAsColumns().size() ); EntityWithNoArgFunctionAsColumn e1 = (EntityWithNoArgFunctionAsColumn) holder.getEntityWithNoArgFunctionAsColumns() .iterator() diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/hql/HQLTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/hql/HQLTest.java index 93e963c499..0a884ba1c5 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/hql/HQLTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/hql/HQLTest.java @@ -288,7 +288,7 @@ public class HQLTest extends BaseEntityManagerFunctionalTestCase { @Test public void test_hql_multiple_root_reference_jpql_example() { - doInJPA(this::entityManagerFactory, entityManager -> { + doInJPA(this::entityManagerFactory, entityManager -> { //tag::hql-multiple-root-reference-jpql-example[] List persons = entityManager.createQuery( "select distinct pr, ph " + diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/hql/HqlOperatorTypesafetyTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/hql/HqlOperatorTypesafetyTest.java index 714888fe5e..1f5fb39263 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/hql/HqlOperatorTypesafetyTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/hql/HqlOperatorTypesafetyTest.java @@ -19,77 +19,77 @@ import static org.junit.jupiter.api.Assertions.fail; @SessionFactory @DomainModel(annotatedClasses = HqlOperatorTypesafetyTest.Book.class) public class HqlOperatorTypesafetyTest { - @Test void testOperatorTyping(SessionFactoryScope scope) { - scope.inSession( s -> { - // these should succeed - s.createSelectionQuery("from Book where title = 'Hibernate'").getResultList(); - s.createSelectionQuery("from Book where title > ''").getResultList(); - s.createSelectionQuery("select edition + 1 from Book").getResultList(); - s.createSelectionQuery("select title || '!' from Book").getResultList(); - try { - s.createSelectionQuery("from Book where title = 1").getResultList(); - fail(); - } - catch (SemanticException se) {} - try { - s.createSelectionQuery("from Book where title > 1").getResultList(); - fail(); - } - catch (SemanticException se) {} - try { - s.createSelectionQuery("select title + 1 from Book").getResultList(); - fail(); - } - catch (SemanticException se) {} - }); - } + @Test void testOperatorTyping(SessionFactoryScope scope) { + scope.inSession( s -> { + // these should succeed + s.createSelectionQuery("from Book where title = 'Hibernate'").getResultList(); + s.createSelectionQuery("from Book where title > ''").getResultList(); + s.createSelectionQuery("select edition + 1 from Book").getResultList(); + s.createSelectionQuery("select title || '!' from Book").getResultList(); + try { + s.createSelectionQuery("from Book where title = 1").getResultList(); + fail(); + } + catch (SemanticException se) {} + try { + s.createSelectionQuery("from Book where title > 1").getResultList(); + fail(); + } + catch (SemanticException se) {} + try { + s.createSelectionQuery("select title + 1 from Book").getResultList(); + fail(); + } + catch (SemanticException se) {} + }); + } - @Test void testSubselectTyping(SessionFactoryScope scope) { - scope.inSession( s -> { - // these should succeed - s.createSelectionQuery("from Book where title in (select title from Book)").getResultList(); - s.createSelectionQuery("from Book where title = any (select title from Book)").getResultList(); + @Test void testSubselectTyping(SessionFactoryScope scope) { + scope.inSession( s -> { + // these should succeed + s.createSelectionQuery("from Book where title in (select title from Book)").getResultList(); + s.createSelectionQuery("from Book where title = any (select title from Book)").getResultList(); - // test tuple length errors - try { - s.createSelectionQuery("from Book where title = any (select title, isbn from Book)").getResultList(); - fail(); - } - catch (SemanticException se) {} - try { - s.createSelectionQuery("from Book where title = every (select title, isbn from Book)").getResultList(); - fail(); - } - catch (SemanticException se) {} - try { - s.createSelectionQuery("from Book where title in (select title, isbn from Book)").getResultList(); - fail(); - } - catch (SemanticException se) {} + // test tuple length errors + try { + s.createSelectionQuery("from Book where title = any (select title, isbn from Book)").getResultList(); + fail(); + } + catch (SemanticException se) {} + try { + s.createSelectionQuery("from Book where title = every (select title, isbn from Book)").getResultList(); + fail(); + } + catch (SemanticException se) {} + try { + s.createSelectionQuery("from Book where title in (select title, isbn from Book)").getResultList(); + fail(); + } + catch (SemanticException se) {} - // test typing errors - try { - s.createSelectionQuery("from Book where 1 = any (select title from Book)").getResultList(); - fail(); - } - catch (SemanticException se) {} - try { - s.createSelectionQuery("from Book where 1 = every (select title from Book)").getResultList(); - fail(); - } - catch (SemanticException se) {} - try { - s.createSelectionQuery("from Book where 1 in (select title from Book)").getResultList(); - fail(); - } - catch (SemanticException se) {} - }); - } + // test typing errors + try { + s.createSelectionQuery("from Book where 1 = any (select title from Book)").getResultList(); + fail(); + } + catch (SemanticException se) {} + try { + s.createSelectionQuery("from Book where 1 = every (select title from Book)").getResultList(); + fail(); + } + catch (SemanticException se) {} + try { + s.createSelectionQuery("from Book where 1 in (select title from Book)").getResultList(); + fail(); + } + catch (SemanticException se) {} + }); + } - @Entity(name = "Book") - static class Book { - @Id String isbn; - String title; - int edition; - } + @Entity(name = "Book") + static class Book { + @Id String isbn; + String title; + int edition; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/hql/IndicesTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/hql/IndicesTest.java index ecfaa240e3..2c451ba5a2 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/hql/IndicesTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/hql/IndicesTest.java @@ -30,89 +30,89 @@ import static org.junit.Assert.assertThat; @JiraKey(value = "HHH-14475") public class IndicesTest extends BaseNonConfigCoreFunctionalTestCase { - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] {Project.class, Role.class, Person.class}; - } + @Override + protected Class[] getAnnotatedClasses() { + return new Class[] {Project.class, Role.class, Person.class}; + } - @Before - public void setUp() { - doInHibernate( this::sessionFactory, session -> { + @Before + public void setUp() { + doInHibernate( this::sessionFactory, session -> { - Project project = new Project(1); - Role role = new Role(1); + Project project = new Project(1); + Role role = new Role(1); - session.persist( project ); - session.persist( role ); + session.persist( project ); + session.persist( role ); - Person person = new Person(1, project, role); + Person person = new Person(1, project, role); - session.persist( person ); - }); - } + session.persist( person ); + }); + } - @Test - public void testSelectIndices() { - doInHibernate( this::sessionFactory, session -> { + @Test + public void testSelectIndices() { + doInHibernate( this::sessionFactory, session -> { - List result = session.createQuery( - "select indices(p.roles) from Person p" - ).list(); + List result = session.createQuery( + "select indices(p.roles) from Person p" + ).list(); - assertThat( result.size(), is( 1 ) ); - }); - } + assertThat( result.size(), is( 1 ) ); + }); + } - @Entity(name = "Person") - public static class Person { + @Entity(name = "Person") + public static class Person { - @Id - private Integer id; + @Id + private Integer id; - @OneToMany - @JoinTable(name = "person_to_role", - joinColumns = @JoinColumn(name = "person_id"), - inverseJoinColumns = @JoinColumn(name = "role_id") - ) - @MapKeyJoinColumn(name = "project_id") - private Map roles; + @OneToMany + @JoinTable(name = "person_to_role", + joinColumns = @JoinColumn(name = "person_id"), + inverseJoinColumns = @JoinColumn(name = "role_id") + ) + @MapKeyJoinColumn(name = "project_id") + private Map roles; - public Person() { - } + public Person() { + } - public Person(Integer id, Project project, Role role) { - this.id = id; - roles = new HashMap<>(); - roles.put(project, role); - } - } + public Person(Integer id, Project project, Role role) { + this.id = id; + roles = new HashMap<>(); + roles.put(project, role); + } + } - @Entity(name = "Project") - public static class Project { + @Entity(name = "Project") + public static class Project { - @Id - private Integer id; + @Id + private Integer id; - public Project() { - } + public Project() { + } - public Project(Integer id) { - this.id = id; - } - } + public Project(Integer id) { + this.id = id; + } + } - @Entity(name = "Role") - @Table(name = "proj_role") - public static class Role { + @Entity(name = "Role") + @Table(name = "proj_role") + public static class Role { - @Id - private Integer id; + @Id + private Integer id; - public Role() { - } + public Role() { + } - public Role(Integer id) { - this.id = id; - } - } + public Role(Integer id) { + this.id = id; + } + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/hql/InferenceTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/hql/InferenceTest.java index dd29312942..433cea55f3 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/hql/InferenceTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/hql/InferenceTest.java @@ -36,14 +36,14 @@ import static org.junit.Assert.assertThat; */ public class InferenceTest extends BaseCoreFunctionalTestCase { - private Person person; + private Person person; - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Person.class - }; - } + @Override + protected Class[] getAnnotatedClasses() { + return new Class[] { + Person.class + }; + } @Before public void setUp() { @@ -62,26 +62,26 @@ public class InferenceTest extends BaseCoreFunctionalTestCase { } ); } - @Test - public void testBinaryArithmeticInference() { - doInHibernate( this::sessionFactory, session -> { - TypedQuery query = session.createQuery( "from Person p where p.id + 1 < :param", Person.class ); - query.setParameter("param", 10); - List resultList = query.getResultList(); - assertThat(resultList, hasItem(person)); - } ); + @Test + public void testBinaryArithmeticInference() { + doInHibernate( this::sessionFactory, session -> { + TypedQuery query = session.createQuery( "from Person p where p.id + 1 < :param", Person.class ); + query.setParameter("param", 10); + List resultList = query.getResultList(); + assertThat(resultList, hasItem(person)); + } ); - } + } - @Test - @JiraKey("HHH-17386") - public void testInferenceSourceResetForOnClause() { - doInHibernate( this::sessionFactory, session -> { - session.createQuery( "from Person p where p in (select p2 from Person p2 join Person p3 on exists (select 1 from Person p4))", Person.class ) - .getResultList(); - } ); + @Test + @JiraKey("HHH-17386") + public void testInferenceSourceResetForOnClause() { + doInHibernate( this::sessionFactory, session -> { + session.createQuery( "from Person p where p in (select p2 from Person p2 join Person p3 on exists (select 1 from Person p4))", Person.class ) + .getResultList(); + } ); - } + } @Test @JiraKey("HHH-18046") @@ -97,58 +97,58 @@ public class InferenceTest extends BaseCoreFunctionalTestCase { } ); } - @Entity(name = "Person") - public static class Person { + @Entity(name = "Person") + public static class Person { - @Id - @GeneratedValue - private Integer id; + @Id + @GeneratedValue + private Integer id; - @Column - private String name; + @Column + private String name; - @Column - private String surname; + @Column + private String surname; - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - public String getSurname() { - return surname; - } + public String getSurname() { + return surname; + } - public void setSurname(String surname) { - this.surname = surname; - } + public void setSurname(String surname) { + this.surname = surname; + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof Person )) return false; + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (!(o instanceof Person )) return false; - Person person = (Person) o; + Person person = (Person) o; - return id != null ? id.equals(person.id) : person.id == null; + return id != null ? id.equals(person.id) : person.id == null; - } + } - @Override - public int hashCode() { - return id != null ? id.hashCode() : 0; - } - } + @Override + public int hashCode() { + return id != null ? id.hashCode() : 0; + } + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/hql/NaturalIdDereferenceTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/hql/NaturalIdDereferenceTest.java index c58d5de23e..64382bbcdd 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/hql/NaturalIdDereferenceTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/hql/NaturalIdDereferenceTest.java @@ -277,7 +277,7 @@ public class NaturalIdDereferenceTest { scope.inTransaction( session -> { Query query = session.createQuery( "SELECT b.normalBook FROM BookRefRef a " + - "JOIN BookRef b ON b.naturalBook.isbn = a.naturalBookRef.naturalBook.isbn" ); + "JOIN BookRef b ON b.naturalBook.isbn = a.naturalBookRef.naturalBook.isbn" ); query.getResultList(); sqlStatementInterceptor.assertExecutedCount( 1 ); assertEquals( 2, sqlStatementInterceptor.getNumberOfJoins( 0 ) ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/hql/Panel.java b/hibernate-core/src/test/java/org/hibernate/orm/test/hql/Panel.java index d7f41aa778..074ac6d66a 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/hql/Panel.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/hql/Panel.java @@ -14,12 +14,12 @@ import jakarta.persistence.Id; @Entity public class Panel implements Serializable { - @Id - private Long id; + @Id + private Long id; - private Long clientId; + private Long clientId; - private String deltaStamp; + private String deltaStamp; public Long getId() { return id; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/hql/Title.java b/hibernate-core/src/test/java/org/hibernate/orm/test/hql/Title.java index a18eadba64..54ee963794 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/hql/Title.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/hql/Title.java @@ -17,25 +17,25 @@ import jakarta.persistence.Table; @Table(name="title") public class Title implements Serializable { - @Id - @GeneratedValue - @Column(name="id_title") - private Integer id; + @Id + @GeneratedValue + @Column(name="id_title") + private Integer id; - private String description; + private String description; - public Integer getId() { - return id; - } - public void setId(Integer id) { - this.id = id; - } - public String getDescription() { - return description; - } - public void setDescription(String description) { - this.description = description; - } + public Integer getId() { + return id; + } + public void setId(Integer id) { + this.id = id; + } + public String getDescription() { + return description; + } + public void setDescription(String description) { + this.description = description; + } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/hql/TrtPanel.java b/hibernate-core/src/test/java/org/hibernate/orm/test/hql/TrtPanel.java index 2435423c85..4645721871 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/hql/TrtPanel.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/hql/TrtPanel.java @@ -16,15 +16,15 @@ import jakarta.persistence.ManyToOne; @Entity public class TrtPanel implements Serializable { - @Id - private Long id; + @Id + private Long id; - @ManyToOne(fetch = FetchType.LAZY) - private Panel panel; + @ManyToOne(fetch = FetchType.LAZY) + private Panel panel; - private Long clientId; + private Long clientId; - private String deltaStamp; + private String deltaStamp; public Long getId() { return id; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/id/Person.java b/hibernate-core/src/test/java/org/hibernate/orm/test/id/Person.java index a902d0d0b5..9fff9005b8 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/id/Person.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/id/Person.java @@ -9,17 +9,17 @@ package org.hibernate.orm.test.id; public class Person { - private long id; + private long id; - public Person() { - } + public Person() { + } - public long getId() { - return id; - } + public long getId() { + return id; + } - public void setId(final long id) { - this.id = id; - } + public void setId(final long id) { + this.id = id; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/id/SequenceStyleGeneratorBehavesLikeSequeceHiloGeneratorWitZeroIncrementSizeTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/id/SequenceStyleGeneratorBehavesLikeSequeceHiloGeneratorWitZeroIncrementSizeTest.java index 7d11d5ed3d..e7089a888e 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/id/SequenceStyleGeneratorBehavesLikeSequeceHiloGeneratorWitZeroIncrementSizeTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/id/SequenceStyleGeneratorBehavesLikeSequeceHiloGeneratorWitZeroIncrementSizeTest.java @@ -122,7 +122,7 @@ public class SequenceStyleGeneratorBehavesLikeSequeceHiloGeneratorWitZeroIncreme sessionFactory = (SessionFactoryImplementor) metadata.buildSessionFactory(); generator.initialize( sessionFactory.getSqlStringGenerationContext() ); - sequenceValueExtractor = new SequenceValueExtractor(sessionFactory.getJdbcServices().getDialect(), TEST_SEQUENCE ); + sequenceValueExtractor = new SequenceValueExtractor(sessionFactory.getJdbcServices().getDialect(), TEST_SEQUENCE ); } @AfterEach diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/id/enhanced/CustomNamingStrategyTests.java b/hibernate-core/src/test/java/org/hibernate/orm/test/id/enhanced/CustomNamingStrategyTests.java index bc2b807c22..b31cda2cbd 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/id/enhanced/CustomNamingStrategyTests.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/id/enhanced/CustomNamingStrategyTests.java @@ -105,10 +105,10 @@ public class CustomNamingStrategyTests { @Entity( name = "TheEntity" ) @Table( name = "ents" ) public static class TheEntity { - @Id + @Id @GeneratedValue( strategy = GenerationType.SEQUENCE ) - private Integer id; - @Basic + private Integer id; + @Basic private String name; private TheEntity() { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/id/sequence/PooledWithCustomNamingStrategyTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/id/sequence/PooledWithCustomNamingStrategyTest.java index be9618f83a..2b1af44e0b 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/id/sequence/PooledWithCustomNamingStrategyTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/id/sequence/PooledWithCustomNamingStrategyTest.java @@ -97,7 +97,7 @@ public class PooledWithCustomNamingStrategyTest { provider.configure( PropertiesHelper.map( Environment.getProperties() ) ); connectionProvider = provider; try (final Connection connection = connectionProvider.getConnection(); - final Statement statement = connection.createStatement()) { + final Statement statement = connection.createStatement()) { statement.execute( "create sequence MY_SEQ start with 1 increment by 5" ); statement.execute( "create table RightEntity(id bigint not null, primary key (id))" ); } @@ -109,7 +109,7 @@ public class PooledWithCustomNamingStrategyTest { @AfterAll public void tearDown() { try (final Connection connection = connectionProvider.getConnection(); - final Statement statement = connection.createStatement()) { + final Statement statement = connection.createStatement()) { statement.execute( "drop sequence MY_SEQ" ); statement.execute( "drop table RightEntity" ); } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/idclass/IdClassWithOneToOneTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/idclass/IdClassWithOneToOneTest.java index 11a67607d7..fbd941e150 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/idclass/IdClassWithOneToOneTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/idclass/IdClassWithOneToOneTest.java @@ -29,100 +29,100 @@ import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; @DomainModel( - annotatedClasses = { - IdClassWithOneToOneTest.Task.class, - IdClassWithOneToOneTest.TaskText.class - } + annotatedClasses = { + IdClassWithOneToOneTest.Task.class, + IdClassWithOneToOneTest.TaskText.class + } ) @SessionFactory(useCollectingStatementInspector = true) public class IdClassWithOneToOneTest { - @BeforeEach - void setup(SessionFactoryScope scope) { - scope.inTransaction( - session -> { - Task task = new Task(new TaskText("en", "Localized in en")); - session.persist( task ); - } - ); - } + @BeforeEach + void setup(SessionFactoryScope scope) { + scope.inTransaction( + session -> { + Task task = new Task(new TaskText("en", "Localized in en")); + session.persist( task ); + } + ); + } - @Test - public void testCreate(SessionFactoryScope scope) { - scope.inTransaction( - session -> { - Task task = session.get(Task.class, 1L); - assertThat( task.text.content, is( "Localized in en" ) ); - assertThat( task.text.locale, is( "en" ) ); - } - ); - } + @Test + public void testCreate(SessionFactoryScope scope) { + scope.inTransaction( + session -> { + Task task = session.get(Task.class, 1L); + assertThat( task.text.content, is( "Localized in en" ) ); + assertThat( task.text.locale, is( "en" ) ); + } + ); + } - @Entity - public static class Task { + @Entity + public static class Task { - @Id - @GeneratedValue - public Long id; + @Id + @GeneratedValue + public Long id; - @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "task") - public TaskText text; + @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "task") + public TaskText text; - public Task() {} + public Task() {} - public Task(TaskText text) { - this.text = text; - text.task = this; - } - } + public Task(TaskText text) { + this.text = text; + text.task = this; + } + } - @Entity - @IdClass(TaskText.TaskTextPK.class) - public static class TaskText { + @Entity + @IdClass(TaskText.TaskTextPK.class) + public static class TaskText { - public static class TaskTextPK implements Serializable { - public Long task; - public String locale; + public static class TaskTextPK implements Serializable { + public Long task; + public String locale; - public TaskTextPK() {} + public TaskTextPK() {} - public TaskTextPK(Long task, String locale) { - this.task = task; - this.locale = locale; - } + public TaskTextPK(Long task, String locale) { + this.task = task; + this.locale = locale; + } - @Override - public boolean equals(Object obj) { - if (!(obj instanceof TaskTextPK)) { - return false; - } else { - TaskTextPK pk = (TaskTextPK) obj; - return Objects.equals(task, pk.task) && locale.equals(pk.locale); - } - } + @Override + public boolean equals(Object obj) { + if (!(obj instanceof TaskTextPK)) { + return false; + } else { + TaskTextPK pk = (TaskTextPK) obj; + return Objects.equals(task, pk.task) && locale.equals(pk.locale); + } + } - @Override - public int hashCode() { - return task.hashCode() + locale.hashCode(); - } - } + @Override + public int hashCode() { + return task.hashCode() + locale.hashCode(); + } + } - public TaskText() {} + public TaskText() {} - public TaskText(String locale, String content) { - this.locale = locale; - this.content = content; - } + public TaskText(String locale, String content) { + this.locale = locale; + this.content = content; + } - @Id - @OneToOne(fetch = FetchType.EAGER) - @OnDelete(action = OnDeleteAction.CASCADE) - @JoinColumn(name = "id") - public Task task; + @Id + @OneToOne(fetch = FetchType.EAGER) + @OnDelete(action = OnDeleteAction.CASCADE) + @JoinColumn(name = "id") + public Task task; - @Id - public String locale; + @Id + public String locale; - public String content; - } + public String content; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/enhanced/forcedtable/BasicForcedTableSequenceTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/enhanced/forcedtable/BasicForcedTableSequenceTest.java index d94277cbb7..bb113fa457 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/enhanced/forcedtable/BasicForcedTableSequenceTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/enhanced/forcedtable/BasicForcedTableSequenceTest.java @@ -32,7 +32,7 @@ public class BasicForcedTableSequenceTest { @Test public void testNormalBoundary(SessionFactoryScope scope) { - final EntityPersister persister = scope.getSessionFactory() + final EntityPersister persister = scope.getSessionFactory() .getMappingMetamodel() .getEntityDescriptor(Entity.class.getName()); assertThat( persister.getGenerator(), instanceOf( SequenceStyleGenerator.class ) ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/enhanced/forcedtable/HiLoForcedTableSequenceTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/enhanced/forcedtable/HiLoForcedTableSequenceTest.java index 7cad63844d..35d9343ae3 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/enhanced/forcedtable/HiLoForcedTableSequenceTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/enhanced/forcedtable/HiLoForcedTableSequenceTest.java @@ -30,7 +30,7 @@ public class HiLoForcedTableSequenceTest { @Test public void testNormalBoundary(SessionFactoryScope scope) { - final EntityPersister persister = scope.getSessionFactory() + final EntityPersister persister = scope.getSessionFactory() .getMappingMetamodel() .getEntityDescriptor(Entity.class.getName()); assertThat( persister.getIdentifierGenerator(), instanceOf( SequenceStyleGenerator.class ) ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/enhanced/forcedtable/PooledForcedTableSequenceTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/enhanced/forcedtable/PooledForcedTableSequenceTest.java index e7e07684d2..14977f3c2d 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/enhanced/forcedtable/PooledForcedTableSequenceTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/enhanced/forcedtable/PooledForcedTableSequenceTest.java @@ -32,7 +32,7 @@ public class PooledForcedTableSequenceTest { @Test public void testNormalBoundary(SessionFactoryScope scope) { - EntityPersister persister = scope.getSessionFactory() + EntityPersister persister = scope.getSessionFactory() .getMappingMetamodel() .getEntityDescriptor(Entity.class.getName()); assertThat( persister.getIdentifierGenerator(), instanceOf( SequenceStyleGenerator.class ) ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/enhanced/sequence/BasicSequenceTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/enhanced/sequence/BasicSequenceTest.java index 10595c4828..a0b7278f81 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/enhanced/sequence/BasicSequenceTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/enhanced/sequence/BasicSequenceTest.java @@ -37,7 +37,7 @@ public class BasicSequenceTest { @Test public void testNormalBoundary(SessionFactoryScope scope) { - final EntityPersister persister = scope.getSessionFactory() + final EntityPersister persister = scope.getSessionFactory() .getMappingMetamodel() .getEntityDescriptor(Entity.class.getName()); assertThat( persister.getGenerator(), instanceOf( SequenceStyleGenerator.class ) ); @@ -68,7 +68,7 @@ public class BasicSequenceTest { public void testSequencePerEntity(SessionFactoryScope scope) { final String overriddenEntityName = "SpecialEntity"; - final EntityPersister persister = scope.getSessionFactory() + final EntityPersister persister = scope.getSessionFactory() .getMappingMetamodel() .getEntityDescriptor(overriddenEntityName); assertThat( persister.getGenerator(), instanceOf( SequenceStyleGenerator.class ) ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/enhanced/sequence/HiLoSequenceMismatchStrategyTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/enhanced/sequence/HiLoSequenceMismatchStrategyTest.java index 8fc8a99973..b9210d005a 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/enhanced/sequence/HiLoSequenceMismatchStrategyTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/enhanced/sequence/HiLoSequenceMismatchStrategyTest.java @@ -111,7 +111,7 @@ public class HiLoSequenceMismatchStrategyTest { @Test public void testSequenceMismatchStrategyNotApplied(SessionFactoryScope scope) { - final EntityPersister persister = scope.getSessionFactory() + final EntityPersister persister = scope.getSessionFactory() .getMappingMetamodel() .getEntityDescriptor(TestEntity.class.getName()); assertThat( persister.getIdentifierGenerator(), instanceOf( SequenceStyleGenerator.class ) ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/enhanced/sequence/HiLoSequenceTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/enhanced/sequence/HiLoSequenceTest.java index 51cb97f4e1..d0614bd843 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/enhanced/sequence/HiLoSequenceTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/enhanced/sequence/HiLoSequenceTest.java @@ -31,7 +31,7 @@ public class HiLoSequenceTest { @Test public void testNormalBoundary(SessionFactoryScope scope) { - final EntityPersister persister = scope.getSessionFactory() + final EntityPersister persister = scope.getSessionFactory() .getMappingMetamodel() .getEntityDescriptor(Entity.class.getName()); assertThat( persister.getIdentifierGenerator(), instanceOf( SequenceStyleGenerator.class ) ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/enhanced/sequence/PooledSequenceTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/enhanced/sequence/PooledSequenceTest.java index 854b66c7b5..70f81e0210 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/enhanced/sequence/PooledSequenceTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/enhanced/sequence/PooledSequenceTest.java @@ -32,7 +32,7 @@ public class PooledSequenceTest { @Test public void testNormalBoundary(SessionFactoryScope scope) { - final EntityPersister persister = scope.getSessionFactory() + final EntityPersister persister = scope.getSessionFactory() .getMappingMetamodel() .getEntityDescriptor(Entity.class.getName()); assertThat( persister.getIdentifierGenerator(), instanceOf( SequenceStyleGenerator.class ) ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/enhanced/table/BasicTableTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/enhanced/table/BasicTableTest.java index 39800910b9..cfa1b158a9 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/enhanced/table/BasicTableTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/enhanced/table/BasicTableTest.java @@ -26,7 +26,7 @@ public class BasicTableTest { @Test public void testNormalBoundary(SessionFactoryScope scope) { - final EntityPersister persister = scope.getSessionFactory() + final EntityPersister persister = scope.getSessionFactory() .getMappingMetamodel() .getEntityDescriptor(Entity.class.getName()); assertThat( persister.getGenerator(), instanceOf( TableGenerator.class ) ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/enhanced/table/HiLoTableTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/enhanced/table/HiLoTableTest.java index 5b73a86c8d..b71ea434d5 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/enhanced/table/HiLoTableTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/enhanced/table/HiLoTableTest.java @@ -26,7 +26,7 @@ import static org.junit.Assert.assertThat; public class HiLoTableTest { @Test public void testNormalBoundary(SessionFactoryScope scope) { - final EntityPersister persister = scope.getSessionFactory() + final EntityPersister persister = scope.getSessionFactory() .getMappingMetamodel() .getEntityDescriptor(Entity.class.getName()); assertThat( persister.getIdentifierGenerator(), instanceOf( TableGenerator.class ) ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/enhanced/table/PooledTableTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/enhanced/table/PooledTableTest.java index de4adebd2e..bcb163be75 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/enhanced/table/PooledTableTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/enhanced/table/PooledTableTest.java @@ -29,7 +29,7 @@ public class PooledTableTest { @Test public void testNormalBoundary(SessionFactoryScope scope) { - final EntityPersister persister = scope.getSessionFactory() + final EntityPersister persister = scope.getSessionFactory() .getMappingMetamodel() .getEntityDescriptor(Entity.class.getName()); assertThat( persister.getIdentifierGenerator(), instanceOf( TableGenerator.class ) ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/userdefined/NativeGenerator.java b/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/userdefined/NativeGenerator.java index 18de913a91..79981e544a 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/userdefined/NativeGenerator.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/userdefined/NativeGenerator.java @@ -27,78 +27,78 @@ import java.util.EnumSet; import java.util.Properties; public class NativeGenerator - implements OnExecutionGenerator, BeforeExecutionGenerator, Configurable, ExportableProducer { + implements OnExecutionGenerator, BeforeExecutionGenerator, Configurable, ExportableProducer { - private final Generator generator; + private final Generator generator; - public NativeGenerator(NativeId nativeId, Member member, GeneratorCreationContext creationContext) { + public NativeGenerator(NativeId nativeId, Member member, GeneratorCreationContext creationContext) { final String strategy = creationContext.getDatabase().getDialect().getNativeIdentifierGeneratorStrategy(); - switch (strategy) { - case "sequence": - generator = new SequenceStyleGenerator(); - break; - case "identity": - creationContext.getProperty().getValue().getColumns().get(0).setIdentity(true); - generator = new IdentityGenerator(); - break; - default: - throw new IllegalArgumentException(); - } - } + switch (strategy) { + case "sequence": + generator = new SequenceStyleGenerator(); + break; + case "identity": + creationContext.getProperty().getValue().getColumns().get(0).setIdentity(true); + generator = new IdentityGenerator(); + break; + default: + throw new IllegalArgumentException(); + } + } - @Override - public EnumSet getEventTypes() { - return generator.getEventTypes(); - } + @Override + public EnumSet getEventTypes() { + return generator.getEventTypes(); + } - @Override - public boolean generatedOnExecution() { - return generator.generatedOnExecution(); - } + @Override + public boolean generatedOnExecution() { + return generator.generatedOnExecution(); + } - @Override - public void configure(GeneratorCreationContext creationContext, Properties parameters) { - if ( generator instanceof Configurable ) { - ((Configurable) generator).configure( creationContext, parameters ); - } - } + @Override + public void configure(GeneratorCreationContext creationContext, Properties parameters) { + if ( generator instanceof Configurable ) { + ((Configurable) generator).configure( creationContext, parameters ); + } + } - @Override - public void registerExportables(Database database) { - if ( generator instanceof ExportableProducer ) { - ((ExportableProducer) generator).registerExportables(database); - } - } + @Override + public void registerExportables(Database database) { + if ( generator instanceof ExportableProducer ) { + ((ExportableProducer) generator).registerExportables(database); + } + } - @Override - public void initialize(SqlStringGenerationContext context) { - if ( generator instanceof Configurable ) { - ((Configurable) generator).initialize(context); - } - } + @Override + public void initialize(SqlStringGenerationContext context) { + if ( generator instanceof Configurable ) { + ((Configurable) generator).initialize(context); + } + } - @Override - public Object generate(SharedSessionContractImplementor session, Object owner, Object currentValue, EventType eventType) { - return ((BeforeExecutionGenerator) generator).generate(session, owner, currentValue, eventType); - } + @Override + public Object generate(SharedSessionContractImplementor session, Object owner, Object currentValue, EventType eventType) { + return ((BeforeExecutionGenerator) generator).generate(session, owner, currentValue, eventType); + } - @Override - public boolean referenceColumnsInSql(Dialect dialect) { - return ((OnExecutionGenerator) generator).referenceColumnsInSql(dialect); - } + @Override + public boolean referenceColumnsInSql(Dialect dialect) { + return ((OnExecutionGenerator) generator).referenceColumnsInSql(dialect); + } - @Override - public boolean writePropertyValue() { - return ((OnExecutionGenerator) generator).writePropertyValue(); - } + @Override + public boolean writePropertyValue() { + return ((OnExecutionGenerator) generator).writePropertyValue(); + } - @Override - public String[] getReferencedColumnValues(Dialect dialect) { - return ((OnExecutionGenerator) generator).getReferencedColumnValues(dialect); - } + @Override + public String[] getReferencedColumnValues(Dialect dialect) { + return ((OnExecutionGenerator) generator).getReferencedColumnValues(dialect); + } - @Override - public InsertGeneratedIdentifierDelegate getGeneratedIdentifierDelegate(EntityPersister persister) { - return ((OnExecutionGenerator) generator).getGeneratedIdentifierDelegate(persister); - } + @Override + public InsertGeneratedIdentifierDelegate getGeneratedIdentifierDelegate(EntityPersister persister) { + return ((OnExecutionGenerator) generator).getGeneratedIdentifierDelegate(persister); + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/userdefined/SimpleGenerator.java b/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/userdefined/SimpleGenerator.java index a4ee53ad85..392d903314 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/userdefined/SimpleGenerator.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/idgen/userdefined/SimpleGenerator.java @@ -18,23 +18,23 @@ import org.hibernate.generator.EventType; */ public class SimpleGenerator implements BeforeExecutionGenerator { - private final AtomicLong sequence; + private final AtomicLong sequence; - public SimpleGenerator(AtomicLong sequence) { - this.sequence = sequence; - } + public SimpleGenerator(AtomicLong sequence) { + this.sequence = sequence; + } - @Override - public Object generate( - SharedSessionContractImplementor session, - Object owner, - Object currentValue, - EventType eventType) { - return sequence.getAndIncrement(); - } + @Override + public Object generate( + SharedSessionContractImplementor session, + Object owner, + Object currentValue, + EventType eventType) { + return sequence.getAndIncrement(); + } - @Override - public EnumSet getEventTypes() { - return EnumSet.of( EventType.INSERT ); - } + @Override + public EnumSet getEventTypes() { + return EnumSet.of( EventType.INSERT ); + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/immutable/entitywithmutablecollection/AbstractEntityWithManyToManyTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/immutable/entitywithmutablecollection/AbstractEntityWithManyToManyTest.java index f704bc5c9d..e2f6635e8b 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/immutable/entitywithmutablecollection/AbstractEntityWithManyToManyTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/immutable/entitywithmutablecollection/AbstractEntityWithManyToManyTest.java @@ -63,8 +63,8 @@ public abstract class AbstractEntityWithManyToManyTest { catch (IllegalArgumentException ex) { isPlanContractsBidirectional = false; } - isPlanVersioned = sessionFactory.getMappingMetamodel().getEntityDescriptor(Plan.class.getName()).isVersioned(); - isContractVersioned = sessionFactory.getMappingMetamodel().getEntityDescriptor(Contract.class.getName()).isVersioned(); + isPlanVersioned = sessionFactory.getMappingMetamodel().getEntityDescriptor(Plan.class.getName()).isVersioned(); + isContractVersioned = sessionFactory.getMappingMetamodel().getEntityDescriptor(Contract.class.getName()).isVersioned(); sessionFactory.getStatistics().clear(); } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/inheritance/DenormalizedTableForeignKeyGeneratorTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/inheritance/DenormalizedTableForeignKeyGeneratorTest.java index 082d471e02..7d3a45faf4 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/inheritance/DenormalizedTableForeignKeyGeneratorTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/inheritance/DenormalizedTableForeignKeyGeneratorTest.java @@ -24,78 +24,78 @@ import static org.assertj.core.api.Assertions.assertThat; */ @JiraKey("HHH-18470") @Jpa( - annotatedClasses = { - DenormalizedTableForeignKeyGeneratorTest.Employee.class, - DenormalizedTableForeignKeyGeneratorTest.Manager.class, - DenormalizedTableForeignKeyGeneratorTest.Address.class, - DenormalizedTableForeignKeyGeneratorTest.Territory.class - } + annotatedClasses = { + DenormalizedTableForeignKeyGeneratorTest.Employee.class, + DenormalizedTableForeignKeyGeneratorTest.Manager.class, + DenormalizedTableForeignKeyGeneratorTest.Address.class, + DenormalizedTableForeignKeyGeneratorTest.Territory.class + } ) @RequiresDialect(H2Dialect.class) public class DenormalizedTableForeignKeyGeneratorTest { - @Test - public void shouldCreateForeignKeyForSubclasses(EntityManagerFactoryScope scope) { - scope.inTransaction( - entityManager -> { - String managerQuery = "select CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS " + - "WHERE TABLE_NAME='MANAGER' " + - "AND CONSTRAINT_TYPE='FOREIGN KEY'"; - List managerForeignKeyNames = entityManager.createNativeQuery(managerQuery).getResultList(); + @Test + public void shouldCreateForeignKeyForSubclasses(EntityManagerFactoryScope scope) { + scope.inTransaction( + entityManager -> { + String managerQuery = "select CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS " + + "WHERE TABLE_NAME='MANAGER' " + + "AND CONSTRAINT_TYPE='FOREIGN KEY'"; + List managerForeignKeyNames = entityManager.createNativeQuery(managerQuery).getResultList(); - String employeeQuery = "select CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS " + - "WHERE TABLE_NAME='EMPLOYEE' " + - "AND CONSTRAINT_TYPE='FOREIGN KEY'"; - String employeeForeignKeyName = entityManager.createNativeQuery(employeeQuery).getSingleResult().toString(); + String employeeQuery = "select CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS " + + "WHERE TABLE_NAME='EMPLOYEE' " + + "AND CONSTRAINT_TYPE='FOREIGN KEY'"; + String employeeForeignKeyName = entityManager.createNativeQuery(employeeQuery).getSingleResult().toString(); - assertThat(employeeForeignKeyName).isNotNull(); - assertThat(managerForeignKeyNames).isNotNull().hasSize(2); - assertThat(managerForeignKeyNames).doesNotContain(employeeForeignKeyName); - } - ); - } + assertThat(employeeForeignKeyName).isNotNull(); + assertThat(managerForeignKeyNames).isNotNull().hasSize(2); + assertThat(managerForeignKeyNames).doesNotContain(employeeForeignKeyName); + } + ); + } - @Entity(name = "Employee") - @Inheritance(strategy = InheritanceType.TABLE_PER_CLASS) - static class Employee implements Serializable { + @Entity(name = "Employee") + @Inheritance(strategy = InheritanceType.TABLE_PER_CLASS) + static class Employee implements Serializable { - @Id - @GeneratedValue - Long id; + @Id + @GeneratedValue + Long id; - @OneToOne(cascade = CascadeType.ALL, orphanRemoval = true) - private Address address; + @OneToOne(cascade = CascadeType.ALL, orphanRemoval = true) + private Address address; - } + } - @Entity(name = "Manager") - static class Manager extends Employee { + @Entity(name = "Manager") + static class Manager extends Employee { - @OneToOne(fetch = FetchType.EAGER, orphanRemoval = true, cascade = CascadeType.ALL) - private Territory territory; - } + @OneToOne(fetch = FetchType.EAGER, orphanRemoval = true, cascade = CascadeType.ALL) + private Territory territory; + } - @Entity(name = "Address") - static class Address { + @Entity(name = "Address") + static class Address { - @Id - @GeneratedValue - Long id; + @Id + @GeneratedValue + Long id; - @Column(nullable = false, columnDefinition = "TEXT") - private String address = ""; - } + @Column(nullable = false, columnDefinition = "TEXT") + private String address = ""; + } - @Entity(name = "Territory") - static class Territory { + @Entity(name = "Territory") + static class Territory { - @Id - @GeneratedValue - Long id; + @Id + @GeneratedValue + Long id; - @Column - private String location = ""; - } + @Column + private String location = ""; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/inheritance/JoinFetchInheritanceTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/inheritance/JoinFetchInheritanceTest.java index ffa31dc53a..23a269db5d 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/inheritance/JoinFetchInheritanceTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/inheritance/JoinFetchInheritanceTest.java @@ -189,7 +189,7 @@ public class JoinFetchInheritanceTest { if ( collection ) { final List kittens = kittenContainer.getKittens(); if ( simpleInitialized && animal.getType().equals( CAT ) || - !simpleInitialized && animal.getType().equals( CAT_EMBEDDED ) ) { + !simpleInitialized && animal.getType().equals( CAT_EMBEDDED ) ) { assertThat( Hibernate.isInitialized( kittens ) ).isTrue(); assertThat( kittens ).hasSizeBetween( 0, 1 ); } @@ -200,7 +200,7 @@ public class JoinFetchInheritanceTest { else { final Kitten kitten = kittenContainer.getSingleKitten(); if ( simpleInitialized && animal.getType().equals( CAT ) || - !simpleInitialized && animal.getType().equals( CAT_EMBEDDED ) ) { + !simpleInitialized && animal.getType().equals( CAT_EMBEDDED ) ) { assertThat( Hibernate.isInitialized( kitten ) ).isTrue(); assertThat( kitten.getName() ).isEqualTo( simpleInitialized ? "kitten_1" : "kitten_2" ); } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/insertordering/InsertOrderingCircularDependencyFalsePositiveTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/insertordering/InsertOrderingCircularDependencyFalsePositiveTest.java index eae1d0ae51..4189c6df4c 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/insertordering/InsertOrderingCircularDependencyFalsePositiveTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/insertordering/InsertOrderingCircularDependencyFalsePositiveTest.java @@ -34,145 +34,145 @@ import static org.hibernate.testing.transaction.TransactionUtil.doInHibernate; @RequiresDialectFeature(DialectChecks.SupportsJdbcDriverProxying.class) public class InsertOrderingCircularDependencyFalsePositiveTest extends BaseNonConfigCoreFunctionalTestCase { - private PreparedStatementSpyConnectionProvider connectionProvider = new PreparedStatementSpyConnectionProvider(); + private PreparedStatementSpyConnectionProvider connectionProvider = new PreparedStatementSpyConnectionProvider(); - @Override - protected Class[] getAnnotatedClasses() { - return new Class[]{ - Wrapper.class, - Condition.class, - SimpleCondition.class, - Expression.class, - ConstantExpression.class, - Condition.class, - CompoundCondition.class, - }; - } + @Override + protected Class[] getAnnotatedClasses() { + return new Class[]{ + Wrapper.class, + Condition.class, + SimpleCondition.class, + Expression.class, + ConstantExpression.class, + Condition.class, + CompoundCondition.class, + }; + } - @Override - protected void addSettings(Map settings) { - settings.put(Environment.ORDER_INSERTS, "true"); - settings.put(Environment.ORDER_UPDATES, "true"); - settings.put(Environment.STATEMENT_BATCH_SIZE, "50"); - settings.put( - org.hibernate.cfg.AvailableSettings.CONNECTION_PROVIDER, - connectionProvider - ); - } + @Override + protected void addSettings(Map settings) { + settings.put(Environment.ORDER_INSERTS, "true"); + settings.put(Environment.ORDER_UPDATES, "true"); + settings.put(Environment.STATEMENT_BATCH_SIZE, "50"); + settings.put( + org.hibernate.cfg.AvailableSettings.CONNECTION_PROVIDER, + connectionProvider + ); + } - @Override - public void releaseResources() { - super.releaseResources(); - connectionProvider.stop(); - } + @Override + public void releaseResources() { + super.releaseResources(); + connectionProvider.stop(); + } - @Override - protected boolean rebuildSessionFactoryOnError() { - return false; - } + @Override + protected boolean rebuildSessionFactoryOnError() { + return false; + } - @Test - public void testBatching() throws SQLException { - doInHibernate(this::sessionFactory, session -> { - connectionProvider.clear(); - // This should be persistable but currently reports that it might be circular - session.persist(Wrapper.create()); - }); - } + @Test + public void testBatching() throws SQLException { + doInHibernate(this::sessionFactory, session -> { + connectionProvider.clear(); + // This should be persistable but currently reports that it might be circular + session.persist(Wrapper.create()); + }); + } - @Entity(name = "Wrapper") - public static class Wrapper { - @Id - private String id; - @OneToOne(cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.EAGER) - private Condition condition; - @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER) - private Set constantExpressions; + @Entity(name = "Wrapper") + public static class Wrapper { + @Id + private String id; + @OneToOne(cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.EAGER) + private Condition condition; + @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER) + private Set constantExpressions; - public Wrapper() { - } + public Wrapper() { + } - public static Wrapper create() { - final Wrapper w = new Wrapper(); - final CompoundCondition cc = new CompoundCondition(); - final SimpleCondition c1 = new SimpleCondition(); - final SimpleCondition c2 = new SimpleCondition(); - final ConstantExpression e1 = new ConstantExpression(); - final ConstantExpression e2 = new ConstantExpression(); - final ConstantExpression e3 = new ConstantExpression(); - final ConstantExpression e4 = new ConstantExpression(); - final ConstantExpression e5 = new ConstantExpression(); - w.id = "w"; - w.condition = cc; - cc.id = "cc"; - cc.first = c1; - cc.second = c2; - c1.id = "c1"; - c1.left = e1; - c1.right = e2; - c2.id = "c2"; - c2.left = e3; - c2.right = e4; - e1.id = "e1"; - e1.value = "e1"; - e2.id = "e2"; - e2.value = "e2"; - e3.id = "e3"; - e3.value = "e3"; - e4.id = "e4"; - e4.value = "e4"; - e5.id = "e5"; - e5.value = "e5"; - w.constantExpressions = new HashSet<>(); - w.constantExpressions.add(e5); - return w; - } - } + public static Wrapper create() { + final Wrapper w = new Wrapper(); + final CompoundCondition cc = new CompoundCondition(); + final SimpleCondition c1 = new SimpleCondition(); + final SimpleCondition c2 = new SimpleCondition(); + final ConstantExpression e1 = new ConstantExpression(); + final ConstantExpression e2 = new ConstantExpression(); + final ConstantExpression e3 = new ConstantExpression(); + final ConstantExpression e4 = new ConstantExpression(); + final ConstantExpression e5 = new ConstantExpression(); + w.id = "w"; + w.condition = cc; + cc.id = "cc"; + cc.first = c1; + cc.second = c2; + c1.id = "c1"; + c1.left = e1; + c1.right = e2; + c2.id = "c2"; + c2.left = e3; + c2.right = e4; + e1.id = "e1"; + e1.value = "e1"; + e2.id = "e2"; + e2.value = "e2"; + e3.id = "e3"; + e3.value = "e3"; + e4.id = "e4"; + e4.value = "e4"; + e5.id = "e5"; + e5.value = "e5"; + w.constantExpressions = new HashSet<>(); + w.constantExpressions.add(e5); + return w; + } + } - @Entity(name = "Condition") + @Entity(name = "Condition") @Table(name = "cond") - public static abstract class Condition { - @Id - protected String id; + public static abstract class Condition { + @Id + protected String id; - public Condition() { - } - } - @Entity(name = "SimpleCondition") - public static class SimpleCondition extends Condition { - @OneToOne(cascade = CascadeType.ALL) - private Expression left; - @OneToOne(cascade = CascadeType.ALL) - private Expression right; + public Condition() { + } + } + @Entity(name = "SimpleCondition") + public static class SimpleCondition extends Condition { + @OneToOne(cascade = CascadeType.ALL) + private Expression left; + @OneToOne(cascade = CascadeType.ALL) + private Expression right; - public SimpleCondition() { - } - } - @Entity(name = "Expression") - public static abstract class Expression { - @Id - protected String id; + public SimpleCondition() { + } + } + @Entity(name = "Expression") + public static abstract class Expression { + @Id + protected String id; - protected Expression() { - } + protected Expression() { + } - } - @Entity(name = "ConstantExpression") - public static class ConstantExpression extends Expression { - @Column(name = "val") - private String value; + } + @Entity(name = "ConstantExpression") + public static class ConstantExpression extends Expression { + @Column(name = "val") + private String value; - public ConstantExpression() { - } - } - @Entity(name = "CompoundCondition") - public static class CompoundCondition extends Condition { - @OneToOne(cascade = CascadeType.ALL) - protected Condition first; - @OneToOne(cascade = CascadeType.ALL) - protected Condition second; + public ConstantExpression() { + } + } + @Entity(name = "CompoundCondition") + public static class CompoundCondition extends Condition { + @OneToOne(cascade = CascadeType.ALL) + protected Condition first; + @OneToOne(cascade = CascadeType.ALL) + protected Condition second; - public CompoundCondition() { - } - } + public CompoundCondition() { + } + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/insertordering/InsertOrderingRCATest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/insertordering/InsertOrderingRCATest.java index c0311dc8ba..621bef7ac6 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/insertordering/InsertOrderingRCATest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/insertordering/InsertOrderingRCATest.java @@ -41,2093 +41,2093 @@ import static org.hibernate.testing.transaction.TransactionUtil.doInHibernate; @RequiresDialectFeature(feature = DialectFeatureChecks.SupportsJdbcDriverProxying.class) public class InsertOrderingRCATest extends BaseNonConfigCoreFunctionalTestCase { - private PreparedStatementSpyConnectionProvider connectionProvider = new PreparedStatementSpyConnectionProvider(); - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[]{ - WeightedCause.class, - TimeManipulation.class, - Symptom.class, - SimpleCondition.class, - RCATemplate.class, - ParameterExpression.class, - NumberedExpression.class, - MathExpression.class, - FieldExpression.class, - Expression.class, - ConstantExpression.class, - ConditionAndExpression.class, - ConditionalExpression.class, - Condition.class, - CompoundCondition.class, - Cause.class, - CalculationExpression.class, - AlertCondition.class, - BaseEntity.class - }; - } - - @Override - protected void addSettings(Map settings) { - settings.put(Environment.ORDER_INSERTS, "true"); - settings.put(Environment.ORDER_UPDATES, "true"); - settings.put(Environment.STATEMENT_BATCH_SIZE, "50"); - settings.put( - org.hibernate.cfg.AvailableSettings.CONNECTION_PROVIDER, - connectionProvider - ); - } - - @Override - public void releaseResources() { - super.releaseResources(); - connectionProvider.stop(); - } - - @Override - protected boolean rebuildSessionFactoryOnError() { - return false; - } - - @Test - public void testBatching() throws SQLException { - doInHibernate(this::sessionFactory, session -> { - connectionProvider.clear(); - for (RCATemplate template : DefaultTemplatesVault.getDefaultRCATemplates()) { - session.persist(template); - } - }); - } - - @Entity(name = "WeightedCause") - @Table(name = "rca_weighted_cause") - public static class WeightedCause extends BaseEntity { - private Cause cause; - private Integer weight; - - public WeightedCause() { - } - - public WeightedCause(Cause cause, Integer weight) { - this.cause = cause; - this.weight = weight; - } - - @OneToOne(cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.EAGER) - @JoinColumn(name = "cause_id") - public Cause getCause() { - return cause; - } - - public void setCause(Cause cause) { - this.cause = cause; - } - - public Integer getWeight() { - return weight; - } - - public void setWeight(Integer weight) { - this.weight = weight; - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - if (!super.equals(o)) { - return false; - } - - WeightedCause cause1 = (WeightedCause) o; - - if (cause != null ? !cause.equals(cause1.cause) : cause1.cause != null) { - return false; - } - if (weight != null ? !weight.equals(cause1.weight) : cause1.weight != null) { - return false; - } - - return true; - } - - @Override - public int hashCode() { - int result = super.hashCode(); - result = 31 * result + (cause != null ? cause.hashCode() : 0); - result = 31 * result + (weight != null ? weight.hashCode() : 0); - return result; - } - } - @Entity(name = "TimeManipulation") - @Table(name = "rca_time_manipulation") - public static class TimeManipulation extends BaseEntity implements Serializable { - private ManipulationType type; - private MathOperator op; - private Long time; - private RelativeToType relativeToType; - private String paramName; - - public TimeManipulation() { - } - - public TimeManipulation(ManipulationType type, MathOperator op, Long time, RelativeToType relativeToType, String paramName) { - this.type = type; - this.op = op; - this.time = time; - this.relativeToType = relativeToType; - this.paramName = paramName; - } - - public ManipulationType getType() { - return type; - } - - public void setType(ManipulationType type) { - this.type = type; - } - - public MathOperator getOp() { - return op; - } - - public void setOp(MathOperator op) { - this.op = op; - } - - public Long getTime() { - return time; - } - - public void setTime(Long time) { - this.time = time; - } - - public RelativeToType getRelativeToType() { - return relativeToType; - } - - public void setRelativeToType(RelativeToType relativeToType) { - this.relativeToType = relativeToType; - } - - public String getParamName() { - return paramName; - } - - public void setParamName(String paramName) { - this.paramName = paramName; - } - } - @Entity(name = "Symptom") - @Table(name = "rca_symptom") - public static class Symptom extends BaseEntity implements Serializable { - private String name; - private String objectType; - private Condition condition; - private String nodeTypeString; - private String processTypeString; - private String filterString; - - public Symptom() { - } - - public Symptom(String name, String objectType, Condition condition) { - this.name = name; - this.objectType = objectType; - this.condition = condition; - } - - public String getObjectType() { - return objectType; - } - - public void setObjectType(String objectType) { - this.objectType = objectType; - } - - @OneToOne(cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.EAGER) - @JoinColumn(name = "condition_id") - public Condition getCondition() { - return condition; - } - - public void setCondition(Condition condition) { - this.condition = condition; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getNodeTypeString() { - return nodeTypeString; - } - - public void setNodeTypeString(String nodeTypeString) { - this.nodeTypeString = nodeTypeString; - } - - public String getProcessTypeString() { - return processTypeString; - } - - public void setProcessTypeString(String processTypeString) { - this.processTypeString = processTypeString; - } - - public String getFilterString() { - return filterString; - } - - public void setFilterString(String filterString) { - this.filterString = filterString; - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - if (!super.equals(o)) { - return false; - } - - Symptom symptom = (Symptom) o; - - if (condition != null ? !condition.equals(symptom.condition) : symptom.condition != null) { - return false; - } - if (name != null ? !name.equals(symptom.name) : symptom.name != null) { - return false; - } - if (objectType != null ? !objectType.equals(symptom.objectType) : symptom.objectType != null) { - return false; - } - - return true; - } - - @Override - public int hashCode() { - int result = super.hashCode(); - result = 31 * result + (name != null ? name.hashCode() : 0); - result = 31 * result + (objectType != null ? objectType.hashCode() : 0); - result = 31 * result + (condition != null ? condition.hashCode() : 0); - return result; - } - } - @Entity(name = "SimpleCondition") - public static class SimpleCondition extends Condition { - private Expression left; - private Operator op; - private Expression right; - - public SimpleCondition() { - } - - public SimpleCondition(Expression left, Operator op, Expression right) { - this.left = left; - this.op = op; - this.right = right; - } - - @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER) - @JoinColumn(name = "left_expression_id") - public Expression getLeft() { - return left; - } - - public void setLeft(Expression left) { - this.left = left; - } - - public Operator getOp() { - return op; - } - - public void setOp(Operator op) { - this.op = op; - } - - @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER) - @JoinColumn(name = "right_expression_id") - public Expression getRight() { - return right; - } - - public void setRight(Expression right) { - this.right = right; - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - if (!super.equals(o)) { - return false; - } - - SimpleCondition that = (SimpleCondition) o; - - if (left != null ? !left.equals(that.left) : that.left != null) { - return false; - } - if (op != that.op) { - return false; - } - if (right != null ? !right.equals(that.right) : that.right != null) { - return false; - } - - return true; - } - - @Override - public int hashCode() { - int result = super.hashCode(); - result = 31 * result + (left != null ? left.hashCode() : 0); - result = 31 * result + (op != null ? op.hashCode() : 0); - result = 31 * result + (right != null ? right.hashCode() : 0); - return result; - } - } - @Entity(name = "RCATemplate") - public static class RCATemplate extends BaseEntity { - private String name; - private Symptom symptom; - private Set possibleCauses; - - public RCATemplate() { - } - - public RCATemplate(String name, Symptom symptom, Set possibleCauses) { - this.name = name; - this.symptom = symptom; - this.possibleCauses = possibleCauses; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - @OneToOne(cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.EAGER) - @JoinColumn(name = "symptom_id") - public Symptom getSymptom() { - return symptom; - - } - - public void setSymptom(Symptom symptom) { - this.symptom = symptom; - } - - @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER) - @JoinTable(name = "template_cause", joinColumns = { - @JoinColumn(name = "f_template_id")}, inverseJoinColumns = { - @JoinColumn(name = "f_cause_id")}) - public Set getPossibleCauses() { - return possibleCauses; - } - - public void setPossibleCauses(Set possibleCauses) { - this.possibleCauses = possibleCauses; - } - - } - @Entity(name = "ParameterExpression") - public static class ParameterExpression extends Expression { - private String parameterName; - private String defaultValue; - - - public ParameterExpression() { - } - - public ParameterExpression(String parameterName, String defaultValue, MetadataFieldType type) { - this.parameterName = parameterName; - this.defaultValue = defaultValue; - this.type = type; - } - - public String getParameterName() { - return parameterName; - } - - public void setParameterName(String parameterName) { - this.parameterName = parameterName; - } - - public String getDefaultValue() { - return defaultValue; - } - - public void setDefaultValue(String defaultValue) { - this.defaultValue = defaultValue; - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - if (!super.equals(o)) { - return false; - } - - ParameterExpression that = (ParameterExpression) o; - - if (defaultValue != null ? !defaultValue.equals(that.defaultValue) : that.defaultValue != null) { - return false; - } - if (parameterName != null ? !parameterName.equals(that.parameterName) : that.parameterName != null) { - return false; - } - - return true; - } - - @Override - public int hashCode() { - int result = super.hashCode(); - result = 31 * result + (parameterName != null ? parameterName.hashCode() : 0); - result = 31 * result + (defaultValue != null ? defaultValue.hashCode() : 0); - return result; - } - } - @Entity(name = "NumberedExpression") - @Table(name = "rca_numbered_exception") - public static class NumberedExpression extends BaseEntity implements Comparable { - private Long num; - private Expression expression; - - public NumberedExpression() { - } - - public NumberedExpression(Long num, Expression expression) { - this.num = num; - this.expression = expression; - } - - public Long getNum() { - return num; - } - - public void setNum(Long num) { - this.num = num; - } - - @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER) - @JoinColumn(name = "num_expression_id") - public Expression getExpression() { - return expression; - } - - public void setExpression(Expression expression) { - this.expression = expression; - } - - @Override - public int compareTo(Object o) { - NumberedExpression other = (NumberedExpression) o; - return (int) (this.num - other.num); - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - if (!super.equals(o)) { - return false; - } - - NumberedExpression that = (NumberedExpression) o; - - if (expression != null ? !expression.equals(that.expression) : that.expression != null) { - return false; - } - if (num != null ? !num.equals(that.num) : that.num != null) { - return false; - } - - return true; - } - - @Override - public int hashCode() { - int result = super.hashCode(); - result = 31 * result + (num != null ? num.hashCode() : 0); - result = 31 * result + (expression != null ? expression.hashCode() : 0); - return result; - } - } - @Entity(name = "MathExpression") - public static class MathExpression extends Expression { - private Expression left; - private Expression right; - private MathOperator op; - - public MathExpression() { - } - - public MathExpression(Expression left, Expression right, MathOperator op) { - this.left = left; - this.right = right; - this.op = op; - } - - @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER) - @JoinColumn(name = "left_expression_id") - public Expression getLeft() { - return left; - } - - public void setLeft(Expression left) { - this.left = left; - } - - @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER) - @JoinColumn(name = "right_expression_id") - public Expression getRight() { - return right; - } - - public void setRight(Expression right) { - this.right = right; - } - - public MathOperator getOp() { - return op; - } - - public void setOp(MathOperator op) { - this.op = op; - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - if (!super.equals(o)) { - return false; - } - - MathExpression that = (MathExpression) o; - - if (left != null ? !left.equals(that.left) : that.left != null) { - return false; - } - if (op != that.op) { - return false; - } - if (right != null ? !right.equals(that.right) : that.right != null) { - return false; - } - - return true; - } - - @Override - public int hashCode() { - int result = super.hashCode(); - result = 31 * result + (left != null ? left.hashCode() : 0); - result = 31 * result + (right != null ? right.hashCode() : 0); - result = 31 * result + (op != null ? op.hashCode() : 0); - return result; - } - } - @Entity(name = "FieldExpression") - public static class FieldExpression extends Expression { - private String objectType; - private String name; - - public FieldExpression() { - } - - public FieldExpression(String objectType, String name) { - this.objectType = objectType; - this.name = name; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getObjectType() { - return objectType; - } - - public void setObjectType(String objectType) { - this.objectType = objectType; - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - if (!super.equals(o)) { - return false; - } - - FieldExpression that = (FieldExpression) o; - - if (name != null ? !name.equals(that.name) : that.name != null) { - return false; - } - if (objectType != null ? !objectType.equals(that.objectType) : that.objectType != null) { - return false; - } - - return true; - } - - @Override - public int hashCode() { - int result = super.hashCode(); - result = 31 * result + (objectType != null ? objectType.hashCode() : 0); - result = 31 * result + (name != null ? name.hashCode() : 0); - return result; - } - } - @Entity(name = "Expression") - @Table(name = "rca_expression") - public static abstract class Expression extends BaseEntity implements Serializable { - protected MetadataFieldType type; - - protected Expression() { - } - - protected Expression(MetadataFieldType type) { - this.type = type; - } - - public MetadataFieldType getType() { - return type; - } - - public void setType(MetadataFieldType type) { - this.type = type; - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - if (!super.equals(o)) { - return false; - } - - Expression that = (Expression) o; - - if (type != that.type) { - return false; - } - - return true; - } - - @Override - public int hashCode() { - int result = super.hashCode(); - result = 31 * result + (type != null ? type.hashCode() : 0); - return result; - } - } - @Entity(name = "ConstantExpression") - public static class ConstantExpression extends Expression { - private String value; - - public ConstantExpression() { - } - - public ConstantExpression(String value, MetadataFieldType type) { - super(type); - this.value = value; - } - - @Column(name = "val") - public String getValue() { - return value; - } - - public void setValue(String value) { - this.value = value; - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - if (!super.equals(o)) { - return false; - } - - ConstantExpression that = (ConstantExpression) o; - - if (value != null ? !value.equals(that.value) : that.value != null) { - return false; - } - - return true; - } - - @Override - public int hashCode() { - int result = super.hashCode(); - result = 31 * result + (value != null ? value.hashCode() : 0); - return result; - } - } - @Entity(name = "ConditionAndExpression") - @Table(name = "rca_cond_and_expr") - public static class ConditionAndExpression extends BaseEntity { - private Condition condition; - private Expression expression; - - public ConditionAndExpression() { - } - - public ConditionAndExpression(Condition condition, Expression expression) { - this.condition = condition; - this.expression = expression; - } - - @OneToOne(cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.EAGER) - @JoinColumn(name = "cond_cond_id") - public Condition getCondition() { - return condition; - } - - public void setCondition(Condition condition) { - this.condition = condition; - } - - @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER) - @JoinColumn(name = "cond_expression_id") - public Expression getExpression() { - return expression; - } - - public void setExpression(Expression expression) { - this.expression = expression; - } - } - @Entity(name = "ConditionalExpression") - public static class ConditionalExpression extends Expression { - private Set possibilities; - - public ConditionalExpression() { - } - - public ConditionalExpression(MetadataFieldType type, Set possibilities) { - super(type); - this.possibilities = possibilities; - } - - @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER) - @JoinTable(name = "rca_cond_posssibility", joinColumns = { - @JoinColumn(name = "f_cond_id")}, inverseJoinColumns = { - @JoinColumn(name = "f_pos_id")}) - public Set getPossibilities() { - return possibilities; - } - - public void setPossibilities(Set possibilities) { - this.possibilities = possibilities; - } - } - @Entity(name = "Condition") - @Table(name = "rca_condition") - public static abstract class Condition extends BaseEntity implements Serializable { - } - @Entity(name = "CompoundCondition") - public static class CompoundCondition extends Condition { - private Condition first; - private Condition second; - private LogicalOperator op; - - public CompoundCondition() { - } - - public CompoundCondition(Condition first, Condition second) { - this.first = first; - this.second = second; - this.op = LogicalOperator.AND; - } - - public CompoundCondition(Condition first, Condition second, LogicalOperator op) { - this.first = first; - this.second = second; - this.op = op; - } - - @OneToOne(cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.EAGER) - @JoinColumn(name = "first_id") - public Condition getFirst() { - return first; - } - - public void setFirst(Condition first) { - this.first = first; - } - - @OneToOne(cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.EAGER) - @JoinColumn(name = "second_id") - public Condition getSecond() { - return second; - } - - public void setSecond(Condition second) { - this.second = second; - } - - public LogicalOperator getOp() { - return op; - } - - public void setOp(LogicalOperator op) { - this.op = op; - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - if (!super.equals(o)) { - return false; - } - - CompoundCondition that = (CompoundCondition) o; - - if (first != null ? !first.equals(that.first) : that.first != null) { - return false; - } - if (op != that.op) { - return false; - } - if (second != null ? !second.equals(that.second) : that.second != null) { - return false; - } - - return true; - } - - @Override - public int hashCode() { - int result = super.hashCode(); - result = 31 * result + (first != null ? first.hashCode() : 0); - result = 31 * result + (second != null ? second.hashCode() : 0); - result = 31 * result + (op != null ? op.hashCode() : 0); - return result; - } - } - @Entity - @Table(name = "rca_cause") - public static class Cause extends BaseEntity implements Serializable { - private String name; - private String nodeType; - private MappingRelationType relationType; - private Set fetchConditions; - private Condition condition; - private Condition auxCondition; - private String messageTemplate; - private String generalMessageTemplate; - private DataManipulationFunction function; - private Set messageTemplateParams; - private Set generalMessageTemplateParams; - private TimeManipulation startTimeManipulation; - private TimeManipulation endTimeManipulation; - private String plugin; - - public Cause() { - } - - public Cause(String name, String nodeType, MappingRelationType relationType, Set fetchConditions, - Condition condition, String messageTemplate, DataManipulationFunction function, Set messageTemplateParams, String plugin) { - this.name = name; - this.nodeType = nodeType; - this.relationType = relationType; - this.fetchConditions = fetchConditions; - this.condition = condition; - this.messageTemplate = messageTemplate; - this.function = function; - this.messageTemplateParams = messageTemplateParams; - this.plugin = plugin; - } - - public String getNodeType() { - return nodeType; - } - - public void setNodeType(String nodeType) { - this.nodeType = nodeType; - } - - public String getPlugin() { - return plugin; - } - - public void setPlugin(String plugin) { - this.plugin = plugin; - } - - @OneToOne(cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.EAGER) - @JoinColumn(name = "condition_id") - public Condition getCondition() { - return condition; - } - - public void setCondition(Condition condition) { - this.condition = condition; - } - - @OneToOne(cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.EAGER) - @JoinColumn(name = "aux_condition_id") - public Condition getAuxCondition() { - return auxCondition; - } - - public void setAuxCondition(Condition auxCondition) { - this.auxCondition = auxCondition; - } - - public String getMessageTemplate() { - return messageTemplate; - } - - public void setMessageTemplate(String messageTemplate) { - this.messageTemplate = messageTemplate; - } - - public String getGeneralMessageTemplate() { - return generalMessageTemplate; - } - - public void setGeneralMessageTemplate(String generalMessageTemplate) { - this.generalMessageTemplate = generalMessageTemplate; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - @Column(name = "functionName") - public DataManipulationFunction getFunction() { - return function; - } - - public void setFunction(DataManipulationFunction function) { - this.function = function; - } - - public MappingRelationType getRelationType() { - return relationType; - } - - public void setRelationType(MappingRelationType relationType) { - this.relationType = relationType; - } - - @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER) - @JoinTable(name = "rca_cause_param", joinColumns = { - @JoinColumn(name = "f_cause_id")}, inverseJoinColumns = { - @JoinColumn(name = "f_param_id")}) - public Set getMessageTemplateParams() { - return messageTemplateParams; - } - - public void setMessageTemplateParams(Set messageTemplateParams) { - this.messageTemplateParams = messageTemplateParams; - } - - @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER) - @JoinTable(name = "rca_cause_general_param", joinColumns = { - @JoinColumn(name = "f_cause_id")}, inverseJoinColumns = { - @JoinColumn(name = "f_param_id")}) - public Set getGeneralMessageTemplateParams() { - return generalMessageTemplateParams; - } - - public void setGeneralMessageTemplateParams(Set generalMessageTemplateParams) { - this.generalMessageTemplateParams = generalMessageTemplateParams; - } - - @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER) - @JoinTable(name = "rca_cause_fetch", joinColumns = { - @JoinColumn(name = "f_cause_id")}, inverseJoinColumns = { - @JoinColumn(name = "f_fetch_id")}) - public Set getFetchConditions() { - return fetchConditions; - } - - public void setFetchConditions(Set fetchConditions) { - this.fetchConditions = fetchConditions; - } - - @OneToOne(cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.EAGER) - @JoinColumn(name = "start_time_manip_id") - public TimeManipulation getStartTimeManipulation() { - return startTimeManipulation; - } - - public void setStartTimeManipulation(TimeManipulation startTimeManipulation) { - this.startTimeManipulation = startTimeManipulation; - } - - @OneToOne(cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.EAGER) - @JoinColumn(name = "end_time_manip_id") - public TimeManipulation getEndTimeManipulation() { - return endTimeManipulation; - } - - public void setEndTimeManipulation(TimeManipulation endTimeManipulation) { - this.endTimeManipulation = endTimeManipulation; - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - if (!super.equals(o)) { - return false; - } - - Cause cause = (Cause) o; - - if (function != cause.function) { - return false; - } - if (messageTemplate != null ? !messageTemplate.equals(cause.messageTemplate) : cause.messageTemplate != null) { - return false; - } - if (name != null ? !name.equals(cause.name) : cause.name != null) { - return false; - } - if (nodeType != null ? !nodeType.equals(cause.nodeType) : cause.nodeType != null) { - return false; - } - if (relationType != cause.relationType) { - return false; - } - - return true; - } - - @Override - public int hashCode() { - int result = super.hashCode(); - result = 31 * result + (name != null ? name.hashCode() : 0); - result = 31 * result + (nodeType != null ? nodeType.hashCode() : 0); - result = 31 * result + (relationType != null ? relationType.hashCode() : 0); - result = 31 * result + (messageTemplate != null ? messageTemplate.hashCode() : 0); - result = 31 * result + (function != null ? function.hashCode() : 0); - return result; - } - } - @Entity(name = "CalculationExpression") - public static class CalculationExpression extends Expression { - private DataManipulationFunction function; - private String objectType; - private String fieldName; - - public CalculationExpression() { - } - - public CalculationExpression(DataManipulationFunction function, String objectType, String fieldName) { - this.function = function; - this.objectType = objectType; - this.fieldName = fieldName; - } - - @Column(name = "functionName") - public DataManipulationFunction getFunction() { - return function; - } - - public void setFunction(DataManipulationFunction function) { - this.function = function; - } - - public String getObjectType() { - return objectType; - } - - public void setObjectType(String objectType) { - this.objectType = objectType; - } - - public String getFieldName() { - return fieldName; - } - - public void setFieldName(String fieldName) { - this.fieldName = fieldName; - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - if (!super.equals(o)) { - return false; - } - - CalculationExpression that = (CalculationExpression) o; - - if (fieldName != null ? !fieldName.equals(that.fieldName) : that.fieldName != null) { - return false; - } - if (function != that.function) { - return false; - } - if (objectType != null ? !objectType.equals(that.objectType) : that.objectType != null) { - return false; - } - - return true; - } - - @Override - public int hashCode() { - int result = super.hashCode(); - result = 31 * result + (function != null ? function.hashCode() : 0); - result = 31 * result + (objectType != null ? objectType.hashCode() : 0); - result = 31 * result + (fieldName != null ? fieldName.hashCode() : 0); - return result; - } - } - @Entity(name = "AlertCondition") - public static class AlertCondition extends Condition { - private String ruleName; - - public AlertCondition() { - } - - public String getRuleName() { - return ruleName; - } - - public void setRuleName(String ruleName) { - this.ruleName = ruleName; - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - if (!super.equals(o)) { - return false; - } - - AlertCondition that = (AlertCondition) o; - - if (ruleName != null ? !ruleName.equals(that.ruleName) : that.ruleName != null) { - return false; - } - - return true; - } - - @Override - public int hashCode() { - int result = super.hashCode(); - result = 31 * result + (ruleName != null ? ruleName.hashCode() : 0); - return result; - } - } - @MappedSuperclass - public static abstract class BaseEntity implements Serializable { - private Long id; - - @Id - @Column(name = "f_id") - @GeneratedValue - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - - BaseEntity that = (BaseEntity) o; - - // noinspection SimplifiableIfStatement - if (id == null || that.id == null) { - return false; // null != everything (including null) - } - return id.equals(that.id); - } - - @Override - public int hashCode() { - return id != null ? id.hashCode() : 0; - } - - } - - public enum RelativeToType { - START, - END - } - - public enum Operator { - EQUALS(" = "), - NOT_EQUALS(" != "), - GREATER_THAN(" > "), - SMALLER_THAN(" < "), - CONTAINS(" contains "), - BEGINS_WITH(" begins with "), - ENDS_WITH(" ends with "); - - private String readable; - - private Operator(String readable) { - this.readable = readable; - } - - @Override - public String toString() { - return readable; - } - } - - public enum MathOperator { - ADD, - SUBTRACT, - MULTIPLY, - DIVIDE, - MAX; - - @Override - public String toString() { - switch (this) { - case ADD: - return "+"; - case SUBTRACT: - return "-"; - case MULTIPLY: - return "*"; - case DIVIDE: - return "/"; - case MAX: - return "max"; - } - return null; - } - - - } - - public enum ManipulationType { - MOVE_IT_BY_ABSOLUTE_TIME, - MOVE_IT_RELATIVE_TO_OTHER_TIME, - ABSOLUTE - } - - public enum LogicalOperator { - AND, - OR - } - - public enum MetadataFieldType { - BOOLEAN, STRING, NULL, NUMERIC - } - - public enum DataManipulationFunction { - AVG, - MAX, - MIN, - COUNT, - SUM, - EXISTS, - LAST, - FIRST, - INCREASED_BY - } - - public enum MappingRelationType { - JOB_BACKING_UP_HOST, JOB_USES_BACKUPCLIENT, JOB_USES_BACKUP_POOL, JOB_USES_MEDIA_SERVER, RECOVERPOINT_CG_COPY_ACTIVE_RPA, JOB_USES_TAPE_DRIVE - } - - public static class DefaultTemplatesVault { - - public static final String NO_AGENT_RAN_ON_CLIENT = "No agent ran on client"; - public static final String BACKUP_AGENT_IS_DOWN_ON_BACKUP_CLIENT = "Backup agent is down on backup client"; - public static final String BACKUP_FAILED_SYMPTOM_NAME = "Backup failed"; - public static final String CG_COPY_RPO_VIOLATION_SYMPTOM_NAME = "CG Copy RPO Violation"; - public static final String PACKET_LOSS = "Packet Loss"; - - private static RCATemplate buildBackupFailedTemplate() { - Symptom symptom = new Symptom(BACKUP_FAILED_SYMPTOM_NAME, "Backupjob", - new SimpleCondition(new FieldExpression("Backupjob", "status"), Operator.EQUALS, new ConstantExpression("failed", MetadataFieldType.STRING))); - symptom.setFilterString("status = 'failed'"); - symptom.setNodeTypeString("clients"); - symptom.setProcessTypeString("backup jobs"); - - // high client cpu ' - WeightedCause cause1 = buildHighClientCpu(); - - // high storage node cpu - WeightedCause cause2 = buildHighStorageNodeCpu(); - - // no space left on device - WeightedCause cause3 = buildNoSpaceOnPool(); - - // no space left on data domain - WeightedCause cause4 = buildNoSpaceOnDD(); - - // no agent ran on client - WeightedCause cause5 = buildNoAgentOnClient(); - - // no agent ran on client - WeightedCause cause6 = buildNoAgentOnClient2(); - - // errors on tape - WeightedCause errorsOnTapeCause = buildErrorsOnTape(); - - // switch port for ethernet - WeightedCause cause7 = buildPortSwitchForEthernet(); - - // switch port for fibre channel - WeightedCause cause8 = buildPortSwitchForFibreChannel(); - - // port settings for ethernet - WeightedCause cause9 = buildDifferentPortSettings(); - - // no space on client - WeightedCause noSpaceOnClientCause = buildNoSpaceOnClient(); - - // todo -all other causes - Set causes = new HashSet<>(); - causes.add(cause1); - causes.add(cause2); - causes.add(cause3); - causes.add(cause4); - causes.add(cause5); - causes.add(cause6); - //causes.add(errorsOnTapeCause); - causes.add(cause7); - causes.add(cause8); - causes.add(cause9); - causes.add(noSpaceOnClientCause); - return new RCATemplate("Backup failed RCA template", symptom, causes); - } - - private static WeightedCause buildNoSpaceOnClient() { - Expression clientName = new FieldExpression("Host", "name"); - NumberedExpression nameFirst = new NumberedExpression(1L, clientName); - - Expression mountpointName = new FieldExpression("FilesystemConfig", "mountpoint"); - NumberedExpression mountpointSecond = new NumberedExpression(2L, mountpointName); - - Expression leftSpace = new MathExpression(new FieldExpression("FilesystemConfig", "totalSpace"), - new FieldExpression("FilesystemStatus", "usedSpace"), - MathOperator.SUBTRACT); - ParameterExpression leftSpaceOnClient = new ParameterExpression("leftSpaceOnClient", "50", MetadataFieldType.NUMERIC); - NumberedExpression spaceThird = new NumberedExpression(3L, leftSpace); - - - Set messageArgs = new HashSet<>(); - messageArgs.add(nameFirst); - messageArgs.add(mountpointSecond); - messageArgs.add(spaceThird); - - Condition fetchCondition1 = new CompoundCondition( - new SimpleCondition(new FieldExpression("FilesystemStatus", "mountpoint"), Operator.EQUALS, new ConstantExpression("C:", MetadataFieldType.STRING)), - new SimpleCondition(new FieldExpression("FilesystemStatus", "agentId"), Operator.EQUALS, new FieldExpression("Host", "id")) - ); - Condition fetchCondition2 = new CompoundCondition( - new SimpleCondition(new FieldExpression("FilesystemConfig", "mountpoint"), Operator.EQUALS, new ConstantExpression("C:", MetadataFieldType.STRING)), - new SimpleCondition(new FieldExpression("FilesystemConfig", "agentId"), Operator.EQUALS, new FieldExpression("Host", "id")) - ); - - Set fetchConditions = new HashSet<>(); - fetchConditions.add(fetchCondition1); - fetchConditions.add(fetchCondition2); - - SimpleCondition condition = new SimpleCondition(leftSpace, Operator.SMALLER_THAN, leftSpaceOnClient); - - Cause noSpaceOnClient = new Cause("No space on Client", "Host", MappingRelationType.JOB_BACKING_UP_HOST, - fetchConditions, condition, "There is a lack of free space in {param}:{param}. The current free space is {param} MB", DataManipulationFunction.LAST, messageArgs, null); - - return new WeightedCause(noSpaceOnClient, 95); - } - - private static WeightedCause buildErrorsOnTape() { - - Expression tapeDriveNameExp = new FieldExpression("TapeDrive", "name"); - NumberedExpression tapeDriveName = new NumberedExpression(1L, tapeDriveNameExp); - - Expression errorsExp = new FieldExpression("TapedriveStatus", "correctedReadErrors"); - - Set messageArgs = new HashSet<>(); - messageArgs.add(tapeDriveName); - - Condition fetchCondition = new SimpleCondition(new FieldExpression("TapedriveStatus", "nodeId"), - Operator.EQUALS, new FieldExpression("TapeDrive", "id")); - Set fetchConditions = new HashSet<>(); - fetchConditions.add(fetchCondition); - - ConstantExpression zero = new ConstantExpression("0", MetadataFieldType.NUMERIC); - - Cause errorsOnTape = new Cause("Errors on tape", "TapeDrive", MappingRelationType.JOB_USES_TAPE_DRIVE, fetchConditions, - new CompoundCondition( - new CompoundCondition( - new CompoundCondition( - new SimpleCondition(new FieldExpression("TapedriveStatus", "correctedReadErrors"), Operator.GREATER_THAN, zero), - new SimpleCondition(new FieldExpression("TapedriveStatus", "correctedWriteErrors"), Operator.GREATER_THAN, zero), - LogicalOperator.OR), - new SimpleCondition(new FieldExpression("TapedriveStatus", "uncorrectedReadErrors"), Operator.GREATER_THAN, zero), - LogicalOperator.OR), - new SimpleCondition(new FieldExpression("TapedriveStatus", "uncorrectedWriteErrors"), Operator.GREATER_THAN, zero), - LogicalOperator.OR), - "Tape drive {param} had errors", DataManipulationFunction.INCREASED_BY, messageArgs, null); - return new WeightedCause(errorsOnTape, 70); - } - - private static WeightedCause buildNoSpaceOnDD() { - Expression ddName = new FieldExpression("DataDomain", "name"); - NumberedExpression ddFirst = new NumberedExpression(1L, ddName); - - - Expression ddUsage = new MathExpression(new MathExpression( - new FieldExpression("FilesystemStatus", "usedSpace"), - new FieldExpression("FilesystemConfig", "totalSpace"), - MathOperator.DIVIDE - ), - new ConstantExpression("100", MetadataFieldType.NUMERIC), MathOperator.MULTIPLY); - NumberedExpression ddSecond = new NumberedExpression(2L, ddUsage); - ParameterExpression ddUsageThreshold = new ParameterExpression("ddUsageThreshold", "80", MetadataFieldType.NUMERIC); - NumberedExpression ddThird = new NumberedExpression(3L, ddUsageThreshold); - Set messageArgs4 = new HashSet<>(); - messageArgs4.add(ddFirst); - messageArgs4.add(ddSecond); - messageArgs4.add(ddThird); - - Condition fetchCondition4 = new CompoundCondition( - new SimpleCondition(new FieldExpression("FilesystemStatus", "mountpoint"), Operator.EQUALS, new ConstantExpression("Data", MetadataFieldType.STRING)), - new SimpleCondition(new FieldExpression("FilesystemStatus", "agentId"), Operator.EQUALS, new FieldExpression("DataDomain", "id")) - ); - Condition fetchCondition5 = new CompoundCondition( - new SimpleCondition(new FieldExpression("FilesystemConfig", "mountpoint"), Operator.EQUALS, new ConstantExpression("Data", MetadataFieldType.STRING)), - new SimpleCondition(new FieldExpression("FilesystemConfig", "agentId"), Operator.EQUALS, new FieldExpression("DataDomain", "id")) - ); - Set fetchConditions4 = new HashSet<>(); - fetchConditions4.add(fetchCondition4); - fetchConditions4.add(fetchCondition5); - - Cause noSpaceOnDD = new Cause("No space on data domain", "DataDomain", MappingRelationType.JOB_USES_BACKUPCLIENT, - fetchConditions4, new SimpleCondition(ddUsage, Operator.GREATER_THAN, ddUsageThreshold), - "The capacity utilization for DataDomain {param} is {param}% which is the above threshold {param}%", DataManipulationFunction.LAST, messageArgs4, null); - - noSpaceOnDD.setGeneralMessageTemplate("The capacity utilization for DataDomain {param} is the above threshold {param}%"); - - Set generalMessageParams = new HashSet<>(); - generalMessageParams.add(ddFirst); - NumberedExpression ddThirdWhichIsNowSecond = new NumberedExpression(2L, new ParameterExpression("ddUsageThreshold", "80", MetadataFieldType.NUMERIC)); - generalMessageParams.add(ddThirdWhichIsNowSecond); - noSpaceOnDD.setGeneralMessageTemplateParams(generalMessageParams); - - return new WeightedCause(noSpaceOnDD, 90); - } - - private static WeightedCause buildNoSpaceOnPool() { - Expression poolName = new FieldExpression("BackupPool", "name"); - NumberedExpression deviceFirst = new NumberedExpression(1L, poolName); - Expression numOfEmptyVolumes = new CalculationExpression(DataManipulationFunction.COUNT, "VolumeStatus", "id"); - NumberedExpression deviceSecond = new NumberedExpression(2L, numOfEmptyVolumes); - Set messageArgs3 = new HashSet<>(); - messageArgs3.add(deviceFirst); - messageArgs3.add(deviceSecond); - - Condition fetchCondition3 = new CompoundCondition( - new SimpleCondition(new FieldExpression("VolumeStatus", "pool"), Operator.EQUALS, new FieldExpression("BackupPool", "name")), - new SimpleCondition(new FieldExpression("VolumeStatus", "agentId"), Operator.EQUALS, new FieldExpression("Backupjob", "agentId")) - ); - Set fetchConditions3 = new HashSet<>(); - fetchConditions3.add(fetchCondition3); - - ConstantExpression threshold = new ConstantExpression("5", MetadataFieldType.NUMERIC); - Cause noSpaceOnDevice = new Cause("No space left on device", "BackupPool", MappingRelationType.JOB_USES_BACKUP_POOL, - fetchConditions3, - new SimpleCondition( - new FieldExpression("VolumeStatus", "state"), - Operator.SMALLER_THAN, - threshold), - "Pool {param} has only {param} empty volumes left", DataManipulationFunction.COUNT, messageArgs3, null); - noSpaceOnDevice.setAuxCondition(new SimpleCondition(new FieldExpression("VolumeStatus", "state"), - Operator.EQUALS, new ConstantExpression("Empty", MetadataFieldType.STRING))); - - noSpaceOnDevice.setGeneralMessageTemplate("Pool {param} has less than {param} empty volumes left"); - Set generalMessageParams = new HashSet<>(); - generalMessageParams.add(deviceFirst); - generalMessageParams.add(new NumberedExpression(2L, threshold)); - noSpaceOnDevice.setGeneralMessageTemplateParams(generalMessageParams); - - return new WeightedCause(noSpaceOnDevice, 80); - } - - private static WeightedCause buildHighStorageNodeCpu() { - Expression storageName = new FieldExpression("Host", "name"); - NumberedExpression storageFirst = new NumberedExpression(1L, storageName); - Expression avgCpuStorage = new CalculationExpression(DataManipulationFunction.AVG, "HostStatus", "cpuUsed"); - NumberedExpression storageSecond = new NumberedExpression(2L, avgCpuStorage); - Set messageArgs2 = new HashSet<>(); - messageArgs2.add(storageFirst); - messageArgs2.add(storageSecond); - - Condition fetchCondition2 = new SimpleCondition(new FieldExpression("HostStatus", "nodeId"), - Operator.EQUALS, new FieldExpression("Host", "id")); - Set fetchConditions2 = new HashSet<>(); - fetchConditions2.add(fetchCondition2); - - ParameterExpression storageNodeHighCPUThreshold = new ParameterExpression("storageNodeHighCPUThreshold", "95", MetadataFieldType.NUMERIC); - Cause highCpuOnStorageNode = new Cause("High storage node CPU", "Host", MappingRelationType.JOB_USES_MEDIA_SERVER, - fetchConditions2, - new SimpleCondition(new FieldExpression("HostStatus", "cpuUsed"), Operator.GREATER_THAN, - storageNodeHighCPUThreshold), "Storage node {param} CPU was {param}", DataManipulationFunction.AVG, - messageArgs2, null); - TimeManipulation startTimeManipulation = new TimeManipulation(ManipulationType.MOVE_IT_RELATIVE_TO_OTHER_TIME, - MathOperator.SUBTRACT, 3600L, RelativeToType.END, "job_cpu_offset"); - highCpuOnStorageNode.setStartTimeManipulation(startTimeManipulation); - - highCpuOnStorageNode.setGeneralMessageTemplate("Storage node {param} CPU was higher than {param}"); - Set generalMessageParams = new HashSet<>(); - generalMessageParams.add(storageFirst); - generalMessageParams.add(new NumberedExpression(2L, storageNodeHighCPUThreshold)); - highCpuOnStorageNode.setGeneralMessageTemplateParams(generalMessageParams); - - return new WeightedCause(highCpuOnStorageNode, 60); - } - - private static WeightedCause buildHighClientCpu() { - Expression clientName = new FieldExpression("Host", "name"); - NumberedExpression clientFirst = new NumberedExpression(1L, clientName); - Expression avgCpu = new CalculationExpression(DataManipulationFunction.AVG, "HostStatus", "cpuUsed"); - NumberedExpression clientSecond = new NumberedExpression(2L, avgCpu); - Set messageArgs1 = new HashSet<>(); - messageArgs1.add(clientFirst); - messageArgs1.add(clientSecond); - - Condition fetchCondition = new SimpleCondition(new FieldExpression("HostStatus", "nodeId"), - Operator.EQUALS, new FieldExpression("Host", "id")); - Set fetchConditions = new HashSet<>(); - fetchConditions.add(fetchCondition); - - - ParameterExpression clientHighCPUThreshold = new ParameterExpression("clientHighCPUThreshold", "95", MetadataFieldType.NUMERIC); - Cause highCpuOnClient = new Cause("High client CPU", "Host", MappingRelationType.JOB_BACKING_UP_HOST, - new HashSet<>(fetchConditions), - new SimpleCondition(new FieldExpression("HostStatus", "cpuUsed"), Operator.GREATER_THAN, - clientHighCPUThreshold), "Client {param} CPU was {param}", DataManipulationFunction.AVG, - messageArgs1, null); - - TimeManipulation startTimeManipulation = new TimeManipulation(ManipulationType.MOVE_IT_RELATIVE_TO_OTHER_TIME, - MathOperator.SUBTRACT, 3600L, RelativeToType.END, "job_cpu_offset"); - highCpuOnClient.setStartTimeManipulation(startTimeManipulation); - - highCpuOnClient.setGeneralMessageTemplate("Client {param} CPU was higher than {param}"); - Set generalMessageParams = new HashSet<>(); - generalMessageParams.add(clientFirst); - generalMessageParams.add(new NumberedExpression(2L, clientHighCPUThreshold)); - highCpuOnClient.setGeneralMessageTemplateParams(generalMessageParams); - - return new WeightedCause(highCpuOnClient, 50); - } - - private static WeightedCause buildNoAgentOnClient() { - Expression clientName = new FieldExpression("Host", "name"); - NumberedExpression clientFirst = new NumberedExpression(1L, clientName); - Set messageArgs1 = new HashSet<>(); - messageArgs1.add(clientFirst); - - Condition fetchHostStatus = new SimpleCondition(new FieldExpression("HostStatus", "nodeId"), - Operator.EQUALS, new FieldExpression("Host", "id")); - - ConditionAndExpression netbackup = new ConditionAndExpression( - new SimpleCondition( - new FieldExpression("Backupjob", "module"), - Operator.EQUALS, - new ConstantExpression("NetBackupModule", MetadataFieldType.STRING) - ), - new ConstantExpression("bpinetd", MetadataFieldType.STRING) - ); - - ConditionAndExpression networker = new ConditionAndExpression( - new SimpleCondition( - new FieldExpression("Backupjob", "module"), - Operator.EQUALS, - new ConstantExpression("NetWorkerModule", MetadataFieldType.STRING) - ), - new ConstantExpression("nsrexecd", MetadataFieldType.STRING) - ); - - ConditionAndExpression backupExec = new ConditionAndExpression( - new SimpleCondition( - new FieldExpression("Backupjob", "module"), - Operator.EQUALS, - new ConstantExpression("BackupExecModule", MetadataFieldType.STRING) - ), - new ConstantExpression("beremote", MetadataFieldType.STRING) - ); - - ConditionAndExpression dataProtector = new ConditionAndExpression( - new SimpleCondition( - new FieldExpression("Backupjob", "module"), - Operator.EQUALS, - new ConstantExpression("DataProtectorModule", MetadataFieldType.STRING) - ), - new ConstantExpression("omniinet", MetadataFieldType.STRING) - ); - - ConditionAndExpression tsm = new ConditionAndExpression( - new SimpleCondition( - new FieldExpression("Backupjob", "module"), - Operator.EQUALS, - new ConstantExpression("TSMModule", MetadataFieldType.STRING) - ), - new ConstantExpression("dsmcsvc", MetadataFieldType.STRING) - ); - - ConditionAndExpression arcServe = new ConditionAndExpression( - new SimpleCondition( - new FieldExpression("Backupjob", "module"), - Operator.EQUALS, - new ConstantExpression("ArcserveModule", MetadataFieldType.STRING) - ), - new ConstantExpression("UnivAgent", MetadataFieldType.STRING) - ); - - ConditionAndExpression commVault = new ConditionAndExpression( - new SimpleCondition( - new FieldExpression("Backupjob", "module"), - Operator.EQUALS, - new ConstantExpression("CommvaultModule", MetadataFieldType.STRING) - ), - new ConstantExpression("evmgrc", MetadataFieldType.STRING) - ); - - ConditionAndExpression avamar = new ConditionAndExpression( - new SimpleCondition( - new FieldExpression("Backupjob", "module"), - Operator.EQUALS, - new ConstantExpression("AvamarModule", MetadataFieldType.STRING) - ), - new ConstantExpression("avagent", MetadataFieldType.STRING) - ); - - Set possibilities = new HashSet<>(); - possibilities.add(netbackup); - possibilities.add(networker); - possibilities.add(backupExec); - possibilities.add(dataProtector); - possibilities.add(tsm); - possibilities.add(arcServe); - possibilities.add(commVault); - possibilities.add(avamar); - - Condition fetchProcessStatus = new CompoundCondition( - new SimpleCondition(new FieldExpression("ProcessStatus", "nodeId"), - Operator.EQUALS, new FieldExpression("Host", "id")), - new SimpleCondition(new FieldExpression("ProcessStatus", "name"), - Operator.CONTAINS, new ConditionalExpression(MetadataFieldType.STRING, possibilities)), - LogicalOperator.AND - ); - - Set fetchConditions = new HashSet<>(); - fetchConditions.add(fetchHostStatus); - fetchConditions.add(fetchProcessStatus); - - Condition condition = new CompoundCondition( - new SimpleCondition( - new CalculationExpression(DataManipulationFunction.COUNT, "HostStatus", "id"), - Operator.GREATER_THAN, - new ConstantExpression("0", MetadataFieldType.NUMERIC) - ), - new SimpleCondition( - new CalculationExpression(DataManipulationFunction.COUNT, "ProcessStatus", "id"), - Operator.EQUALS, - new ConstantExpression("0", MetadataFieldType.NUMERIC) - ), - LogicalOperator.AND - ); - - Cause noAgentOnClient = new Cause( - NO_AGENT_RAN_ON_CLIENT, "Host", MappingRelationType.JOB_BACKING_UP_HOST, - fetchConditions, condition, "Backup agent was down on host: {param}", DataManipulationFunction.LAST, - messageArgs1, null); - - return new WeightedCause(noAgentOnClient, 100); - } - - private static WeightedCause buildNoAgentOnClient2() { - - Expression agentName = new FieldExpression("BackupClient", "name"); - NumberedExpression agentFirst = new NumberedExpression(1L, agentName); - Set messageArgs1 = new HashSet<>(); - messageArgs1.add(agentFirst); - - Condition fetchCondition6 = new SimpleCondition(new FieldExpression("ClientStatus", "nodeId"), - Operator.EQUALS, new FieldExpression("BackupClient", "id")); - - Set fetchConditions6 = new HashSet<>(); - fetchConditions6.add(fetchCondition6); - - - Cause AgentDown = new Cause(BACKUP_AGENT_IS_DOWN_ON_BACKUP_CLIENT, "BackupClient", MappingRelationType.JOB_USES_BACKUPCLIENT, - fetchConditions6, - new CompoundCondition( - new SimpleCondition(new FieldExpression("ClientStatus", "responding"), Operator.EQUALS, new ConstantExpression("true", MetadataFieldType.BOOLEAN)), - new SimpleCondition(new FieldExpression("ClientStatus", "daemonRunning"), Operator.EQUALS, new ConstantExpression("false", MetadataFieldType.BOOLEAN))), - "Backup agent {param} is down on backup client", DataManipulationFunction.LAST, messageArgs1, null); - - return new WeightedCause(AgentDown, 101); - } - - private static WeightedCause buildPortSwitchForEthernet() { - Expression portName = new FieldExpression("EthernetPort", "name"); - Expression nodeType = new FieldExpression("NetintStatus", "module"); - Expression nodeName = new FieldExpression("NetintStatus", "agentName"); - NumberedExpression portNameFirst = new NumberedExpression(1L, portName); - NumberedExpression nodeTypeSecond = new NumberedExpression(2L, nodeType); - NumberedExpression nodeNameThird = new NumberedExpression(3L, nodeName); - Set messageArgs1 = new HashSet<>(); - messageArgs1.add(portNameFirst); - messageArgs1.add(nodeTypeSecond); - messageArgs1.add(nodeNameThird); - - Condition fetchCondition7 = new SimpleCondition(new FieldExpression("NetintStatus", "nodeId"), - Operator.EQUALS, new FieldExpression("EthernetPort", "id")); - - Set fetchConditions7 = new HashSet<>(); - fetchConditions7.add(fetchCondition7); - - - Cause SwitchPortDown = new Cause("Switch port is down for ethernet", "EthernetPort", null, - fetchConditions7, - new SimpleCondition(new FieldExpression("NetintStatus", "linkup"), Operator.EQUALS, new ConstantExpression("false", MetadataFieldType.BOOLEAN)), - "Ethernet port:{param} for {param}:{param} is down", DataManipulationFunction.EXISTS, messageArgs1, "com.emc.dpa.analysis.rca.RCAPortSwitchIsDownPlugin"); - - return new WeightedCause(SwitchPortDown, 61); - } - - - private static WeightedCause buildDifferentPortSettings() { - Set messageArgs1 = new HashSet<>(); - - Condition fetchCondition1 = new SimpleCondition(new FieldExpression("NetintStatus", "nodeId"), - Operator.EQUALS, new FieldExpression("EthernetPort", "id")); - - Condition fetchCondition2 = new SimpleCondition(new FieldExpression("NetintConfig", "nodeId"), - Operator.EQUALS, new FieldExpression("EthernetPort", "id")); - - Set fetchConditions = new HashSet<>(); - fetchConditions.add(fetchCondition1); - fetchConditions.add(fetchCondition2); - - Cause PortSettings = new Cause("Different Port Settings", "EthernetPort", null, - fetchConditions, - new SimpleCondition(new FieldExpression("NetintStatus", "speed"), Operator.NOT_EQUALS, - new ConstantExpression("0", MetadataFieldType.NUMERIC)), - "", DataManipulationFunction.EXISTS, messageArgs1, "com.emc.dpa.analysis.rca.RCASwitchSettingsPlugin"); - - return new WeightedCause(PortSettings, 63); - } - - - private static WeightedCause buildPortSwitchForFibreChannel() { - Expression portName = new FieldExpression("FibreChannelPort", "name"); - Expression nodeType = new FieldExpression("FcportStatus", "module"); - Expression nodeName = new FieldExpression("FcportStatus", "agentName"); - NumberedExpression portNameFirst = new NumberedExpression(1L, portName); - NumberedExpression nodeTypeSecond = new NumberedExpression(2L, nodeType); - NumberedExpression nodeNameThird = new NumberedExpression(3L, nodeName); - Set messageArgs1 = new HashSet<>(); - messageArgs1.add(portNameFirst); - messageArgs1.add(nodeTypeSecond); - messageArgs1.add(nodeNameThird); - - Condition fetchCondition7 = new SimpleCondition(new FieldExpression("FcportStatus", "nodeId"), - Operator.EQUALS, new FieldExpression("FibreChannelPort", "id")); - - Set fetchConditions7 = new HashSet<>(); - fetchConditions7.add(fetchCondition7); - - - Cause SwitchPortDown = new Cause("Switch port is down for fibre channel", "FibreChannelPort", null, - fetchConditions7, - new SimpleCondition(new FieldExpression("FcportStatus", "linkup"), Operator.EQUALS, new ConstantExpression("false", MetadataFieldType.BOOLEAN)), - "Fibre channel port:{param} for {param}:{param} is down", DataManipulationFunction.EXISTS, messageArgs1, "com.emc.dpa.analysis.rca.RCAPortSwitchIsDownPlugin"); - - return new WeightedCause(SwitchPortDown, 60); - - } - - - private static RCATemplate buildRPAHighLoadTemplate() { - Symptom symptom = new Symptom("CG Copy high load", "CgCopyPerf", - new SimpleCondition(new FieldExpression("CgCopyPerf", "highLoadTime"), Operator.GREATER_THAN, new ConstantExpression("0", MetadataFieldType.NUMERIC))); - symptom.setFilterString("highLoadTime > 0"); - symptom.setNodeTypeString("cg copies"); - symptom.setProcessTypeString("replications"); - - - WeightedCause cause1 = buildHighRPAThroughput(); - WeightedCause cause2 = buildCGCopyFF(); - WeightedCause cause3 = buildPacketLoss(); - - Set causes = new HashSet<>(); - causes.add(cause1); - causes.add(cause2); - causes.add(cause3); - - return new RCATemplate("CG copy High load template", symptom, causes); - } - - private static WeightedCause buildHighRPAThroughput() { - - ParameterExpression highThroughputThreshold = new ParameterExpression("highThroughputThreshold", "122880", MetadataFieldType.NUMERIC); - ConstantExpression megaSize = new ConstantExpression("1024", MetadataFieldType.NUMERIC); - - Expression agentName = new FieldExpression("RpaPerfView", "agentName"); - NumberedExpression rpaFirst = new NumberedExpression(1L, agentName); - Expression rpaName = new FieldExpression("AbstractRecoverPointAppliance", "name"); - NumberedExpression rpaSecond = new NumberedExpression(2L, rpaName); - Expression site = new FieldExpression("RpaPerfView", "site"); - NumberedExpression rpaThird = new NumberedExpression(3L, site); - - MathExpression multiplyWanCompression = new MathExpression( - new FieldExpression("RpaPerfView", "wanThroughput"), - new FieldExpression("RpaPerfView", "compression"), - MathOperator.MULTIPLY); - - Expression wanThroughput = new MathExpression(new FieldExpression("RpaPerfView", "wanThroughput"), multiplyWanCompression, MathOperator.MAX); - Expression maxThroughput = new MathExpression(new FieldExpression("RpaPerfView", "sanThroughput"), wanThroughput, MathOperator.MAX); - Expression maxThroughputMB = new MathExpression(maxThroughput, megaSize, MathOperator.DIVIDE); - NumberedExpression rpaFourth = new NumberedExpression(4L, maxThroughputMB); - Expression limitThroughputMB = new MathExpression(highThroughputThreshold, megaSize, MathOperator.DIVIDE); - NumberedExpression rpaFifth = new NumberedExpression(5L, limitThroughputMB); - Set messageArgs1 = new HashSet<>(); - messageArgs1.add(rpaFirst); - messageArgs1.add(rpaSecond); - messageArgs1.add(rpaThird); - messageArgs1.add(rpaFourth); - messageArgs1.add(rpaFifth); - - Condition fetchCondition = new SimpleCondition(new FieldExpression("RpaPerfView", "nodeId"), - Operator.EQUALS, new FieldExpression("AbstractRecoverPointAppliance", "id")); - Set fetchConditions = new HashSet<>(); - fetchConditions.add(fetchCondition); - - - ///(san != null and san>120) || (wan != null and (((compression = null || compression = 0) and wan > 120) || ((compression != null and compression != 0) and wan*compression > 120))) - Condition condition = new CompoundCondition( - new CompoundCondition( - new SimpleCondition(new FieldExpression("RpaPerfView", "sanThroughput"), Operator.NOT_EQUALS, new ConstantExpression("null", MetadataFieldType.NULL)), - new SimpleCondition(new FieldExpression("RpaPerfView", "sanThroughput"), Operator.GREATER_THAN, highThroughputThreshold), - LogicalOperator.AND), - new CompoundCondition( - new SimpleCondition(new FieldExpression("RpaPerfView", "wanThroughput"), Operator.NOT_EQUALS, new ConstantExpression("null", MetadataFieldType.NULL)), - new CompoundCondition( - new CompoundCondition( - new SimpleCondition(new FieldExpression("RpaPerfView", "wanThroughput"), Operator.GREATER_THAN, highThroughputThreshold), - new CompoundCondition( - new SimpleCondition(new FieldExpression("RpaPerfView", "compression"), Operator.EQUALS, new ConstantExpression("null", MetadataFieldType.NULL)), - new SimpleCondition(new FieldExpression("RpaPerfView", "compression"), Operator.EQUALS, new ConstantExpression("0", MetadataFieldType.NUMERIC)), - LogicalOperator.OR), - LogicalOperator.AND), - new CompoundCondition( - new CompoundCondition( - new SimpleCondition(new FieldExpression("RpaPerfView", "compression"), Operator.NOT_EQUALS, new ConstantExpression("null", MetadataFieldType.NULL)), - new SimpleCondition(new FieldExpression("RpaPerfView", "compression"), Operator.NOT_EQUALS, new ConstantExpression("0", MetadataFieldType.NUMERIC)), - LogicalOperator.AND), - new SimpleCondition(multiplyWanCompression, Operator.GREATER_THAN, highThroughputThreshold), - LogicalOperator.AND), - LogicalOperator.OR), - LogicalOperator.AND), - LogicalOperator.OR); - - Cause rpaThroughputHigh = new Cause("High RPA throughput", "AbstractRecoverPointAppliance", MappingRelationType.RECOVERPOINT_CG_COPY_ACTIVE_RPA, - fetchConditions, condition, "The throughput for RPA: {param}:{param} at site {param} was {param}MB, above the RPA throughput limitation ({param}MB)", DataManipulationFunction.EXISTS, - messageArgs1, null); - - TimeManipulation startTimeManipulation = new TimeManipulation( - ManipulationType.MOVE_IT_BY_ABSOLUTE_TIME, - MathOperator.SUBTRACT, - 5 * 60L, - null, - "rpa_throughput_offset" - ); - rpaThroughputHigh.setStartTimeManipulation(startTimeManipulation); - - rpaThroughputHigh.setGeneralMessageTemplate("The throughput for RPA: {param}:{param} at site {param} was above the RPA throughput limitation ({param}MB)"); - Set generalMessageParams = new HashSet<>(); - generalMessageParams.add(rpaFirst); - generalMessageParams.add(rpaSecond); - generalMessageParams.add(rpaThird); - NumberedExpression rpaFifthWichIsNowForth = new NumberedExpression(4L, new MathExpression(highThroughputThreshold, megaSize, MathOperator.DIVIDE)); - generalMessageParams.add(rpaFifthWichIsNowForth); - rpaThroughputHigh.setGeneralMessageTemplateParams(generalMessageParams); - - WeightedCause cause = new WeightedCause(rpaThroughputHigh, 100); - return cause; - } - - private static WeightedCause buildCGCopyFF() { - Expression cgCopyName = new FieldExpression("AbstractRecoverPointConsistencyGroupCopy", "name"); - NumberedExpression cgCopyFirst = new NumberedExpression(1L, cgCopyName); - Set messageArgs1 = new HashSet<>(); - messageArgs1.add(cgCopyFirst); - - Condition fetchCondition = new SimpleCondition(new FieldExpression("CgCopyStatus", "nodeId"), - Operator.EQUALS, new FieldExpression("AbstractRecoverPointConsistencyGroupCopy", "id")); - Set fetchConditions = new HashSet<>(); - fetchConditions.add(fetchCondition); - - Condition condition = - new CompoundCondition( - new SimpleCondition(new FieldExpression("CgCopyStatus", "journalMode"), Operator.NOT_EQUALS, new ConstantExpression("null", MetadataFieldType.NULL)), - new SimpleCondition(new FieldExpression("CgCopyStatus", "journalMode"), Operator.EQUALS, new ConstantExpression("Fast Forward", MetadataFieldType.STRING)), - LogicalOperator.AND); - - Cause rpaFastForward = new Cause("High RPA throughput", "AbstractRecoverPointConsistencyGroupCopy", null, - fetchConditions, condition, "Cg Copy {param} has a high latency on writing to remote storage (Fast Forward)", DataManipulationFunction.EXISTS, - messageArgs1, null); - - WeightedCause cause = new WeightedCause(rpaFastForward, 80); - return cause; - } - - private static RCATemplate buildRPOViolationTemplate() { - Symptom symptom = new Symptom(CG_COPY_RPO_VIOLATION_SYMPTOM_NAME, "AnalysisAlert", - new CompoundCondition( - // todo - check state - not closed, currently don't bother - new SimpleCondition(new FieldExpression("AnalysisAlert", "message"), Operator.EQUALS, new ConstantExpression("RPO Violation", MetadataFieldType.STRING)), - new SimpleCondition(new FieldExpression("AnalysisAlert", "component"), Operator.CONTAINS, new ConstantExpression("CG Copy", MetadataFieldType.STRING)) - ) - ); - symptom.setFilterString("message = 'RPO Violation' AND component like '%CG Copy%'"); - symptom.setNodeTypeString("cg copies"); - symptom.setProcessTypeString("replications"); - - - WeightedCause cause1 = buildHighRPAThroughput(); - WeightedCause cause2 = buildCGCopyFF(); - WeightedCause cause3 = buildPacketLoss(); - - Set causes = new HashSet<>(); - causes.add(cause1); - causes.add(cause2); - causes.add(cause3); - - return new RCATemplate("CG copy RPO Violation template", symptom, causes); - } - - private static WeightedCause buildPacketLoss() { - - Expression packetLossSize = new FieldExpression("RpaPerfView", "packetLoss"); - NumberedExpression clientFirst = new NumberedExpression(1L, packetLossSize); - Set messageArgs1 = new HashSet<>(); - messageArgs1.add(clientFirst); - - Condition fetchCondition = new SimpleCondition(new FieldExpression("RpaPerfView", "nodeId"), - Operator.EQUALS, new FieldExpression("AbstractRecoverPointAppliance", "id")); - Set fetchConditions = new HashSet<>(); - fetchConditions.add(fetchCondition); - Condition condition = new SimpleCondition(new FieldExpression("RpaPerfView", "packetLoss"), Operator.GREATER_THAN, - new ConstantExpression("1", MetadataFieldType.NUMERIC)); - - Cause packetLoss = new Cause(PACKET_LOSS, "AbstractRecoverPointAppliance", MappingRelationType.RECOVERPOINT_CG_COPY_ACTIVE_RPA, - fetchConditions, condition, - "There is a bottleneck on the bandwidth. Found packet-loss ({param}) on the link.", DataManipulationFunction.EXISTS, - messageArgs1, null); - - packetLoss.setGeneralMessageTemplate("There is a bottleneck on the bandwidth. Found packet-loss (>1) on the link."); - - return new WeightedCause(packetLoss, 200); - } - - public static List getDefaultRCATemplates() { - return Arrays.asList(buildBackupFailedTemplate(), buildRPAHighLoadTemplate(), buildRPOViolationTemplate()); - } - - } + private PreparedStatementSpyConnectionProvider connectionProvider = new PreparedStatementSpyConnectionProvider(); + + @Override + protected Class[] getAnnotatedClasses() { + return new Class[]{ + WeightedCause.class, + TimeManipulation.class, + Symptom.class, + SimpleCondition.class, + RCATemplate.class, + ParameterExpression.class, + NumberedExpression.class, + MathExpression.class, + FieldExpression.class, + Expression.class, + ConstantExpression.class, + ConditionAndExpression.class, + ConditionalExpression.class, + Condition.class, + CompoundCondition.class, + Cause.class, + CalculationExpression.class, + AlertCondition.class, + BaseEntity.class + }; + } + + @Override + protected void addSettings(Map settings) { + settings.put(Environment.ORDER_INSERTS, "true"); + settings.put(Environment.ORDER_UPDATES, "true"); + settings.put(Environment.STATEMENT_BATCH_SIZE, "50"); + settings.put( + org.hibernate.cfg.AvailableSettings.CONNECTION_PROVIDER, + connectionProvider + ); + } + + @Override + public void releaseResources() { + super.releaseResources(); + connectionProvider.stop(); + } + + @Override + protected boolean rebuildSessionFactoryOnError() { + return false; + } + + @Test + public void testBatching() throws SQLException { + doInHibernate(this::sessionFactory, session -> { + connectionProvider.clear(); + for (RCATemplate template : DefaultTemplatesVault.getDefaultRCATemplates()) { + session.persist(template); + } + }); + } + + @Entity(name = "WeightedCause") + @Table(name = "rca_weighted_cause") + public static class WeightedCause extends BaseEntity { + private Cause cause; + private Integer weight; + + public WeightedCause() { + } + + public WeightedCause(Cause cause, Integer weight) { + this.cause = cause; + this.weight = weight; + } + + @OneToOne(cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.EAGER) + @JoinColumn(name = "cause_id") + public Cause getCause() { + return cause; + } + + public void setCause(Cause cause) { + this.cause = cause; + } + + public Integer getWeight() { + return weight; + } + + public void setWeight(Integer weight) { + this.weight = weight; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + if (!super.equals(o)) { + return false; + } + + WeightedCause cause1 = (WeightedCause) o; + + if (cause != null ? !cause.equals(cause1.cause) : cause1.cause != null) { + return false; + } + if (weight != null ? !weight.equals(cause1.weight) : cause1.weight != null) { + return false; + } + + return true; + } + + @Override + public int hashCode() { + int result = super.hashCode(); + result = 31 * result + (cause != null ? cause.hashCode() : 0); + result = 31 * result + (weight != null ? weight.hashCode() : 0); + return result; + } + } + @Entity(name = "TimeManipulation") + @Table(name = "rca_time_manipulation") + public static class TimeManipulation extends BaseEntity implements Serializable { + private ManipulationType type; + private MathOperator op; + private Long time; + private RelativeToType relativeToType; + private String paramName; + + public TimeManipulation() { + } + + public TimeManipulation(ManipulationType type, MathOperator op, Long time, RelativeToType relativeToType, String paramName) { + this.type = type; + this.op = op; + this.time = time; + this.relativeToType = relativeToType; + this.paramName = paramName; + } + + public ManipulationType getType() { + return type; + } + + public void setType(ManipulationType type) { + this.type = type; + } + + public MathOperator getOp() { + return op; + } + + public void setOp(MathOperator op) { + this.op = op; + } + + public Long getTime() { + return time; + } + + public void setTime(Long time) { + this.time = time; + } + + public RelativeToType getRelativeToType() { + return relativeToType; + } + + public void setRelativeToType(RelativeToType relativeToType) { + this.relativeToType = relativeToType; + } + + public String getParamName() { + return paramName; + } + + public void setParamName(String paramName) { + this.paramName = paramName; + } + } + @Entity(name = "Symptom") + @Table(name = "rca_symptom") + public static class Symptom extends BaseEntity implements Serializable { + private String name; + private String objectType; + private Condition condition; + private String nodeTypeString; + private String processTypeString; + private String filterString; + + public Symptom() { + } + + public Symptom(String name, String objectType, Condition condition) { + this.name = name; + this.objectType = objectType; + this.condition = condition; + } + + public String getObjectType() { + return objectType; + } + + public void setObjectType(String objectType) { + this.objectType = objectType; + } + + @OneToOne(cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.EAGER) + @JoinColumn(name = "condition_id") + public Condition getCondition() { + return condition; + } + + public void setCondition(Condition condition) { + this.condition = condition; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getNodeTypeString() { + return nodeTypeString; + } + + public void setNodeTypeString(String nodeTypeString) { + this.nodeTypeString = nodeTypeString; + } + + public String getProcessTypeString() { + return processTypeString; + } + + public void setProcessTypeString(String processTypeString) { + this.processTypeString = processTypeString; + } + + public String getFilterString() { + return filterString; + } + + public void setFilterString(String filterString) { + this.filterString = filterString; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + if (!super.equals(o)) { + return false; + } + + Symptom symptom = (Symptom) o; + + if (condition != null ? !condition.equals(symptom.condition) : symptom.condition != null) { + return false; + } + if (name != null ? !name.equals(symptom.name) : symptom.name != null) { + return false; + } + if (objectType != null ? !objectType.equals(symptom.objectType) : symptom.objectType != null) { + return false; + } + + return true; + } + + @Override + public int hashCode() { + int result = super.hashCode(); + result = 31 * result + (name != null ? name.hashCode() : 0); + result = 31 * result + (objectType != null ? objectType.hashCode() : 0); + result = 31 * result + (condition != null ? condition.hashCode() : 0); + return result; + } + } + @Entity(name = "SimpleCondition") + public static class SimpleCondition extends Condition { + private Expression left; + private Operator op; + private Expression right; + + public SimpleCondition() { + } + + public SimpleCondition(Expression left, Operator op, Expression right) { + this.left = left; + this.op = op; + this.right = right; + } + + @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER) + @JoinColumn(name = "left_expression_id") + public Expression getLeft() { + return left; + } + + public void setLeft(Expression left) { + this.left = left; + } + + public Operator getOp() { + return op; + } + + public void setOp(Operator op) { + this.op = op; + } + + @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER) + @JoinColumn(name = "right_expression_id") + public Expression getRight() { + return right; + } + + public void setRight(Expression right) { + this.right = right; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + if (!super.equals(o)) { + return false; + } + + SimpleCondition that = (SimpleCondition) o; + + if (left != null ? !left.equals(that.left) : that.left != null) { + return false; + } + if (op != that.op) { + return false; + } + if (right != null ? !right.equals(that.right) : that.right != null) { + return false; + } + + return true; + } + + @Override + public int hashCode() { + int result = super.hashCode(); + result = 31 * result + (left != null ? left.hashCode() : 0); + result = 31 * result + (op != null ? op.hashCode() : 0); + result = 31 * result + (right != null ? right.hashCode() : 0); + return result; + } + } + @Entity(name = "RCATemplate") + public static class RCATemplate extends BaseEntity { + private String name; + private Symptom symptom; + private Set possibleCauses; + + public RCATemplate() { + } + + public RCATemplate(String name, Symptom symptom, Set possibleCauses) { + this.name = name; + this.symptom = symptom; + this.possibleCauses = possibleCauses; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @OneToOne(cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.EAGER) + @JoinColumn(name = "symptom_id") + public Symptom getSymptom() { + return symptom; + + } + + public void setSymptom(Symptom symptom) { + this.symptom = symptom; + } + + @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER) + @JoinTable(name = "template_cause", joinColumns = { + @JoinColumn(name = "f_template_id")}, inverseJoinColumns = { + @JoinColumn(name = "f_cause_id")}) + public Set getPossibleCauses() { + return possibleCauses; + } + + public void setPossibleCauses(Set possibleCauses) { + this.possibleCauses = possibleCauses; + } + + } + @Entity(name = "ParameterExpression") + public static class ParameterExpression extends Expression { + private String parameterName; + private String defaultValue; + + + public ParameterExpression() { + } + + public ParameterExpression(String parameterName, String defaultValue, MetadataFieldType type) { + this.parameterName = parameterName; + this.defaultValue = defaultValue; + this.type = type; + } + + public String getParameterName() { + return parameterName; + } + + public void setParameterName(String parameterName) { + this.parameterName = parameterName; + } + + public String getDefaultValue() { + return defaultValue; + } + + public void setDefaultValue(String defaultValue) { + this.defaultValue = defaultValue; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + if (!super.equals(o)) { + return false; + } + + ParameterExpression that = (ParameterExpression) o; + + if (defaultValue != null ? !defaultValue.equals(that.defaultValue) : that.defaultValue != null) { + return false; + } + if (parameterName != null ? !parameterName.equals(that.parameterName) : that.parameterName != null) { + return false; + } + + return true; + } + + @Override + public int hashCode() { + int result = super.hashCode(); + result = 31 * result + (parameterName != null ? parameterName.hashCode() : 0); + result = 31 * result + (defaultValue != null ? defaultValue.hashCode() : 0); + return result; + } + } + @Entity(name = "NumberedExpression") + @Table(name = "rca_numbered_exception") + public static class NumberedExpression extends BaseEntity implements Comparable { + private Long num; + private Expression expression; + + public NumberedExpression() { + } + + public NumberedExpression(Long num, Expression expression) { + this.num = num; + this.expression = expression; + } + + public Long getNum() { + return num; + } + + public void setNum(Long num) { + this.num = num; + } + + @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER) + @JoinColumn(name = "num_expression_id") + public Expression getExpression() { + return expression; + } + + public void setExpression(Expression expression) { + this.expression = expression; + } + + @Override + public int compareTo(Object o) { + NumberedExpression other = (NumberedExpression) o; + return (int) (this.num - other.num); + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + if (!super.equals(o)) { + return false; + } + + NumberedExpression that = (NumberedExpression) o; + + if (expression != null ? !expression.equals(that.expression) : that.expression != null) { + return false; + } + if (num != null ? !num.equals(that.num) : that.num != null) { + return false; + } + + return true; + } + + @Override + public int hashCode() { + int result = super.hashCode(); + result = 31 * result + (num != null ? num.hashCode() : 0); + result = 31 * result + (expression != null ? expression.hashCode() : 0); + return result; + } + } + @Entity(name = "MathExpression") + public static class MathExpression extends Expression { + private Expression left; + private Expression right; + private MathOperator op; + + public MathExpression() { + } + + public MathExpression(Expression left, Expression right, MathOperator op) { + this.left = left; + this.right = right; + this.op = op; + } + + @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER) + @JoinColumn(name = "left_expression_id") + public Expression getLeft() { + return left; + } + + public void setLeft(Expression left) { + this.left = left; + } + + @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER) + @JoinColumn(name = "right_expression_id") + public Expression getRight() { + return right; + } + + public void setRight(Expression right) { + this.right = right; + } + + public MathOperator getOp() { + return op; + } + + public void setOp(MathOperator op) { + this.op = op; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + if (!super.equals(o)) { + return false; + } + + MathExpression that = (MathExpression) o; + + if (left != null ? !left.equals(that.left) : that.left != null) { + return false; + } + if (op != that.op) { + return false; + } + if (right != null ? !right.equals(that.right) : that.right != null) { + return false; + } + + return true; + } + + @Override + public int hashCode() { + int result = super.hashCode(); + result = 31 * result + (left != null ? left.hashCode() : 0); + result = 31 * result + (right != null ? right.hashCode() : 0); + result = 31 * result + (op != null ? op.hashCode() : 0); + return result; + } + } + @Entity(name = "FieldExpression") + public static class FieldExpression extends Expression { + private String objectType; + private String name; + + public FieldExpression() { + } + + public FieldExpression(String objectType, String name) { + this.objectType = objectType; + this.name = name; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getObjectType() { + return objectType; + } + + public void setObjectType(String objectType) { + this.objectType = objectType; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + if (!super.equals(o)) { + return false; + } + + FieldExpression that = (FieldExpression) o; + + if (name != null ? !name.equals(that.name) : that.name != null) { + return false; + } + if (objectType != null ? !objectType.equals(that.objectType) : that.objectType != null) { + return false; + } + + return true; + } + + @Override + public int hashCode() { + int result = super.hashCode(); + result = 31 * result + (objectType != null ? objectType.hashCode() : 0); + result = 31 * result + (name != null ? name.hashCode() : 0); + return result; + } + } + @Entity(name = "Expression") + @Table(name = "rca_expression") + public static abstract class Expression extends BaseEntity implements Serializable { + protected MetadataFieldType type; + + protected Expression() { + } + + protected Expression(MetadataFieldType type) { + this.type = type; + } + + public MetadataFieldType getType() { + return type; + } + + public void setType(MetadataFieldType type) { + this.type = type; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + if (!super.equals(o)) { + return false; + } + + Expression that = (Expression) o; + + if (type != that.type) { + return false; + } + + return true; + } + + @Override + public int hashCode() { + int result = super.hashCode(); + result = 31 * result + (type != null ? type.hashCode() : 0); + return result; + } + } + @Entity(name = "ConstantExpression") + public static class ConstantExpression extends Expression { + private String value; + + public ConstantExpression() { + } + + public ConstantExpression(String value, MetadataFieldType type) { + super(type); + this.value = value; + } + + @Column(name = "val") + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + if (!super.equals(o)) { + return false; + } + + ConstantExpression that = (ConstantExpression) o; + + if (value != null ? !value.equals(that.value) : that.value != null) { + return false; + } + + return true; + } + + @Override + public int hashCode() { + int result = super.hashCode(); + result = 31 * result + (value != null ? value.hashCode() : 0); + return result; + } + } + @Entity(name = "ConditionAndExpression") + @Table(name = "rca_cond_and_expr") + public static class ConditionAndExpression extends BaseEntity { + private Condition condition; + private Expression expression; + + public ConditionAndExpression() { + } + + public ConditionAndExpression(Condition condition, Expression expression) { + this.condition = condition; + this.expression = expression; + } + + @OneToOne(cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.EAGER) + @JoinColumn(name = "cond_cond_id") + public Condition getCondition() { + return condition; + } + + public void setCondition(Condition condition) { + this.condition = condition; + } + + @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER) + @JoinColumn(name = "cond_expression_id") + public Expression getExpression() { + return expression; + } + + public void setExpression(Expression expression) { + this.expression = expression; + } + } + @Entity(name = "ConditionalExpression") + public static class ConditionalExpression extends Expression { + private Set possibilities; + + public ConditionalExpression() { + } + + public ConditionalExpression(MetadataFieldType type, Set possibilities) { + super(type); + this.possibilities = possibilities; + } + + @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER) + @JoinTable(name = "rca_cond_posssibility", joinColumns = { + @JoinColumn(name = "f_cond_id")}, inverseJoinColumns = { + @JoinColumn(name = "f_pos_id")}) + public Set getPossibilities() { + return possibilities; + } + + public void setPossibilities(Set possibilities) { + this.possibilities = possibilities; + } + } + @Entity(name = "Condition") + @Table(name = "rca_condition") + public static abstract class Condition extends BaseEntity implements Serializable { + } + @Entity(name = "CompoundCondition") + public static class CompoundCondition extends Condition { + private Condition first; + private Condition second; + private LogicalOperator op; + + public CompoundCondition() { + } + + public CompoundCondition(Condition first, Condition second) { + this.first = first; + this.second = second; + this.op = LogicalOperator.AND; + } + + public CompoundCondition(Condition first, Condition second, LogicalOperator op) { + this.first = first; + this.second = second; + this.op = op; + } + + @OneToOne(cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.EAGER) + @JoinColumn(name = "first_id") + public Condition getFirst() { + return first; + } + + public void setFirst(Condition first) { + this.first = first; + } + + @OneToOne(cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.EAGER) + @JoinColumn(name = "second_id") + public Condition getSecond() { + return second; + } + + public void setSecond(Condition second) { + this.second = second; + } + + public LogicalOperator getOp() { + return op; + } + + public void setOp(LogicalOperator op) { + this.op = op; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + if (!super.equals(o)) { + return false; + } + + CompoundCondition that = (CompoundCondition) o; + + if (first != null ? !first.equals(that.first) : that.first != null) { + return false; + } + if (op != that.op) { + return false; + } + if (second != null ? !second.equals(that.second) : that.second != null) { + return false; + } + + return true; + } + + @Override + public int hashCode() { + int result = super.hashCode(); + result = 31 * result + (first != null ? first.hashCode() : 0); + result = 31 * result + (second != null ? second.hashCode() : 0); + result = 31 * result + (op != null ? op.hashCode() : 0); + return result; + } + } + @Entity + @Table(name = "rca_cause") + public static class Cause extends BaseEntity implements Serializable { + private String name; + private String nodeType; + private MappingRelationType relationType; + private Set fetchConditions; + private Condition condition; + private Condition auxCondition; + private String messageTemplate; + private String generalMessageTemplate; + private DataManipulationFunction function; + private Set messageTemplateParams; + private Set generalMessageTemplateParams; + private TimeManipulation startTimeManipulation; + private TimeManipulation endTimeManipulation; + private String plugin; + + public Cause() { + } + + public Cause(String name, String nodeType, MappingRelationType relationType, Set fetchConditions, + Condition condition, String messageTemplate, DataManipulationFunction function, Set messageTemplateParams, String plugin) { + this.name = name; + this.nodeType = nodeType; + this.relationType = relationType; + this.fetchConditions = fetchConditions; + this.condition = condition; + this.messageTemplate = messageTemplate; + this.function = function; + this.messageTemplateParams = messageTemplateParams; + this.plugin = plugin; + } + + public String getNodeType() { + return nodeType; + } + + public void setNodeType(String nodeType) { + this.nodeType = nodeType; + } + + public String getPlugin() { + return plugin; + } + + public void setPlugin(String plugin) { + this.plugin = plugin; + } + + @OneToOne(cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.EAGER) + @JoinColumn(name = "condition_id") + public Condition getCondition() { + return condition; + } + + public void setCondition(Condition condition) { + this.condition = condition; + } + + @OneToOne(cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.EAGER) + @JoinColumn(name = "aux_condition_id") + public Condition getAuxCondition() { + return auxCondition; + } + + public void setAuxCondition(Condition auxCondition) { + this.auxCondition = auxCondition; + } + + public String getMessageTemplate() { + return messageTemplate; + } + + public void setMessageTemplate(String messageTemplate) { + this.messageTemplate = messageTemplate; + } + + public String getGeneralMessageTemplate() { + return generalMessageTemplate; + } + + public void setGeneralMessageTemplate(String generalMessageTemplate) { + this.generalMessageTemplate = generalMessageTemplate; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @Column(name = "functionName") + public DataManipulationFunction getFunction() { + return function; + } + + public void setFunction(DataManipulationFunction function) { + this.function = function; + } + + public MappingRelationType getRelationType() { + return relationType; + } + + public void setRelationType(MappingRelationType relationType) { + this.relationType = relationType; + } + + @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER) + @JoinTable(name = "rca_cause_param", joinColumns = { + @JoinColumn(name = "f_cause_id")}, inverseJoinColumns = { + @JoinColumn(name = "f_param_id")}) + public Set getMessageTemplateParams() { + return messageTemplateParams; + } + + public void setMessageTemplateParams(Set messageTemplateParams) { + this.messageTemplateParams = messageTemplateParams; + } + + @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER) + @JoinTable(name = "rca_cause_general_param", joinColumns = { + @JoinColumn(name = "f_cause_id")}, inverseJoinColumns = { + @JoinColumn(name = "f_param_id")}) + public Set getGeneralMessageTemplateParams() { + return generalMessageTemplateParams; + } + + public void setGeneralMessageTemplateParams(Set generalMessageTemplateParams) { + this.generalMessageTemplateParams = generalMessageTemplateParams; + } + + @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER) + @JoinTable(name = "rca_cause_fetch", joinColumns = { + @JoinColumn(name = "f_cause_id")}, inverseJoinColumns = { + @JoinColumn(name = "f_fetch_id")}) + public Set getFetchConditions() { + return fetchConditions; + } + + public void setFetchConditions(Set fetchConditions) { + this.fetchConditions = fetchConditions; + } + + @OneToOne(cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.EAGER) + @JoinColumn(name = "start_time_manip_id") + public TimeManipulation getStartTimeManipulation() { + return startTimeManipulation; + } + + public void setStartTimeManipulation(TimeManipulation startTimeManipulation) { + this.startTimeManipulation = startTimeManipulation; + } + + @OneToOne(cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.EAGER) + @JoinColumn(name = "end_time_manip_id") + public TimeManipulation getEndTimeManipulation() { + return endTimeManipulation; + } + + public void setEndTimeManipulation(TimeManipulation endTimeManipulation) { + this.endTimeManipulation = endTimeManipulation; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + if (!super.equals(o)) { + return false; + } + + Cause cause = (Cause) o; + + if (function != cause.function) { + return false; + } + if (messageTemplate != null ? !messageTemplate.equals(cause.messageTemplate) : cause.messageTemplate != null) { + return false; + } + if (name != null ? !name.equals(cause.name) : cause.name != null) { + return false; + } + if (nodeType != null ? !nodeType.equals(cause.nodeType) : cause.nodeType != null) { + return false; + } + if (relationType != cause.relationType) { + return false; + } + + return true; + } + + @Override + public int hashCode() { + int result = super.hashCode(); + result = 31 * result + (name != null ? name.hashCode() : 0); + result = 31 * result + (nodeType != null ? nodeType.hashCode() : 0); + result = 31 * result + (relationType != null ? relationType.hashCode() : 0); + result = 31 * result + (messageTemplate != null ? messageTemplate.hashCode() : 0); + result = 31 * result + (function != null ? function.hashCode() : 0); + return result; + } + } + @Entity(name = "CalculationExpression") + public static class CalculationExpression extends Expression { + private DataManipulationFunction function; + private String objectType; + private String fieldName; + + public CalculationExpression() { + } + + public CalculationExpression(DataManipulationFunction function, String objectType, String fieldName) { + this.function = function; + this.objectType = objectType; + this.fieldName = fieldName; + } + + @Column(name = "functionName") + public DataManipulationFunction getFunction() { + return function; + } + + public void setFunction(DataManipulationFunction function) { + this.function = function; + } + + public String getObjectType() { + return objectType; + } + + public void setObjectType(String objectType) { + this.objectType = objectType; + } + + public String getFieldName() { + return fieldName; + } + + public void setFieldName(String fieldName) { + this.fieldName = fieldName; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + if (!super.equals(o)) { + return false; + } + + CalculationExpression that = (CalculationExpression) o; + + if (fieldName != null ? !fieldName.equals(that.fieldName) : that.fieldName != null) { + return false; + } + if (function != that.function) { + return false; + } + if (objectType != null ? !objectType.equals(that.objectType) : that.objectType != null) { + return false; + } + + return true; + } + + @Override + public int hashCode() { + int result = super.hashCode(); + result = 31 * result + (function != null ? function.hashCode() : 0); + result = 31 * result + (objectType != null ? objectType.hashCode() : 0); + result = 31 * result + (fieldName != null ? fieldName.hashCode() : 0); + return result; + } + } + @Entity(name = "AlertCondition") + public static class AlertCondition extends Condition { + private String ruleName; + + public AlertCondition() { + } + + public String getRuleName() { + return ruleName; + } + + public void setRuleName(String ruleName) { + this.ruleName = ruleName; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + if (!super.equals(o)) { + return false; + } + + AlertCondition that = (AlertCondition) o; + + if (ruleName != null ? !ruleName.equals(that.ruleName) : that.ruleName != null) { + return false; + } + + return true; + } + + @Override + public int hashCode() { + int result = super.hashCode(); + result = 31 * result + (ruleName != null ? ruleName.hashCode() : 0); + return result; + } + } + @MappedSuperclass + public static abstract class BaseEntity implements Serializable { + private Long id; + + @Id + @Column(name = "f_id") + @GeneratedValue + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + + BaseEntity that = (BaseEntity) o; + + // noinspection SimplifiableIfStatement + if (id == null || that.id == null) { + return false; // null != everything (including null) + } + return id.equals(that.id); + } + + @Override + public int hashCode() { + return id != null ? id.hashCode() : 0; + } + + } + + public enum RelativeToType { + START, + END + } + + public enum Operator { + EQUALS(" = "), + NOT_EQUALS(" != "), + GREATER_THAN(" > "), + SMALLER_THAN(" < "), + CONTAINS(" contains "), + BEGINS_WITH(" begins with "), + ENDS_WITH(" ends with "); + + private String readable; + + private Operator(String readable) { + this.readable = readable; + } + + @Override + public String toString() { + return readable; + } + } + + public enum MathOperator { + ADD, + SUBTRACT, + MULTIPLY, + DIVIDE, + MAX; + + @Override + public String toString() { + switch (this) { + case ADD: + return "+"; + case SUBTRACT: + return "-"; + case MULTIPLY: + return "*"; + case DIVIDE: + return "/"; + case MAX: + return "max"; + } + return null; + } + + + } + + public enum ManipulationType { + MOVE_IT_BY_ABSOLUTE_TIME, + MOVE_IT_RELATIVE_TO_OTHER_TIME, + ABSOLUTE + } + + public enum LogicalOperator { + AND, + OR + } + + public enum MetadataFieldType { + BOOLEAN, STRING, NULL, NUMERIC + } + + public enum DataManipulationFunction { + AVG, + MAX, + MIN, + COUNT, + SUM, + EXISTS, + LAST, + FIRST, + INCREASED_BY + } + + public enum MappingRelationType { + JOB_BACKING_UP_HOST, JOB_USES_BACKUPCLIENT, JOB_USES_BACKUP_POOL, JOB_USES_MEDIA_SERVER, RECOVERPOINT_CG_COPY_ACTIVE_RPA, JOB_USES_TAPE_DRIVE + } + + public static class DefaultTemplatesVault { + + public static final String NO_AGENT_RAN_ON_CLIENT = "No agent ran on client"; + public static final String BACKUP_AGENT_IS_DOWN_ON_BACKUP_CLIENT = "Backup agent is down on backup client"; + public static final String BACKUP_FAILED_SYMPTOM_NAME = "Backup failed"; + public static final String CG_COPY_RPO_VIOLATION_SYMPTOM_NAME = "CG Copy RPO Violation"; + public static final String PACKET_LOSS = "Packet Loss"; + + private static RCATemplate buildBackupFailedTemplate() { + Symptom symptom = new Symptom(BACKUP_FAILED_SYMPTOM_NAME, "Backupjob", + new SimpleCondition(new FieldExpression("Backupjob", "status"), Operator.EQUALS, new ConstantExpression("failed", MetadataFieldType.STRING))); + symptom.setFilterString("status = 'failed'"); + symptom.setNodeTypeString("clients"); + symptom.setProcessTypeString("backup jobs"); + + // high client cpu ' + WeightedCause cause1 = buildHighClientCpu(); + + // high storage node cpu + WeightedCause cause2 = buildHighStorageNodeCpu(); + + // no space left on device + WeightedCause cause3 = buildNoSpaceOnPool(); + + // no space left on data domain + WeightedCause cause4 = buildNoSpaceOnDD(); + + // no agent ran on client + WeightedCause cause5 = buildNoAgentOnClient(); + + // no agent ran on client + WeightedCause cause6 = buildNoAgentOnClient2(); + + // errors on tape + WeightedCause errorsOnTapeCause = buildErrorsOnTape(); + + // switch port for ethernet + WeightedCause cause7 = buildPortSwitchForEthernet(); + + // switch port for fibre channel + WeightedCause cause8 = buildPortSwitchForFibreChannel(); + + // port settings for ethernet + WeightedCause cause9 = buildDifferentPortSettings(); + + // no space on client + WeightedCause noSpaceOnClientCause = buildNoSpaceOnClient(); + + // todo -all other causes + Set causes = new HashSet<>(); + causes.add(cause1); + causes.add(cause2); + causes.add(cause3); + causes.add(cause4); + causes.add(cause5); + causes.add(cause6); + //causes.add(errorsOnTapeCause); + causes.add(cause7); + causes.add(cause8); + causes.add(cause9); + causes.add(noSpaceOnClientCause); + return new RCATemplate("Backup failed RCA template", symptom, causes); + } + + private static WeightedCause buildNoSpaceOnClient() { + Expression clientName = new FieldExpression("Host", "name"); + NumberedExpression nameFirst = new NumberedExpression(1L, clientName); + + Expression mountpointName = new FieldExpression("FilesystemConfig", "mountpoint"); + NumberedExpression mountpointSecond = new NumberedExpression(2L, mountpointName); + + Expression leftSpace = new MathExpression(new FieldExpression("FilesystemConfig", "totalSpace"), + new FieldExpression("FilesystemStatus", "usedSpace"), + MathOperator.SUBTRACT); + ParameterExpression leftSpaceOnClient = new ParameterExpression("leftSpaceOnClient", "50", MetadataFieldType.NUMERIC); + NumberedExpression spaceThird = new NumberedExpression(3L, leftSpace); + + + Set messageArgs = new HashSet<>(); + messageArgs.add(nameFirst); + messageArgs.add(mountpointSecond); + messageArgs.add(spaceThird); + + Condition fetchCondition1 = new CompoundCondition( + new SimpleCondition(new FieldExpression("FilesystemStatus", "mountpoint"), Operator.EQUALS, new ConstantExpression("C:", MetadataFieldType.STRING)), + new SimpleCondition(new FieldExpression("FilesystemStatus", "agentId"), Operator.EQUALS, new FieldExpression("Host", "id")) + ); + Condition fetchCondition2 = new CompoundCondition( + new SimpleCondition(new FieldExpression("FilesystemConfig", "mountpoint"), Operator.EQUALS, new ConstantExpression("C:", MetadataFieldType.STRING)), + new SimpleCondition(new FieldExpression("FilesystemConfig", "agentId"), Operator.EQUALS, new FieldExpression("Host", "id")) + ); + + Set fetchConditions = new HashSet<>(); + fetchConditions.add(fetchCondition1); + fetchConditions.add(fetchCondition2); + + SimpleCondition condition = new SimpleCondition(leftSpace, Operator.SMALLER_THAN, leftSpaceOnClient); + + Cause noSpaceOnClient = new Cause("No space on Client", "Host", MappingRelationType.JOB_BACKING_UP_HOST, + fetchConditions, condition, "There is a lack of free space in {param}:{param}. The current free space is {param} MB", DataManipulationFunction.LAST, messageArgs, null); + + return new WeightedCause(noSpaceOnClient, 95); + } + + private static WeightedCause buildErrorsOnTape() { + + Expression tapeDriveNameExp = new FieldExpression("TapeDrive", "name"); + NumberedExpression tapeDriveName = new NumberedExpression(1L, tapeDriveNameExp); + + Expression errorsExp = new FieldExpression("TapedriveStatus", "correctedReadErrors"); + + Set messageArgs = new HashSet<>(); + messageArgs.add(tapeDriveName); + + Condition fetchCondition = new SimpleCondition(new FieldExpression("TapedriveStatus", "nodeId"), + Operator.EQUALS, new FieldExpression("TapeDrive", "id")); + Set fetchConditions = new HashSet<>(); + fetchConditions.add(fetchCondition); + + ConstantExpression zero = new ConstantExpression("0", MetadataFieldType.NUMERIC); + + Cause errorsOnTape = new Cause("Errors on tape", "TapeDrive", MappingRelationType.JOB_USES_TAPE_DRIVE, fetchConditions, + new CompoundCondition( + new CompoundCondition( + new CompoundCondition( + new SimpleCondition(new FieldExpression("TapedriveStatus", "correctedReadErrors"), Operator.GREATER_THAN, zero), + new SimpleCondition(new FieldExpression("TapedriveStatus", "correctedWriteErrors"), Operator.GREATER_THAN, zero), + LogicalOperator.OR), + new SimpleCondition(new FieldExpression("TapedriveStatus", "uncorrectedReadErrors"), Operator.GREATER_THAN, zero), + LogicalOperator.OR), + new SimpleCondition(new FieldExpression("TapedriveStatus", "uncorrectedWriteErrors"), Operator.GREATER_THAN, zero), + LogicalOperator.OR), + "Tape drive {param} had errors", DataManipulationFunction.INCREASED_BY, messageArgs, null); + return new WeightedCause(errorsOnTape, 70); + } + + private static WeightedCause buildNoSpaceOnDD() { + Expression ddName = new FieldExpression("DataDomain", "name"); + NumberedExpression ddFirst = new NumberedExpression(1L, ddName); + + + Expression ddUsage = new MathExpression(new MathExpression( + new FieldExpression("FilesystemStatus", "usedSpace"), + new FieldExpression("FilesystemConfig", "totalSpace"), + MathOperator.DIVIDE + ), + new ConstantExpression("100", MetadataFieldType.NUMERIC), MathOperator.MULTIPLY); + NumberedExpression ddSecond = new NumberedExpression(2L, ddUsage); + ParameterExpression ddUsageThreshold = new ParameterExpression("ddUsageThreshold", "80", MetadataFieldType.NUMERIC); + NumberedExpression ddThird = new NumberedExpression(3L, ddUsageThreshold); + Set messageArgs4 = new HashSet<>(); + messageArgs4.add(ddFirst); + messageArgs4.add(ddSecond); + messageArgs4.add(ddThird); + + Condition fetchCondition4 = new CompoundCondition( + new SimpleCondition(new FieldExpression("FilesystemStatus", "mountpoint"), Operator.EQUALS, new ConstantExpression("Data", MetadataFieldType.STRING)), + new SimpleCondition(new FieldExpression("FilesystemStatus", "agentId"), Operator.EQUALS, new FieldExpression("DataDomain", "id")) + ); + Condition fetchCondition5 = new CompoundCondition( + new SimpleCondition(new FieldExpression("FilesystemConfig", "mountpoint"), Operator.EQUALS, new ConstantExpression("Data", MetadataFieldType.STRING)), + new SimpleCondition(new FieldExpression("FilesystemConfig", "agentId"), Operator.EQUALS, new FieldExpression("DataDomain", "id")) + ); + Set fetchConditions4 = new HashSet<>(); + fetchConditions4.add(fetchCondition4); + fetchConditions4.add(fetchCondition5); + + Cause noSpaceOnDD = new Cause("No space on data domain", "DataDomain", MappingRelationType.JOB_USES_BACKUPCLIENT, + fetchConditions4, new SimpleCondition(ddUsage, Operator.GREATER_THAN, ddUsageThreshold), + "The capacity utilization for DataDomain {param} is {param}% which is the above threshold {param}%", DataManipulationFunction.LAST, messageArgs4, null); + + noSpaceOnDD.setGeneralMessageTemplate("The capacity utilization for DataDomain {param} is the above threshold {param}%"); + + Set generalMessageParams = new HashSet<>(); + generalMessageParams.add(ddFirst); + NumberedExpression ddThirdWhichIsNowSecond = new NumberedExpression(2L, new ParameterExpression("ddUsageThreshold", "80", MetadataFieldType.NUMERIC)); + generalMessageParams.add(ddThirdWhichIsNowSecond); + noSpaceOnDD.setGeneralMessageTemplateParams(generalMessageParams); + + return new WeightedCause(noSpaceOnDD, 90); + } + + private static WeightedCause buildNoSpaceOnPool() { + Expression poolName = new FieldExpression("BackupPool", "name"); + NumberedExpression deviceFirst = new NumberedExpression(1L, poolName); + Expression numOfEmptyVolumes = new CalculationExpression(DataManipulationFunction.COUNT, "VolumeStatus", "id"); + NumberedExpression deviceSecond = new NumberedExpression(2L, numOfEmptyVolumes); + Set messageArgs3 = new HashSet<>(); + messageArgs3.add(deviceFirst); + messageArgs3.add(deviceSecond); + + Condition fetchCondition3 = new CompoundCondition( + new SimpleCondition(new FieldExpression("VolumeStatus", "pool"), Operator.EQUALS, new FieldExpression("BackupPool", "name")), + new SimpleCondition(new FieldExpression("VolumeStatus", "agentId"), Operator.EQUALS, new FieldExpression("Backupjob", "agentId")) + ); + Set fetchConditions3 = new HashSet<>(); + fetchConditions3.add(fetchCondition3); + + ConstantExpression threshold = new ConstantExpression("5", MetadataFieldType.NUMERIC); + Cause noSpaceOnDevice = new Cause("No space left on device", "BackupPool", MappingRelationType.JOB_USES_BACKUP_POOL, + fetchConditions3, + new SimpleCondition( + new FieldExpression("VolumeStatus", "state"), + Operator.SMALLER_THAN, + threshold), + "Pool {param} has only {param} empty volumes left", DataManipulationFunction.COUNT, messageArgs3, null); + noSpaceOnDevice.setAuxCondition(new SimpleCondition(new FieldExpression("VolumeStatus", "state"), + Operator.EQUALS, new ConstantExpression("Empty", MetadataFieldType.STRING))); + + noSpaceOnDevice.setGeneralMessageTemplate("Pool {param} has less than {param} empty volumes left"); + Set generalMessageParams = new HashSet<>(); + generalMessageParams.add(deviceFirst); + generalMessageParams.add(new NumberedExpression(2L, threshold)); + noSpaceOnDevice.setGeneralMessageTemplateParams(generalMessageParams); + + return new WeightedCause(noSpaceOnDevice, 80); + } + + private static WeightedCause buildHighStorageNodeCpu() { + Expression storageName = new FieldExpression("Host", "name"); + NumberedExpression storageFirst = new NumberedExpression(1L, storageName); + Expression avgCpuStorage = new CalculationExpression(DataManipulationFunction.AVG, "HostStatus", "cpuUsed"); + NumberedExpression storageSecond = new NumberedExpression(2L, avgCpuStorage); + Set messageArgs2 = new HashSet<>(); + messageArgs2.add(storageFirst); + messageArgs2.add(storageSecond); + + Condition fetchCondition2 = new SimpleCondition(new FieldExpression("HostStatus", "nodeId"), + Operator.EQUALS, new FieldExpression("Host", "id")); + Set fetchConditions2 = new HashSet<>(); + fetchConditions2.add(fetchCondition2); + + ParameterExpression storageNodeHighCPUThreshold = new ParameterExpression("storageNodeHighCPUThreshold", "95", MetadataFieldType.NUMERIC); + Cause highCpuOnStorageNode = new Cause("High storage node CPU", "Host", MappingRelationType.JOB_USES_MEDIA_SERVER, + fetchConditions2, + new SimpleCondition(new FieldExpression("HostStatus", "cpuUsed"), Operator.GREATER_THAN, + storageNodeHighCPUThreshold), "Storage node {param} CPU was {param}", DataManipulationFunction.AVG, + messageArgs2, null); + TimeManipulation startTimeManipulation = new TimeManipulation(ManipulationType.MOVE_IT_RELATIVE_TO_OTHER_TIME, + MathOperator.SUBTRACT, 3600L, RelativeToType.END, "job_cpu_offset"); + highCpuOnStorageNode.setStartTimeManipulation(startTimeManipulation); + + highCpuOnStorageNode.setGeneralMessageTemplate("Storage node {param} CPU was higher than {param}"); + Set generalMessageParams = new HashSet<>(); + generalMessageParams.add(storageFirst); + generalMessageParams.add(new NumberedExpression(2L, storageNodeHighCPUThreshold)); + highCpuOnStorageNode.setGeneralMessageTemplateParams(generalMessageParams); + + return new WeightedCause(highCpuOnStorageNode, 60); + } + + private static WeightedCause buildHighClientCpu() { + Expression clientName = new FieldExpression("Host", "name"); + NumberedExpression clientFirst = new NumberedExpression(1L, clientName); + Expression avgCpu = new CalculationExpression(DataManipulationFunction.AVG, "HostStatus", "cpuUsed"); + NumberedExpression clientSecond = new NumberedExpression(2L, avgCpu); + Set messageArgs1 = new HashSet<>(); + messageArgs1.add(clientFirst); + messageArgs1.add(clientSecond); + + Condition fetchCondition = new SimpleCondition(new FieldExpression("HostStatus", "nodeId"), + Operator.EQUALS, new FieldExpression("Host", "id")); + Set fetchConditions = new HashSet<>(); + fetchConditions.add(fetchCondition); + + + ParameterExpression clientHighCPUThreshold = new ParameterExpression("clientHighCPUThreshold", "95", MetadataFieldType.NUMERIC); + Cause highCpuOnClient = new Cause("High client CPU", "Host", MappingRelationType.JOB_BACKING_UP_HOST, + new HashSet<>(fetchConditions), + new SimpleCondition(new FieldExpression("HostStatus", "cpuUsed"), Operator.GREATER_THAN, + clientHighCPUThreshold), "Client {param} CPU was {param}", DataManipulationFunction.AVG, + messageArgs1, null); + + TimeManipulation startTimeManipulation = new TimeManipulation(ManipulationType.MOVE_IT_RELATIVE_TO_OTHER_TIME, + MathOperator.SUBTRACT, 3600L, RelativeToType.END, "job_cpu_offset"); + highCpuOnClient.setStartTimeManipulation(startTimeManipulation); + + highCpuOnClient.setGeneralMessageTemplate("Client {param} CPU was higher than {param}"); + Set generalMessageParams = new HashSet<>(); + generalMessageParams.add(clientFirst); + generalMessageParams.add(new NumberedExpression(2L, clientHighCPUThreshold)); + highCpuOnClient.setGeneralMessageTemplateParams(generalMessageParams); + + return new WeightedCause(highCpuOnClient, 50); + } + + private static WeightedCause buildNoAgentOnClient() { + Expression clientName = new FieldExpression("Host", "name"); + NumberedExpression clientFirst = new NumberedExpression(1L, clientName); + Set messageArgs1 = new HashSet<>(); + messageArgs1.add(clientFirst); + + Condition fetchHostStatus = new SimpleCondition(new FieldExpression("HostStatus", "nodeId"), + Operator.EQUALS, new FieldExpression("Host", "id")); + + ConditionAndExpression netbackup = new ConditionAndExpression( + new SimpleCondition( + new FieldExpression("Backupjob", "module"), + Operator.EQUALS, + new ConstantExpression("NetBackupModule", MetadataFieldType.STRING) + ), + new ConstantExpression("bpinetd", MetadataFieldType.STRING) + ); + + ConditionAndExpression networker = new ConditionAndExpression( + new SimpleCondition( + new FieldExpression("Backupjob", "module"), + Operator.EQUALS, + new ConstantExpression("NetWorkerModule", MetadataFieldType.STRING) + ), + new ConstantExpression("nsrexecd", MetadataFieldType.STRING) + ); + + ConditionAndExpression backupExec = new ConditionAndExpression( + new SimpleCondition( + new FieldExpression("Backupjob", "module"), + Operator.EQUALS, + new ConstantExpression("BackupExecModule", MetadataFieldType.STRING) + ), + new ConstantExpression("beremote", MetadataFieldType.STRING) + ); + + ConditionAndExpression dataProtector = new ConditionAndExpression( + new SimpleCondition( + new FieldExpression("Backupjob", "module"), + Operator.EQUALS, + new ConstantExpression("DataProtectorModule", MetadataFieldType.STRING) + ), + new ConstantExpression("omniinet", MetadataFieldType.STRING) + ); + + ConditionAndExpression tsm = new ConditionAndExpression( + new SimpleCondition( + new FieldExpression("Backupjob", "module"), + Operator.EQUALS, + new ConstantExpression("TSMModule", MetadataFieldType.STRING) + ), + new ConstantExpression("dsmcsvc", MetadataFieldType.STRING) + ); + + ConditionAndExpression arcServe = new ConditionAndExpression( + new SimpleCondition( + new FieldExpression("Backupjob", "module"), + Operator.EQUALS, + new ConstantExpression("ArcserveModule", MetadataFieldType.STRING) + ), + new ConstantExpression("UnivAgent", MetadataFieldType.STRING) + ); + + ConditionAndExpression commVault = new ConditionAndExpression( + new SimpleCondition( + new FieldExpression("Backupjob", "module"), + Operator.EQUALS, + new ConstantExpression("CommvaultModule", MetadataFieldType.STRING) + ), + new ConstantExpression("evmgrc", MetadataFieldType.STRING) + ); + + ConditionAndExpression avamar = new ConditionAndExpression( + new SimpleCondition( + new FieldExpression("Backupjob", "module"), + Operator.EQUALS, + new ConstantExpression("AvamarModule", MetadataFieldType.STRING) + ), + new ConstantExpression("avagent", MetadataFieldType.STRING) + ); + + Set possibilities = new HashSet<>(); + possibilities.add(netbackup); + possibilities.add(networker); + possibilities.add(backupExec); + possibilities.add(dataProtector); + possibilities.add(tsm); + possibilities.add(arcServe); + possibilities.add(commVault); + possibilities.add(avamar); + + Condition fetchProcessStatus = new CompoundCondition( + new SimpleCondition(new FieldExpression("ProcessStatus", "nodeId"), + Operator.EQUALS, new FieldExpression("Host", "id")), + new SimpleCondition(new FieldExpression("ProcessStatus", "name"), + Operator.CONTAINS, new ConditionalExpression(MetadataFieldType.STRING, possibilities)), + LogicalOperator.AND + ); + + Set fetchConditions = new HashSet<>(); + fetchConditions.add(fetchHostStatus); + fetchConditions.add(fetchProcessStatus); + + Condition condition = new CompoundCondition( + new SimpleCondition( + new CalculationExpression(DataManipulationFunction.COUNT, "HostStatus", "id"), + Operator.GREATER_THAN, + new ConstantExpression("0", MetadataFieldType.NUMERIC) + ), + new SimpleCondition( + new CalculationExpression(DataManipulationFunction.COUNT, "ProcessStatus", "id"), + Operator.EQUALS, + new ConstantExpression("0", MetadataFieldType.NUMERIC) + ), + LogicalOperator.AND + ); + + Cause noAgentOnClient = new Cause( + NO_AGENT_RAN_ON_CLIENT, "Host", MappingRelationType.JOB_BACKING_UP_HOST, + fetchConditions, condition, "Backup agent was down on host: {param}", DataManipulationFunction.LAST, + messageArgs1, null); + + return new WeightedCause(noAgentOnClient, 100); + } + + private static WeightedCause buildNoAgentOnClient2() { + + Expression agentName = new FieldExpression("BackupClient", "name"); + NumberedExpression agentFirst = new NumberedExpression(1L, agentName); + Set messageArgs1 = new HashSet<>(); + messageArgs1.add(agentFirst); + + Condition fetchCondition6 = new SimpleCondition(new FieldExpression("ClientStatus", "nodeId"), + Operator.EQUALS, new FieldExpression("BackupClient", "id")); + + Set fetchConditions6 = new HashSet<>(); + fetchConditions6.add(fetchCondition6); + + + Cause AgentDown = new Cause(BACKUP_AGENT_IS_DOWN_ON_BACKUP_CLIENT, "BackupClient", MappingRelationType.JOB_USES_BACKUPCLIENT, + fetchConditions6, + new CompoundCondition( + new SimpleCondition(new FieldExpression("ClientStatus", "responding"), Operator.EQUALS, new ConstantExpression("true", MetadataFieldType.BOOLEAN)), + new SimpleCondition(new FieldExpression("ClientStatus", "daemonRunning"), Operator.EQUALS, new ConstantExpression("false", MetadataFieldType.BOOLEAN))), + "Backup agent {param} is down on backup client", DataManipulationFunction.LAST, messageArgs1, null); + + return new WeightedCause(AgentDown, 101); + } + + private static WeightedCause buildPortSwitchForEthernet() { + Expression portName = new FieldExpression("EthernetPort", "name"); + Expression nodeType = new FieldExpression("NetintStatus", "module"); + Expression nodeName = new FieldExpression("NetintStatus", "agentName"); + NumberedExpression portNameFirst = new NumberedExpression(1L, portName); + NumberedExpression nodeTypeSecond = new NumberedExpression(2L, nodeType); + NumberedExpression nodeNameThird = new NumberedExpression(3L, nodeName); + Set messageArgs1 = new HashSet<>(); + messageArgs1.add(portNameFirst); + messageArgs1.add(nodeTypeSecond); + messageArgs1.add(nodeNameThird); + + Condition fetchCondition7 = new SimpleCondition(new FieldExpression("NetintStatus", "nodeId"), + Operator.EQUALS, new FieldExpression("EthernetPort", "id")); + + Set fetchConditions7 = new HashSet<>(); + fetchConditions7.add(fetchCondition7); + + + Cause SwitchPortDown = new Cause("Switch port is down for ethernet", "EthernetPort", null, + fetchConditions7, + new SimpleCondition(new FieldExpression("NetintStatus", "linkup"), Operator.EQUALS, new ConstantExpression("false", MetadataFieldType.BOOLEAN)), + "Ethernet port:{param} for {param}:{param} is down", DataManipulationFunction.EXISTS, messageArgs1, "com.emc.dpa.analysis.rca.RCAPortSwitchIsDownPlugin"); + + return new WeightedCause(SwitchPortDown, 61); + } + + + private static WeightedCause buildDifferentPortSettings() { + Set messageArgs1 = new HashSet<>(); + + Condition fetchCondition1 = new SimpleCondition(new FieldExpression("NetintStatus", "nodeId"), + Operator.EQUALS, new FieldExpression("EthernetPort", "id")); + + Condition fetchCondition2 = new SimpleCondition(new FieldExpression("NetintConfig", "nodeId"), + Operator.EQUALS, new FieldExpression("EthernetPort", "id")); + + Set fetchConditions = new HashSet<>(); + fetchConditions.add(fetchCondition1); + fetchConditions.add(fetchCondition2); + + Cause PortSettings = new Cause("Different Port Settings", "EthernetPort", null, + fetchConditions, + new SimpleCondition(new FieldExpression("NetintStatus", "speed"), Operator.NOT_EQUALS, + new ConstantExpression("0", MetadataFieldType.NUMERIC)), + "", DataManipulationFunction.EXISTS, messageArgs1, "com.emc.dpa.analysis.rca.RCASwitchSettingsPlugin"); + + return new WeightedCause(PortSettings, 63); + } + + + private static WeightedCause buildPortSwitchForFibreChannel() { + Expression portName = new FieldExpression("FibreChannelPort", "name"); + Expression nodeType = new FieldExpression("FcportStatus", "module"); + Expression nodeName = new FieldExpression("FcportStatus", "agentName"); + NumberedExpression portNameFirst = new NumberedExpression(1L, portName); + NumberedExpression nodeTypeSecond = new NumberedExpression(2L, nodeType); + NumberedExpression nodeNameThird = new NumberedExpression(3L, nodeName); + Set messageArgs1 = new HashSet<>(); + messageArgs1.add(portNameFirst); + messageArgs1.add(nodeTypeSecond); + messageArgs1.add(nodeNameThird); + + Condition fetchCondition7 = new SimpleCondition(new FieldExpression("FcportStatus", "nodeId"), + Operator.EQUALS, new FieldExpression("FibreChannelPort", "id")); + + Set fetchConditions7 = new HashSet<>(); + fetchConditions7.add(fetchCondition7); + + + Cause SwitchPortDown = new Cause("Switch port is down for fibre channel", "FibreChannelPort", null, + fetchConditions7, + new SimpleCondition(new FieldExpression("FcportStatus", "linkup"), Operator.EQUALS, new ConstantExpression("false", MetadataFieldType.BOOLEAN)), + "Fibre channel port:{param} for {param}:{param} is down", DataManipulationFunction.EXISTS, messageArgs1, "com.emc.dpa.analysis.rca.RCAPortSwitchIsDownPlugin"); + + return new WeightedCause(SwitchPortDown, 60); + + } + + + private static RCATemplate buildRPAHighLoadTemplate() { + Symptom symptom = new Symptom("CG Copy high load", "CgCopyPerf", + new SimpleCondition(new FieldExpression("CgCopyPerf", "highLoadTime"), Operator.GREATER_THAN, new ConstantExpression("0", MetadataFieldType.NUMERIC))); + symptom.setFilterString("highLoadTime > 0"); + symptom.setNodeTypeString("cg copies"); + symptom.setProcessTypeString("replications"); + + + WeightedCause cause1 = buildHighRPAThroughput(); + WeightedCause cause2 = buildCGCopyFF(); + WeightedCause cause3 = buildPacketLoss(); + + Set causes = new HashSet<>(); + causes.add(cause1); + causes.add(cause2); + causes.add(cause3); + + return new RCATemplate("CG copy High load template", symptom, causes); + } + + private static WeightedCause buildHighRPAThroughput() { + + ParameterExpression highThroughputThreshold = new ParameterExpression("highThroughputThreshold", "122880", MetadataFieldType.NUMERIC); + ConstantExpression megaSize = new ConstantExpression("1024", MetadataFieldType.NUMERIC); + + Expression agentName = new FieldExpression("RpaPerfView", "agentName"); + NumberedExpression rpaFirst = new NumberedExpression(1L, agentName); + Expression rpaName = new FieldExpression("AbstractRecoverPointAppliance", "name"); + NumberedExpression rpaSecond = new NumberedExpression(2L, rpaName); + Expression site = new FieldExpression("RpaPerfView", "site"); + NumberedExpression rpaThird = new NumberedExpression(3L, site); + + MathExpression multiplyWanCompression = new MathExpression( + new FieldExpression("RpaPerfView", "wanThroughput"), + new FieldExpression("RpaPerfView", "compression"), + MathOperator.MULTIPLY); + + Expression wanThroughput = new MathExpression(new FieldExpression("RpaPerfView", "wanThroughput"), multiplyWanCompression, MathOperator.MAX); + Expression maxThroughput = new MathExpression(new FieldExpression("RpaPerfView", "sanThroughput"), wanThroughput, MathOperator.MAX); + Expression maxThroughputMB = new MathExpression(maxThroughput, megaSize, MathOperator.DIVIDE); + NumberedExpression rpaFourth = new NumberedExpression(4L, maxThroughputMB); + Expression limitThroughputMB = new MathExpression(highThroughputThreshold, megaSize, MathOperator.DIVIDE); + NumberedExpression rpaFifth = new NumberedExpression(5L, limitThroughputMB); + Set messageArgs1 = new HashSet<>(); + messageArgs1.add(rpaFirst); + messageArgs1.add(rpaSecond); + messageArgs1.add(rpaThird); + messageArgs1.add(rpaFourth); + messageArgs1.add(rpaFifth); + + Condition fetchCondition = new SimpleCondition(new FieldExpression("RpaPerfView", "nodeId"), + Operator.EQUALS, new FieldExpression("AbstractRecoverPointAppliance", "id")); + Set fetchConditions = new HashSet<>(); + fetchConditions.add(fetchCondition); + + + ///(san != null and san>120) || (wan != null and (((compression = null || compression = 0) and wan > 120) || ((compression != null and compression != 0) and wan*compression > 120))) + Condition condition = new CompoundCondition( + new CompoundCondition( + new SimpleCondition(new FieldExpression("RpaPerfView", "sanThroughput"), Operator.NOT_EQUALS, new ConstantExpression("null", MetadataFieldType.NULL)), + new SimpleCondition(new FieldExpression("RpaPerfView", "sanThroughput"), Operator.GREATER_THAN, highThroughputThreshold), + LogicalOperator.AND), + new CompoundCondition( + new SimpleCondition(new FieldExpression("RpaPerfView", "wanThroughput"), Operator.NOT_EQUALS, new ConstantExpression("null", MetadataFieldType.NULL)), + new CompoundCondition( + new CompoundCondition( + new SimpleCondition(new FieldExpression("RpaPerfView", "wanThroughput"), Operator.GREATER_THAN, highThroughputThreshold), + new CompoundCondition( + new SimpleCondition(new FieldExpression("RpaPerfView", "compression"), Operator.EQUALS, new ConstantExpression("null", MetadataFieldType.NULL)), + new SimpleCondition(new FieldExpression("RpaPerfView", "compression"), Operator.EQUALS, new ConstantExpression("0", MetadataFieldType.NUMERIC)), + LogicalOperator.OR), + LogicalOperator.AND), + new CompoundCondition( + new CompoundCondition( + new SimpleCondition(new FieldExpression("RpaPerfView", "compression"), Operator.NOT_EQUALS, new ConstantExpression("null", MetadataFieldType.NULL)), + new SimpleCondition(new FieldExpression("RpaPerfView", "compression"), Operator.NOT_EQUALS, new ConstantExpression("0", MetadataFieldType.NUMERIC)), + LogicalOperator.AND), + new SimpleCondition(multiplyWanCompression, Operator.GREATER_THAN, highThroughputThreshold), + LogicalOperator.AND), + LogicalOperator.OR), + LogicalOperator.AND), + LogicalOperator.OR); + + Cause rpaThroughputHigh = new Cause("High RPA throughput", "AbstractRecoverPointAppliance", MappingRelationType.RECOVERPOINT_CG_COPY_ACTIVE_RPA, + fetchConditions, condition, "The throughput for RPA: {param}:{param} at site {param} was {param}MB, above the RPA throughput limitation ({param}MB)", DataManipulationFunction.EXISTS, + messageArgs1, null); + + TimeManipulation startTimeManipulation = new TimeManipulation( + ManipulationType.MOVE_IT_BY_ABSOLUTE_TIME, + MathOperator.SUBTRACT, + 5 * 60L, + null, + "rpa_throughput_offset" + ); + rpaThroughputHigh.setStartTimeManipulation(startTimeManipulation); + + rpaThroughputHigh.setGeneralMessageTemplate("The throughput for RPA: {param}:{param} at site {param} was above the RPA throughput limitation ({param}MB)"); + Set generalMessageParams = new HashSet<>(); + generalMessageParams.add(rpaFirst); + generalMessageParams.add(rpaSecond); + generalMessageParams.add(rpaThird); + NumberedExpression rpaFifthWichIsNowForth = new NumberedExpression(4L, new MathExpression(highThroughputThreshold, megaSize, MathOperator.DIVIDE)); + generalMessageParams.add(rpaFifthWichIsNowForth); + rpaThroughputHigh.setGeneralMessageTemplateParams(generalMessageParams); + + WeightedCause cause = new WeightedCause(rpaThroughputHigh, 100); + return cause; + } + + private static WeightedCause buildCGCopyFF() { + Expression cgCopyName = new FieldExpression("AbstractRecoverPointConsistencyGroupCopy", "name"); + NumberedExpression cgCopyFirst = new NumberedExpression(1L, cgCopyName); + Set messageArgs1 = new HashSet<>(); + messageArgs1.add(cgCopyFirst); + + Condition fetchCondition = new SimpleCondition(new FieldExpression("CgCopyStatus", "nodeId"), + Operator.EQUALS, new FieldExpression("AbstractRecoverPointConsistencyGroupCopy", "id")); + Set fetchConditions = new HashSet<>(); + fetchConditions.add(fetchCondition); + + Condition condition = + new CompoundCondition( + new SimpleCondition(new FieldExpression("CgCopyStatus", "journalMode"), Operator.NOT_EQUALS, new ConstantExpression("null", MetadataFieldType.NULL)), + new SimpleCondition(new FieldExpression("CgCopyStatus", "journalMode"), Operator.EQUALS, new ConstantExpression("Fast Forward", MetadataFieldType.STRING)), + LogicalOperator.AND); + + Cause rpaFastForward = new Cause("High RPA throughput", "AbstractRecoverPointConsistencyGroupCopy", null, + fetchConditions, condition, "Cg Copy {param} has a high latency on writing to remote storage (Fast Forward)", DataManipulationFunction.EXISTS, + messageArgs1, null); + + WeightedCause cause = new WeightedCause(rpaFastForward, 80); + return cause; + } + + private static RCATemplate buildRPOViolationTemplate() { + Symptom symptom = new Symptom(CG_COPY_RPO_VIOLATION_SYMPTOM_NAME, "AnalysisAlert", + new CompoundCondition( + // todo - check state - not closed, currently don't bother + new SimpleCondition(new FieldExpression("AnalysisAlert", "message"), Operator.EQUALS, new ConstantExpression("RPO Violation", MetadataFieldType.STRING)), + new SimpleCondition(new FieldExpression("AnalysisAlert", "component"), Operator.CONTAINS, new ConstantExpression("CG Copy", MetadataFieldType.STRING)) + ) + ); + symptom.setFilterString("message = 'RPO Violation' AND component like '%CG Copy%'"); + symptom.setNodeTypeString("cg copies"); + symptom.setProcessTypeString("replications"); + + + WeightedCause cause1 = buildHighRPAThroughput(); + WeightedCause cause2 = buildCGCopyFF(); + WeightedCause cause3 = buildPacketLoss(); + + Set causes = new HashSet<>(); + causes.add(cause1); + causes.add(cause2); + causes.add(cause3); + + return new RCATemplate("CG copy RPO Violation template", symptom, causes); + } + + private static WeightedCause buildPacketLoss() { + + Expression packetLossSize = new FieldExpression("RpaPerfView", "packetLoss"); + NumberedExpression clientFirst = new NumberedExpression(1L, packetLossSize); + Set messageArgs1 = new HashSet<>(); + messageArgs1.add(clientFirst); + + Condition fetchCondition = new SimpleCondition(new FieldExpression("RpaPerfView", "nodeId"), + Operator.EQUALS, new FieldExpression("AbstractRecoverPointAppliance", "id")); + Set fetchConditions = new HashSet<>(); + fetchConditions.add(fetchCondition); + Condition condition = new SimpleCondition(new FieldExpression("RpaPerfView", "packetLoss"), Operator.GREATER_THAN, + new ConstantExpression("1", MetadataFieldType.NUMERIC)); + + Cause packetLoss = new Cause(PACKET_LOSS, "AbstractRecoverPointAppliance", MappingRelationType.RECOVERPOINT_CG_COPY_ACTIVE_RPA, + fetchConditions, condition, + "There is a bottleneck on the bandwidth. Found packet-loss ({param}) on the link.", DataManipulationFunction.EXISTS, + messageArgs1, null); + + packetLoss.setGeneralMessageTemplate("There is a bottleneck on the bandwidth. Found packet-loss (>1) on the link."); + + return new WeightedCause(packetLoss, 200); + } + + public static List getDefaultRCATemplates() { + return Arrays.asList(buildBackupFailedTemplate(), buildRPAHighLoadTemplate(), buildRPOViolationTemplate()); + } + + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/insertordering/InsertOrderingRootEntityNameDependencyTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/insertordering/InsertOrderingRootEntityNameDependencyTest.java index 3b98ca0917..6bc6399bea 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/insertordering/InsertOrderingRootEntityNameDependencyTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/insertordering/InsertOrderingRootEntityNameDependencyTest.java @@ -33,159 +33,159 @@ import static org.hibernate.testing.transaction.TransactionUtil.doInHibernate; @RequiresDialectFeature(DialectChecks.SupportsJdbcDriverProxying.class) public class InsertOrderingRootEntityNameDependencyTest extends BaseNonConfigCoreFunctionalTestCase { - private PreparedStatementSpyConnectionProvider connectionProvider = new PreparedStatementSpyConnectionProvider(); + private PreparedStatementSpyConnectionProvider connectionProvider = new PreparedStatementSpyConnectionProvider(); - @Override - protected Class[] getAnnotatedClasses() { - return new Class[]{ - Wrapper.class, - Condition.class, - SimpleCondition.class, - Expression.class, - ConstantExpression.class, - Condition.class, - CompoundCondition.class, - }; - } + @Override + protected Class[] getAnnotatedClasses() { + return new Class[]{ + Wrapper.class, + Condition.class, + SimpleCondition.class, + Expression.class, + ConstantExpression.class, + Condition.class, + CompoundCondition.class, + }; + } - @Override - protected void addSettings(Map settings) { - settings.put(Environment.ORDER_INSERTS, "true"); - settings.put(Environment.ORDER_UPDATES, "true"); - settings.put(Environment.STATEMENT_BATCH_SIZE, "50"); - settings.put( - org.hibernate.cfg.AvailableSettings.CONNECTION_PROVIDER, - connectionProvider - ); - } + @Override + protected void addSettings(Map settings) { + settings.put(Environment.ORDER_INSERTS, "true"); + settings.put(Environment.ORDER_UPDATES, "true"); + settings.put(Environment.STATEMENT_BATCH_SIZE, "50"); + settings.put( + org.hibernate.cfg.AvailableSettings.CONNECTION_PROVIDER, + connectionProvider + ); + } - @Override - public void releaseResources() { - super.releaseResources(); - connectionProvider.stop(); - } + @Override + public void releaseResources() { + super.releaseResources(); + connectionProvider.stop(); + } - @Override - protected boolean rebuildSessionFactoryOnError() { - return false; - } + @Override + protected boolean rebuildSessionFactoryOnError() { + return false; + } - @Test - public void testBatching() throws SQLException { - doInHibernate(this::sessionFactory, session -> { - connectionProvider.clear(); - session.persist(Wrapper.create()); - }); - } + @Test + public void testBatching() throws SQLException { + doInHibernate(this::sessionFactory, session -> { + connectionProvider.clear(); + session.persist(Wrapper.create()); + }); + } - @Entity(name = "Wrapper") - public static class Wrapper { - @Id - private String id; - @OneToOne(cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.EAGER) - private Condition condition; - @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER) - private Set constantExpressions; + @Entity(name = "Wrapper") + public static class Wrapper { + @Id + private String id; + @OneToOne(cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.EAGER) + private Condition condition; + @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER) + private Set constantExpressions; - @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER) - private Set otherConditions; + @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER) + private Set otherConditions; - public Wrapper() { - } + public Wrapper() { + } - public static Wrapper create() { - final Wrapper w = new Wrapper(); - final CompoundCondition cc = new CompoundCondition(); - final SimpleCondition c1 = new SimpleCondition(); - final SimpleCondition c2 = new SimpleCondition(); - final SimpleCondition c3 = new SimpleCondition(); - final ConstantExpression e1 = new ConstantExpression(); - final ConstantExpression e2 = new ConstantExpression(); - final ConstantExpression e3 = new ConstantExpression(); - final ConstantExpression e4 = new ConstantExpression(); - final ConstantExpression e5 = new ConstantExpression(); - final ConstantExpression e6 = new ConstantExpression(); - final ConstantExpression e7 = new ConstantExpression(); - w.id = "w"; - w.condition = cc; - cc.id = "cc"; - cc.first = c1; - cc.second = c2; - c1.id = "c1"; - c1.left = e1; - c1.right = e2; - c2.id = "c2"; - c2.left = e3; - c2.right = e4; - c3.id = "c3"; - c3.left = e6; - c3.right = e7; - e1.id = "e1"; - e1.value = "e1"; - e2.id = "e2"; - e2.value = "e2"; - e3.id = "e3"; - e3.value = "e3"; - e4.id = "e4"; - e4.value = "e4"; - e5.id = "e5"; - e5.value = "e5"; - e6.id = "e6"; - e6.value = "e6"; - e7.id = "e7"; - e7.value = "e7"; - w.constantExpressions = new HashSet<>(); - w.constantExpressions.add(e5); - w.otherConditions = new HashSet<>(); - w.otherConditions.add(c3); - return w; - } - } + public static Wrapper create() { + final Wrapper w = new Wrapper(); + final CompoundCondition cc = new CompoundCondition(); + final SimpleCondition c1 = new SimpleCondition(); + final SimpleCondition c2 = new SimpleCondition(); + final SimpleCondition c3 = new SimpleCondition(); + final ConstantExpression e1 = new ConstantExpression(); + final ConstantExpression e2 = new ConstantExpression(); + final ConstantExpression e3 = new ConstantExpression(); + final ConstantExpression e4 = new ConstantExpression(); + final ConstantExpression e5 = new ConstantExpression(); + final ConstantExpression e6 = new ConstantExpression(); + final ConstantExpression e7 = new ConstantExpression(); + w.id = "w"; + w.condition = cc; + cc.id = "cc"; + cc.first = c1; + cc.second = c2; + c1.id = "c1"; + c1.left = e1; + c1.right = e2; + c2.id = "c2"; + c2.left = e3; + c2.right = e4; + c3.id = "c3"; + c3.left = e6; + c3.right = e7; + e1.id = "e1"; + e1.value = "e1"; + e2.id = "e2"; + e2.value = "e2"; + e3.id = "e3"; + e3.value = "e3"; + e4.id = "e4"; + e4.value = "e4"; + e5.id = "e5"; + e5.value = "e5"; + e6.id = "e6"; + e6.value = "e6"; + e7.id = "e7"; + e7.value = "e7"; + w.constantExpressions = new HashSet<>(); + w.constantExpressions.add(e5); + w.otherConditions = new HashSet<>(); + w.otherConditions.add(c3); + return w; + } + } - @Entity(name = "Condition") - @Table(name = "cond") - public static abstract class Condition { - @Id - protected String id; + @Entity(name = "Condition") + @Table(name = "cond") + public static abstract class Condition { + @Id + protected String id; - public Condition() { - } - } - @Entity(name = "SimpleCondition") - public static class SimpleCondition extends Condition { - @OneToOne(cascade = CascadeType.ALL) - private Expression left; - @OneToOne(cascade = CascadeType.ALL) - private Expression right; + public Condition() { + } + } + @Entity(name = "SimpleCondition") + public static class SimpleCondition extends Condition { + @OneToOne(cascade = CascadeType.ALL) + private Expression left; + @OneToOne(cascade = CascadeType.ALL) + private Expression right; - public SimpleCondition() { - } - } - @Entity(name = "Expression") - public static abstract class Expression { - @Id - protected String id; + public SimpleCondition() { + } + } + @Entity(name = "Expression") + public static abstract class Expression { + @Id + protected String id; - protected Expression() { - } + protected Expression() { + } - } - @Entity(name = "ConstantExpression") - public static class ConstantExpression extends Expression { - @Column(name = "val") - private String value; + } + @Entity(name = "ConstantExpression") + public static class ConstantExpression extends Expression { + @Column(name = "val") + private String value; - public ConstantExpression() { - } - } - @Entity(name = "CompoundCondition") - public static class CompoundCondition extends Condition { - @OneToOne(cascade = CascadeType.ALL) - protected Condition first; - @OneToOne(cascade = CascadeType.ALL) - protected Condition second; + public ConstantExpression() { + } + } + @Entity(name = "CompoundCondition") + public static class CompoundCondition extends Condition { + @OneToOne(cascade = CascadeType.ALL) + protected Condition first; + @OneToOne(cascade = CascadeType.ALL) + protected Condition second; - public CompoundCondition() { - } - } + public CompoundCondition() { + } + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/interceptor/InterceptorTransactionEventTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/interceptor/InterceptorTransactionEventTest.java index ab84939a8d..2add0fde1c 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/interceptor/InterceptorTransactionEventTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/interceptor/InterceptorTransactionEventTest.java @@ -21,50 +21,50 @@ public class InterceptorTransactionEventTest extends BaseCoreFunctionalTestCase @Test public void testTransactionEvents() { - LoggingInterceptor interceptor = new LoggingInterceptor(); + LoggingInterceptor interceptor = new LoggingInterceptor(); - Session s = openSession(interceptor); + Session s = openSession(interceptor); Transaction tx = s.beginTransaction(); // Do nothing, open and closing the transaction is enough tx.commit(); s.close(); - assertTrue("afterTransactionBeginCalled not called", interceptor.isAfterTransactionBeginCalled()); - assertTrue("afterTransactionCompletionCalled not called", interceptor.isAfterTransactionCompletionCalled()); - assertTrue("beforeTransactionCompletionCalled not called", interceptor.isBeforeTransactionCompletionCalled()); - } + assertTrue("afterTransactionBeginCalled not called", interceptor.isAfterTransactionBeginCalled()); + assertTrue("afterTransactionCompletionCalled not called", interceptor.isAfterTransactionCompletionCalled()); + assertTrue("beforeTransactionCompletionCalled not called", interceptor.isBeforeTransactionCompletionCalled()); + } - private static class LoggingInterceptor implements Interceptor { - private boolean afterTransactionBeginCalled; - private boolean afterTransactionCompletionCalled; - private boolean beforeTransactionCompletionCalled; + private static class LoggingInterceptor implements Interceptor { + private boolean afterTransactionBeginCalled; + private boolean afterTransactionCompletionCalled; + private boolean beforeTransactionCompletionCalled; - @Override - public void afterTransactionBegin(Transaction tx) { - afterTransactionBeginCalled = true; - } + @Override + public void afterTransactionBegin(Transaction tx) { + afterTransactionBeginCalled = true; + } - @Override - public void afterTransactionCompletion(Transaction tx) { - afterTransactionCompletionCalled = true; - } + @Override + public void afterTransactionCompletion(Transaction tx) { + afterTransactionCompletionCalled = true; + } - @Override - public void beforeTransactionCompletion(Transaction tx) { - beforeTransactionCompletionCalled = true; - } + @Override + public void beforeTransactionCompletion(Transaction tx) { + beforeTransactionCompletionCalled = true; + } - public boolean isAfterTransactionBeginCalled() { - return afterTransactionBeginCalled; - } + public boolean isAfterTransactionBeginCalled() { + return afterTransactionBeginCalled; + } - public boolean isAfterTransactionCompletionCalled() { - return afterTransactionCompletionCalled; - } + public boolean isAfterTransactionCompletionCalled() { + return afterTransactionCompletionCalled; + } - public boolean isBeforeTransactionCompletionCalled() { - return beforeTransactionCompletionCalled; - } + public boolean isBeforeTransactionCompletionCalled() { + return beforeTransactionCompletionCalled; + } - } + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jdbc/GeneralWorkTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jdbc/GeneralWorkTest.java index 2b3e83b363..eb20f9f020 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jdbc/GeneralWorkTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jdbc/GeneralWorkTest.java @@ -154,7 +154,7 @@ public class GeneralWorkTest extends BaseCoreFunctionalTestCase { return; } try { - s.getJdbcCoordinator().getLogicalConnection().getResourceRegistry().release( statement ); + s.getJdbcCoordinator().getLogicalConnection().getResourceRegistry().release( statement ); } catch (Exception e) { // ignore @@ -166,7 +166,7 @@ public class GeneralWorkTest extends BaseCoreFunctionalTestCase { return; } try { - s.getJdbcCoordinator().getLogicalConnection().getResourceRegistry().release( resultSet, statement ); + s.getJdbcCoordinator().getLogicalConnection().getResourceRegistry().release( resultSet, statement ); } catch (Exception e) { // ignore diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jdbc/LobCreatorTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jdbc/LobCreatorTest.java index c9476ac3bb..a7b44575b9 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jdbc/LobCreatorTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jdbc/LobCreatorTest.java @@ -76,7 +76,7 @@ public class LobCreatorTest { connection.close(); } - @Test + @Test public void testJdbc3LobCreator() throws SQLException { final Connection connection = createConnectionProxy( 3, new JdbcLobBuilderImpl() ); final H2Dialect dialect = new H2Dialect(); @@ -97,7 +97,7 @@ public class LobCreatorTest { connection.close(); } - @Test + @Test public void testJdbc4UnsupportedLobCreator() throws SQLException { final Connection connection = createConnectionProxy( 4, new JdbcLobBuilderImpl() ); final H2Dialect dialect = new H2Dialect(); @@ -118,7 +118,7 @@ public class LobCreatorTest { connection.close(); } - @Test + @Test public void testConfiguredNonContextualLobCreator() throws SQLException { final Connection connection = createConnectionProxy( 4, new JdbcLobBuilderImpl( LobTypes.BLOB, LobTypes.CLOB, LobTypes.NCLOB ) ); final H2Dialect dialect = new H2Dialect(); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jdbc/internal/AggressiveReleaseTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jdbc/internal/AggressiveReleaseTest.java index eac9332b15..42c4389016 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jdbc/internal/AggressiveReleaseTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jdbc/internal/AggressiveReleaseTest.java @@ -130,7 +130,7 @@ public class AggressiveReleaseTest extends BaseSessionFactoryFunctionalTest { ps.setLong( 1, 1 ); ps.setString( 2, "name" ); jdbcCoord.getResultSetReturn().execute( ps, sql ); - assertTrue( jdbcCoord.getLogicalConnection().getResourceRegistry().hasRegisteredResources() ); + assertTrue( jdbcCoord.getLogicalConnection().getResourceRegistry().hasRegisteredResources() ); assertEquals( 1, connectionProvider.getAcquiredConnections().size() ); assertEquals( 0, connectionProvider.getReleasedConnections().size() ); resourceRegistry.release( ps ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jdbc/internal/BasicConnectionTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jdbc/internal/BasicConnectionTest.java index 789054f3cc..d876acb74c 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jdbc/internal/BasicConnectionTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jdbc/internal/BasicConnectionTest.java @@ -114,6 +114,6 @@ public class BasicConnectionTest extends BaseCoreFunctionalTestCase { } private ResourceRegistry getResourceRegistry(JdbcCoordinator jdbcCoord) { - return jdbcCoord.getLogicalConnection().getResourceRegistry(); - } + return jdbcCoord.getLogicalConnection().getResourceRegistry(); + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jdbc/internal/BatchingTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jdbc/internal/BatchingTest.java index 99ad404a2e..bf39465cbb 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jdbc/internal/BatchingTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jdbc/internal/BatchingTest.java @@ -74,7 +74,7 @@ public class BatchingTest extends BaseCoreFunctionalTestCase implements BatchKey insertBatch.addToBatch( jdbcValueBindings, null ); assertThat( batchObserver.getExplicitExecutionCount() ).isEqualTo( 0 ); assertThat( batchObserver.getImplicitExecutionCount() ).isEqualTo( 0 ); - assertThat( jdbcCoordinator.getLogicalConnection().getResourceRegistry().hasRegisteredResources() ).isTrue(); + assertThat( jdbcCoordinator.getLogicalConnection().getResourceRegistry().hasRegisteredResources() ).isTrue(); // bind values for #2 - again, nothing at JDBC level (we have statement from earlier) jdbcValueBindings.bindValue( 2, SANDBOX_TBL, "ID", ParameterUsage.SET ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jdbc/refcursor/StandardRefCursorSupportTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jdbc/refcursor/StandardRefCursorSupportTest.java index 6c5a684869..935b6a449b 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jdbc/refcursor/StandardRefCursorSupportTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jdbc/refcursor/StandardRefCursorSupportTest.java @@ -27,16 +27,16 @@ import static org.junit.Assert.assertThat; @JiraKey(value = "HHH-10612") public class StandardRefCursorSupportTest { - interface TestDatabaseMetaData extends DatabaseMetaData { - boolean supportsRefCursors() throws SQLException; - } + interface TestDatabaseMetaData extends DatabaseMetaData { + boolean supportsRefCursors() throws SQLException; + } - @Test - public void testSupportsRefCursorsAboveJava8() throws Exception { - TestDatabaseMetaData metaMock = Mockito.mock(TestDatabaseMetaData.class); - Mockito.when(metaMock.supportsRefCursors()).thenReturn(true); + @Test + public void testSupportsRefCursorsAboveJava8() throws Exception { + TestDatabaseMetaData metaMock = Mockito.mock(TestDatabaseMetaData.class); + Mockito.when(metaMock.supportsRefCursors()).thenReturn(true); - boolean result = StandardRefCursorSupport.supportsRefCursors(metaMock); - assertThat(result, is(true)); - } + boolean result = StandardRefCursorSupport.supportsRefCursors(metaMock); + assertThat(result, is(true)); + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/joinedsubclass/JoinedSubclassWithExplicitDiscriminatorTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/joinedsubclass/JoinedSubclassWithExplicitDiscriminatorTest.java index 7436c3bbf2..3b4482ab89 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/joinedsubclass/JoinedSubclassWithExplicitDiscriminatorTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/joinedsubclass/JoinedSubclassWithExplicitDiscriminatorTest.java @@ -48,14 +48,14 @@ public class JoinedSubclassWithExplicitDiscriminatorTest { @Test @SkipForDialect( dialectClass = AltibaseDialect.class, reason = "'TYPE' is a keyword in Altibase and escaped here") public void metadataAssertions(SessionFactoryScope scope) { - EntityPersister p = scope.getSessionFactory().getMappingMetamodel().getEntityDescriptor(Dog.class.getName()); + EntityPersister p = scope.getSessionFactory().getMappingMetamodel().getEntityDescriptor(Dog.class.getName()); assertNotNull( p ); final JoinedSubclassEntityPersister dogPersister = assertTyping( JoinedSubclassEntityPersister.class, p ); assertEquals( "string", dogPersister.getDiscriminatorType().getName() ); assertEquals( "type", dogPersister.getDiscriminatorColumnName() ); assertEquals( "dog", dogPersister.getDiscriminatorValue() ); - p = scope.getSessionFactory().getMappingMetamodel().getEntityDescriptor(Cat.class.getName()); + p = scope.getSessionFactory().getMappingMetamodel().getEntityDescriptor(Cat.class.getName()); assertNotNull( p ); final JoinedSubclassEntityPersister catPersister = assertTyping( JoinedSubclassEntityPersister.class, p ); assertEquals( "string", catPersister.getDiscriminatorType().getName() ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/joinedsubclass/JoinedSubclassWithIgnoredExplicitDiscriminatorTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/joinedsubclass/JoinedSubclassWithIgnoredExplicitDiscriminatorTest.java index eb208d50d8..5e0f01406d 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/joinedsubclass/JoinedSubclassWithIgnoredExplicitDiscriminatorTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/joinedsubclass/JoinedSubclassWithIgnoredExplicitDiscriminatorTest.java @@ -54,14 +54,14 @@ public class JoinedSubclassWithIgnoredExplicitDiscriminatorTest { @Test public void metadataAssertions(SessionFactoryScope scope) { - EntityPersister p = scope.getSessionFactory().getMappingMetamodel().getEntityDescriptor(Dog.class.getName()); + EntityPersister p = scope.getSessionFactory().getMappingMetamodel().getEntityDescriptor(Dog.class.getName()); assertNotNull( p ); final JoinedSubclassEntityPersister dogPersister = assertTyping( JoinedSubclassEntityPersister.class, p ); assertEquals( "integer", dogPersister.getDiscriminatorType().getName() ); assertEquals( "clazz_", dogPersister.getDiscriminatorColumnName() ); assertTrue( Integer.class.isInstance( dogPersister.getDiscriminatorValue() ) ); - p = scope.getSessionFactory().getMappingMetamodel().getEntityDescriptor(Cat.class.getName()); + p = scope.getSessionFactory().getMappingMetamodel().getEntityDescriptor(Cat.class.getName()); assertNotNull( p ); final JoinedSubclassEntityPersister catPersister = assertTyping( JoinedSubclassEntityPersister.class, p ); assertEquals( "integer", catPersister.getDiscriminatorType().getName() ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/joinedsubclass/JoinedSubclassWithImplicitDiscriminatorTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/joinedsubclass/JoinedSubclassWithImplicitDiscriminatorTest.java index 38da0c9363..fd745bb09e 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/joinedsubclass/JoinedSubclassWithImplicitDiscriminatorTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/joinedsubclass/JoinedSubclassWithImplicitDiscriminatorTest.java @@ -50,7 +50,7 @@ public class JoinedSubclassWithImplicitDiscriminatorTest { @Test public void metadataAssertions(SessionFactoryScope scope) { - EntityPersister p = scope.getSessionFactory().getMappingMetamodel().getEntityDescriptor(Dog.class.getName()); + EntityPersister p = scope.getSessionFactory().getMappingMetamodel().getEntityDescriptor(Dog.class.getName()); assertNotNull( p ); final JoinedSubclassEntityPersister dogPersister = assertTyping( JoinedSubclassEntityPersister.class, p ); assertEquals( @@ -63,7 +63,7 @@ public class JoinedSubclassWithImplicitDiscriminatorTest { ); assertEquals( "Dog", dogPersister.getDiscriminatorValue() ); - p = scope.getSessionFactory().getMappingMetamodel().getEntityDescriptor(Cat.class.getName()); + p = scope.getSessionFactory().getMappingMetamodel().getEntityDescriptor(Cat.class.getName()); assertNotNull( p ); final JoinedSubclassEntityPersister catPersister = assertTyping( JoinedSubclassEntityPersister.class, p ); assertEquals( diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/BaseEntityManagerFunctionalTestCase.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/BaseEntityManagerFunctionalTestCase.java index 6eb0cf6e9d..8a0ff791ad 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/BaseEntityManagerFunctionalTestCase.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/BaseEntityManagerFunctionalTestCase.java @@ -306,13 +306,13 @@ public abstract class BaseEntityManagerFunctionalTestCase extends BaseUnitTestCa if ( em.getTransaction().isActive() ) { em.getTransaction().rollback(); - log.warn("You left an open transaction! Fix your test case. For now, we are closing it for you."); + log.warn("You left an open transaction! Fix your test case. For now, we are closing it for you."); } if ( em.isOpen() ) { // as we open an EM before the test runs, it will still be open if the test uses a custom EM. // or, the person may have forgotten to close. So, do not raise a "fail", but log the fact. em.close(); - log.warn("The EntityManager is not closed. Closing it."); + log.warn("The EntityManager is not closed. Closing it."); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/Cat.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/Cat.java index 1261cbee9e..40ddc4cd51 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/Cat.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/Cat.java @@ -105,7 +105,7 @@ public class Cat implements Serializable { @PostUpdate private void someLateUpdateWorking() { - log.debug("PostUpdate for: " + this.toString()); + log.debug("PostUpdate for: " + this.toString()); postVersion++; } @@ -156,25 +156,25 @@ public class Cat implements Serializable { * of this object. */ @Override - public String toString() + public String toString() { - final String TAB = " "; + final String TAB = " "; - String retValue = ""; + String retValue = ""; - retValue = "Cat ( " - + super.toString() + TAB - + "id = " + this.id + TAB - + "name = " + this.name + TAB - + "dateOfBirth = " + this.dateOfBirth + TAB - + "age = " + this.age + TAB - + "length = " + this.length + TAB - + "lastUpdate = " + this.lastUpdate + TAB - + "manualVersion = " + this.manualVersion + TAB - + "postVersion = " + Cat.postVersion + TAB - + "kittens = " + this.kittens + TAB - + " )"; + retValue = "Cat ( " + + super.toString() + TAB + + "id = " + this.id + TAB + + "name = " + this.name + TAB + + "dateOfBirth = " + this.dateOfBirth + TAB + + "age = " + this.age + TAB + + "length = " + this.length + TAB + + "lastUpdate = " + this.lastUpdate + TAB + + "manualVersion = " + this.manualVersion + TAB + + "postVersion = " + Cat.postVersion + TAB + + "kittens = " + this.kittens + TAB + + " )"; - return retValue; + return retValue; } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/CompositeId.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/CompositeId.java index 711a7cd5df..4c6c254b64 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/CompositeId.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/CompositeId.java @@ -15,48 +15,48 @@ import jakarta.persistence.Embeddable; @Embeddable public class CompositeId implements Serializable { - private int id1; - private int id2; + private int id1; + private int id2; - public CompositeId() { - } + public CompositeId() { + } - public CompositeId(int id1, int id2) { - this.id1 = id1; - this.id2 = id2; - } + public CompositeId(int id1, int id2) { + this.id1 = id1; + this.id2 = id2; + } - public int getId1() { - return id1; - } + public int getId1() { + return id1; + } - public void setId1( int id1 ) { - this.id1 = id1; - } + public void setId1( int id1 ) { + this.id1 = id1; + } - public int getId2() { - return id2; - } + public int getId2() { + return id2; + } - public void setId2( int id2 ) { - this.id2 = id2; - } + public void setId2( int id2 ) { + this.id2 = id2; + } - @Override - public boolean equals( Object obj ) { - if (obj == null) return false; - if (getClass() != obj.getClass()) return false; - final CompositeId other = (CompositeId)obj; - if (this.id1 != other.id1) return false; - if (this.id2 != other.id2) return false; - return true; - } + @Override + public boolean equals( Object obj ) { + if (obj == null) return false; + if (getClass() != obj.getClass()) return false; + final CompositeId other = (CompositeId)obj; + if (this.id1 != other.id1) return false; + if (this.id2 != other.id2) return false; + return true; + } - @Override - public int hashCode() { - int hash = 5; - hash = 73 * hash + this.id1; - hash = 73 * hash + this.id2; - return hash; - } + @Override + public int hashCode() { + int hash = 5; + hash = 73 * hash + this.id1; + hash = 73 * hash + this.id2; + return hash; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/CompositeIdFkUpdateTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/CompositeIdFkUpdateTest.java index a1f4074acc..227bcd7297 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/CompositeIdFkUpdateTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/CompositeIdFkUpdateTest.java @@ -18,50 +18,50 @@ import jakarta.persistence.Query; import static org.assertj.core.api.Assertions.assertThat; @Jpa(annotatedClasses = { - EntityWithCompositeIdFkAssociation.class, - EntityWithCompositeId.class, - CompositeId.class + EntityWithCompositeIdFkAssociation.class, + EntityWithCompositeId.class, + CompositeId.class }) public class CompositeIdFkUpdateTest { - @Test - public void testUpdateAssociationSetNull(EntityManagerFactoryScope scope) { - scope.inTransaction( - entityManager -> { - Query q = entityManager.createQuery( - "update EntityWithCompositeIdFkAssociation e set e.association = null" ); + @Test + public void testUpdateAssociationSetNull(EntityManagerFactoryScope scope) { + scope.inTransaction( + entityManager -> { + Query q = entityManager.createQuery( + "update EntityWithCompositeIdFkAssociation e set e.association = null" ); - q.executeUpdate(); - } - ); - } + q.executeUpdate(); + } + ); + } - @Test - public void testUpdateAssociationSetRubbish(EntityManagerFactoryScope scope) { - scope.inTransaction( - entityManager -> { - try { - entityManager.createQuery( - "update EntityWithCompositeIdFkAssociation e set e.association = 1" ); - Assertions.fail( "Expected query type validation to fail due to illegal assignment" ); - } - catch (IllegalArgumentException ex) { - assertThat( ex.getCause() ).isInstanceOf( SemanticException.class ); - assertThat( ex.getCause() ).hasMessageContaining( "Cannot assign expression of type" ); - } - } - ); - } + @Test + public void testUpdateAssociationSetRubbish(EntityManagerFactoryScope scope) { + scope.inTransaction( + entityManager -> { + try { + entityManager.createQuery( + "update EntityWithCompositeIdFkAssociation e set e.association = 1" ); + Assertions.fail( "Expected query type validation to fail due to illegal assignment" ); + } + catch (IllegalArgumentException ex) { + assertThat( ex.getCause() ).isInstanceOf( SemanticException.class ); + assertThat( ex.getCause() ).hasMessageContaining( "Cannot assign expression of type" ); + } + } + ); + } - @Test - public void testUpdateAssociationSetAssociationPart(EntityManagerFactoryScope scope) { - scope.inTransaction( - entityManager -> { - Query q = entityManager.createQuery( - "update EntityWithCompositeIdFkAssociation e set e.association.id.id1 = 1" ); + @Test + public void testUpdateAssociationSetAssociationPart(EntityManagerFactoryScope scope) { + scope.inTransaction( + entityManager -> { + Query q = entityManager.createQuery( + "update EntityWithCompositeIdFkAssociation e set e.association.id.id1 = 1" ); - q.executeUpdate(); - } - ); - } + q.executeUpdate(); + } + ); + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/CompositeIdRowValueTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/CompositeIdRowValueTest.java index a99504442d..dec13e940a 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/CompositeIdRowValueTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/CompositeIdRowValueTest.java @@ -19,23 +19,23 @@ import static org.hamcrest.core.Is.is; @JiraKey( value = "HHH-9029") @Jpa(annotatedClasses = { - EntityWithCompositeId.class, - CompositeId.class + EntityWithCompositeId.class, + CompositeId.class }) public class CompositeIdRowValueTest { - @Test - public void testTupleAfterSubQuery(EntityManagerFactoryScope scope) { - scope.inTransaction( - entityManager -> { - Query q = entityManager.createQuery("SELECT e FROM EntityWithCompositeId e " - + "WHERE EXISTS (SELECT 1 FROM EntityWithCompositeId) " - + "AND e.id = :id"); + @Test + public void testTupleAfterSubQuery(EntityManagerFactoryScope scope) { + scope.inTransaction( + entityManager -> { + Query q = entityManager.createQuery("SELECT e FROM EntityWithCompositeId e " + + "WHERE EXISTS (SELECT 1 FROM EntityWithCompositeId) " + + "AND e.id = :id"); - q.setParameter("id", new CompositeId(1, 2)); + q.setParameter("id", new CompositeId(1, 2)); - assertThat(q.getResultList().size(), is(0)); - } - ); - } + assertThat(q.getResultList().size(), is(0)); + } + ); + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/CountEntityWithCompositeIdTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/CountEntityWithCompositeIdTest.java index 9ddb51c394..00d1d49651 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/CountEntityWithCompositeIdTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/CountEntityWithCompositeIdTest.java @@ -19,30 +19,30 @@ import static org.hamcrest.core.Is.is; import static org.hamcrest.MatcherAssert.assertThat; @Jpa(annotatedClasses = { - EntityWithCompositeId.class, - CompositeId.class + EntityWithCompositeId.class, + CompositeId.class }) public class CountEntityWithCompositeIdTest { - @Test - public void shouldCount(EntityManagerFactoryScope scope) { - scope.inTransaction( - entityManager -> { - CriteriaBuilder cb = entityManager.getCriteriaBuilder(); - CriteriaQuery cq = cb.createQuery(Long.class); - Root r = cq.from(EntityWithCompositeId.class); - cq.multiselect(cb.count(r)); - assertThat(entityManager.createQuery(cq).getSingleResult().intValue(), is(0)); - } - ); - scope.inTransaction( - entityManager -> { - HibernateCriteriaBuilder cb = (HibernateCriteriaBuilder) entityManager.getCriteriaBuilder(); - CriteriaQuery cq = cb.createQuery(Long.class); - cq.from(EntityWithCompositeId.class); - cq.select(cb.count()); - assertThat(entityManager.createQuery(cq).getSingleResult().intValue(), is(0)); - } - ); - } + @Test + public void shouldCount(EntityManagerFactoryScope scope) { + scope.inTransaction( + entityManager -> { + CriteriaBuilder cb = entityManager.getCriteriaBuilder(); + CriteriaQuery cq = cb.createQuery(Long.class); + Root r = cq.from(EntityWithCompositeId.class); + cq.multiselect(cb.count(r)); + assertThat(entityManager.createQuery(cq).getSingleResult().intValue(), is(0)); + } + ); + scope.inTransaction( + entityManager -> { + HibernateCriteriaBuilder cb = (HibernateCriteriaBuilder) entityManager.getCriteriaBuilder(); + CriteriaQuery cq = cb.createQuery(Long.class); + cq.from(EntityWithCompositeId.class); + cq.select(cb.count()); + assertThat(entityManager.createQuery(cq).getSingleResult().intValue(), is(0)); + } + ); + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/EntityManagerTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/EntityManagerTest.java index 28d3011e60..4f9bcad60f 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/EntityManagerTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/EntityManagerTest.java @@ -404,40 +404,40 @@ public class EntityManagerTest extends BaseEntityManagerFunctionalTestCase { } } - @Test - public void testPersistExisting() throws Exception { - EntityManager em = getOrCreateEntityManager(); - em.getTransaction().begin(); - Wallet w = new Wallet(); - w.setBrand( "Lacoste" ); - w.setModel( "Minimic" ); - w.setSerial( "0100202002" ); - em.persist( w ); - w = new Wallet(); - w.setBrand( "Lacoste" ); - w.setModel( "Minimic" ); - w.setSerial( "0100202002" ); - try { - em.persist( w ); - } - catch ( EntityExistsException eee ) { - //success - if ( em.getTransaction() != null ) { - em.getTransaction().rollback(); - } - em.close(); - return; - } - try { - em.getTransaction().commit(); - fail( "Should have raised an exception" ); - } - catch ( PersistenceException pe ) { - } - finally { - em.close(); - } - } + @Test + public void testPersistExisting() throws Exception { + EntityManager em = getOrCreateEntityManager(); + em.getTransaction().begin(); + Wallet w = new Wallet(); + w.setBrand( "Lacoste" ); + w.setModel( "Minimic" ); + w.setSerial( "0100202002" ); + em.persist( w ); + w = new Wallet(); + w.setBrand( "Lacoste" ); + w.setModel( "Minimic" ); + w.setSerial( "0100202002" ); + try { + em.persist( w ); + } + catch ( EntityExistsException eee ) { + //success + if ( em.getTransaction() != null ) { + em.getTransaction().rollback(); + } + em.close(); + return; + } + try { + em.getTransaction().commit(); + fail( "Should have raised an exception" ); + } + catch ( PersistenceException pe ) { + } + finally { + em.close(); + } + } @Test public void testFactoryClosed() throws Exception { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/EntityWithCompositeId.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/EntityWithCompositeId.java index cc2900a7f2..ca48d74f26 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/EntityWithCompositeId.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/EntityWithCompositeId.java @@ -16,23 +16,23 @@ import jakarta.persistence.Entity; @Entity public class EntityWithCompositeId implements Serializable { - @EmbeddedId - private CompositeId id; - private String description; + @EmbeddedId + private CompositeId id; + private String description; - public CompositeId getId() { - return id; - } + public CompositeId getId() { + return id; + } - public void setId(CompositeId id) { - this.id = id; - } + public void setId(CompositeId id) { + this.id = id; + } - public String getDescription() { - return description; - } + public String getDescription() { + return description; + } - public void setDescription(String description) { - this.description = description; - } + public void setDescription(String description) { + this.description = description; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/EntityWithCompositeIdFkAssociation.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/EntityWithCompositeIdFkAssociation.java index 9c7fb17267..42aafac3a8 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/EntityWithCompositeIdFkAssociation.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/EntityWithCompositeIdFkAssociation.java @@ -20,24 +20,24 @@ import jakarta.persistence.Table; @Table(name = "entity_composite_fk") public class EntityWithCompositeIdFkAssociation implements Serializable { - @Id - private int id; - @ManyToOne - private EntityWithCompositeId association; + @Id + private int id; + @ManyToOne + private EntityWithCompositeId association; - public int getId() { - return id; - } + public int getId() { + return id; + } - public void setId(int id) { - this.id = id; - } + public void setId(int id) { + this.id = id; + } - public EntityWithCompositeId getAssociation() { - return association; - } + public EntityWithCompositeId getAssociation() { + return association; + } - public void setAssociation(EntityWithCompositeId association) { - this.association = association; - } + public void setAssociation(EntityWithCompositeId association) { + this.association = association; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/Kitten.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/Kitten.java index baa1cfa61d..f21a79e5e3 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/Kitten.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/Kitten.java @@ -46,16 +46,16 @@ public class Kitten { */ public String toString() { - final String TAB = " "; + final String TAB = " "; - String retValue = ""; + String retValue = ""; - retValue = "Kitten ( " - + super.toString() + TAB - + "id = " + this.id + TAB - + "name = " + this.name + TAB - + " )"; + retValue = "Kitten ( " + + super.toString() + TAB + + "id = " + this.id + TAB + + "name = " + this.name + TAB + + " )"; - return retValue; + return retValue; } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/association/toone/CriteriaJoinFetchTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/association/toone/CriteriaJoinFetchTest.java index 5e1d2031a8..8435365a49 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/association/toone/CriteriaJoinFetchTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/association/toone/CriteriaJoinFetchTest.java @@ -140,7 +140,7 @@ public class CriteriaJoinFetchTest { final Fetch fetch = customer.fetch( address, JoinType.INNER ); fetch.fetch( entityManager.getMetamodel() - .entity( Address.class ).getSingularAttribute( "note" ), JoinType.INNER ); + .entity( Address.class ).getSingularAttribute( "note" ), JoinType.INNER ); criteriaQuery.select( customer ); final TypedQuery query = entityManager.createQuery( criteriaQuery ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/callbacks/PrePersistIdTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/callbacks/PrePersistIdTest.java index 4cd2145a49..93a7607ebc 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/callbacks/PrePersistIdTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/callbacks/PrePersistIdTest.java @@ -24,22 +24,22 @@ import static org.junit.jupiter.api.Assertions.assertTrue; @SessionFactory @DomainModel(annotatedClasses = PrePersistIdTest.GeneratedIdInCallback.class) public class PrePersistIdTest { - @Test void test(SessionFactoryScope scope) { - scope.inTransaction(s -> { - GeneratedIdInCallback entity = new GeneratedIdInCallback(); - s.persist(entity); - assertTrue(entity.success); - assertNotNull(entity.uuid); - }); - } + @Test void test(SessionFactoryScope scope) { + scope.inTransaction(s -> { + GeneratedIdInCallback entity = new GeneratedIdInCallback(); + s.persist(entity); + assertTrue(entity.success); + assertNotNull(entity.uuid); + }); + } - @Entity(name = "GeneratedIdInCallback") - static class GeneratedIdInCallback { - @Transient boolean success; - @Id @GeneratedValue UUID uuid; - @PrePersist void checkId() { - success = uuid != null; - assertNotNull(uuid); - } - } + @Entity(name = "GeneratedIdInCallback") + static class GeneratedIdInCallback { + @Transient boolean success; + @Id @GeneratedValue UUID uuid; + @PrePersist void checkId() { + success = uuid != null; + assertNotNull(uuid); + } + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/cascade/Author.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/cascade/Author.java index 592411bb1c..7ebaea43c0 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/cascade/Author.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/cascade/Author.java @@ -14,7 +14,7 @@ import jakarta.persistence.Id; */ @Entity public class Author { - @Id @GeneratedValue - private Long id; +@Id @GeneratedValue +private Long id; } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/cascade/multicircle/B.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/cascade/multicircle/B.java index 047444e0e8..e81ddf30e6 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/cascade/multicircle/B.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/cascade/multicircle/B.java @@ -11,15 +11,15 @@ package org.hibernate.orm.test.jpa.cascade.multicircle; */ @jakarta.persistence.Entity public class B extends AbstractEntity { - private static final long serialVersionUID = 325417243L; + private static final long serialVersionUID = 325417243L; - /** - * No documentation - */ - @jakarta.persistence.OneToMany(cascade = { - jakarta.persistence.CascadeType.MERGE, jakarta.persistence.CascadeType.PERSIST, jakarta.persistence.CascadeType.REFRESH} - , mappedBy = "b") - private java.util.Set gCollection = new java.util.HashSet(); + /** + * No documentation + */ + @jakarta.persistence.OneToMany(cascade = { + jakarta.persistence.CascadeType.MERGE, jakarta.persistence.CascadeType.PERSIST, jakarta.persistence.CascadeType.REFRESH} + , mappedBy = "b") + private java.util.Set gCollection = new java.util.HashSet(); /** @@ -32,30 +32,30 @@ public class B extends AbstractEntity { - /** - * No documentation - */ - @jakarta.persistence.ManyToOne(cascade = { - jakarta.persistence.CascadeType.MERGE, jakarta.persistence.CascadeType.PERSIST, jakarta.persistence.CascadeType.REFRESH} - , optional = false) - private D d; + /** + * No documentation + */ + @jakarta.persistence.ManyToOne(cascade = { + jakarta.persistence.CascadeType.MERGE, jakarta.persistence.CascadeType.PERSIST, jakarta.persistence.CascadeType.REFRESH} + , optional = false) + private D d; - public java.util.Set getGCollection() { - return gCollection; - } + public java.util.Set getGCollection() { + return gCollection; + } - public void setGCollection( - java.util.Set parameter) { - this.gCollection = parameter; - } + public void setGCollection( + java.util.Set parameter) { + this.gCollection = parameter; + } - public C getC() { - return c; - } + public C getC() { + return c; + } - public void setC(C parameter) { - this.c = parameter; - } + public void setC(C parameter) { + this.c = parameter; + } public D getD() { return d; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/cascade/multicircle/C.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/cascade/multicircle/C.java index 7f93aef8f7..2b78848c7c 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/cascade/multicircle/C.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/cascade/multicircle/C.java @@ -13,7 +13,7 @@ import java.util.Set; */ @jakarta.persistence.Entity public class C extends AbstractEntity { - private static final long serialVersionUID = 1226955752L; + private static final long serialVersionUID = 1226955752L; @jakarta.persistence.OneToMany(mappedBy = "c") private Set bCollection = new java.util.HashSet(); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/cascade/multicircle/D.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/cascade/multicircle/D.java index 8f4b54290b..a3485796b5 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/cascade/multicircle/D.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/cascade/multicircle/D.java @@ -11,7 +11,7 @@ package org.hibernate.orm.test.jpa.cascade.multicircle; */ @jakarta.persistence.Entity public class D extends AbstractEntity { - private static final long serialVersionUID = 2417176961L; + private static final long serialVersionUID = 2417176961L; @jakarta.persistence.OneToMany(mappedBy = "d") private java.util.Set bCollection = new java.util.HashSet(); @@ -22,11 +22,11 @@ public class D extends AbstractEntity { @jakarta.persistence.ManyToOne(optional = false) private E e; - @jakarta.persistence.OneToMany(cascade = { - jakarta.persistence.CascadeType.MERGE, jakarta.persistence.CascadeType.PERSIST, jakarta.persistence.CascadeType.REFRESH}, + @jakarta.persistence.OneToMany(cascade = { + jakarta.persistence.CascadeType.MERGE, jakarta.persistence.CascadeType.PERSIST, jakarta.persistence.CascadeType.REFRESH}, mappedBy = "d" - ) - private java.util.Set fCollection = new java.util.HashSet(); + ) + private java.util.Set fCollection = new java.util.HashSet(); public java.util.Set getBCollection() { return bCollection; @@ -50,12 +50,12 @@ public class D extends AbstractEntity { this.e = e; } - public java.util.Set getFCollection() { - return fCollection; - } - public void setFCollection( + public java.util.Set getFCollection() { + return fCollection; + } + public void setFCollection( java.util.Set parameter) { - this.fCollection = parameter; - } + this.fCollection = parameter; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/cascade/multicircle/E.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/cascade/multicircle/E.java index d54bfb1504..360dfdc926 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/cascade/multicircle/E.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/cascade/multicircle/E.java @@ -11,7 +11,7 @@ package org.hibernate.orm.test.jpa.cascade.multicircle; */ @jakarta.persistence.Entity public class E extends AbstractEntity { - private static final long serialVersionUID = 1226955558L; + private static final long serialVersionUID = 1226955558L; @jakarta.persistence.OneToMany(mappedBy = "e") private java.util.Set dCollection = new java.util.HashSet(); @@ -26,10 +26,10 @@ public class E extends AbstractEntity { this.dCollection = dCollection; } - public F getF() { - return f; - } - public void setF(F parameter) { - this.f = parameter; - } + public F getF() { + return f; + } + public void setF(F parameter) { + this.f = parameter; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/cascade/multicircle/F.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/cascade/multicircle/F.java index 88b324349e..065c43b87d 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/cascade/multicircle/F.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/cascade/multicircle/F.java @@ -11,15 +11,15 @@ package org.hibernate.orm.test.jpa.cascade.multicircle; */ @jakarta.persistence.Entity public class F extends AbstractEntity { - private static final long serialVersionUID = 1471534025L; + private static final long serialVersionUID = 1471534025L; - /** - * No documentation - */ - @jakarta.persistence.OneToMany(cascade = { - jakarta.persistence.CascadeType.MERGE, jakarta.persistence.CascadeType.PERSIST, jakarta.persistence.CascadeType.REFRESH} - , mappedBy = "f") - private java.util.Set eCollection = new java.util.HashSet(); + /** + * No documentation + */ + @jakarta.persistence.OneToMany(cascade = { + jakarta.persistence.CascadeType.MERGE, jakarta.persistence.CascadeType.PERSIST, jakarta.persistence.CascadeType.REFRESH} + , mappedBy = "f") + private java.util.Set eCollection = new java.util.HashSet(); @jakarta.persistence.ManyToOne(optional = false) private D d; @@ -27,20 +27,20 @@ public class F extends AbstractEntity { @jakarta.persistence.ManyToOne(optional = false) private G g; - public java.util.Set getECollection() { - return eCollection; - } - public void setECollection( - java.util.Set parameter) { - this.eCollection = parameter; - } + public java.util.Set getECollection() { + return eCollection; + } + public void setECollection( + java.util.Set parameter) { + this.eCollection = parameter; + } - public D getD() { - return d; - } - public void setD(D parameter) { - this.d = parameter; - } + public D getD() { + return d; + } + public void setD(D parameter) { + this.d = parameter; + } public G getG() { return g; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/cascade/multicircle/G.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/cascade/multicircle/G.java index d9327575f1..bed0089c80 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/cascade/multicircle/G.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/cascade/multicircle/G.java @@ -11,13 +11,13 @@ package org.hibernate.orm.test.jpa.cascade.multicircle; */ @jakarta.persistence.Entity public class G extends AbstractEntity { - private static final long serialVersionUID = 325417437L; + private static final long serialVersionUID = 325417437L; @jakarta.persistence.ManyToOne(optional = false) private B b; - @jakarta.persistence.OneToMany(mappedBy = "g") - private java.util.Set fCollection = new java.util.HashSet(); + @jakarta.persistence.OneToMany(mappedBy = "g") + private java.util.Set fCollection = new java.util.HashSet(); public B getB() { return b; @@ -26,11 +26,11 @@ public class G extends AbstractEntity { this.b = parameter; } - public java.util.Set getFCollection() { - return fCollection; - } - public void setFCollection( - java.util.Set parameter) { - this.fCollection = parameter; - } + public java.util.Set getFCollection() { + return fCollection; + } + public void setFCollection( + java.util.Set parameter) { + this.fCollection = parameter; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/cascade/multilevel/Bottom.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/cascade/multilevel/Bottom.java index a26b96b07a..38fae79a86 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/cascade/multilevel/Bottom.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/cascade/multilevel/Bottom.java @@ -15,25 +15,25 @@ import jakarta.persistence.Table; @Entity @Table(name = "BOTTOM") public class Bottom { - @Id - @GeneratedValue - private Long id; - @OneToOne(mappedBy = "bottom") - private Middle middle; + @Id + @GeneratedValue + private Long id; + @OneToOne(mappedBy = "bottom") + private Middle middle; - Long getId() { - return id; - } + Long getId() { + return id; + } - void setId(Long id) { - this.id = id; - } + void setId(Long id) { + this.id = id; + } - Middle getMiddle() { - return middle; - } + Middle getMiddle() { + return middle; + } - void setMiddle(Middle middle) { - this.middle = middle; - } + void setMiddle(Middle middle) { + this.middle = middle; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/cascade/multilevel/Middle.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/cascade/multilevel/Middle.java index e65867a198..0a0bf99eaf 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/cascade/multilevel/Middle.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/cascade/multilevel/Middle.java @@ -17,45 +17,45 @@ import jakarta.persistence.Table; @Entity @Table(name = "MIDDLE") public class Middle { - @Id - private Long id; - @ManyToOne - private Top top; + @Id + private Long id; + @ManyToOne + private Top top; - @OneToOne(cascade = { CascadeType.ALL }) - @JoinColumn(name = "BOTTOM_ID") - private Bottom bottom; + @OneToOne(cascade = { CascadeType.ALL }) + @JoinColumn(name = "BOTTOM_ID") + private Bottom bottom; - private Middle() { + private Middle() { - } + } - public Middle(Long i) { - this.id = i; - } + public Middle(Long i) { + this.id = i; + } - Long getId() { - return id; - } + Long getId() { + return id; + } - void setId(Long id) { - this.id = id; - } + void setId(Long id) { + this.id = id; + } - Top getTop() { - return top; - } + Top getTop() { + return top; + } - void setTop(Top top) { - this.top = top; - } + void setTop(Top top) { + this.top = top; + } - Bottom getBottom() { - return bottom; - } + Bottom getBottom() { + return bottom; + } - void setBottom(Bottom bottom) { - this.bottom = bottom; - bottom.setMiddle(this); - } + void setBottom(Bottom bottom) { + this.bottom = bottom; + bottom.setMiddle(this); + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/cascade/multilevel/Top.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/cascade/multilevel/Top.java index afe9d0d9d1..5c66adffb7 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/cascade/multilevel/Top.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/cascade/multilevel/Top.java @@ -18,34 +18,34 @@ import jakarta.persistence.Table; @Entity @Table(name = "T_TOP") public class Top { - @Id - @GeneratedValue - private Long id; + @Id + @GeneratedValue + private Long id; - @OneToMany(cascade = { CascadeType.ALL }, mappedBy = "top") - List middles; + @OneToMany(cascade = { CascadeType.ALL }, mappedBy = "top") + List middles; - Long getId() { - return id; - } + Long getId() { + return id; + } - void setId(Long id) { - this.id = id; - } + void setId(Long id) { + this.id = id; + } - List getMiddles() { - if (middles == null) { - middles = new ArrayList(); - } - return middles; - } + List getMiddles() { + if (middles == null) { + middles = new ArrayList(); + } + return middles; + } - void setMiddles(List middles) { - this.middles = middles; - } + void setMiddles(List middles) { + this.middles = middles; + } - void addMiddle(Middle middle) { - this.getMiddles().add(middle); - middle.setTop(this); - } + void addMiddle(Middle middle) { + this.getMiddles().add(middle); + middle.setTop(this); + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/collection/Child.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/collection/Child.java index 104b7e6733..4a4d2824ef 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/collection/Child.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/collection/Child.java @@ -13,28 +13,28 @@ import jakarta.persistence.ManyToOne; @Entity public class Child { - private Integer id; - private Parent daddy; + private Integer id; + private Parent daddy; - public Child() { + public Child() { - } + } - @Id - public Integer getId() { - return id; - } - public void setId(Integer id) { - this.id = id; - } + @Id + public Integer getId() { + return id; + } + public void setId(Integer id) { + this.id = id; + } - @ManyToOne - public Parent getDaddy() { - return daddy; - } - public void setDaddy(Parent daddy) { - this.daddy = daddy; - } + @ManyToOne + public Parent getDaddy() { + return daddy; + } + public void setDaddy(Parent daddy) { + this.daddy = daddy; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/collection/Parent.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/collection/Parent.java index ce802d6dcc..bd1951dd2d 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/collection/Parent.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/collection/Parent.java @@ -20,37 +20,37 @@ import jakarta.persistence.Transient; @Entity public class Parent { - private Integer id; - private Set children = new HashSet(); - private int nrOfChildren; + private Integer id; + private Set children = new HashSet(); + private int nrOfChildren; - public Parent() { + public Parent() { - } + } - @Id - public Integer getId() { - return id; - } - public void setId(Integer id) { - this.id = id; - } + @Id + public Integer getId() { + return id; + } + public void setId(Integer id) { + this.id = id; + } - @OneToMany(mappedBy="daddy", fetch=FetchType.EAGER, cascade=CascadeType.ALL) - public Set getChildren() { - return children; - } - public void setChildren(Set children) { - this.children = children; - } + @OneToMany(mappedBy="daddy", fetch=FetchType.EAGER, cascade=CascadeType.ALL) + public Set getChildren() { + return children; + } + public void setChildren(Set children) { + this.children = children; + } - @PostLoad - public void postLoad() { - nrOfChildren = children.size(); - } + @PostLoad + public void postLoad() { + nrOfChildren = children.size(); + } - @Transient - public int getNrOfChildren() { - return nrOfChildren; - } + @Transient + public int getNrOfChildren() { + return nrOfChildren; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/compliance/CriteriaFunctionParametersBindingTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/compliance/CriteriaFunctionParametersBindingTest.java index e26d9c9df3..53fc73ef75 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/compliance/CriteriaFunctionParametersBindingTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/compliance/CriteriaFunctionParametersBindingTest.java @@ -52,7 +52,7 @@ public class CriteriaFunctionParametersBindingTest { @AfterEach public void tearDown(EntityManagerFactoryScope scope) { scope.inTransaction( entityManager -> - entityManager.createQuery( "delete from Person" ).executeUpdate() ); + entityManager.createQuery( "delete from Person" ).executeUpdate() ); } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/compliance/CriteriaGetParametersTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/compliance/CriteriaGetParametersTest.java index 3752a0610e..1c4e2d095b 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/compliance/CriteriaGetParametersTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/compliance/CriteriaGetParametersTest.java @@ -93,7 +93,7 @@ public class CriteriaGetParametersTest { final EntityType Person_ = entityManager.getMetamodel().entity( Person.class ); Join a = customer.join( Person_.getCollection( "addresses", Address.class ) ); cquery.where( cbuilder.like( a.get( "street" ), "sh\\_ll", - cbuilder.literal( '\\' ) + cbuilder.literal( '\\' ) ) ); cquery.select( customer ); TypedQuery tquery = entityManager.createQuery( cquery ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/compliance/LocateTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/compliance/LocateTest.java index 8b96200175..3a1244f94f 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/compliance/LocateTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/compliance/LocateTest.java @@ -97,7 +97,7 @@ public class LocateTest { final Expression locate = criteriaBuilder.locate( personRoot.get( "name" ), - "nd" , + "nd" , 1 ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/connection/DataSourceInjectionTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/connection/DataSourceInjectionTest.java index c08ac506bc..1e66987e32 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/connection/DataSourceInjectionTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/connection/DataSourceInjectionTest.java @@ -35,9 +35,9 @@ import org.junit.jupiter.api.Test; * @author Emmanuel Bernard */ public class DataSourceInjectionTest { - @Test + @Test public void testDatasourceInjection() throws Exception { - withPuRoot( + withPuRoot( puRootUrl -> { final PersistenceUnitInfoAdapter persistenceUnitInfo = createPuDescriptor( puRootUrl, new FakeDataSource() ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/criteria/PowerFunctionTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/criteria/PowerFunctionTest.java index 3e121a9476..c89782861b 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/criteria/PowerFunctionTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/criteria/PowerFunctionTest.java @@ -59,7 +59,7 @@ public class PowerFunctionTest { if ( getDialect( scope ) instanceof DerbyDialect ) { /** - for Derby dialect we are emulating the power function see {@link CommonFunctionFactory#power_expLn()}. + for Derby dialect we are emulating the power function see {@link CommonFunctionFactory#power_expLn()}. */ assertThat( results.get( 0 ) ).isEqualTo( 2500D, Offset.offset( 0.000000000001 ) ); } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/criteria/components/ComponentInWhereClauseTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/criteria/components/ComponentInWhereClauseTest.java index 02481c50be..da8f0dabf9 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/criteria/components/ComponentInWhereClauseTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/criteria/components/ComponentInWhereClauseTest.java @@ -214,8 +214,8 @@ public class ComponentInWhereClauseTest { Root root = query.from( Employee.class ); query.where( root.get( "projects" ) - .get( "currentProject" ) - .in( projects.getCurrentProject() ) ); + .get( "currentProject" ) + .in( projects.getCurrentProject() ) ); final List results = entityManager.createQuery( query ).getResultList(); assertThat( results.size(), is( 1 ) ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/criteria/enumcollection/User.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/criteria/enumcollection/User.java index 87b5a579cd..8b08c4b75b 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/criteria/enumcollection/User.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/criteria/enumcollection/User.java @@ -37,7 +37,7 @@ public class User { @Enumerated(EnumType.STRING) @ElementCollection(targetClass = Role.class, fetch = FetchType.LAZY) @JoinTable(name = "user_role", - joinColumns = {@JoinColumn(name = "user_id")}) + joinColumns = {@JoinColumn(name = "user_id")}) @Column(name = "role_name", nullable = false) public Set getRoles() { return roles; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/criteria/nulliteral/CriteriaLiteralsTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/criteria/nulliteral/CriteriaLiteralsTest.java index fe457728f3..2774967e55 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/criteria/nulliteral/CriteriaLiteralsTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/criteria/nulliteral/CriteriaLiteralsTest.java @@ -130,7 +130,7 @@ public class CriteriaLiteralsTest extends BaseEntityManagerFunctionalTestCase { doInJPA( this::entityManagerFactory, entityManager -> { testNumericLiterals( entityManager, - "select 'abc',b1_0.name from Book b1_0 where b1_0.id=1" + "select 'abc',b1_0.name from Book b1_0 where b1_0.id=1" ); } ); } @@ -140,7 +140,7 @@ public class CriteriaLiteralsTest extends BaseEntityManagerFunctionalTestCase { doInJPA( this::entityManagerFactory, entityManager -> { testNumericLiterals( entityManager, - "select 'abc',b1_0.name from Book b1_0 where b1_0.id=1" + "select 'abc',b1_0.name from Book b1_0 where b1_0.id=1" ); } ); } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/criteria/paths/AbstractPathImplTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/criteria/paths/AbstractPathImplTest.java index c918f21386..91dab58fc4 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/criteria/paths/AbstractPathImplTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/criteria/paths/AbstractPathImplTest.java @@ -32,41 +32,41 @@ import static org.junit.jupiter.api.Assertions.fail; * @author James Gilbertson */ public class AbstractPathImplTest extends AbstractMetamodelSpecificTest { - @BeforeEach - public void prepareTestData() { - EntityManager em = getOrCreateEntityManager(); - em.getTransaction().begin(); + @BeforeEach + public void prepareTestData() { + EntityManager em = getOrCreateEntityManager(); + em.getTransaction().begin(); - Thing thing = new Thing(); - thing.setId( "thing1" ); - thing.setName( "A Thing" ); - em.persist( thing ); + Thing thing = new Thing(); + thing.setId( "thing1" ); + thing.setName( "A Thing" ); + em.persist( thing ); - thing = new Thing(); - thing.setId( "thing2" ); - thing.setName( "Another Thing" ); - em.persist( thing ); + thing = new Thing(); + thing.setId( "thing2" ); + thing.setName( "Another Thing" ); + em.persist( thing ); - ThingWithQuantity thingWithQuantity = new ThingWithQuantity(); - thingWithQuantity.setId( "thingWithQuantity3" ); - thingWithQuantity.setName( "3 Things" ); - thingWithQuantity.setQuantity( 3 ); - em.persist( thingWithQuantity ); + ThingWithQuantity thingWithQuantity = new ThingWithQuantity(); + thingWithQuantity.setId( "thingWithQuantity3" ); + thingWithQuantity.setName( "3 Things" ); + thingWithQuantity.setQuantity( 3 ); + em.persist( thingWithQuantity ); - em.getTransaction().commit(); - em.close(); - } + em.getTransaction().commit(); + em.close(); + } - @AfterEach - public void cleanupTestData() { - EntityManager em = getOrCreateEntityManager(); - em.getTransaction().begin(); - em.remove( em.find( Thing.class, "thing1" ) ); - em.remove( em.find( Thing.class, "thing2" ) ); - em.remove( em.find( ThingWithQuantity.class, "thingWithQuantity3" ) ); - em.getTransaction().commit(); - em.close(); - } + @AfterEach + public void cleanupTestData() { + EntityManager em = getOrCreateEntityManager(); + em.getTransaction().begin(); + em.remove( em.find( Thing.class, "thing1" ) ); + em.remove( em.find( Thing.class, "thing2" ) ); + em.remove( em.find( ThingWithQuantity.class, "thingWithQuantity3" ) ); + em.getTransaction().commit(); + em.close(); + } @ExpectedException(value = IllegalArgumentException.class) @Test diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/criteria/paths/SingularAttributeJoinTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/criteria/paths/SingularAttributeJoinTest.java index 5e04d2e8a7..ea503775d0 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/criteria/paths/SingularAttributeJoinTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/criteria/paths/SingularAttributeJoinTest.java @@ -24,33 +24,33 @@ import org.junit.jupiter.api.Test; * @author Brad Koehn */ @Jpa( - integrationSettings = { @Setting(name = AvailableSettings.JPA_METAMODEL_POPULATION, value = "enabled") }, - xmlMappings = { "org/hibernate/orm/test/jpa/criteria/paths/PolicyAndDistribution.hbm.xml" } + integrationSettings = { @Setting(name = AvailableSettings.JPA_METAMODEL_POPULATION, value = "enabled") }, + xmlMappings = { "org/hibernate/orm/test/jpa/criteria/paths/PolicyAndDistribution.hbm.xml" } ) public class SingularAttributeJoinTest { - @Test - public void testEntityModeMapJoinCriteriaQuery(EntityManagerFactoryScope scope) { - scope.inEntityManager( - entityManager -> { - CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder(); - CriteriaQuery criteriaQuery = criteriaBuilder.createQuery(); - jakarta.persistence.metamodel.EntityType distributionEntity = getEntityType(scope, "Distribution"); - From distributionFrom = criteriaQuery.from(distributionEntity); - From policyJoin = distributionFrom.join("policy"); - Path policyId = policyJoin.get("policyId"); - criteriaQuery.select(policyId); - TypedQuery typedQuery = entityManager.createQuery(criteriaQuery); - } - ); - } + @Test + public void testEntityModeMapJoinCriteriaQuery(EntityManagerFactoryScope scope) { + scope.inEntityManager( + entityManager -> { + CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder(); + CriteriaQuery criteriaQuery = criteriaBuilder.createQuery(); + jakarta.persistence.metamodel.EntityType distributionEntity = getEntityType(scope, "Distribution"); + From distributionFrom = criteriaQuery.from(distributionEntity); + From policyJoin = distributionFrom.join("policy"); + Path policyId = policyJoin.get("policyId"); + criteriaQuery.select(policyId); + TypedQuery typedQuery = entityManager.createQuery(criteriaQuery); + } + ); + } - private jakarta.persistence.metamodel.EntityType getEntityType(EntityManagerFactoryScope scope, String entityName) { - for(jakarta.persistence.metamodel.EntityType entityType : scope.getEntityManagerFactory().getMetamodel().getEntities()) { - if (entityType.getName().equals("Distribution")) { - return entityType; - } - } - throw new IllegalStateException("Unable to find entity " + entityName); - } + private jakarta.persistence.metamodel.EntityType getEntityType(EntityManagerFactoryScope scope, String entityName) { + for(jakarta.persistence.metamodel.EntityType entityType : scope.getEntityManagerFactory().getMetamodel().getEntities()) { + if (entityType.getName().equals("Distribution")) { + return entityType; + } + } + throw new IllegalStateException("Unable to find entity " + entityName); + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/criteria/query/CriteriaDefinitionTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/criteria/query/CriteriaDefinitionTest.java index 5998b94781..d867052106 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/criteria/query/CriteriaDefinitionTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/criteria/query/CriteriaDefinitionTest.java @@ -26,133 +26,133 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; @Jpa(annotatedClasses = CriteriaDefinitionTest.Message.class) public class CriteriaDefinitionTest { - @Test void test(SessionFactoryScope scope) { - scope.inTransaction( s -> { - s.persist( new Message(1L, "hello") ); - s.persist( new Message(2L, "bye") ); - }); + @Test void test(SessionFactoryScope scope) { + scope.inTransaction( s -> { + s.persist( new Message(1L, "hello") ); + s.persist( new Message(2L, "bye") ); + }); - var factory = scope.getSessionFactory(); + var factory = scope.getSessionFactory(); - var query1 = new CriteriaDefinition<>(factory, Object[].class) {{ - var message = from(Message.class); - select(array(message.get("id"), message.get("text"))); - where(like(message.get("text"), "hell%"), message.get("id").equalTo(1)); - orderBy(asc(message.get("id"))); - }}; + var query1 = new CriteriaDefinition<>(factory, Object[].class) {{ + var message = from(Message.class); + select(array(message.get("id"), message.get("text"))); + where(like(message.get("text"), "hell%"), message.get("id").equalTo(1)); + orderBy(asc(message.get("id"))); + }}; - var query2 = new CriteriaDefinition<>(factory, Message.class) {{ - var message = from(Message.class); - where(like(message.get("text"), "hell%"), message.get("id").equalTo(1)); - orderBy(asc(message.get("id"))); - }}; + var query2 = new CriteriaDefinition<>(factory, Message.class) {{ + var message = from(Message.class); + where(like(message.get("text"), "hell%"), message.get("id").equalTo(1)); + orderBy(asc(message.get("id"))); + }}; - var query3 = new CriteriaDefinition<>(factory, Message.class, "from Msg") {{ - var message = (JpaRoot) getSelection(); - where(ilike(message.get("text"), "%e%")); - orderBy(asc(message.get("text"))); - }}; + var query3 = new CriteriaDefinition<>(factory, Message.class, "from Msg") {{ + var message = (JpaRoot) getSelection(); + where(ilike(message.get("text"), "%e%")); + orderBy(asc(message.get("text"))); + }}; - var query4 = new CriteriaDefinition<>(factory, Message.class) {{ - var message = from(Message.class); - restrict(like(message.get("text"), "hell%")); - restrict(message.get("id").equalTo(1)); - orderBy(asc(message.get("id"))); - }}; + var query4 = new CriteriaDefinition<>(factory, Message.class) {{ + var message = from(Message.class); + restrict(like(message.get("text"), "hell%")); + restrict(message.get("id").equalTo(1)); + orderBy(asc(message.get("id"))); + }}; - var query5 = new CriteriaDefinition<>(query4, Long.class) {{ - select(count()); - orderBy(); - }}; + var query5 = new CriteriaDefinition<>(query4, Long.class) {{ + select(count()); + orderBy(); + }}; - scope.inSession(session -> { - var idAndText = session.createSelectionQuery(query1).getSingleResult(); - assertNotNull(idAndText); - assertEquals(1L,idAndText[0]); - assertEquals("hello",idAndText[1]); + scope.inSession(session -> { + var idAndText = session.createSelectionQuery(query1).getSingleResult(); + assertNotNull(idAndText); + assertEquals(1L,idAndText[0]); + assertEquals("hello",idAndText[1]); - var message = session.createSelectionQuery(query2).getSingleResult(); - assertNotNull(message); - assertEquals(1L,message.id); - assertEquals("hello",message.text); + var message = session.createSelectionQuery(query2).getSingleResult(); + assertNotNull(message); + assertEquals(1L,message.id); + assertEquals("hello",message.text); - var messages = session.createSelectionQuery(query3).getResultList(); - assertEquals(2,messages.size()); + var messages = session.createSelectionQuery(query3).getResultList(); + assertEquals(2,messages.size()); - var msg = session.createSelectionQuery(query4).getSingleResult(); - assertNotNull(msg); - assertEquals(1L,msg.id); - assertEquals("hello",msg.text); + var msg = session.createSelectionQuery(query4).getSingleResult(); + assertNotNull(msg); + assertEquals(1L,msg.id); + assertEquals("hello",msg.text); - long count = session.createSelectionQuery(query5).getSingleResult(); - assertEquals(1L,count); - }); - } + long count = session.createSelectionQuery(query5).getSingleResult(); + assertEquals(1L,count); + }); + } - @Test void test(EntityManagerFactoryScope scope) { - scope.inTransaction( s -> { - s.persist( new Message(1L, "hello") ); - s.persist( new Message(2L, "bye") ); - }); + @Test void test(EntityManagerFactoryScope scope) { + scope.inTransaction( s -> { + s.persist( new Message(1L, "hello") ); + s.persist( new Message(2L, "bye") ); + }); - EntityManagerFactory factory = scope.getEntityManagerFactory(); + EntityManagerFactory factory = scope.getEntityManagerFactory(); - var query1 = new CriteriaDefinition<>(factory, Object[].class) {{ - var message = from(Message.class); - select(array(message.get("id"), message.get("text"))); - where(like(message.get("text"), "hell%"), message.get("id").equalTo(1)); - orderBy(asc(message.get("id"))); - }}; + var query1 = new CriteriaDefinition<>(factory, Object[].class) {{ + var message = from(Message.class); + select(array(message.get("id"), message.get("text"))); + where(like(message.get("text"), "hell%"), message.get("id").equalTo(1)); + orderBy(asc(message.get("id"))); + }}; - var query2 = new CriteriaDefinition<>(factory, Message.class) {{ - var message = from(Message.class); - where(like(message.get("text"), "hell%"), message.get("id").equalTo(1)); - orderBy(asc(message.get("id"))); - }}; + var query2 = new CriteriaDefinition<>(factory, Message.class) {{ + var message = from(Message.class); + where(like(message.get("text"), "hell%"), message.get("id").equalTo(1)); + orderBy(asc(message.get("id"))); + }}; - var query3 = new CriteriaDefinition<>(factory, Message.class, "from Msg") {{ - var message = (JpaRoot) getSelection(); - where(ilike(message.get("text"), "%e%")); - orderBy(asc(message.get("text"))); - }}; + var query3 = new CriteriaDefinition<>(factory, Message.class, "from Msg") {{ + var message = (JpaRoot) getSelection(); + where(ilike(message.get("text"), "%e%")); + orderBy(asc(message.get("text"))); + }}; - var query4 = new CriteriaDefinition<>(factory, Message.class) {{ - var message = from(Message.class); - restrict(like(message.get("text"), "hell%")); - restrict(message.get("id").equalTo(1)); - orderBy(asc(message.get("id"))); - }}; + var query4 = new CriteriaDefinition<>(factory, Message.class) {{ + var message = from(Message.class); + restrict(like(message.get("text"), "hell%")); + restrict(message.get("id").equalTo(1)); + orderBy(asc(message.get("id"))); + }}; - scope.inTransaction(entityManager -> { - var idAndText = entityManager.createQuery(query1).getSingleResult(); - assertNotNull(idAndText); - assertEquals(1L,idAndText[0]); - assertEquals("hello",idAndText[1]); + scope.inTransaction(entityManager -> { + var idAndText = entityManager.createQuery(query1).getSingleResult(); + assertNotNull(idAndText); + assertEquals(1L,idAndText[0]); + assertEquals("hello",idAndText[1]); - var message = entityManager.createQuery(query2).getSingleResult(); - assertNotNull(message); - assertEquals(1L,message.id); - assertEquals("hello",message.text); + var message = entityManager.createQuery(query2).getSingleResult(); + assertNotNull(message); + assertEquals(1L,message.id); + assertEquals("hello",message.text); - var messages = entityManager.createQuery(query3).getResultList(); - assertEquals(2,messages.size()); + var messages = entityManager.createQuery(query3).getResultList(); + assertEquals(2,messages.size()); - var msg = entityManager.createQuery(query4).getSingleResult(); - assertNotNull(msg); - assertEquals(1L,msg.id); - assertEquals("hello",msg.text); - }); - } + var msg = entityManager.createQuery(query4).getSingleResult(); + assertNotNull(msg); + assertEquals(1L,msg.id); + assertEquals("hello",msg.text); + }); + } - @Entity(name="Msg") - static class Message { - public Message(Long id, String text) { - this.id = id; - this.text = text; - } - Message() {} - @Id - Long id; - String text; - } + @Entity(name="Msg") + static class Message { + public Message(Long id, String text) { + this.id = id; + this.text = text; + } + Message() {} + @Id + Long id; + String text; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/criteria/query/CriteriaFromHqlTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/criteria/query/CriteriaFromHqlTest.java index 901c83efab..082ddce56d 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/criteria/query/CriteriaFromHqlTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/criteria/query/CriteriaFromHqlTest.java @@ -22,33 +22,33 @@ import static org.junit.jupiter.api.Assertions.assertEquals; @DomainModel(annotatedClasses = CriteriaFromHqlTest.Message.class) public class CriteriaFromHqlTest { - @Test void test(SessionFactoryScope scope) { - scope.inTransaction( s -> { - s.persist( new Message(1L, "hello") ); - s.persist( new Message(2L, "bye") ); - }); + @Test void test(SessionFactoryScope scope) { + scope.inTransaction( s -> { + s.persist( new Message(1L, "hello") ); + s.persist( new Message(2L, "bye") ); + }); - scope.inSession( s -> { - JpaCriteriaQuery query = - s.getFactory().getCriteriaBuilder() - .createQuery("select id, text from Msg order by id", Object[].class); - assertEquals(2, query.getSelection().getSelectionItems().size()); - assertEquals(1, query.getOrderList().size()); - assertEquals(1, query.getRoots().size()); - List list = s.createSelectionQuery(query).getResultList(); - assertEquals(2, list.size()); - }); - } + scope.inSession( s -> { + JpaCriteriaQuery query = + s.getFactory().getCriteriaBuilder() + .createQuery("select id, text from Msg order by id", Object[].class); + assertEquals(2, query.getSelection().getSelectionItems().size()); + assertEquals(1, query.getOrderList().size()); + assertEquals(1, query.getRoots().size()); + List list = s.createSelectionQuery(query).getResultList(); + assertEquals(2, list.size()); + }); + } - @Entity(name="Msg") - static class Message { - public Message(Long id, String text) { - this.id = id; - this.text = text; - } - Message() {} - @Id - Long id; - String text; - } + @Entity(name="Msg") + static class Message { + public Message(Long id, String text) { + this.id = id; + this.text = text; + } + Message() {} + @Id + Long id; + String text; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/criteria/subquery/CorrelatedSubqueryTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/criteria/subquery/CorrelatedSubqueryTest.java index 0926980819..12e5bf8c73 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/criteria/subquery/CorrelatedSubqueryTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/criteria/subquery/CorrelatedSubqueryTest.java @@ -129,15 +129,15 @@ public class CorrelatedSubqueryTest extends AbstractMetamodelSpecificTest { public void testCorrelatedJoinsFromSubquery() { CriteriaBuilder builder = entityManagerFactory().getCriteriaBuilder(); CriteriaQuery cquery = builder.createQuery(Customer.class); - Root customer = cquery.from(Customer.class); - cquery.select(customer); - Subquery sq = cquery.subquery(Order.class); - Join sqo = sq.correlate(customer.join(Customer_.orders)); - sq.select(sqo); - Set> cJoins = sq.getCorrelatedJoins(); + Root customer = cquery.from(Customer.class); + cquery.select(customer); + Subquery sq = cquery.subquery(Order.class); + Join sqo = sq.correlate(customer.join(Customer_.orders)); + sq.select(sqo); + Set> cJoins = sq.getCorrelatedJoins(); - // ensure the join is returned in #getCorrelatedJoins - assertEquals( cJoins.size(), 1); + // ensure the join is returned in #getCorrelatedJoins + assertEquals( cJoins.size(), 1); } @Test diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/criteria/tuple/TupleQueryRetrievePrimitiveTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/criteria/tuple/TupleQueryRetrievePrimitiveTest.java index a62604db8d..9d4f093553 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/criteria/tuple/TupleQueryRetrievePrimitiveTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/criteria/tuple/TupleQueryRetrievePrimitiveTest.java @@ -27,71 +27,71 @@ import jakarta.persistence.criteria.Root; @JiraKey( value = "HHH-15454" ) public class TupleQueryRetrievePrimitiveTest extends AbstractMetamodelSpecificTest { - public static final int QUANTITY_OF_THING = 3; - public static final String THING_WITH_QUANTITY_3_ID = "thingWithQuantity3"; - private EntityManager em; + public static final int QUANTITY_OF_THING = 3; + public static final String THING_WITH_QUANTITY_3_ID = "thingWithQuantity3"; + private EntityManager em; - @BeforeEach - public void createThingWithQuantity() { - em = getOrCreateEntityManager(); - em.getTransaction().begin(); + @BeforeEach + public void createThingWithQuantity() { + em = getOrCreateEntityManager(); + em.getTransaction().begin(); - ThingWithQuantity thing = new ThingWithQuantity(); - thing.setId( THING_WITH_QUANTITY_3_ID ); - thing.setName( "3 Things" ); - thing.setQuantity(QUANTITY_OF_THING); - em.persist( thing ); + ThingWithQuantity thing = new ThingWithQuantity(); + thing.setId( THING_WITH_QUANTITY_3_ID ); + thing.setName( "3 Things" ); + thing.setQuantity(QUANTITY_OF_THING); + em.persist( thing ); - em.getTransaction().commit(); - } + em.getTransaction().commit(); + } - @AfterEach - public void endEntityManager() { - em.getTransaction().begin(); - em.remove( em.find( ThingWithQuantity.class, THING_WITH_QUANTITY_3_ID ) ); - em.getTransaction().commit(); - em.close(); - } + @AfterEach + public void endEntityManager() { + em.getTransaction().begin(); + em.remove( em.find( ThingWithQuantity.class, THING_WITH_QUANTITY_3_ID ) ); + em.getTransaction().commit(); + em.close(); + } - @Test - public void testRetrieveTupleEntryWithPrimitiveType() { - final Tuple result = queryTuple(); - final int quantity = result.get(ThingWithQuantity_.quantity.getName(), int.class); - assertEquals(QUANTITY_OF_THING, quantity); - } + @Test + public void testRetrieveTupleEntryWithPrimitiveType() { + final Tuple result = queryTuple(); + final int quantity = result.get(ThingWithQuantity_.quantity.getName(), int.class); + assertEquals(QUANTITY_OF_THING, quantity); + } - @Test - public void testRetrieveTupleEntryWithMetadata() { - final Tuple result = queryTuple(); - final int quantity = result.get( ThingWithQuantity_.quantity.getName(), ThingWithQuantity_.quantity.getJavaType()); - assertEquals(QUANTITY_OF_THING, quantity); - } + @Test + public void testRetrieveTupleEntryWithMetadata() { + final Tuple result = queryTuple(); + final int quantity = result.get( ThingWithQuantity_.quantity.getName(), ThingWithQuantity_.quantity.getJavaType()); + assertEquals(QUANTITY_OF_THING, quantity); + } - @Test - public void testRetrieveTupleEntryFromIndex() { - final Tuple result = queryTuple(); - final int quantity = result.get(0, ThingWithQuantity_.quantity.getJavaType()); - assertEquals(QUANTITY_OF_THING, quantity); - } + @Test + public void testRetrieveTupleEntryFromIndex() { + final Tuple result = queryTuple(); + final int quantity = result.get(0, ThingWithQuantity_.quantity.getJavaType()); + assertEquals(QUANTITY_OF_THING, quantity); + } - @Test - public void testRetrieveTupleEntryWithTupleElement() { - final CriteriaBuilder cb = em.getCriteriaBuilder(); - final CriteriaQuery query = cb.createTupleQuery(); - final Root thingWithQuantity = query.from( ThingWithQuantity.class); - final Path tupleElement = thingWithQuantity.get( ThingWithQuantity_.quantity); - query.multiselect(tupleElement.alias(ThingWithQuantity_.quantity.getName())); - Tuple result = em.createQuery(query).setMaxResults(1).getSingleResult(); - final int quantity = result.get(tupleElement); - assertEquals(QUANTITY_OF_THING, quantity); - } + @Test + public void testRetrieveTupleEntryWithTupleElement() { + final CriteriaBuilder cb = em.getCriteriaBuilder(); + final CriteriaQuery query = cb.createTupleQuery(); + final Root thingWithQuantity = query.from( ThingWithQuantity.class); + final Path tupleElement = thingWithQuantity.get( ThingWithQuantity_.quantity); + query.multiselect(tupleElement.alias(ThingWithQuantity_.quantity.getName())); + Tuple result = em.createQuery(query).setMaxResults(1).getSingleResult(); + final int quantity = result.get(tupleElement); + assertEquals(QUANTITY_OF_THING, quantity); + } - private Tuple queryTuple() { - final CriteriaBuilder cb = em.getCriteriaBuilder(); - final CriteriaQuery query = cb.createTupleQuery(); - final Root thingWithQuantity = query.from(ThingWithQuantity.class); - query.multiselect(thingWithQuantity.get(ThingWithQuantity_.quantity).alias(ThingWithQuantity_.quantity.getName())); - return em.createQuery(query).setMaxResults(1).getSingleResult(); - } + private Tuple queryTuple() { + final CriteriaBuilder cb = em.getCriteriaBuilder(); + final CriteriaQuery query = cb.createTupleQuery(); + final Root thingWithQuantity = query.from(ThingWithQuantity.class); + query.multiselect(thingWithQuantity.get(ThingWithQuantity_.quantity).alias(ThingWithQuantity_.quantity.getName())); + return em.createQuery(query).setMaxResults(1).getSingleResult(); + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/criteria/valuehandlingmode/inline/ComponentInWhereClauseTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/criteria/valuehandlingmode/inline/ComponentInWhereClauseTest.java index 00c41221a2..3afa67f971 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/criteria/valuehandlingmode/inline/ComponentInWhereClauseTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/criteria/valuehandlingmode/inline/ComponentInWhereClauseTest.java @@ -88,8 +88,8 @@ public class ComponentInWhereClauseTest { Root root = query.from( Employee.class ); query.where( root.get( "projects" ) - .get( "currentProject" ) - .in( projects.getCurrentProject() ) ); + .get( "currentProject" ) + .in( projects.getCurrentProject() ) ); final List results = entityManager.createQuery( query ).getResultList(); assertThat( results.size(), is( 1 ) ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/ejb3configuration/InterceptorTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/ejb3configuration/InterceptorTest.java index 25f781ae8e..1484d9679c 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/ejb3configuration/InterceptorTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/ejb3configuration/InterceptorTest.java @@ -60,10 +60,10 @@ public class InterceptorTest { } // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - // test deprecated Interceptor settings + // test deprecated Interceptor settings - @Test - public void testDeprecatedConfiguredInterceptor() { + @Test + public void testDeprecatedConfiguredInterceptor() { Map settings = basicSettings(); settings.put( AvailableSettings.INTERCEPTOR, ExceptionInterceptor.class.getName() ); buildEntityManagerFactory( settings ); @@ -81,7 +81,7 @@ public class InterceptorTest { catch ( IllegalStateException e ) { assertEquals( ExceptionInterceptor.EXCEPTION_MESSAGE, e.getMessage() ); } - } + } @Test public void testDeprecatedConfiguredSessionInterceptor() { @@ -109,13 +109,13 @@ public class InterceptorTest { // test Interceptor settings @Test - public void testConfiguredInterceptor() { + public void testConfiguredInterceptor() { Map settings = basicSettings(); settings.put( org.hibernate.cfg.AvailableSettings.INTERCEPTOR, ExceptionInterceptor.class.getName() ); buildEntityManagerFactory( settings ); - Item i = new Item(); - i.setName( "Laptop" ); + Item i = new Item(); + i.setName( "Laptop" ); try { doInJPA( this::entityManagerFactory, entityManager -> { @@ -127,16 +127,16 @@ public class InterceptorTest { catch ( IllegalStateException e ) { assertEquals( ExceptionInterceptor.EXCEPTION_MESSAGE, e.getMessage() ); } - } + } - @Test - public void testConfiguredSessionInterceptor() { + @Test + public void testConfiguredSessionInterceptor() { Map settings = basicSettings(); settings.put( org.hibernate.cfg.AvailableSettings.SESSION_SCOPED_INTERCEPTOR, LocalExceptionInterceptor.class.getName() ); buildEntityManagerFactory( settings ); - Item i = new Item(); - i.setName( "Laptop" ); + Item i = new Item(); + i.setName( "Laptop" ); try { doInJPA( this::entityManagerFactory, entityManager -> { @@ -148,10 +148,10 @@ public class InterceptorTest { catch ( IllegalStateException e ) { assertEquals( LocalExceptionInterceptor.LOCAL_EXCEPTION_MESSAGE, e.getMessage() ); } - } + } - @Test - public void testConfiguredSessionInterceptorWithSessionFactory() { + @Test + public void testConfiguredSessionInterceptorWithSessionFactory() { StandardServiceRegistryImpl standardRegistry = ServiceRegistryUtil.serviceRegistry(); @@ -196,10 +196,10 @@ public class InterceptorTest { } } - @Test - public void testConfiguredSessionInterceptorSupplier() { - Map settings = basicSettings(); - settings.put( org.hibernate.cfg.AvailableSettings.SESSION_SCOPED_INTERCEPTOR, (Supplier) LocalExceptionInterceptor::new); + @Test + public void testConfiguredSessionInterceptorSupplier() { + Map settings = basicSettings(); + settings.put( org.hibernate.cfg.AvailableSettings.SESSION_SCOPED_INTERCEPTOR, (Supplier) LocalExceptionInterceptor::new); buildEntityManagerFactory( settings ); Item i = new Item(); @@ -215,16 +215,16 @@ public class InterceptorTest { catch ( IllegalStateException e ) { assertEquals( LocalExceptionInterceptor.LOCAL_EXCEPTION_MESSAGE, e.getMessage() ); } - } + } - @Test - public void testEmptyCreateEntityManagerFactoryAndPropertyUse() { + @Test + public void testEmptyCreateEntityManagerFactoryAndPropertyUse() { Map settings = basicSettings(); settings.put( AvailableSettings.INTERCEPTOR, ExceptionInterceptor.class.getName() ); buildEntityManagerFactory( settings ); - Item i = new Item(); - i.setName( "Laptop" ); + Item i = new Item(); + i.setName( "Laptop" ); try { doInJPA( this::entityManagerFactory, entityManager -> { @@ -236,16 +236,16 @@ public class InterceptorTest { catch ( IllegalStateException e ) { assertEquals( ExceptionInterceptor.EXCEPTION_MESSAGE, e.getMessage() ); } - } + } - @Test - public void testOnLoadCallInInterceptor() { + @Test + public void testOnLoadCallInInterceptor() { Map settings = basicSettings(); settings.put( AvailableSettings.INTERCEPTOR, new ExceptionInterceptor( true ) ); buildEntityManagerFactory( settings ); - Item i = new Item(); - i.setName( "Laptop" ); + Item i = new Item(); + i.setName( "Laptop" ); try { doInJPA( this::entityManagerFactory, entityManager -> { @@ -266,16 +266,16 @@ public class InterceptorTest { catch ( IllegalStateException e ) { assertEquals( LocalExceptionInterceptor.LOCAL_EXCEPTION_MESSAGE, e.getMessage() ); } - } + } - protected Map basicSettings() { + protected Map basicSettings() { return SettingsGenerator.generateSettings( AvailableSettings.HBM2DDL_AUTO, "create-drop", AvailableSettings.DIALECT, DialectContext.getDialect().getClass().getName(), AvailableSettings.LOADED_CLASSES, Arrays.asList( getAnnotatedClasses() ) ); - } + } private void buildEntityManagerFactory(Map settings) { entityManagerFactory = Bootstrap diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/ejb3configuration/PersisterClassProviderTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/ejb3configuration/PersisterClassProviderTest.java index aaed839e4d..d0e95ebe98 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/ejb3configuration/PersisterClassProviderTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/ejb3configuration/PersisterClassProviderTest.java @@ -109,7 +109,7 @@ public class PersisterClassProviderTest { entityManagerFactory.close(); } catch ( PersistenceException e ) { - Assertions.assertNotNull( e.getCause() ); + Assertions.assertNotNull( e.getCause() ); Assertions.assertNotNull( e.getCause().getCause() ); Assertions.assertEquals( GoofyException.class, e.getCause().getCause().getClass() ); @@ -390,7 +390,7 @@ public class PersisterClassProviderTest { return false; } - @Override + @Override public int[] getNaturalIdentifierProperties() { return new int[0]; } @@ -407,16 +407,16 @@ public class PersisterClassProviderTest { } @Override - public boolean hasNaturalIdCache() { - return false; - } + public boolean hasNaturalIdCache() { + return false; + } - @Override - public NaturalIdDataAccess getNaturalIdCacheAccessStrategy() { - return null; - } + @Override + public NaturalIdDataAccess getNaturalIdCacheAccessStrategy() { + return null; + } - @Override + @Override public IdentifierGenerator getIdentifierGenerator() { return null; } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/ejb3configuration/SessionFactoryObserverTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/ejb3configuration/SessionFactoryObserverTest.java index 61f18099f7..facb77716a 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/ejb3configuration/SessionFactoryObserverTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/ejb3configuration/SessionFactoryObserverTest.java @@ -25,7 +25,7 @@ import jakarta.persistence.EntityManagerFactory; * @author Emmanuel Bernard */ public class SessionFactoryObserverTest { - @Test + @Test public void testSessionFactoryObserverProperty() { Map settings = ServiceRegistryUtil.createBaseSettings(); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/exception/ExceptionTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/exception/ExceptionTest.java index 98fc798d02..e5153afe84 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/exception/ExceptionTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/exception/ExceptionTest.java @@ -109,7 +109,7 @@ public class ExceptionTest { fail( "Non existent entity should raise an exception when state is accessed" ); } catch ( EntityNotFoundException e ) { - //"success" + //"success" } finally { em.close(); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/factory/puUtil/LegacyEntity.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/factory/puUtil/LegacyEntity.java index 72dc7b83db..fdda13c082 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/factory/puUtil/LegacyEntity.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/factory/puUtil/LegacyEntity.java @@ -14,64 +14,64 @@ import jakarta.persistence.IdClass; @IdClass(LegacyEntityPk.class) public class LegacyEntity { - @Id - private int primitivePk1; + @Id + private int primitivePk1; - @Id - private int primitivePk2; + @Id + private int primitivePk2; - private String foo; + private String foo; - public LegacyEntity() {} + public LegacyEntity() {} - public int getPrimitivePk1() { - return primitivePk1; - } + public int getPrimitivePk1() { + return primitivePk1; + } - public void setPrimitivePk1(int primitivePk1) { - this.primitivePk1 = primitivePk1; - } + public void setPrimitivePk1(int primitivePk1) { + this.primitivePk1 = primitivePk1; + } - public int getPrimitivePk2() { - return primitivePk2; - } + public int getPrimitivePk2() { + return primitivePk2; + } - public void setPrimitivePk2(int primitivePk2) { - this.primitivePk2 = primitivePk2; - } + public void setPrimitivePk2(int primitivePk2) { + this.primitivePk2 = primitivePk2; + } - public String getFoo() { - return foo; - } + public String getFoo() { + return foo; + } - public void setFoo(String foo) { - this.foo = foo; - } + public void setFoo(String foo) { + this.foo = foo; + } - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; - LegacyEntity that = (LegacyEntity) o; + LegacyEntity that = (LegacyEntity) o; - if (primitivePk1 != that.primitivePk1) return false; - return primitivePk2 == that.primitivePk2; + if (primitivePk1 != that.primitivePk1) return false; + return primitivePk2 == that.primitivePk2; - } + } - @Override - public int hashCode() { - int result = primitivePk1; - result = 31 * result + primitivePk2; - return result; - } + @Override + public int hashCode() { + int result = primitivePk1; + result = 31 * result + primitivePk2; + return result; + } - @Override - public String toString() { - return "LegacyEntity{" + - "primitivePk1=" + primitivePk1 + - ", primitivePk2=" + primitivePk2 + - '}'; - } + @Override + public String toString() { + return "LegacyEntity{" + + "primitivePk1=" + primitivePk1 + + ", primitivePk2=" + primitivePk2 + + '}'; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/factory/puUtil/LegacyEntityPk.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/factory/puUtil/LegacyEntityPk.java index 39c235809f..20f6e1c1fd 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/factory/puUtil/LegacyEntityPk.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/factory/puUtil/LegacyEntityPk.java @@ -10,45 +10,45 @@ import java.io.Serializable; public class LegacyEntityPk implements Serializable { - private int primitivePk1; + private int primitivePk1; - private int primitivePk2; + private int primitivePk2; - public LegacyEntityPk() { - } + public LegacyEntityPk() { + } - public int getPrimitivePk1() { - return primitivePk1; - } + public int getPrimitivePk1() { + return primitivePk1; + } - public void setPrimitivePk1(int primitivePk1) { - this.primitivePk1 = primitivePk1; - } + public void setPrimitivePk1(int primitivePk1) { + this.primitivePk1 = primitivePk1; + } - public int getPrimitivePk2() { - return primitivePk2; - } + public int getPrimitivePk2() { + return primitivePk2; + } - public void setPrimitivePk2(int primitivePk2) { - this.primitivePk2 = primitivePk2; - } + public void setPrimitivePk2(int primitivePk2) { + this.primitivePk2 = primitivePk2; + } - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; - LegacyEntityPk that = (LegacyEntityPk) o; + LegacyEntityPk that = (LegacyEntityPk) o; - if (primitivePk1 != that.primitivePk1) return false; - return primitivePk2 == that.primitivePk2; + if (primitivePk1 != that.primitivePk1) return false; + return primitivePk2 == that.primitivePk2; - } + } - @Override - public int hashCode() { - int result = primitivePk1; - result = 31 * result + primitivePk2; - return result; - } + @Override + public int hashCode() { + int result = primitivePk1; + result = 31 * result + primitivePk2; + return result; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/factory/puUtil/ModernEntity.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/factory/puUtil/ModernEntity.java index 9af23b84ef..6efb48e7d6 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/factory/puUtil/ModernEntity.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/factory/puUtil/ModernEntity.java @@ -13,51 +13,51 @@ import jakarta.persistence.Id; @Entity(name = "ModernEntity") public class ModernEntity { - @Id - @GeneratedValue - private int id; + @Id + @GeneratedValue + private int id; - private int foo; + private int foo; - public ModernEntity() { - } + public ModernEntity() { + } - public int getId() { - return id; - } + public int getId() { + return id; + } - public void setId(int id) { - this.id = id; - } + public void setId(int id) { + this.id = id; + } - public int getFoo() { - return foo; - } + public int getFoo() { + return foo; + } - public void setFoo(int foo) { - this.foo = foo; - } + public void setFoo(int foo) { + this.foo = foo; + } - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; - ModernEntity that = (ModernEntity) o; + ModernEntity that = (ModernEntity) o; - return id == that.id; + return id == that.id; - } + } - @Override - public int hashCode() { - return id; - } + @Override + public int hashCode() { + return id; + } - @Override - public String toString() { - return "ModernEntity{" + - "id=" + id + - '}'; - } + @Override + public String toString() { + return "ModernEntity{" + + "id=" + id + + '}'; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/factory/puUtil/NestedLegacyEntity.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/factory/puUtil/NestedLegacyEntity.java index 7e75483a1e..3a3d1374f3 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/factory/puUtil/NestedLegacyEntity.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/factory/puUtil/NestedLegacyEntity.java @@ -16,60 +16,60 @@ import jakarta.persistence.ManyToOne; @IdClass(NestedLegacyEntityPk.class) public class NestedLegacyEntity { - @Id - @ManyToOne - @JoinColumn(name = "legacyFk1", referencedColumnName = "primitivePk1") - @JoinColumn(name = "legacyFk2", referencedColumnName = "primitivePk2") - private LegacyEntity legacyEntity; + @Id + @ManyToOne + @JoinColumn(name = "legacyFk1", referencedColumnName = "primitivePk1") + @JoinColumn(name = "legacyFk2", referencedColumnName = "primitivePk2") + private LegacyEntity legacyEntity; - @Id - @ManyToOne - @JoinColumn(name = "modernFk", referencedColumnName = "id") - private ModernEntity modernEntity; + @Id + @ManyToOne + @JoinColumn(name = "modernFk", referencedColumnName = "id") + private ModernEntity modernEntity; - public NestedLegacyEntity() { - } + public NestedLegacyEntity() { + } - public LegacyEntity getLegacyEntity() { - return legacyEntity; - } + public LegacyEntity getLegacyEntity() { + return legacyEntity; + } - public void setLegacyEntity(LegacyEntity legacyEntity) { - this.legacyEntity = legacyEntity; - } + public void setLegacyEntity(LegacyEntity legacyEntity) { + this.legacyEntity = legacyEntity; + } - public ModernEntity getModernEntity() { - return modernEntity; - } + public ModernEntity getModernEntity() { + return modernEntity; + } - public void setModernEntity(ModernEntity modernEntity) { - this.modernEntity = modernEntity; - } + public void setModernEntity(ModernEntity modernEntity) { + this.modernEntity = modernEntity; + } - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; - NestedLegacyEntity that = (NestedLegacyEntity) o; + NestedLegacyEntity that = (NestedLegacyEntity) o; - if (legacyEntity != null ? !legacyEntity.equals(that.legacyEntity) : that.legacyEntity != null) return false; - return modernEntity != null ? modernEntity.equals(that.modernEntity) : that.modernEntity == null; + if (legacyEntity != null ? !legacyEntity.equals(that.legacyEntity) : that.legacyEntity != null) return false; + return modernEntity != null ? modernEntity.equals(that.modernEntity) : that.modernEntity == null; - } + } - @Override - public int hashCode() { - int result = legacyEntity != null ? legacyEntity.hashCode() : 0; - result = 31 * result + (modernEntity != null ? modernEntity.hashCode() : 0); - return result; - } + @Override + public int hashCode() { + int result = legacyEntity != null ? legacyEntity.hashCode() : 0; + result = 31 * result + (modernEntity != null ? modernEntity.hashCode() : 0); + return result; + } - @Override - public String toString() { - return "NestedLegacyEntity{" + - "legacyEntity=" + legacyEntity + - ", modernEntity=" + modernEntity + - '}'; - } + @Override + public String toString() { + return "NestedLegacyEntity{" + + "legacyEntity=" + legacyEntity + + ", modernEntity=" + modernEntity + + '}'; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/factory/puUtil/NestedLegacyEntityPk.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/factory/puUtil/NestedLegacyEntityPk.java index 309fd20c79..66fb17b7e7 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/factory/puUtil/NestedLegacyEntityPk.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/factory/puUtil/NestedLegacyEntityPk.java @@ -10,45 +10,45 @@ import java.io.Serializable; public class NestedLegacyEntityPk implements Serializable { - private LegacyEntityPk legacyEntity; + private LegacyEntityPk legacyEntity; - private int modernEntity; + private int modernEntity; - public NestedLegacyEntityPk() { - } + public NestedLegacyEntityPk() { + } - public LegacyEntityPk getLegacyEntity() { - return legacyEntity; - } + public LegacyEntityPk getLegacyEntity() { + return legacyEntity; + } - public void setLegacyEntity(LegacyEntityPk legacyEntity) { - this.legacyEntity = legacyEntity; - } + public void setLegacyEntity(LegacyEntityPk legacyEntity) { + this.legacyEntity = legacyEntity; + } - public int getModernEntity() { - return modernEntity; - } + public int getModernEntity() { + return modernEntity; + } - public void setModernEntity(int modernEntity) { - this.modernEntity = modernEntity; - } + public void setModernEntity(int modernEntity) { + this.modernEntity = modernEntity; + } - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; - NestedLegacyEntityPk that = (NestedLegacyEntityPk) o; + NestedLegacyEntityPk that = (NestedLegacyEntityPk) o; - if (modernEntity != that.modernEntity) return false; - return legacyEntity != null ? legacyEntity.equals(that.legacyEntity) : that.legacyEntity == null; + if (modernEntity != that.modernEntity) return false; + return legacyEntity != null ? legacyEntity.equals(that.legacyEntity) : that.legacyEntity == null; - } + } - @Override - public int hashCode() { - int result = legacyEntity != null ? legacyEntity.hashCode() : 0; - result = 31 * result + modernEntity; - return result; - } + @Override + public int hashCode() { + int result = legacyEntity != null ? legacyEntity.hashCode() : 0; + result = 31 * result + modernEntity; + return result; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/graphs/EntityGraphTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/graphs/EntityGraphTest.java index a86fc8411e..ba65a8fbad 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/graphs/EntityGraphTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/graphs/EntityGraphTest.java @@ -99,84 +99,84 @@ public class EntityGraphTest extends BaseEntityManagerFunctionalTestCase { em.close(); } - @Test - public void loadCollection() { - EntityManager em = getOrCreateEntityManager(); - em.getTransaction().begin(); + @Test + public void loadCollection() { + EntityManager em = getOrCreateEntityManager(); + em.getTransaction().begin(); - Bar bar = new Bar(); - em.persist( bar ); + Bar bar = new Bar(); + em.persist( bar ); - Foo foo = new Foo(); - foo.bar = bar; - bar.foos.add(foo); - em.persist( foo ); + Foo foo = new Foo(); + foo.bar = bar; + bar.foos.add(foo); + em.persist( foo ); - em.getTransaction().commit(); - em.clear(); + em.getTransaction().commit(); + em.clear(); - em.getTransaction().begin(); + em.getTransaction().begin(); - EntityGraph barGraph = em.createEntityGraph( Bar.class ); - barGraph.addAttributeNodes("foos"); + EntityGraph barGraph = em.createEntityGraph( Bar.class ); + barGraph.addAttributeNodes("foos"); - Map properties = new HashMap(); - properties.put( "javax.persistence.loadgraph", barGraph); + Map properties = new HashMap(); + properties.put( "javax.persistence.loadgraph", barGraph); - Bar result = em.find( Bar.class, bar.id, properties ); + Bar result = em.find( Bar.class, bar.id, properties ); - assertTrue( Hibernate.isInitialized( result ) ); - assertTrue( Hibernate.isInitialized( result.foos ) ); + assertTrue( Hibernate.isInitialized( result ) ); + assertTrue( Hibernate.isInitialized( result.foos ) ); - em.getTransaction().commit(); - em.close(); - } + em.getTransaction().commit(); + em.close(); + } - @Test - public void loadInverseCollection() { - EntityManager em = getOrCreateEntityManager(); - em.getTransaction().begin(); + @Test + public void loadInverseCollection() { + EntityManager em = getOrCreateEntityManager(); + em.getTransaction().begin(); - Bar bar = new Bar(); - em.persist( bar ); - Baz baz = new Baz(); - em.persist( baz ); + Bar bar = new Bar(); + em.persist( bar ); + Baz baz = new Baz(); + em.persist( baz ); - Foo foo = new Foo(); - foo.bar = bar; - foo.baz = baz; - bar.foos.add(foo); - baz.foos.add(foo); - em.persist( foo ); + Foo foo = new Foo(); + foo.bar = bar; + foo.baz = baz; + bar.foos.add(foo); + baz.foos.add(foo); + em.persist( foo ); - em.getTransaction().commit(); - em.clear(); + em.getTransaction().commit(); + em.clear(); - em.getTransaction().begin(); + em.getTransaction().begin(); - EntityGraph fooGraph = em.createEntityGraph( Foo.class ); - fooGraph.addAttributeNodes("bar"); - fooGraph.addAttributeNodes("baz"); - Subgraph barGraph = fooGraph.addSubgraph("bar", Bar.class); - barGraph.addAttributeNodes("foos"); + EntityGraph fooGraph = em.createEntityGraph( Foo.class ); + fooGraph.addAttributeNodes("bar"); + fooGraph.addAttributeNodes("baz"); + Subgraph barGraph = fooGraph.addSubgraph("bar", Bar.class); + barGraph.addAttributeNodes("foos"); - Map properties = new HashMap(); - properties.put( "javax.persistence.loadgraph", fooGraph ); + Map properties = new HashMap(); + properties.put( "javax.persistence.loadgraph", fooGraph ); - Foo result = em.find( Foo.class, foo.id, properties ); + Foo result = em.find( Foo.class, foo.id, properties ); - assertTrue( Hibernate.isInitialized( result ) ); - assertTrue( Hibernate.isInitialized( result.bar ) ); - assertTrue( Hibernate.isInitialized( result.bar.getFoos()) ); - assertTrue( Hibernate.isInitialized( result.baz ) ); - // sanity check -- ensure the only bi-directional fetch was the one identified by the graph - assertFalse( Hibernate.isInitialized( result.baz.getFoos()) ); + assertTrue( Hibernate.isInitialized( result ) ); + assertTrue( Hibernate.isInitialized( result.bar ) ); + assertTrue( Hibernate.isInitialized( result.bar.getFoos()) ); + assertTrue( Hibernate.isInitialized( result.baz ) ); + // sanity check -- ensure the only bi-directional fetch was the one identified by the graph + assertFalse( Hibernate.isInitialized( result.baz.getFoos()) ); - em.getTransaction().commit(); - em.close(); - } + em.getTransaction().commit(); + em.close(); + } - /** + /** * JPA 2.1 spec: "Add a node to the graph that corresponds to a managed type with inheritance. This allows for * multiple subclass subgraphs to be defined for this node of the entity graph. Subclass subgraphs will * automatically include the specified attributes of superclass subgraphs." @@ -228,87 +228,87 @@ public class EntityGraphTest extends BaseEntityManagerFunctionalTestCase { em.close(); } - @Test - @JiraKey(value = "HHH-9080") - public void attributeNodeInheritanceTest() { - EntityManager em = getOrCreateEntityManager(); - em.getTransaction().begin(); + @Test + @JiraKey(value = "HHH-9080") + public void attributeNodeInheritanceTest() { + EntityManager em = getOrCreateEntityManager(); + em.getTransaction().begin(); - Manager manager = new Manager(); - em.persist( manager ); - Employee employee = new Employee(); - manager.friends.add( employee); - em.persist( employee ); - Manager anotherManager = new Manager(); - manager.managers.add(anotherManager); - em.persist( anotherManager ); - em.getTransaction().commit(); - em.clear(); + Manager manager = new Manager(); + em.persist( manager ); + Employee employee = new Employee(); + manager.friends.add( employee); + em.persist( employee ); + Manager anotherManager = new Manager(); + manager.managers.add(anotherManager); + em.persist( anotherManager ); + em.getTransaction().commit(); + em.clear(); - em.getTransaction().begin(); + em.getTransaction().begin(); - EntityGraph entityGraph = em.createEntityGraph( Manager.class ); - entityGraph.addAttributeNodes( "friends" ); - entityGraph.addAttributeNodes( "managers" ); + EntityGraph entityGraph = em.createEntityGraph( Manager.class ); + entityGraph.addAttributeNodes( "friends" ); + entityGraph.addAttributeNodes( "managers" ); - Map properties = new HashMap(); - properties.put( "javax.persistence.loadgraph", entityGraph ); + Map properties = new HashMap(); + properties.put( "javax.persistence.loadgraph", entityGraph ); - Manager result = em.find( Manager.class, manager.id, properties ); + Manager result = em.find( Manager.class, manager.id, properties ); - assertTrue( Hibernate.isInitialized( result ) ); - assertTrue( Hibernate.isInitialized( result.friends ) ); - assertEquals( result.friends.size(), 1 ); - assertTrue( Hibernate.isInitialized( result.managers) ); - assertEquals( result.managers.size(), 1 ); + assertTrue( Hibernate.isInitialized( result ) ); + assertTrue( Hibernate.isInitialized( result.friends ) ); + assertEquals( result.friends.size(), 1 ); + assertTrue( Hibernate.isInitialized( result.managers) ); + assertEquals( result.managers.size(), 1 ); - em.getTransaction().commit(); - em.close(); - } + em.getTransaction().commit(); + em.close(); + } - @Test - @JiraKey(value = "HHH-9735") - public void loadIsMemeberQueriedCollection() { + @Test + @JiraKey(value = "HHH-9735") + public void loadIsMemeberQueriedCollection() { - EntityManager em = getOrCreateEntityManager(); - em.getTransaction().begin(); + EntityManager em = getOrCreateEntityManager(); + em.getTransaction().begin(); - Bar bar = new Bar(); - em.persist( bar ); + Bar bar = new Bar(); + em.persist( bar ); - Foo foo = new Foo(); - foo.bar = bar; - bar.foos.add(foo); - em.persist( foo ); + Foo foo = new Foo(); + foo.bar = bar; + bar.foos.add(foo); + em.persist( foo ); - em.getTransaction().commit(); - em.clear(); + em.getTransaction().commit(); + em.clear(); - em.getTransaction().begin(); - foo = em.find(Foo.class, foo.id); + em.getTransaction().begin(); + foo = em.find(Foo.class, foo.id); - CriteriaBuilder cb = em.getCriteriaBuilder(); - CriteriaQuery cq = cb.createQuery(Bar.class); - Root from = cq.from(Bar.class); + CriteriaBuilder cb = em.getCriteriaBuilder(); + CriteriaQuery cq = cb.createQuery(Bar.class); + Root from = cq.from(Bar.class); - Expression> foos = from.get("foos"); + Expression> foos = from.get("foos"); - cq.where(cb.isMember(foo, foos)); + cq.where(cb.isMember(foo, foos)); - TypedQuery query = em.createQuery(cq); + TypedQuery query = em.createQuery(cq); - EntityGraph barGraph = em.createEntityGraph( Bar.class ); - barGraph.addAttributeNodes("foos"); - query.setHint("javax.persistence.loadgraph", barGraph); + EntityGraph barGraph = em.createEntityGraph( Bar.class ); + barGraph.addAttributeNodes("foos"); + query.setHint("javax.persistence.loadgraph", barGraph); - Bar result = query.getSingleResult(); + Bar result = query.getSingleResult(); - assertTrue( Hibernate.isInitialized( result ) ); - assertTrue( Hibernate.isInitialized( result.foos ) ); + assertTrue( Hibernate.isInitialized( result ) ); + assertTrue( Hibernate.isInitialized( result.foos ) ); - em.getTransaction().commit(); - em.close(); - } + em.getTransaction().commit(); + em.close(); + } @Test @JiraKey(value = "HHH-15859") @@ -486,9 +486,9 @@ public class EntityGraphTest extends BaseEntityManagerFunctionalTestCase { em.close(); } - @Entity(name = "Foo") + @Entity(name = "Foo") @Table(name = "foo") - public static class Foo { + public static class Foo { @Id @GeneratedValue @@ -509,8 +509,8 @@ public class EntityGraphTest extends BaseEntityManagerFunctionalTestCase { @GeneratedValue public Integer id; - @OneToMany(mappedBy = "bar") - public Set foos = new HashSet(); + @OneToMany(mappedBy = "bar") + public Set foos = new HashSet(); public Set getFoos() { return foos; @@ -519,14 +519,14 @@ public class EntityGraphTest extends BaseEntityManagerFunctionalTestCase { @Entity(name = "Baz") @Table(name = "baz") - public static class Baz { + public static class Baz { @Id @GeneratedValue - public Integer id; + public Integer id; - @OneToMany(mappedBy = "baz") - public Set foos = new HashSet(); + @OneToMany(mappedBy = "baz") + public Set foos = new HashSet(); public Set getFoos() { return foos; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/graphs/queryhint/QueryHintEntityGraphTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/graphs/queryhint/QueryHintEntityGraphTest.java index ed45cb837a..de5db11938 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/graphs/queryhint/QueryHintEntityGraphTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/graphs/queryhint/QueryHintEntityGraphTest.java @@ -480,29 +480,29 @@ public class QueryHintEntityGraphTest extends BaseEntityManagerFunctionalTestCas public void testCollectionSizeLoadedWithGraph() { doInJPA( this::entityManagerFactory, entityManager -> { - Student student1 = new Student(); - student1.setId( 1 ); - student1.setName( "Student 1" ); - Student student2 = new Student(); - student2.setId( 2 ); - student2.setName( "Student 2" ); + Student student1 = new Student(); + student1.setId( 1 ); + student1.setName( "Student 1" ); + Student student2 = new Student(); + student2.setId( 2 ); + student2.setName( "Student 2" ); - Course course1 = new Course(); - course1.setName( "Full Time" ); - Course course2 = new Course(); - course2.setName( "Part Time" ); + Course course1 = new Course(); + course1.setName( "Full Time" ); + Course course2 = new Course(); + course2.setName( "Part Time" ); - Set std1Courses = new HashSet(); - std1Courses.add( course1 ); - std1Courses.add( course2 ); - student1.setCourses( std1Courses ); + Set std1Courses = new HashSet(); + std1Courses.add( course1 ); + std1Courses.add( course2 ); + student1.setCourses( std1Courses ); - Set std2Courses = new HashSet(); - std2Courses.add( course2 ); - student2.setCourses( std2Courses ); + Set std2Courses = new HashSet(); + std2Courses.add( course2 ); + student2.setCourses( std2Courses ); - entityManager.persist( student1 ); - entityManager.persist( student2 ); + entityManager.persist( student1 ); + entityManager.persist( student2 ); }); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/lob/BlobTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/lob/BlobTest.java index 118017aa9b..225bb47fa1 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/lob/BlobTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/lob/BlobTest.java @@ -37,15 +37,15 @@ public class BlobTest { Long readerId = scope.fromTransaction( entityManager -> { try (ByteArrayOutputStream baos = new ByteArrayOutputStream(); - ObjectOutputStream oos = new ObjectOutputStream( baos )) { + ObjectOutputStream oos = new ObjectOutputStream( baos )) { Map image = new HashMap<>(); image.put( "meta", "metadata" ); image.put( "data", "imagedata" ); ImageReader reader = new ImageReader(); oos.writeObject( image ); reader.setImage( entityManager.unwrap( Session.class ) - .getLobHelper() - .createBlob( baos.toByteArray() ) ); + .getLobHelper() + .createBlob( baos.toByteArray() ) ); entityManager.persist( reader ); return reader.getId(); } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/lock/LockTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/lock/LockTest.java index e0ce5fb5c6..25c6c282f4 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/lock/LockTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/lock/LockTest.java @@ -101,8 +101,8 @@ public class LockTest extends BaseEntityManagerFunctionalTestCase { @Test(timeout = 5 * 1000) //5 seconds @JiraKey( value = "HHH-7252" ) @RequiresDialectFeature( value = DialectChecks.SupportsLockTimeouts.class, - comment = "Test verifies proper exception throwing when a lock timeout is specified.", - jiraKey = "HHH-7252" ) + comment = "Test verifies proper exception throwing when a lock timeout is specified.", + jiraKey = "HHH-7252" ) @SkipForDialect(value = CockroachDialect.class, comment = "for update clause does not imply locking. See https://github.com/cockroachdb/cockroach/issues/88995") @SkipForDialect(value = AltibaseDialect.class, comment = "Altibase close socket after lock timeout occurred") public void testFindWithPessimisticWriteLockTimeoutException() { @@ -186,8 +186,8 @@ public class LockTest extends BaseEntityManagerFunctionalTestCase { } catch (PersistenceException pe) { log.info("EntityManager.find() for PESSIMISTIC_WRITE with timeout of 0 threw a PersistenceException.\n" + - "This is likely a consequence of " + getDialect().getClass().getName() + " not properly mapping SQL errors into the correct HibernateException subtypes.\n" + - "See HHH-7251 for an example of one such situation.", pe); + "This is likely a consequence of " + getDialect().getClass().getName() + " not properly mapping SQL errors into the correct HibernateException subtypes.\n" + + "See HHH-7251 for an example of one such situation.", pe); fail( "EntityManager should be throwing LockTimeoutException." ); } } ); @@ -852,7 +852,7 @@ public class LockTest extends BaseEntityManagerFunctionalTestCase { @Test @RequiresDialect(OracleDialect.class) @RequiresDialect(PostgreSQLDialect.class) - @RequiresDialectFeature( DialectChecks.SupportsLockTimeouts.class ) + @RequiresDialectFeature( DialectChecks.SupportsLockTimeouts.class ) public void testContendedPessimisticWriteLockNoWait() throws Exception { final CountDownLatch latch = new CountDownLatch( 1 ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/lock/NativeSQLQueryTimeoutTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/lock/NativeSQLQueryTimeoutTest.java index 80421999dc..f94e1cb078 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/lock/NativeSQLQueryTimeoutTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/lock/NativeSQLQueryTimeoutTest.java @@ -40,9 +40,9 @@ public class NativeSQLQueryTimeoutTest extends BaseEntityManagerFunctionalTestCa doInJPA( this::entityManagerFactory, entityManager -> { try { entityManager.createNativeQuery( - "select 1 " + + "select 1 " + "from pg_sleep(2) " - ) + ) .getResultList(); fail("Should have thrown lock timeout exception!"); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/mapping/Phone.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/mapping/Phone.java index 1eb82a988a..8d4fe657fb 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/mapping/Phone.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/mapping/Phone.java @@ -17,35 +17,35 @@ import jakarta.persistence.Table; @Table(name = "PHONE") public class Phone implements java.io.Serializable { - private Integer id; - private String brandName; - private float price; + private Integer id; + private String brandName; + private float price; - public Phone() { - } + public Phone() { + } @Id - @Column(name="ID") - public Integer getId() { - return id; - } - public void setId(Integer id) { - this.id = id; - } + @Column(name="ID") + public Integer getId() { + return id; + } + public void setId(Integer id) { + this.id = id; + } - @Column(name="BRANDNAME") - public String getBrandName() { - return brandName; - } - public void setBrandName(String bName) { - this.brandName = bName; - } + @Column(name="BRANDNAME") + public String getBrandName() { + return brandName; + } + public void setBrandName(String bName) { + this.brandName = bName; + } - @Column(name="PRICE") - public float getPrice() { - return price; - } - public void setPrice(float price) { - this.price = price; - } + @Column(name="PRICE") + public float getPrice() { + return price; + } + public void setPrice(float price) { + this.price = price; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/mapping/WrapperArrayHandlingTests.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/mapping/WrapperArrayHandlingTests.java index 0cccea1056..65a24901ef 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/mapping/WrapperArrayHandlingTests.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/mapping/WrapperArrayHandlingTests.java @@ -59,9 +59,9 @@ public class WrapperArrayHandlingTests { @Entity( name = "TheEntity" ) @Table( name = "TheEntity" ) public static class TheEntity { - @Id - private Integer id; - @Basic + @Id + private Integer id; + @Basic private String name; @Basic private Character[] characters; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/metadata/MetadataTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/metadata/MetadataTest.java index 4837170afb..492d43153c 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/metadata/MetadataTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/metadata/MetadataTest.java @@ -46,412 +46,412 @@ import static org.junit.jupiter.api.Assertions.fail; * @author Emmanuel Bernard */ @Jpa( - annotatedClasses = { - Fridge.class, - FoodItem.class, - Person.class, - Giant.class, - House.class, - Dog.class, - Cat.class, - Cattish.class, - Feline.class, - Garden.class, - Flower.class, - JoinedManyToOneOwner.class, - Parent.class, - Child.class - } + annotatedClasses = { + Fridge.class, + FoodItem.class, + Person.class, + Giant.class, + House.class, + Dog.class, + Cat.class, + Cattish.class, + Feline.class, + Garden.class, + Flower.class, + JoinedManyToOneOwner.class, + Parent.class, + Child.class + } ) public class MetadataTest { - @Test - public void testBaseOfService(EntityManagerFactoryScope scope) { - EntityManagerFactory emf = scope.getEntityManagerFactory(); - assertNotNull(emf.getMetamodel()); - final EntityType entityType = emf.getMetamodel().entity(Fridge.class); - assertNotNull(entityType); + @Test + public void testBaseOfService(EntityManagerFactoryScope scope) { + EntityManagerFactory emf = scope.getEntityManagerFactory(); + assertNotNull(emf.getMetamodel()); + final EntityType entityType = emf.getMetamodel().entity(Fridge.class); + assertNotNull(entityType); - } + } - @Test - public void testInvalidAttributeCausesIllegalArgumentException(EntityManagerFactoryScope scope) { - // should not matter the exact subclass of ManagedType since this is implemented on the base class but - // check each anyway.. + @Test + public void testInvalidAttributeCausesIllegalArgumentException(EntityManagerFactoryScope scope) { + // should not matter the exact subclass of ManagedType since this is implemented on the base class but + // check each anyway.. - // entity - checkNonExistentAttributeAccess(scope.getEntityManagerFactory().getMetamodel().entity(Fridge.class)); + // entity + checkNonExistentAttributeAccess(scope.getEntityManagerFactory().getMetamodel().entity(Fridge.class)); - // embeddable - checkNonExistentAttributeAccess(scope.getEntityManagerFactory().getMetamodel().embeddable(Address.class)); - } + // embeddable + checkNonExistentAttributeAccess(scope.getEntityManagerFactory().getMetamodel().embeddable(Address.class)); + } - private void checkNonExistentAttributeAccess(ManagedType managedType) { - final String NAME = "NO_SUCH_ATTRIBUTE"; - try { - managedType.getAttribute(NAME); - fail("Lookup of non-existent attribute (getAttribute) should have caused IAE : " + managedType); - } catch (IllegalArgumentException expected) { - } - try { - managedType.getSingularAttribute(NAME); - fail("Lookup of non-existent attribute (getSingularAttribute) should have caused IAE : " + managedType); - } catch (IllegalArgumentException expected) { - } - try { - managedType.getCollection(NAME); - fail("Lookup of non-existent attribute (getCollection) should have caused IAE : " + managedType); - } catch (IllegalArgumentException expected) { - } - } + private void checkNonExistentAttributeAccess(ManagedType managedType) { + final String NAME = "NO_SUCH_ATTRIBUTE"; + try { + managedType.getAttribute(NAME); + fail("Lookup of non-existent attribute (getAttribute) should have caused IAE : " + managedType); + } catch (IllegalArgumentException expected) { + } + try { + managedType.getSingularAttribute(NAME); + fail("Lookup of non-existent attribute (getSingularAttribute) should have caused IAE : " + managedType); + } catch (IllegalArgumentException expected) { + } + try { + managedType.getCollection(NAME); + fail("Lookup of non-existent attribute (getCollection) should have caused IAE : " + managedType); + } catch (IllegalArgumentException expected) { + } + } - @Test - public void testBuildingMetamodelWithParameterizedCollection() { - Metadata metadata = new MetadataSources( ServiceRegistryUtil.serviceRegistry() ) - .addAnnotatedClass(WithGenericCollection.class) - .buildMetadata(); - SessionFactoryImplementor sfi = (SessionFactoryImplementor) metadata.buildSessionFactory(); - sfi.close(); - } + @Test + public void testBuildingMetamodelWithParameterizedCollection() { + Metadata metadata = new MetadataSources( ServiceRegistryUtil.serviceRegistry() ) + .addAnnotatedClass(WithGenericCollection.class) + .buildMetadata(); + SessionFactoryImplementor sfi = (SessionFactoryImplementor) metadata.buildSessionFactory(); + sfi.close(); + } - @Test - public void testLogicalManyToOne(EntityManagerFactoryScope scope) { - final EntityType entityType = scope.getEntityManagerFactory().getMetamodel().entity( - JoinedManyToOneOwner.class); - final SingularAttribute attr = entityType.getDeclaredSingularAttribute("house"); - assertEquals(Attribute.PersistentAttributeType.MANY_TO_ONE, attr.getPersistentAttributeType()); - assertEquals(House.class, attr.getBindableJavaType()); - final EntityType houseType = scope.getEntityManagerFactory().getMetamodel().entity(House.class); - assertEquals(houseType.getBindableJavaType(), attr.getBindableJavaType()); - assertFalse(entityType.getDeclaredSingularAttribute("house2").isOptional()); - } + @Test + public void testLogicalManyToOne(EntityManagerFactoryScope scope) { + final EntityType entityType = scope.getEntityManagerFactory().getMetamodel().entity( + JoinedManyToOneOwner.class); + final SingularAttribute attr = entityType.getDeclaredSingularAttribute("house"); + assertEquals(Attribute.PersistentAttributeType.MANY_TO_ONE, attr.getPersistentAttributeType()); + assertEquals(House.class, attr.getBindableJavaType()); + final EntityType houseType = scope.getEntityManagerFactory().getMetamodel().entity(House.class); + assertEquals(houseType.getBindableJavaType(), attr.getBindableJavaType()); + assertFalse(entityType.getDeclaredSingularAttribute("house2").isOptional()); + } - @Test - public void testEntity(EntityManagerFactoryScope scope) { - final EntityType fridgeType = scope.getEntityManagerFactory().getMetamodel().entity(Fridge.class); - assertEquals(Fridge.class, fridgeType.getBindableJavaType()); - assertEquals(Bindable.BindableType.ENTITY_TYPE, fridgeType.getBindableType()); - SingularAttribute wrapped = fridgeType.getDeclaredSingularAttribute( - "temperature", - Integer.class - ); - assertNotNull(wrapped); - SingularAttribute primitive = fridgeType.getDeclaredSingularAttribute( - "temperature", - int.class - ); - assertNotNull(primitive); - assertNotNull(fridgeType.getDeclaredSingularAttribute("temperature")); - assertNotNull(fridgeType.getDeclaredAttribute("temperature")); - final SingularAttribute id = fridgeType.getDeclaredId(Long.class); - assertNotNull(id); - assertTrue(id.isId()); - try { - fridgeType.getDeclaredId(java.util.Date.class); - fail("expecting failure"); - } catch (IllegalArgumentException ignore) { - // expected result - } - final SingularAttribute id2 = fridgeType.getId(Long.class); - assertNotNull(id2); + @Test + public void testEntity(EntityManagerFactoryScope scope) { + final EntityType fridgeType = scope.getEntityManagerFactory().getMetamodel().entity(Fridge.class); + assertEquals(Fridge.class, fridgeType.getBindableJavaType()); + assertEquals(Bindable.BindableType.ENTITY_TYPE, fridgeType.getBindableType()); + SingularAttribute wrapped = fridgeType.getDeclaredSingularAttribute( + "temperature", + Integer.class + ); + assertNotNull(wrapped); + SingularAttribute primitive = fridgeType.getDeclaredSingularAttribute( + "temperature", + int.class + ); + assertNotNull(primitive); + assertNotNull(fridgeType.getDeclaredSingularAttribute("temperature")); + assertNotNull(fridgeType.getDeclaredAttribute("temperature")); + final SingularAttribute id = fridgeType.getDeclaredId(Long.class); + assertNotNull(id); + assertTrue(id.isId()); + try { + fridgeType.getDeclaredId(java.util.Date.class); + fail("expecting failure"); + } catch (IllegalArgumentException ignore) { + // expected result + } + final SingularAttribute id2 = fridgeType.getId(Long.class); + assertNotNull(id2); - assertEquals("Fridge", fridgeType.getName()); - assertEquals(Long.class, fridgeType.getIdType().getJavaType()); - assertTrue(fridgeType.hasSingleIdAttribute()); - assertFalse(fridgeType.hasVersionAttribute()); - assertEquals(Type.PersistenceType.ENTITY, fridgeType.getPersistenceType()); + assertEquals("Fridge", fridgeType.getName()); + assertEquals(Long.class, fridgeType.getIdType().getJavaType()); + assertTrue(fridgeType.hasSingleIdAttribute()); + assertFalse(fridgeType.hasVersionAttribute()); + assertEquals(Type.PersistenceType.ENTITY, fridgeType.getPersistenceType()); - assertEquals(4, fridgeType.getDeclaredAttributes().size()); + assertEquals(4, fridgeType.getDeclaredAttributes().size()); - final EntityType houseType = scope.getEntityManagerFactory().getMetamodel().entity(House.class); - assertEquals("House", houseType.getName()); - assertTrue(houseType.hasSingleIdAttribute()); - final SingularAttribute houseId = houseType.getDeclaredId(House.Key.class); - assertNotNull(houseId); - assertTrue(houseId.isId()); - assertEquals(Attribute.PersistentAttributeType.EMBEDDED, houseId.getPersistentAttributeType()); + final EntityType houseType = scope.getEntityManagerFactory().getMetamodel().entity(House.class); + assertEquals("House", houseType.getName()); + assertTrue(houseType.hasSingleIdAttribute()); + final SingularAttribute houseId = houseType.getDeclaredId(House.Key.class); + assertNotNull(houseId); + assertTrue(houseId.isId()); + assertEquals(Attribute.PersistentAttributeType.EMBEDDED, houseId.getPersistentAttributeType()); - final EntityType personType = scope.getEntityManagerFactory().getMetamodel().entity(Person.class); - assertEquals("Homo", personType.getName()); - assertFalse(personType.hasSingleIdAttribute()); - final Set> ids = personType.getIdClassAttributes(); - assertNotNull(ids); - assertEquals(2, ids.size()); - for (SingularAttribute localId : ids) { - assertTrue(localId.isId()); - assertSame(personType, localId.getDeclaringType()); - assertSame(localId, personType.getDeclaredAttribute(localId.getName())); - assertSame(localId, personType.getDeclaredSingularAttribute(localId.getName())); - assertSame(localId, personType.getAttribute(localId.getName())); - assertSame(localId, personType.getSingularAttribute(localId.getName())); - assertTrue(personType.getAttributes().contains(localId)); - } + final EntityType personType = scope.getEntityManagerFactory().getMetamodel().entity(Person.class); + assertEquals("Homo", personType.getName()); + assertFalse(personType.hasSingleIdAttribute()); + final Set> ids = personType.getIdClassAttributes(); + assertNotNull(ids); + assertEquals(2, ids.size()); + for (SingularAttribute localId : ids) { + assertTrue(localId.isId()); + assertSame(personType, localId.getDeclaringType()); + assertSame(localId, personType.getDeclaredAttribute(localId.getName())); + assertSame(localId, personType.getDeclaredSingularAttribute(localId.getName())); + assertSame(localId, personType.getAttribute(localId.getName())); + assertSame(localId, personType.getSingularAttribute(localId.getName())); + assertTrue(personType.getAttributes().contains(localId)); + } - final EntityType giantType = scope.getEntityManagerFactory().getMetamodel().entity(Giant.class); - assertEquals("HomoGigantus", giantType.getName()); - assertFalse(giantType.hasSingleIdAttribute()); - final Set> giantIds = giantType.getIdClassAttributes(); - assertNotNull(giantIds); - assertEquals(2, giantIds.size()); - assertEquals(personType.getIdClassAttributes(), giantIds); - for (SingularAttribute localGiantId : giantIds) { - assertTrue(localGiantId.isId()); - try { - giantType.getDeclaredAttribute(localGiantId.getName()); - fail(localGiantId.getName() + " is a declared attribute, but shouldn't be"); - } catch (IllegalArgumentException ex) { - // expected - } - try { - giantType.getDeclaredSingularAttribute(localGiantId.getName()); - fail(localGiantId.getName() + " is a declared singular attribute, but shouldn't be"); - } catch (IllegalArgumentException ex) { - // expected - } - assertSame(localGiantId, giantType.getAttribute(localGiantId.getName())); - assertTrue(giantType.getAttributes().contains(localGiantId)); - } + final EntityType giantType = scope.getEntityManagerFactory().getMetamodel().entity(Giant.class); + assertEquals("HomoGigantus", giantType.getName()); + assertFalse(giantType.hasSingleIdAttribute()); + final Set> giantIds = giantType.getIdClassAttributes(); + assertNotNull(giantIds); + assertEquals(2, giantIds.size()); + assertEquals(personType.getIdClassAttributes(), giantIds); + for (SingularAttribute localGiantId : giantIds) { + assertTrue(localGiantId.isId()); + try { + giantType.getDeclaredAttribute(localGiantId.getName()); + fail(localGiantId.getName() + " is a declared attribute, but shouldn't be"); + } catch (IllegalArgumentException ex) { + // expected + } + try { + giantType.getDeclaredSingularAttribute(localGiantId.getName()); + fail(localGiantId.getName() + " is a declared singular attribute, but shouldn't be"); + } catch (IllegalArgumentException ex) { + // expected + } + assertSame(localGiantId, giantType.getAttribute(localGiantId.getName())); + assertTrue(giantType.getAttributes().contains(localGiantId)); + } - final EntityType foodType = scope.getEntityManagerFactory().getMetamodel().entity(FoodItem.class); - assertTrue(foodType.hasVersionAttribute()); - final SingularAttribute version = foodType.getVersion(Long.class); - assertNotNull(version); - assertTrue(version.isVersion()); - assertEquals(3, foodType.getDeclaredAttributes().size()); + final EntityType foodType = scope.getEntityManagerFactory().getMetamodel().entity(FoodItem.class); + assertTrue(foodType.hasVersionAttribute()); + final SingularAttribute version = foodType.getVersion(Long.class); + assertNotNull(version); + assertTrue(version.isVersion()); + assertEquals(3, foodType.getDeclaredAttributes().size()); - } + } - @Test - public void testBasic(EntityManagerFactoryScope scope) { - final EntityType entityType = scope.getEntityManagerFactory().getMetamodel().entity(Fridge.class); - final SingularAttribute singularAttribute = entityType.getDeclaredSingularAttribute( - "temperature", - Integer.class - ); + @Test + public void testBasic(EntityManagerFactoryScope scope) { + final EntityType entityType = scope.getEntityManagerFactory().getMetamodel().entity(Fridge.class); + final SingularAttribute singularAttribute = entityType.getDeclaredSingularAttribute( + "temperature", + Integer.class + ); assertEquals( int.class, singularAttribute.getBindableJavaType() ); assertEquals( int.class, singularAttribute.getType().getJavaType() ); - assertEquals(Bindable.BindableType.SINGULAR_ATTRIBUTE, singularAttribute.getBindableType()); - assertFalse(singularAttribute.isId()); - assertFalse(singularAttribute.isOptional()); - assertFalse(entityType.getDeclaredSingularAttribute("brand", String.class).isOptional()); - assertFalse(entityType.getDeclaredSingularAttribute("height", Integer.class).isOptional()); - assertEquals(Type.PersistenceType.BASIC, singularAttribute.getType().getPersistenceType()); - final Attribute attribute = entityType.getDeclaredAttribute("temperature"); - assertNotNull(attribute); - assertEquals("temperature", attribute.getName()); - assertEquals(Fridge.class, attribute.getDeclaringType().getJavaType()); - assertEquals(Attribute.PersistentAttributeType.BASIC, attribute.getPersistentAttributeType()); + assertEquals(Bindable.BindableType.SINGULAR_ATTRIBUTE, singularAttribute.getBindableType()); + assertFalse(singularAttribute.isId()); + assertFalse(singularAttribute.isOptional()); + assertFalse(entityType.getDeclaredSingularAttribute("brand", String.class).isOptional()); + assertFalse(entityType.getDeclaredSingularAttribute("height", Integer.class).isOptional()); + assertEquals(Type.PersistenceType.BASIC, singularAttribute.getType().getPersistenceType()); + final Attribute attribute = entityType.getDeclaredAttribute("temperature"); + assertNotNull(attribute); + assertEquals("temperature", attribute.getName()); + assertEquals(Fridge.class, attribute.getDeclaringType().getJavaType()); + assertEquals(Attribute.PersistentAttributeType.BASIC, attribute.getPersistentAttributeType()); assertEquals( int.class, attribute.getJavaType() ); - assertFalse(attribute.isAssociation()); - assertFalse(attribute.isCollection()); + assertFalse(attribute.isAssociation()); + assertFalse(attribute.isCollection()); - boolean found = false; - for (Attribute attr : entityType.getDeclaredAttributes()) { - if ("temperature".equals(attr.getName())) { - found = true; - break; - } - } - assertTrue(found); - } + boolean found = false; + for (Attribute attr : entityType.getDeclaredAttributes()) { + if ("temperature".equals(attr.getName())) { + found = true; + break; + } + } + assertTrue(found); + } - @Test - public void testEmbeddable(EntityManagerFactoryScope scope) { - final EntityType entityType = scope.getEntityManagerFactory().getMetamodel().entity(House.class); - final SingularAttribute address = entityType.getDeclaredSingularAttribute( - "address", - Address.class - ); - assertNotNull(address); - assertEquals(Attribute.PersistentAttributeType.EMBEDDED, address.getPersistentAttributeType()); - assertFalse(address.isCollection()); - assertFalse(address.isAssociation()); - final EmbeddableType
addressType = (EmbeddableType
) address.getType(); - assertEquals(Type.PersistenceType.EMBEDDABLE, addressType.getPersistenceType()); - assertEquals(3, addressType.getDeclaredAttributes().size()); - assertTrue(addressType.getDeclaredSingularAttribute("address1").isOptional()); - assertFalse(addressType.getDeclaredSingularAttribute("address2").isOptional()); + @Test + public void testEmbeddable(EntityManagerFactoryScope scope) { + final EntityType entityType = scope.getEntityManagerFactory().getMetamodel().entity(House.class); + final SingularAttribute address = entityType.getDeclaredSingularAttribute( + "address", + Address.class + ); + assertNotNull(address); + assertEquals(Attribute.PersistentAttributeType.EMBEDDED, address.getPersistentAttributeType()); + assertFalse(address.isCollection()); + assertFalse(address.isAssociation()); + final EmbeddableType
addressType = (EmbeddableType
) address.getType(); + assertEquals(Type.PersistenceType.EMBEDDABLE, addressType.getPersistenceType()); + assertEquals(3, addressType.getDeclaredAttributes().size()); + assertTrue(addressType.getDeclaredSingularAttribute("address1").isOptional()); + assertFalse(addressType.getDeclaredSingularAttribute("address2").isOptional()); - final EmbeddableType
directType = scope.getEntityManagerFactory() - .getMetamodel() - .embeddable(Address.class); - assertNotNull(directType); - assertEquals(Type.PersistenceType.EMBEDDABLE, directType.getPersistenceType()); - } + final EmbeddableType
directType = scope.getEntityManagerFactory() + .getMetamodel() + .embeddable(Address.class); + assertNotNull(directType); + assertEquals(Type.PersistenceType.EMBEDDABLE, directType.getPersistenceType()); + } - @Test - public void testCollection(EntityManagerFactoryScope scope) { - final EntityType entiytype = scope.getEntityManagerFactory().getMetamodel().entity(Garden.class); - final Set> attributes = entiytype.getPluralAttributes(); - assertEquals(1, attributes.size()); - PluralAttribute flowers = attributes.iterator().next(); - assertTrue(flowers instanceof ListAttribute); - } + @Test + public void testCollection(EntityManagerFactoryScope scope) { + final EntityType entiytype = scope.getEntityManagerFactory().getMetamodel().entity(Garden.class); + final Set> attributes = entiytype.getPluralAttributes(); + assertEquals(1, attributes.size()); + PluralAttribute flowers = attributes.iterator().next(); + assertTrue(flowers instanceof ListAttribute); + } - @Test - @JiraKey(value = "HHH-14346") - public void testEmptyPluralAttributeSet(EntityManagerFactoryScope scope) { - final EntityType entityType = scope.getEntityManagerFactory().getMetamodel().entity(Feline.class); - final Set> attributes = entityType.getPluralAttributes(); - assertEquals(0, attributes.size()); - } + @Test + @JiraKey(value = "HHH-14346") + public void testEmptyPluralAttributeSet(EntityManagerFactoryScope scope) { + final EntityType entityType = scope.getEntityManagerFactory().getMetamodel().entity(Feline.class); + final Set> attributes = entityType.getPluralAttributes(); + assertEquals(0, attributes.size()); + } - @Test - public void testElementCollection(EntityManagerFactoryScope scope) { - final EntityType entityType = scope.getEntityManagerFactory().getMetamodel().entity(House.class); - final SetAttribute rooms = entityType.getDeclaredSet("rooms", Room.class); - assertNotNull(rooms); - assertFalse(rooms.isAssociation()); - assertTrue(rooms.isCollection()); - assertEquals(Attribute.PersistentAttributeType.ELEMENT_COLLECTION, rooms.getPersistentAttributeType()); - assertEquals(Room.class, rooms.getBindableJavaType()); - assertEquals(Bindable.BindableType.PLURAL_ATTRIBUTE, rooms.getBindableType()); - assertEquals(Set.class, rooms.getJavaType()); - assertEquals(PluralAttribute.CollectionType.SET, rooms.getCollectionType()); - assertEquals(3, entityType.getDeclaredPluralAttributes().size()); - assertEquals(Type.PersistenceType.EMBEDDABLE, rooms.getElementType().getPersistenceType()); + @Test + public void testElementCollection(EntityManagerFactoryScope scope) { + final EntityType entityType = scope.getEntityManagerFactory().getMetamodel().entity(House.class); + final SetAttribute rooms = entityType.getDeclaredSet("rooms", Room.class); + assertNotNull(rooms); + assertFalse(rooms.isAssociation()); + assertTrue(rooms.isCollection()); + assertEquals(Attribute.PersistentAttributeType.ELEMENT_COLLECTION, rooms.getPersistentAttributeType()); + assertEquals(Room.class, rooms.getBindableJavaType()); + assertEquals(Bindable.BindableType.PLURAL_ATTRIBUTE, rooms.getBindableType()); + assertEquals(Set.class, rooms.getJavaType()); + assertEquals(PluralAttribute.CollectionType.SET, rooms.getCollectionType()); + assertEquals(3, entityType.getDeclaredPluralAttributes().size()); + assertEquals(Type.PersistenceType.EMBEDDABLE, rooms.getElementType().getPersistenceType()); - final MapAttribute roomsByName = entityType.getDeclaredMap( - "roomsByName", String.class, Room.class - ); - assertNotNull(roomsByName); - assertEquals(String.class, roomsByName.getKeyJavaType()); - assertEquals(Type.PersistenceType.BASIC, roomsByName.getKeyType().getPersistenceType()); - assertEquals(PluralAttribute.CollectionType.MAP, roomsByName.getCollectionType()); + final MapAttribute roomsByName = entityType.getDeclaredMap( + "roomsByName", String.class, Room.class + ); + assertNotNull(roomsByName); + assertEquals(String.class, roomsByName.getKeyJavaType()); + assertEquals(Type.PersistenceType.BASIC, roomsByName.getKeyType().getPersistenceType()); + assertEquals(PluralAttribute.CollectionType.MAP, roomsByName.getCollectionType()); - final ListAttribute roomsBySize = entityType.getDeclaredList("roomsBySize", Room.class); - assertNotNull(roomsBySize); - assertEquals(Type.PersistenceType.EMBEDDABLE, roomsBySize.getElementType().getPersistenceType()); - assertEquals(PluralAttribute.CollectionType.LIST, roomsBySize.getCollectionType()); - } + final ListAttribute roomsBySize = entityType.getDeclaredList("roomsBySize", Room.class); + assertNotNull(roomsBySize); + assertEquals(Type.PersistenceType.EMBEDDABLE, roomsBySize.getElementType().getPersistenceType()); + assertEquals(PluralAttribute.CollectionType.LIST, roomsBySize.getCollectionType()); + } - @Test - public void testHierarchy(EntityManagerFactoryScope scope) { - final EntityType cat = scope.getEntityManagerFactory().getMetamodel().entity(Cat.class); - assertNotNull(cat); - assertEquals(7, cat.getAttributes().size()); - assertEquals(1, cat.getDeclaredAttributes().size()); - ensureProperMember(cat.getDeclaredAttributes()); + @Test + public void testHierarchy(EntityManagerFactoryScope scope) { + final EntityType cat = scope.getEntityManagerFactory().getMetamodel().entity(Cat.class); + assertNotNull(cat); + assertEquals(7, cat.getAttributes().size()); + assertEquals(1, cat.getDeclaredAttributes().size()); + ensureProperMember(cat.getDeclaredAttributes()); - assertTrue(cat.hasVersionAttribute()); - assertEquals("version", cat.getVersion(Long.class).getName()); - verifyDeclaredVersionNotPresent(cat); - verifyDeclaredIdNotPresentAndIdPresent(cat); + assertTrue(cat.hasVersionAttribute()); + assertEquals("version", cat.getVersion(Long.class).getName()); + verifyDeclaredVersionNotPresent(cat); + verifyDeclaredIdNotPresentAndIdPresent(cat); - assertEquals(Type.PersistenceType.MAPPED_SUPERCLASS, cat.getSupertype().getPersistenceType()); - MappedSuperclassType cattish = (MappedSuperclassType) cat.getSupertype(); - assertEquals(6, cattish.getAttributes().size()); - assertEquals(1, cattish.getDeclaredAttributes().size()); - ensureProperMember(cattish.getDeclaredAttributes()); + assertEquals(Type.PersistenceType.MAPPED_SUPERCLASS, cat.getSupertype().getPersistenceType()); + MappedSuperclassType cattish = (MappedSuperclassType) cat.getSupertype(); + assertEquals(6, cattish.getAttributes().size()); + assertEquals(1, cattish.getDeclaredAttributes().size()); + ensureProperMember(cattish.getDeclaredAttributes()); - assertTrue(cattish.hasVersionAttribute()); - assertEquals("version", cattish.getVersion(Long.class).getName()); - verifyDeclaredVersionNotPresent(cattish); - verifyDeclaredIdNotPresentAndIdPresent(cattish); + assertTrue(cattish.hasVersionAttribute()); + assertEquals("version", cattish.getVersion(Long.class).getName()); + verifyDeclaredVersionNotPresent(cattish); + verifyDeclaredIdNotPresentAndIdPresent(cattish); - assertEquals(Type.PersistenceType.ENTITY, cattish.getSupertype().getPersistenceType()); - EntityType feline = (EntityType) cattish.getSupertype(); - assertEquals(5, feline.getAttributes().size()); - assertEquals(1, feline.getDeclaredAttributes().size()); - ensureProperMember(feline.getDeclaredAttributes()); + assertEquals(Type.PersistenceType.ENTITY, cattish.getSupertype().getPersistenceType()); + EntityType feline = (EntityType) cattish.getSupertype(); + assertEquals(5, feline.getAttributes().size()); + assertEquals(1, feline.getDeclaredAttributes().size()); + ensureProperMember(feline.getDeclaredAttributes()); - assertTrue(feline.hasVersionAttribute()); - assertEquals("version", feline.getVersion(Long.class).getName()); - verifyDeclaredVersionNotPresent(feline); - verifyDeclaredIdNotPresentAndIdPresent(feline); + assertTrue(feline.hasVersionAttribute()); + assertEquals("version", feline.getVersion(Long.class).getName()); + verifyDeclaredVersionNotPresent(feline); + verifyDeclaredIdNotPresentAndIdPresent(feline); - assertEquals(Type.PersistenceType.MAPPED_SUPERCLASS, feline.getSupertype().getPersistenceType()); - MappedSuperclassType animal = (MappedSuperclassType) feline.getSupertype(); - assertEquals(4, animal.getAttributes().size()); - assertEquals(2, animal.getDeclaredAttributes().size()); - ensureProperMember(animal.getDeclaredAttributes()); + assertEquals(Type.PersistenceType.MAPPED_SUPERCLASS, feline.getSupertype().getPersistenceType()); + MappedSuperclassType animal = (MappedSuperclassType) feline.getSupertype(); + assertEquals(4, animal.getAttributes().size()); + assertEquals(2, animal.getDeclaredAttributes().size()); + ensureProperMember(animal.getDeclaredAttributes()); - assertTrue(animal.hasVersionAttribute()); - assertEquals("version", animal.getVersion(Long.class).getName()); - verifyDeclaredVersionNotPresent(animal); - assertEquals("id", animal.getId(Long.class).getName()); - final SingularAttribute id = animal.getDeclaredId(Long.class); - assertEquals("id", id.getName()); - assertNotNull(id.getJavaMember()); + assertTrue(animal.hasVersionAttribute()); + assertEquals("version", animal.getVersion(Long.class).getName()); + verifyDeclaredVersionNotPresent(animal); + assertEquals("id", animal.getId(Long.class).getName()); + final SingularAttribute id = animal.getDeclaredId(Long.class); + assertEquals("id", id.getName()); + assertNotNull(id.getJavaMember()); - assertEquals(Type.PersistenceType.MAPPED_SUPERCLASS, animal.getSupertype().getPersistenceType()); - MappedSuperclassType thing = (MappedSuperclassType) animal.getSupertype(); - assertEquals(2, thing.getAttributes().size()); - assertEquals(2, thing.getDeclaredAttributes().size()); - ensureProperMember(thing.getDeclaredAttributes()); - final SingularAttribute weight = thing.getDeclaredSingularAttribute("weight", Double.class); - assertEquals(Double.class, weight.getJavaType()); + assertEquals(Type.PersistenceType.MAPPED_SUPERCLASS, animal.getSupertype().getPersistenceType()); + MappedSuperclassType thing = (MappedSuperclassType) animal.getSupertype(); + assertEquals(2, thing.getAttributes().size()); + assertEquals(2, thing.getDeclaredAttributes().size()); + ensureProperMember(thing.getDeclaredAttributes()); + final SingularAttribute weight = thing.getDeclaredSingularAttribute("weight", Double.class); + assertEquals(Double.class, weight.getJavaType()); - assertEquals("version", thing.getVersion(Long.class).getName()); - final SingularAttribute version = thing.getDeclaredVersion(Long.class); - assertEquals("version", version.getName()); - assertNotNull(version.getJavaMember()); - assertNull(thing.getId(Long.class)); + assertEquals("version", thing.getVersion(Long.class).getName()); + final SingularAttribute version = thing.getDeclaredVersion(Long.class); + assertEquals("version", version.getName()); + assertNotNull(version.getJavaMember()); + assertNull(thing.getId(Long.class)); - assertNull(thing.getSupertype()); - } + assertNull(thing.getSupertype()); + } - @Test - public void testBackrefAndGenerics(EntityManagerFactoryScope scope) { - final EntityType parent = scope.getEntityManagerFactory().getMetamodel().entity(Parent.class); - assertNotNull(parent); - final SetAttribute children = parent.getSet("children"); - assertNotNull(children); - assertEquals(1, parent.getPluralAttributes().size()); - assertEquals(4, parent.getAttributes().size()); - final EntityType child = scope.getEntityManagerFactory().getMetamodel().entity(Child.class); - assertNotNull(child); - assertEquals(2, child.getAttributes().size()); - final SingularAttribute attribute = parent.getSingularAttribute( - "siblings", Parent.Relatives.class - ); - final EmbeddableType siblings = (EmbeddableType) attribute.getType(); - assertNotNull(siblings); - final SetAttribute siblingsCollection = siblings.getSet("siblings"); - assertNotNull(siblingsCollection); - final Type collectionElement = siblingsCollection.getElementType(); - assertNotNull(collectionElement); - assertEquals(collectionElement, child); - } + @Test + public void testBackrefAndGenerics(EntityManagerFactoryScope scope) { + final EntityType parent = scope.getEntityManagerFactory().getMetamodel().entity(Parent.class); + assertNotNull(parent); + final SetAttribute children = parent.getSet("children"); + assertNotNull(children); + assertEquals(1, parent.getPluralAttributes().size()); + assertEquals(4, parent.getAttributes().size()); + final EntityType child = scope.getEntityManagerFactory().getMetamodel().entity(Child.class); + assertNotNull(child); + assertEquals(2, child.getAttributes().size()); + final SingularAttribute attribute = parent.getSingularAttribute( + "siblings", Parent.Relatives.class + ); + final EmbeddableType siblings = (EmbeddableType) attribute.getType(); + assertNotNull(siblings); + final SetAttribute siblingsCollection = siblings.getSet("siblings"); + assertNotNull(siblingsCollection); + final Type collectionElement = siblingsCollection.getElementType(); + assertNotNull(collectionElement); + assertEquals(collectionElement, child); + } - @Test - @Jira("https://hibernate.atlassian.net/browse/HHH-17465") - public void testInheritedVersion(EntityManagerFactoryScope scope) { - EntityManagerFactory emf = scope.getEntityManagerFactory(); - assertNotNull(emf.getMetamodel()); - final EntityType entityType = emf.getMetamodel().entity(Cat.class); - assertTrue(entityType.hasVersionAttribute()); - assertTrue(entityType.getSingularAttribute("version").isVersion()); + @Test + @Jira("https://hibernate.atlassian.net/browse/HHH-17465") + public void testInheritedVersion(EntityManagerFactoryScope scope) { + EntityManagerFactory emf = scope.getEntityManagerFactory(); + assertNotNull(emf.getMetamodel()); + final EntityType entityType = emf.getMetamodel().entity(Cat.class); + assertTrue(entityType.hasVersionAttribute()); + assertTrue(entityType.getSingularAttribute("version").isVersion()); - } + } - private void ensureProperMember(Set attributes) { - //we do not update the set so we are safe - @SuppressWarnings("unchecked") final Set> safeAttributes = (Set>) attributes; - for (Attribute attribute : safeAttributes) { - final String name = attribute.getJavaMember().getName(); - assertNotNull(attribute.getJavaMember()); - assertTrue(name.toLowerCase(Locale.ROOT).endsWith(attribute.getName().toLowerCase(Locale.ROOT))); - } - } + private void ensureProperMember(Set attributes) { + //we do not update the set so we are safe + @SuppressWarnings("unchecked") final Set> safeAttributes = (Set>) attributes; + for (Attribute attribute : safeAttributes) { + final String name = attribute.getJavaMember().getName(); + assertNotNull(attribute.getJavaMember()); + assertTrue(name.toLowerCase(Locale.ROOT).endsWith(attribute.getName().toLowerCase(Locale.ROOT))); + } + } - private void verifyDeclaredIdNotPresentAndIdPresent(IdentifiableType type) { - assertEquals("id", type.getId(Long.class).getName()); - try { - type.getDeclaredId(Long.class); - fail("Should not have a declared id"); - } catch (IllegalArgumentException e) { - //success - } - } + private void verifyDeclaredIdNotPresentAndIdPresent(IdentifiableType type) { + assertEquals("id", type.getId(Long.class).getName()); + try { + type.getDeclaredId(Long.class); + fail("Should not have a declared id"); + } catch (IllegalArgumentException e) { + //success + } + } - private void verifyDeclaredVersionNotPresent(IdentifiableType type) { - try { - type.getDeclaredVersion(Long.class); - fail("Should not have a declared version"); - } catch (IllegalArgumentException e) { - //success - } - } + private void verifyDeclaredVersionNotPresent(IdentifiableType type) { + try { + type.getDeclaredVersion(Long.class); + fail("Should not have a declared version"); + } catch (IllegalArgumentException e) { + //success + } + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/metadata/WithGenericCollection.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/metadata/WithGenericCollection.java index 06cc8868d3..ab6a27d0cc 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/metadata/WithGenericCollection.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/metadata/WithGenericCollection.java @@ -26,50 +26,50 @@ import jakarta.persistence.Table; @Entity @Table(name = "WITH_GENERIC_COLLECTION") public class WithGenericCollection implements java.io.Serializable { - @Id - @Column(name = "ID") - private String id; + @Id + @Column(name = "ID") + private String id; - @Basic(optional=false) - private double d; + @Basic(optional=false) + private double d; - @ManyToOne(optional=false) - @JoinColumn(name="PARENT_ID", insertable=false, updatable=false) - private WithGenericCollection parent = null; + @ManyToOne(optional=false) + @JoinColumn(name="PARENT_ID", insertable=false, updatable=false) + private WithGenericCollection parent = null; - @OneToMany(cascade = CascadeType.ALL) - @JoinColumn(name="PARENT_ID") - private List> children = new ArrayList>(); + @OneToMany(cascade = CascadeType.ALL) + @JoinColumn(name="PARENT_ID") + private List> children = new ArrayList>(); - public WithGenericCollection() { - } + public WithGenericCollection() { + } - //==================================================================== - // getters and setters for State fields + //==================================================================== + // getters and setters for State fields - public String getId() { - return id; - } + public String getId() { + return id; + } - public void setId(String id) { - this.id = id; - } + public void setId(String id) { + this.id = id; + } - public void setD(double d) { - this.d = d; - } + public void setD(double d) { + this.d = d; + } - public double getD() { - return d; - } + public double getD() { + return d; + } - public List> getChildren() { - return children; - } + public List> getChildren() { + return children; + } - public void setChildren(List> children) { - this.children = children; - } + public void setChildren(List> children) { + this.children = children; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/metamodel/BaseEmbeddedEntity.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/metamodel/BaseEmbeddedEntity.java index 73778002e2..ae614783f4 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/metamodel/BaseEmbeddedEntity.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/metamodel/BaseEmbeddedEntity.java @@ -16,46 +16,46 @@ import jakarta.persistence.MappedSuperclass; @MappedSuperclass public abstract class BaseEmbeddedEntity implements Serializable { - private I id; + private I id; - public BaseEmbeddedEntity() { - } + public BaseEmbeddedEntity() { + } - public BaseEmbeddedEntity(I id) { - this.id = id; - } + public BaseEmbeddedEntity(I id) { + this.id = id; + } - @EmbeddedId - public I getId() { - return id; - } + @EmbeddedId + public I getId() { + return id; + } - public void setId(I id) { - this.id = id; - } + public void setId(I id) { + this.id = id; + } - @Override - public int hashCode() { - int hash = 3; - hash = 47 * hash + (this.id != null ? this.id.hashCode() : 0); - return hash; - } + @Override + public int hashCode() { + int hash = 3; + hash = 47 * hash + (this.id != null ? this.id.hashCode() : 0); + return hash; + } - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - final BaseEmbeddedEntity other = (BaseEmbeddedEntity) obj; - if (this.id != other.id && (this.id == null || !this.id.equals(other.id))) { - return false; - } - return true; - } + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final BaseEmbeddedEntity other = (BaseEmbeddedEntity) obj; + if (this.id != other.id && (this.id == null || !this.id.equals(other.id))) { + return false; + } + return true; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/metamodel/Person.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/metamodel/Person.java index a61cac7970..afc00a3849 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/metamodel/Person.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/metamodel/Person.java @@ -14,31 +14,31 @@ import jakarta.persistence.Entity; @Entity public class Person extends BaseEmbeddedEntity { - private String firstName; - private String lastName; + private String firstName; + private String lastName; - public Person() { - } + public Person() { + } - public Person(PersonId id, String firstName, String lastName) { - super(id); - this.firstName = firstName; - this.lastName = lastName; - } + public Person(PersonId id, String firstName, String lastName) { + super(id); + this.firstName = firstName; + this.lastName = lastName; + } - public String getFirstName() { - return firstName; - } + public String getFirstName() { + return firstName; + } - public void setFirstName(String firstName) { - this.firstName = firstName; - } + public void setFirstName(String firstName) { + this.firstName = firstName; + } - public String getLastName() { - return lastName; - } + public String getLastName() { + return lastName; + } - public void setLastName(String lastName) { - this.lastName = lastName; - } + public void setLastName(String lastName) { + this.lastName = lastName; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/metamodel/PersonId.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/metamodel/PersonId.java index ca0a53c219..23af9c2df5 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/metamodel/PersonId.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/metamodel/PersonId.java @@ -15,59 +15,59 @@ import jakarta.persistence.Embeddable; @Embeddable public class PersonId implements Serializable { - private String ssn; - private String name; + private String ssn; + private String name; - public PersonId() { - } + public PersonId() { + } - public PersonId(String ssn, String name) { - this.ssn = ssn; - this.name = name; - } + public PersonId(String ssn, String name) { + this.ssn = ssn; + this.name = name; + } - public String getSsn() { - return ssn; - } + public String getSsn() { + return ssn; + } - public void setSsn(String ssn) { - this.ssn = ssn; - } + public void setSsn(String ssn) { + this.ssn = ssn; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - @Override - public int hashCode() { - int hash = 7; - hash = 67 * hash + (this.ssn != null ? this.ssn.hashCode() : 0); - hash = 67 * hash + (this.name != null ? this.name.hashCode() : 0); - return hash; - } + @Override + public int hashCode() { + int hash = 7; + hash = 67 * hash + (this.ssn != null ? this.ssn.hashCode() : 0); + hash = 67 * hash + (this.name != null ? this.name.hashCode() : 0); + return hash; + } - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - final PersonId other = (PersonId) obj; - if ((this.ssn == null) ? (other.ssn != null) : !this.ssn.equals(other.ssn)) { - return false; - } - if ((this.name == null) ? (other.name != null) : !this.name.equals(other.name)) { - return false; - } - return true; - } + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final PersonId other = (PersonId) obj; + if ((this.ssn == null) ? (other.ssn != null) : !this.ssn.equals(other.ssn)) { + return false; + } + if ((this.name == null) ? (other.name != null) : !this.name.equals(other.name)) { + return false; + } + return true; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/metamodel/ShelfLife.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/metamodel/ShelfLife.java index 6376f052d3..d08d7b4075 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/metamodel/ShelfLife.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/metamodel/ShelfLife.java @@ -11,8 +11,8 @@ import jakarta.persistence.Embeddable; @Embeddable public class ShelfLife implements java.io.Serializable { - private Date inceptionDate; - private Date soldDate; + private Date inceptionDate; + private Date soldDate; public ShelfLife() { } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/metamodel/attributeInSuper/AbstractWorkOrderId.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/metamodel/attributeInSuper/AbstractWorkOrderId.java index 99fa8ec7e8..c106178c73 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/metamodel/attributeInSuper/AbstractWorkOrderId.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/metamodel/attributeInSuper/AbstractWorkOrderId.java @@ -17,5 +17,5 @@ import jakarta.persistence.MappedSuperclass; public class AbstractWorkOrderId implements Serializable { private String workOrder; private Long plantId; - /* other stuffs */ + /* other stuffs */ } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/metamodel/attributeInSuper/WorkOrder.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/metamodel/attributeInSuper/WorkOrder.java index 69c60ad494..4dd860d5a8 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/metamodel/attributeInSuper/WorkOrder.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/metamodel/attributeInSuper/WorkOrder.java @@ -20,5 +20,5 @@ public class WorkOrder implements Serializable { @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, mappedBy = "workOrder") @OrderBy("operation, bomItemNumber") private Set components; - /* other stuffs */ +/* other stuffs */ } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/metamodel/attributeInSuper/WorkOrderComponentId.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/metamodel/attributeInSuper/WorkOrderComponentId.java index deda2213a8..ac43c6e954 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/metamodel/attributeInSuper/WorkOrderComponentId.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/metamodel/attributeInSuper/WorkOrderComponentId.java @@ -14,5 +14,5 @@ import jakarta.persistence.Embeddable; @Embeddable public class WorkOrderComponentId extends AbstractWorkOrderId { private Long lineNumber; - /* other stuffs */ + /* other stuffs */ } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/orphan/onetomany/DeleteSharedOneToManyOrphansTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/orphan/onetomany/DeleteSharedOneToManyOrphansTest.java index b6609f676a..2eeda7c8ee 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/orphan/onetomany/DeleteSharedOneToManyOrphansTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/orphan/onetomany/DeleteSharedOneToManyOrphansTest.java @@ -43,8 +43,8 @@ import org.junit.jupiter.api.BeforeEach; public class DeleteSharedOneToManyOrphansTest { /* - A value of DEFAULT_BATCH_FETCH_SIZE > 1 along with the initialization of the Item#higherItemRelations - collection causes the issue + A value of DEFAULT_BATCH_FETCH_SIZE > 1 along with the initialization of the Item#higherItemRelations + collection causes the issue */ @BeforeEach diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/orphan/onetoone/multilevelcascade/Preisregelung.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/orphan/onetoone/multilevelcascade/Preisregelung.java index 0b6ddd529c..1a7b4187b7 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/orphan/onetoone/multilevelcascade/Preisregelung.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/orphan/onetoone/multilevelcascade/Preisregelung.java @@ -15,27 +15,27 @@ import jakarta.persistence.OneToOne; @Entity public class Preisregelung { - @Id + @Id @GeneratedValue - private Long id; + private Long id; - @OneToOne(mappedBy = "preisregelung", cascade = CascadeType.ALL, fetch = FetchType.LAZY, orphanRemoval = true) - private Tranchenmodell tranchenmodell; + @OneToOne(mappedBy = "preisregelung", cascade = CascadeType.ALL, fetch = FetchType.LAZY, orphanRemoval = true) + private Tranchenmodell tranchenmodell; - public Long getId() { - return id; - } + public Long getId() { + return id; + } public void setId(Long id) { this.id = id; } - public Tranchenmodell getTranchenmodell() { - return tranchenmodell; - } + public Tranchenmodell getTranchenmodell() { + return tranchenmodell; + } - public void setTranchenmodell(Tranchenmodell tranchenmodell) { - this.tranchenmodell = tranchenmodell; - } + public void setTranchenmodell(Tranchenmodell tranchenmodell) { + this.tranchenmodell = tranchenmodell; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/orphan/onetoone/multilevelcascade/Tranche.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/orphan/onetoone/multilevelcascade/Tranche.java index eb43e4f64e..5eb534efdf 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/orphan/onetoone/multilevelcascade/Tranche.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/orphan/onetoone/multilevelcascade/Tranche.java @@ -17,31 +17,31 @@ import jakarta.persistence.OneToOne; @Entity public class Tranche { - @Id + @Id @GeneratedValue private Long id; - @ManyToOne(optional = false, fetch = FetchType.EAGER) - private Tranchenmodell tranchenmodell; + @ManyToOne(optional = false, fetch = FetchType.EAGER) + private Tranchenmodell tranchenmodell; @OneToOne(mappedBy = "tranche", cascade = CascadeType.ALL, fetch = FetchType.LAZY, orphanRemoval = true) private Y y; public Long getId() { - return id; - } + return id; + } public void setId(Long id) { this.id = id; } - public Tranchenmodell getTranchenmodell() { - return tranchenmodell; - } + public Tranchenmodell getTranchenmodell() { + return tranchenmodell; + } - public void setTranchenmodell(Tranchenmodell tranchenmodell) { - this.tranchenmodell = tranchenmodell; - } + public void setTranchenmodell(Tranchenmodell tranchenmodell) { + this.tranchenmodell = tranchenmodell; + } public Y getY() { return y; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/orphan/onetoone/multilevelcascade/Tranchenmodell.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/orphan/onetoone/multilevelcascade/Tranchenmodell.java index bc5a5303fb..4c2de45f68 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/orphan/onetoone/multilevelcascade/Tranchenmodell.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/orphan/onetoone/multilevelcascade/Tranchenmodell.java @@ -20,39 +20,39 @@ import jakarta.persistence.OrderColumn; @Entity public class Tranchenmodell { - @Id + @Id @GeneratedValue private Long id; - @OneToMany(cascade = CascadeType.ALL, mappedBy = "tranchenmodell", fetch = FetchType.LAZY, orphanRemoval = true) + @OneToMany(cascade = CascadeType.ALL, mappedBy = "tranchenmodell", fetch = FetchType.LAZY, orphanRemoval = true) @OrderColumn - private List tranchen = new ArrayList(); + private List tranchen = new ArrayList(); - @OneToOne(optional = true, fetch = FetchType.LAZY) - private Preisregelung preisregelung; + @OneToOne(optional = true, fetch = FetchType.LAZY) + private Preisregelung preisregelung; @OneToOne(mappedBy = "tranchenmodell", cascade = CascadeType.ALL, fetch = FetchType.LAZY, orphanRemoval = true) private X x; - public Long getId() { - return id; - } + public Long getId() { + return id; + } public void setId(Long id) { this.id = id; } - public List getTranchen() { - return tranchen; - } + public List getTranchen() { + return tranchen; + } - public Preisregelung getPreisregelung() { - return preisregelung; - } + public Preisregelung getPreisregelung() { + return preisregelung; + } - public void setPreisregelung(Preisregelung preisregelung) { - this.preisregelung = preisregelung; - } + public void setPreisregelung(Preisregelung preisregelung) { + this.preisregelung = preisregelung; + } public X getX() { return x; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/query/NamedQueryTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/query/NamedQueryTest.java index 6c172d59d5..9dfd907133 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/query/NamedQueryTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/query/NamedQueryTest.java @@ -63,108 +63,108 @@ public class NamedQueryTest extends BaseEntityManagerFunctionalTestCase { @After public void tearDown() { doInJPA( this::entityManagerFactory, entityManager -> { - entityManager.createQuery( "delete from Game" ).executeUpdate(); - } + entityManager.createQuery( "delete from Game" ).executeUpdate(); + } ); } @Test public void testNamedQueriesOrdinalParametersAreOneBased() { doInJPA( this::entityManagerFactory, entityManager -> { - Query query = entityManager.createNamedQuery( "NamedQuery" ); - query.setParameter( 1, GAME_TITLES[0] ); - List list = query.getResultList(); - assertEquals( 1, list.size() ); - } + Query query = entityManager.createNamedQuery( "NamedQuery" ); + query.setParameter( 1, GAME_TITLES[0] ); + List list = query.getResultList(); + assertEquals( 1, list.size() ); + } ); } @Test public void testNamedQueryOrdinalParametersConflict() { doInJPA( this::entityManagerFactory, entityManager -> { - Query query = entityManager.createNamedQuery( "NamedQuery" ); - query.setParameter( 1, GAME_TITLES[0] ); - List list = query.getResultList(); - assertEquals( 1, list.size() ); + Query query = entityManager.createNamedQuery( "NamedQuery" ); + query.setParameter( 1, GAME_TITLES[0] ); + List list = query.getResultList(); + assertEquals( 1, list.size() ); - final Session session = entityManager.unwrap( Session.class ); - final org.hibernate.query.Query sessionQuery = session.createQuery( "select g from Game g where title = ?1" ); - sessionQuery.setParameter( 1, GAME_TITLES[0] ); - list = sessionQuery.getResultList(); + final Session session = entityManager.unwrap( Session.class ); + final org.hibernate.query.Query sessionQuery = session.createQuery( "select g from Game g where title = ?1" ); + sessionQuery.setParameter( 1, GAME_TITLES[0] ); + list = sessionQuery.getResultList(); - query.setParameter( 1, GAME_TITLES[0] ); - assertEquals( 1, list.size() ); - } + query.setParameter( 1, GAME_TITLES[0] ); + assertEquals( 1, list.size() ); + } ); } @Test public void testNamedQueryOrdinalParametersConflict2() { doInJPA( this::entityManagerFactory, entityManager -> { - Query query = entityManager.createNamedQuery( "NamedQuery" ); - query.setParameter( 1, GAME_TITLES[0] ); - List list = query.getResultList(); - assertEquals( 1, list.size() ); + Query query = entityManager.createNamedQuery( "NamedQuery" ); + query.setParameter( 1, GAME_TITLES[0] ); + List list = query.getResultList(); + assertEquals( 1, list.size() ); - final Session session = entityManager.unwrap( Session.class ); - final org.hibernate.query.Query sessionQuery = session.getNamedQuery( "NamedQuery" ); - sessionQuery.setParameter( 1, GAME_TITLES[0] ); - list = sessionQuery.getResultList(); + final Session session = entityManager.unwrap( Session.class ); + final org.hibernate.query.Query sessionQuery = session.getNamedQuery( "NamedQuery" ); + sessionQuery.setParameter( 1, GAME_TITLES[0] ); + list = sessionQuery.getResultList(); - query.setParameter( 1, GAME_TITLES[0] ); - assertEquals( 1, list.size() ); - } + query.setParameter( 1, GAME_TITLES[0] ); + assertEquals( 1, list.size() ); + } ); } @Test public void testNativeNamedQueriesOrdinalParametersAreOneBased() { doInJPA( this::entityManagerFactory, entityManager -> { - Query query = entityManager.createNamedQuery( "NamedNativeQuery" ); - query.setParameter( 1, GAME_TITLES[0] ); - List list = query.getResultList(); - assertEquals( 1, list.size() ); - } + Query query = entityManager.createNamedQuery( "NamedNativeQuery" ); + query.setParameter( 1, GAME_TITLES[0] ); + List list = query.getResultList(); + assertEquals( 1, list.size() ); + } ); } @Test public void testNativeNamedQueriesOrdinalParametersConflict() { doInJPA( this::entityManagerFactory, entityManager -> { - Query query = entityManager.createNamedQuery( "NamedNativeQuery" ); - query.setParameter( 1, GAME_TITLES[0] ); - List list = query.getResultList(); - assertEquals( 1, list.size() ); + Query query = entityManager.createNamedQuery( "NamedNativeQuery" ); + query.setParameter( 1, GAME_TITLES[0] ); + List list = query.getResultList(); + assertEquals( 1, list.size() ); - final Session session = entityManager.unwrap( Session.class ); - final org.hibernate.query.Query sessionQuery = session.createNativeQuery( - "select * from Game g where title = ?" ); - sessionQuery.setParameter( 1, GAME_TITLES[0] ); - list = sessionQuery.getResultList(); + final Session session = entityManager.unwrap( Session.class ); + final org.hibernate.query.Query sessionQuery = session.createNativeQuery( + "select * from Game g where title = ?" ); + sessionQuery.setParameter( 1, GAME_TITLES[0] ); + list = sessionQuery.getResultList(); - query.setParameter( 1, GAME_TITLES[0] ); - assertEquals( 1, list.size() ); - } + query.setParameter( 1, GAME_TITLES[0] ); + assertEquals( 1, list.size() ); + } ); } @Test public void testNativeNamedQueriesOrdinalParametersConflict2() { doInJPA( this::entityManagerFactory, entityManager -> { - Query query = entityManager.createNamedQuery( "NamedNativeQuery" ); - query.setParameter( 1, GAME_TITLES[0] ); - List list = query.getResultList(); - assertEquals( 1, list.size() ); + Query query = entityManager.createNamedQuery( "NamedNativeQuery" ); + query.setParameter( 1, GAME_TITLES[0] ); + List list = query.getResultList(); + assertEquals( 1, list.size() ); - final Session session = entityManager.unwrap( Session.class ); - final org.hibernate.query.Query sessionQuery = session.getNamedNativeQuery( - "NamedNativeQuery" ); - sessionQuery.setParameter( 1, GAME_TITLES[0] ); - list = sessionQuery.getResultList(); + final Session session = entityManager.unwrap( Session.class ); + final org.hibernate.query.Query sessionQuery = session.getNamedNativeQuery( + "NamedNativeQuery" ); + sessionQuery.setParameter( 1, GAME_TITLES[0] ); + list = sessionQuery.getResultList(); - query.setParameter( 1, GAME_TITLES[0] ); - assertEquals( 1, list.size() ); - } + query.setParameter( 1, GAME_TITLES[0] ); + assertEquals( 1, list.size() ); + } ); } @@ -276,11 +276,11 @@ public class NamedQueryTest extends BaseEntityManagerFunctionalTestCase { @JiraKey(value = "HHH-14816") public void testQueryHintLockMode() { doInJPA( this::entityManagerFactory, entityManager -> { - Query query = entityManager.createNamedQuery( "NamedNativeQuery" ); - query.setHint( HINT_NATIVE_LOCK_MODE, "none" ); - query.setParameter( 1, GAME_TITLES[0] ); - assertEquals( LockMode.NONE, query.getHints().get( HINT_NATIVE_LOCK_MODE ) ); - } + Query query = entityManager.createNamedQuery( "NamedNativeQuery" ); + query.setHint( HINT_NATIVE_LOCK_MODE, "none" ); + query.setParameter( 1, GAME_TITLES[0] ); + assertEquals( LockMode.NONE, query.getHints().get( HINT_NATIVE_LOCK_MODE ) ); + } ); } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/query/TupleNativeQueryTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/query/TupleNativeQueryTest.java index b4438c1fdb..4ac95f8451 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/query/TupleNativeQueryTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/query/TupleNativeQueryTest.java @@ -29,760 +29,760 @@ import static org.junit.Assert.assertNull; @RequiresDialect(H2Dialect.class) public class TupleNativeQueryTest extends BaseEntityManagerFunctionalTestCase { - @Override - protected Class[] getAnnotatedClasses() { - return new Class[]{User.class}; - } - - @Before - public void setUp() { - doInJPA(this::entityManagerFactory, entityManager -> { - User user = new User("Arnold"); - entityManager.persist(user); - }); - } - - @After - public void tearDown() { - doInJPA(this::entityManagerFactory, entityManager -> { - CriteriaDelete delete = entityManager.getCriteriaBuilder().createCriteriaDelete(User.class); - delete.from(User.class); - entityManager.createQuery(delete).executeUpdate(); - }); - } - - @Test - public void testPositionalGetterShouldWorkProperly() { - doInJPA(this::entityManagerFactory, entityManager -> { - List result = getTupleResult(entityManager); - Tuple tuple = result.get(0); - assertEquals(1L, tuple.get(0)); - assertEquals("Arnold", tuple.get(1)); - }); - } - - @Test - public void testPositionalGetterWithClassShouldWorkProperly() { - doInJPA(this::entityManagerFactory, entityManager -> { - List result = getTupleResult(entityManager); - Tuple tuple = result.get(0); - assertEquals(Long.valueOf(1L), tuple.get(0, Long.class)); - assertEquals("Arnold", tuple.get(1, String.class)); - }); - } - - - @Test(expected = IllegalArgumentException.class) - public void testPositionalGetterShouldThrowExceptionWhenLessThanZeroGiven() { - doInJPA(this::entityManagerFactory, entityManager -> { - List result = getTupleResult(entityManager); - Tuple tuple = result.get(0); - tuple.get(-1); - }); - } - - - @Test(expected = IllegalArgumentException.class) - public void testPositionalGetterWithClassShouldThrowExceptionWhenLessThanZeroGiven() { - doInJPA(this::entityManagerFactory, entityManager -> { - List result = getTupleResult(entityManager); - Tuple tuple = result.get(0); - tuple.get(-1); - }); - } - - - @Test(expected = IllegalArgumentException.class) - public void testPositionalGetterShouldThrowExceptionWhenTupleSizePositionGiven() { - doInJPA(this::entityManagerFactory, entityManager -> { - List result = getTupleResult(entityManager); - Tuple tuple = result.get(0); - tuple.get(2); - }); - } - - - @Test(expected = IllegalArgumentException.class) - public void testPositionalGetterWithClassShouldThrowExceptionWhenTupleSizePositionGiven() { - doInJPA(this::entityManagerFactory, entityManager -> { - List result = getTupleResult(entityManager); - Tuple tuple = result.get(0); - tuple.get(2); - }); - } - - - @Test(expected = IllegalArgumentException.class) - public void testPositionalGetterShouldThrowExceptionWhenExceedingPositionGiven() { - doInJPA(this::entityManagerFactory, entityManager -> { - List result = getTupleResult(entityManager); - Tuple tuple = result.get(0); - tuple.get(3); - }); - } - - - @Test(expected = IllegalArgumentException.class) - public void testPositionalGetterWithClassShouldThrowExceptionWhenExceedingPositionGiven() { - doInJPA(this::entityManagerFactory, entityManager -> { - List result = getTupleResult(entityManager); - Tuple tuple = result.get(0); - tuple.get(3); - }); - } - - - @Test - public void testAliasGetterWithoutExplicitAliasShouldWorkProperly() { - doInJPA(this::entityManagerFactory, entityManager -> { - List result = getTupleResult(entityManager); - Tuple tuple = result.get(0); - assertEquals(1L, tuple.get("ID")); - assertEquals("Arnold", tuple.get("FIRSTNAME")); - }); - } - - @Test - public void testAliasGetterShouldWorkWithoutExplicitAliasWhenLowerCaseAliasGiven() { - doInJPA(this::entityManagerFactory, entityManager -> { - List result = getTupleResult(entityManager); - Tuple tuple = result.get(0); - tuple.get("id"); - }); - } - - @Test(expected = IllegalArgumentException.class) - public void testAliasGetterShouldThrowExceptionWithoutExplicitAliasWhenWrongAliasGiven() { - doInJPA(this::entityManagerFactory, entityManager -> { - List result = getTupleResult(entityManager); - Tuple tuple = result.get(0); - tuple.get("e"); - }); - } - - @Test - public void testAliasGetterWithClassWithoutExplicitAliasShouldWorkProperly() { - doInJPA(this::entityManagerFactory, entityManager -> { - List result = getTupleResult(entityManager); - Tuple tuple = result.get(0); - assertEquals(Long.valueOf(1L), tuple.get("ID", Long.class)); - assertEquals("Arnold", tuple.get("FIRSTNAME", String.class)); - }); - } - - - @Test - public void testAliasGetterWithExplicitAliasShouldWorkProperly() { - doInJPA(this::entityManagerFactory, entityManager -> { - List result = getTupleAliasedResult(entityManager); - Tuple tuple = result.get(0); - assertEquals(1L, tuple.get("ALIAS1")); - assertEquals("Arnold", tuple.get("ALIAS2")); - }); - } - - @Test - public void testAliasGetterWithClassWithExplicitAliasShouldWorkProperly() { - doInJPA(this::entityManagerFactory, entityManager -> { - List result = getTupleAliasedResult(entityManager); - Tuple tuple = result.get(0); - assertEquals(Long.valueOf(1L), tuple.get("ALIAS1", Long.class)); - assertEquals("Arnold", tuple.get("ALIAS2", String.class)); - }); - } - - @Test - public void testToArrayShouldWorkProperly() { - doInJPA(this::entityManagerFactory, entityManager -> { - List tuples = getTupleResult(entityManager); - Object[] result = tuples.get(0).toArray(); - assertArrayEquals(new Object[]{1L, "Arnold"}, result); - }); - } - - @Test - public void testGetElementsShouldWorkProperly() { - doInJPA(this::entityManagerFactory, entityManager -> { - List tuples = getTupleResult(entityManager); - List> result = tuples.get(0).getElements(); - assertEquals(2, result.size()); - assertEquals(Long.class, result.get(0).getJavaType()); - assertEquals("ID", result.get(0).getAlias()); - assertEquals(String.class, result.get(1).getJavaType()); - assertEquals("FIRSTNAME", result.get(1).getAlias()); - }); - } - - @Test - public void testPositionalGetterWithNamedNativeQueryShouldWorkProperly() { - doInJPA(this::entityManagerFactory, entityManager -> { - List result = getTupleNamedResult(entityManager, "standard"); - Tuple tuple = result.get(0); - assertEquals(1L, tuple.get(0)); - assertEquals("Arnold", tuple.get(1)); - }); - } - - @Test - public void testPositionalGetterWithNamedNativeQueryWithClassShouldWorkProperly() { - doInJPA(this::entityManagerFactory, entityManager -> { - List result = getTupleNamedResult(entityManager, "standard"); - Tuple tuple = result.get(0); - assertEquals(Long.valueOf(1L), tuple.get(0, Long.class)); - assertEquals("Arnold", tuple.get(1, String.class)); - }); - } - - - @Test(expected = IllegalArgumentException.class) - public void testPositionalGetterWithNamedNativeQueryShouldThrowExceptionWhenLessThanZeroGiven() { - doInJPA(this::entityManagerFactory, entityManager -> { - List result = getTupleNamedResult(entityManager, "standard"); - Tuple tuple = result.get(0); - tuple.get(-1); - }); - } - - - @Test(expected = IllegalArgumentException.class) - public void testPositionalGetterWithNamedNativeQueryWithClassShouldThrowExceptionWhenLessThanZeroGiven() { - doInJPA(this::entityManagerFactory, entityManager -> { - List result = getTupleNamedResult(entityManager, "standard"); - Tuple tuple = result.get(0); - tuple.get(-1); - }); - } - - - @Test(expected = IllegalArgumentException.class) - public void testPositionalGetterWithNamedNativeQueryShouldThrowExceptionWhenTupleSizePositionGiven() { - doInJPA(this::entityManagerFactory, entityManager -> { - List result = getTupleNamedResult(entityManager, "standard"); - Tuple tuple = result.get(0); - tuple.get(2); - }); - } - - - @Test(expected = IllegalArgumentException.class) - public void testPositionalGetterWithNamedNativeQueryWithClassShouldThrowExceptionWhenTupleSizePositionGiven() { - doInJPA(this::entityManagerFactory, entityManager -> { - List result = getTupleNamedResult(entityManager, "standard"); - Tuple tuple = result.get(0); - tuple.get(2); - }); - } - - - @Test(expected = IllegalArgumentException.class) - public void testPositionalGetterWithNamedNativeQueryShouldThrowExceptionWhenExceedingPositionGiven() { - doInJPA(this::entityManagerFactory, entityManager -> { - List result = getTupleNamedResult(entityManager, "standard"); - Tuple tuple = result.get(0); - tuple.get(3); - }); - } - - - @Test(expected = IllegalArgumentException.class) - public void testPositionalGetterWithNamedNativeQueryWithClassShouldThrowExceptionWhenExceedingPositionGiven() { - doInJPA(this::entityManagerFactory, entityManager -> { - List result = getTupleNamedResult(entityManager, "standard"); - Tuple tuple = result.get(0); - tuple.get(3); - }); - } - - - @Test - public void testAliasGetterWithNamedNativeQueryWithoutExplicitAliasShouldWorkProperly() { - doInJPA(this::entityManagerFactory, entityManager -> { - List result = getTupleNamedResult(entityManager, "standard"); - Tuple tuple = result.get(0); - assertEquals(1L, tuple.get("ID")); - assertEquals("Arnold", tuple.get("FIRSTNAME")); - }); - } - - @Test - public void testAliasGetterWithNamedNativeQueryShouldWorkWithoutExplicitAliasWhenLowerCaseAliasGiven() { - doInJPA(this::entityManagerFactory, entityManager -> { - List result = getTupleNamedResult(entityManager, "standard"); - Tuple tuple = result.get(0); - tuple.get("id"); - }); - } - - @Test(expected = IllegalArgumentException.class) - public void testAliasGetterWithNamedNativeQueryShouldThrowExceptionWithoutExplicitAliasWhenWrongAliasGiven() { - doInJPA(this::entityManagerFactory, entityManager -> { - List result = getTupleNamedResult(entityManager, "standard"); - Tuple tuple = result.get(0); - tuple.get("e"); - }); - } - - @Test - public void testAliasGetterWithNamedNativeQueryWithClassWithoutExplicitAliasShouldWorkProperly() { - doInJPA(this::entityManagerFactory, entityManager -> { - List result = getTupleNamedResult(entityManager, "standard"); - Tuple tuple = result.get(0); - assertEquals(Long.valueOf(1L), tuple.get("ID", Long.class)); - assertEquals("Arnold", tuple.get("FIRSTNAME", String.class)); - }); - } - - - @Test - public void testAliasGetterWithNamedNativeQueryWithExplicitAliasShouldWorkProperly() { - doInJPA(this::entityManagerFactory, entityManager -> { - List result = getTupleNamedResult(entityManager, "standard_with_alias"); - Tuple tuple = result.get(0); - assertEquals(1L, tuple.get("ALIAS1")); - assertEquals("Arnold", tuple.get("ALIAS2")); - }); - } - - @Test - public void testAliasGetterWithNamedNativeQueryWithClassWithExplicitAliasShouldWorkProperly() { - doInJPA(this::entityManagerFactory, entityManager -> { - List result = getTupleNamedResult(entityManager, "standard_with_alias"); - Tuple tuple = result.get(0); - assertEquals(Long.valueOf(1L), tuple.get("ALIAS1", Long.class)); - assertEquals("Arnold", tuple.get("ALIAS2", String.class)); - }); - } - - @Test - public void testToArrayShouldWithNamedNativeQueryWorkProperly() { - doInJPA(this::entityManagerFactory, entityManager -> { - List tuples = getTupleNamedResult(entityManager, "standard"); - Object[] result = tuples.get(0).toArray(); - assertArrayEquals(new Object[]{1L, "Arnold"}, result); - }); - } - - @Test - public void testGetElementsWithNamedNativeQueryShouldWorkProperly() { - doInJPA(this::entityManagerFactory, entityManager -> { - List tuples = getTupleNamedResult(entityManager, "standard"); - List> result = tuples.get(0).getElements(); - assertEquals(2, result.size()); - assertEquals(Long.class, result.get(0).getJavaType()); - assertEquals("ID", result.get(0).getAlias()); - assertEquals(String.class, result.get(1).getJavaType()); - assertEquals("FIRSTNAME", result.get(1).getAlias()); - }); - } - - @Test - public void testStreamedPositionalGetterShouldWorkProperly() { - doInJPA(this::entityManagerFactory, entityManager -> { - List result = getStreamedTupleResult(entityManager); - Tuple tuple = result.get(0); - assertEquals(1L, tuple.get(0)); - assertEquals("Arnold", tuple.get(1)); - }); - } - - @Test - public void testStreamedPositionalGetterWithClassShouldWorkProperly() { - doInJPA(this::entityManagerFactory, entityManager -> { - List result = getStreamedTupleResult(entityManager); - Tuple tuple = result.get(0); - assertEquals(Long.valueOf(1L), tuple.get(0, Long.class)); - assertEquals("Arnold", tuple.get(1, String.class)); - }); - } - - - @Test(expected = IllegalArgumentException.class) - public void testStreamedPositionalGetterShouldThrowExceptionWhenLessThanZeroGiven() { - doInJPA(this::entityManagerFactory, entityManager -> { - List result = getStreamedTupleResult(entityManager); - Tuple tuple = result.get(0); - tuple.get(-1); - }); - } - - - @Test(expected = IllegalArgumentException.class) - public void testStreamedPositionalGetterWithClassShouldThrowExceptionWhenLessThanZeroGiven() { - doInJPA(this::entityManagerFactory, entityManager -> { - List result = getStreamedTupleResult(entityManager); - Tuple tuple = result.get(0); - tuple.get(-1); - }); - } - - - @Test(expected = IllegalArgumentException.class) - public void testStreamedPositionalGetterShouldThrowExceptionWhenTupleSizePositionGiven() { - doInJPA(this::entityManagerFactory, entityManager -> { - List result = getStreamedTupleResult(entityManager); - Tuple tuple = result.get(0); - tuple.get(2); - }); - } - - - @Test(expected = IllegalArgumentException.class) - public void testStreamedPositionalGetterWithClassShouldThrowExceptionWhenTupleSizePositionGiven() { - doInJPA(this::entityManagerFactory, entityManager -> { - List result = getStreamedTupleResult(entityManager); - Tuple tuple = result.get(0); - tuple.get(2); - }); - } - - - @Test(expected = IllegalArgumentException.class) - public void testStreamedPositionalGetterShouldThrowExceptionWhenExceedingPositionGiven() { - doInJPA(this::entityManagerFactory, entityManager -> { - List result = getStreamedTupleResult(entityManager); - Tuple tuple = result.get(0); - tuple.get(3); - }); - } - - - @Test(expected = IllegalArgumentException.class) - public void testStreamedPositionalGetterWithClassShouldThrowExceptionWhenExceedingPositionGiven() { - doInJPA(this::entityManagerFactory, entityManager -> { - List result = getStreamedTupleResult(entityManager); - Tuple tuple = result.get(0); - tuple.get(3); - }); - } - - - @Test - public void testStreamedAliasGetterWithoutExplicitAliasShouldWorkProperly() { - doInJPA(this::entityManagerFactory, entityManager -> { - List result = getStreamedTupleResult(entityManager); - Tuple tuple = result.get(0); - assertEquals(1L, tuple.get("ID")); - assertEquals("Arnold", tuple.get("FIRSTNAME")); - }); - } - - @Test - public void testStreamedAliasGetterShouldWorkWithoutExplicitAliasWhenLowerCaseAliasGiven() { - doInJPA(this::entityManagerFactory, entityManager -> { - List result = getStreamedTupleResult(entityManager); - Tuple tuple = result.get(0); - tuple.get("id"); - }); - } - - @Test(expected = IllegalArgumentException.class) - public void testStreamedAliasGetterShouldThrowExceptionWithoutExplicitAliasWhenWrongAliasGiven() { - doInJPA(this::entityManagerFactory, entityManager -> { - List result = getStreamedTupleResult(entityManager); - Tuple tuple = result.get(0); - tuple.get("e"); - }); - } - - @Test - public void testStreamedAliasGetterWithClassWithoutExplicitAliasShouldWorkProperly() { - doInJPA(this::entityManagerFactory, entityManager -> { - List result = getStreamedTupleResult(entityManager); - Tuple tuple = result.get(0); - assertEquals(Long.valueOf(1L), tuple.get("ID", Long.class)); - assertEquals("Arnold", tuple.get("FIRSTNAME", String.class)); - }); - } - - - @Test - public void testStreamedAliasGetterWithExplicitAliasShouldWorkProperly() { - doInJPA(this::entityManagerFactory, entityManager -> { - List result = getTupleAliasedResult(entityManager); - Tuple tuple = result.get(0); - assertEquals(1L, tuple.get("ALIAS1")); - assertEquals("Arnold", tuple.get("ALIAS2")); - }); - } - - @Test - public void testStreamedAliasGetterWithClassWithExplicitAliasShouldWorkProperly() { - doInJPA(this::entityManagerFactory, entityManager -> { - List result = getTupleAliasedResult(entityManager); - Tuple tuple = result.get(0); - assertEquals(Long.valueOf(1L), tuple.get("ALIAS1", Long.class)); - assertEquals("Arnold", tuple.get("ALIAS2", String.class)); - }); - } - - @Test - public void testStreamedToArrayShouldWorkProperly() { - doInJPA(this::entityManagerFactory, entityManager -> { - List tuples = getStreamedTupleResult(entityManager); - Object[] result = tuples.get(0).toArray(); - assertArrayEquals(new Object[]{1L, "Arnold"}, result); - }); - } - - @Test - public void testStreamedGetElementsShouldWorkProperly() { - doInJPA(this::entityManagerFactory, entityManager -> { - List tuples = getStreamedTupleResult(entityManager); - List> result = tuples.get(0).getElements(); - assertEquals(2, result.size()); - assertEquals(Long.class, result.get(0).getJavaType()); - assertEquals("ID", result.get(0).getAlias()); - assertEquals(String.class, result.get(1).getJavaType()); - assertEquals("FIRSTNAME", result.get(1).getAlias()); - }); - } - - @Test - public void testStreamedPositionalGetterWithNamedNativeQueryShouldWorkProperly() { - doInJPA(this::entityManagerFactory, entityManager -> { - List result = getStreamedNamedTupleResult(entityManager, "standard"); - Tuple tuple = result.get(0); - assertEquals(1L, tuple.get(0)); - assertEquals("Arnold", tuple.get(1)); - }); - } - - @Test - public void testStreamedPositionalGetterWithNamedNativeQueryWithClassShouldWorkProperly() { - doInJPA(this::entityManagerFactory, entityManager -> { - List result = getStreamedNamedTupleResult(entityManager, "standard"); - Tuple tuple = result.get(0); - assertEquals(Long.valueOf(1L), tuple.get(0, Long.class)); - assertEquals("Arnold", tuple.get(1, String.class)); - }); - } - - - @Test(expected = IllegalArgumentException.class) - public void testStreamedPositionalGetterWithNamedNativeQueryShouldThrowExceptionWhenLessThanZeroGiven() { - doInJPA(this::entityManagerFactory, entityManager -> { - List result = getStreamedNamedTupleResult(entityManager, "standard"); - Tuple tuple = result.get(0); - tuple.get(-1); - }); - } - - - @Test(expected = IllegalArgumentException.class) - public void testStreamedPositionalGetterWithNamedNativeQueryWithClassShouldThrowExceptionWhenLessThanZeroGiven() { - doInJPA(this::entityManagerFactory, entityManager -> { - List result = getStreamedNamedTupleResult(entityManager, "standard"); - Tuple tuple = result.get(0); - tuple.get(-1); - }); - } - - - @Test(expected = IllegalArgumentException.class) - public void testStreamedPositionalGetterWithNamedNativeQueryShouldThrowExceptionWhenTupleSizePositionGiven() { - doInJPA(this::entityManagerFactory, entityManager -> { - List result = getStreamedNamedTupleResult(entityManager, "standard"); - Tuple tuple = result.get(0); - tuple.get(2); - }); - } - - - @Test(expected = IllegalArgumentException.class) - public void testStreamedPositionalGetterWithNamedNativeQueryWithClassShouldThrowExceptionWhenTupleSizePositionGiven() { - doInJPA(this::entityManagerFactory, entityManager -> { - List result = getStreamedNamedTupleResult(entityManager, "standard"); - Tuple tuple = result.get(0); - tuple.get(2); - }); - } - - - @Test(expected = IllegalArgumentException.class) - public void testStreamedPositionalGetterWithNamedNativeQueryShouldThrowExceptionWhenExceedingPositionGiven() { - doInJPA(this::entityManagerFactory, entityManager -> { - List result = getStreamedNamedTupleResult(entityManager, "standard"); - Tuple tuple = result.get(0); - tuple.get(3); - }); - } - - - @Test(expected = IllegalArgumentException.class) - public void testStreamedPositionalGetterWithNamedNativeQueryWithClassShouldThrowExceptionWhenExceedingPositionGiven() { - doInJPA(this::entityManagerFactory, entityManager -> { - List result = getStreamedNamedTupleResult(entityManager, "standard"); - Tuple tuple = result.get(0); - tuple.get(3); - }); - } - - - @Test - public void testStreamedAliasGetterWithNamedNativeQueryWithoutExplicitAliasShouldWorkProperly() { - doInJPA(this::entityManagerFactory, entityManager -> { - List result = getStreamedNamedTupleResult(entityManager, "standard"); - Tuple tuple = result.get(0); - assertEquals(1L, tuple.get("ID")); - assertEquals("Arnold", tuple.get("FIRSTNAME")); - }); - } - - @Test - public void testStreamedAliasGetterWithNamedNativeQueryShouldWorkWithoutExplicitAliasWhenLowerCaseAliasGiven() { - doInJPA(this::entityManagerFactory, entityManager -> { - List result = getStreamedNamedTupleResult(entityManager, "standard"); - Tuple tuple = result.get(0); - tuple.get("id"); - }); - } - - @Test(expected = IllegalArgumentException.class) - public void testStreamedAliasGetterWithNamedNativeQueryShouldThrowExceptionWithoutExplicitAliasWhenWrongAliasGiven() { - doInJPA(this::entityManagerFactory, entityManager -> { - List result = getStreamedNamedTupleResult(entityManager, "standard"); - Tuple tuple = result.get(0); - tuple.get("e"); - }); - } - - @Test - public void testStreamedAliasGetterWithNamedNativeQueryWithClassWithoutExplicitAliasShouldWorkProperly() { - doInJPA(this::entityManagerFactory, entityManager -> { - List result = getStreamedNamedTupleResult(entityManager, "standard"); - Tuple tuple = result.get(0); - assertEquals(Long.valueOf(1L), tuple.get("ID", Long.class)); - assertEquals("Arnold", tuple.get("FIRSTNAME", String.class)); - }); - } - - - @Test - public void testStreamedAliasGetterWithNamedNativeQueryWithExplicitAliasShouldWorkProperly() { - doInJPA(this::entityManagerFactory, entityManager -> { - List result = getStreamedNamedTupleResult(entityManager, "standard_with_alias"); - Tuple tuple = result.get(0); - assertEquals(1L, tuple.get("ALIAS1")); - assertEquals("Arnold", tuple.get("ALIAS2")); - }); - } - - @Test - public void testStreamedAliasGetterWithNamedNativeQueryWithClassWithExplicitAliasShouldWorkProperly() { - doInJPA(this::entityManagerFactory, entityManager -> { - List result = getStreamedNamedTupleResult(entityManager, "standard_with_alias"); - Tuple tuple = result.get(0); - assertEquals(Long.valueOf(1L), tuple.get("ALIAS1", Long.class)); - assertEquals("Arnold", tuple.get("ALIAS2", String.class)); - }); - } - - @Test - public void testStreamedToArrayShouldWithNamedNativeQueryWorkProperly() { - doInJPA(this::entityManagerFactory, entityManager -> { - List tuples = getStreamedNamedTupleResult(entityManager, "standard"); - Object[] result = tuples.get(0).toArray(); - assertArrayEquals(new Object[]{1L, "Arnold"}, result); - }); - } - - @Test - public void testStreamedGetElementsWithNamedNativeQueryShouldWorkProperly() { - doInJPA(this::entityManagerFactory, entityManager -> { - List tuples = getStreamedNamedTupleResult(entityManager, "standard"); - List> result = tuples.get(0).getElements(); - assertEquals(2, result.size()); - assertEquals(Long.class, result.get(0).getJavaType()); - assertEquals("ID", result.get(0).getAlias()); - assertEquals(String.class, result.get(1).getJavaType()); - assertEquals("FIRSTNAME", result.get(1).getAlias()); - }); - } - - @Test - @JiraKey(value = "HHH-11897") - public void testGetElementsShouldNotThrowExceptionWhenResultContainsNullValue() { - doInJPA(this::entityManagerFactory, entityManager -> { - User user = entityManager.find(User.class, 1L); - user.firstName = null; - }); - doInJPA(this::entityManagerFactory, entityManager -> { - List tuples = getTupleResult(entityManager); - final Tuple tuple = tuples.get(0); - List> result = tuple.getElements(); - assertEquals(2, result.size()); - final TupleElement firstTupleElement = result.get(0); - assertEquals(Long.class, firstTupleElement.getJavaType()); - assertEquals("ID", firstTupleElement.getAlias()); - assertEquals(1L, tuple.get(firstTupleElement.getAlias())); - final TupleElement secondTupleElement = result.get(1); - assertEquals(Object.class, secondTupleElement.getJavaType()); - assertEquals("FIRSTNAME", secondTupleElement.getAlias()); - assertNull(tuple.get(secondTupleElement.getAlias())); - }); - } - - @SuppressWarnings("unchecked") - private List getTupleAliasedResult(EntityManager entityManager) { - Query query = entityManager.createNativeQuery("SELECT id AS alias1, firstname AS alias2 FROM users", Tuple.class); - return (List) query.getResultList(); - } - - @SuppressWarnings("unchecked") - private List getStreamedTupleAliasedResult(EntityManager entityManager) { - NativeQueryImpl query = (NativeQueryImpl) entityManager.createNativeQuery( - "SELECT id AS alias1, firstname AS alias2 FROM users", - Tuple.class - ); - return (List) query.stream().collect(Collectors.toList()); - } - - @SuppressWarnings("unchecked") - private List getTupleResult(EntityManager entityManager) { - Query query = entityManager.createNativeQuery("SELECT id, firstname FROM users", Tuple.class); - return (List) query.getResultList(); - } - - @SuppressWarnings("unchecked") - private List getTupleNamedResult(EntityManager entityManager, String name) { - return entityManager.createNamedQuery(name, Tuple.class).getResultList(); - } - - @SuppressWarnings("unchecked") - private List getStreamedTupleResult(EntityManager entityManager) { - NativeQueryImplementor query = (NativeQueryImplementor) entityManager.createNativeQuery( "SELECT id, firstname FROM users", Tuple.class); - return (List) query.stream().collect(Collectors.toList()); - } - - @SuppressWarnings("unchecked") - private List getStreamedNamedTupleResult(EntityManager entityManager, String name) { - return (List)((NativeQueryImplementor) entityManager.createNamedQuery(name, Tuple.class)).stream().collect(Collectors.toList()); - } - - @Entity - @Table(name = "users") - @NamedNativeQueries({ - @NamedNativeQuery( - name = "standard", - query = "SELECT id, firstname FROM users" - ), - @NamedNativeQuery( - name = "standard_with_alias", - query = "SELECT id AS alias1, firstname AS alias2 FROM users" - ) - }) - public static class User { - @Id - private long id; - - private String firstName; - - public User() { - } - - public User(String firstName) { - this.id = 1L; - this.firstName = firstName; - } - } + @Override + protected Class[] getAnnotatedClasses() { + return new Class[]{User.class}; + } + + @Before + public void setUp() { + doInJPA(this::entityManagerFactory, entityManager -> { + User user = new User("Arnold"); + entityManager.persist(user); + }); + } + + @After + public void tearDown() { + doInJPA(this::entityManagerFactory, entityManager -> { + CriteriaDelete delete = entityManager.getCriteriaBuilder().createCriteriaDelete(User.class); + delete.from(User.class); + entityManager.createQuery(delete).executeUpdate(); + }); + } + + @Test + public void testPositionalGetterShouldWorkProperly() { + doInJPA(this::entityManagerFactory, entityManager -> { + List result = getTupleResult(entityManager); + Tuple tuple = result.get(0); + assertEquals(1L, tuple.get(0)); + assertEquals("Arnold", tuple.get(1)); + }); + } + + @Test + public void testPositionalGetterWithClassShouldWorkProperly() { + doInJPA(this::entityManagerFactory, entityManager -> { + List result = getTupleResult(entityManager); + Tuple tuple = result.get(0); + assertEquals(Long.valueOf(1L), tuple.get(0, Long.class)); + assertEquals("Arnold", tuple.get(1, String.class)); + }); + } + + + @Test(expected = IllegalArgumentException.class) + public void testPositionalGetterShouldThrowExceptionWhenLessThanZeroGiven() { + doInJPA(this::entityManagerFactory, entityManager -> { + List result = getTupleResult(entityManager); + Tuple tuple = result.get(0); + tuple.get(-1); + }); + } + + + @Test(expected = IllegalArgumentException.class) + public void testPositionalGetterWithClassShouldThrowExceptionWhenLessThanZeroGiven() { + doInJPA(this::entityManagerFactory, entityManager -> { + List result = getTupleResult(entityManager); + Tuple tuple = result.get(0); + tuple.get(-1); + }); + } + + + @Test(expected = IllegalArgumentException.class) + public void testPositionalGetterShouldThrowExceptionWhenTupleSizePositionGiven() { + doInJPA(this::entityManagerFactory, entityManager -> { + List result = getTupleResult(entityManager); + Tuple tuple = result.get(0); + tuple.get(2); + }); + } + + + @Test(expected = IllegalArgumentException.class) + public void testPositionalGetterWithClassShouldThrowExceptionWhenTupleSizePositionGiven() { + doInJPA(this::entityManagerFactory, entityManager -> { + List result = getTupleResult(entityManager); + Tuple tuple = result.get(0); + tuple.get(2); + }); + } + + + @Test(expected = IllegalArgumentException.class) + public void testPositionalGetterShouldThrowExceptionWhenExceedingPositionGiven() { + doInJPA(this::entityManagerFactory, entityManager -> { + List result = getTupleResult(entityManager); + Tuple tuple = result.get(0); + tuple.get(3); + }); + } + + + @Test(expected = IllegalArgumentException.class) + public void testPositionalGetterWithClassShouldThrowExceptionWhenExceedingPositionGiven() { + doInJPA(this::entityManagerFactory, entityManager -> { + List result = getTupleResult(entityManager); + Tuple tuple = result.get(0); + tuple.get(3); + }); + } + + + @Test + public void testAliasGetterWithoutExplicitAliasShouldWorkProperly() { + doInJPA(this::entityManagerFactory, entityManager -> { + List result = getTupleResult(entityManager); + Tuple tuple = result.get(0); + assertEquals(1L, tuple.get("ID")); + assertEquals("Arnold", tuple.get("FIRSTNAME")); + }); + } + + @Test + public void testAliasGetterShouldWorkWithoutExplicitAliasWhenLowerCaseAliasGiven() { + doInJPA(this::entityManagerFactory, entityManager -> { + List result = getTupleResult(entityManager); + Tuple tuple = result.get(0); + tuple.get("id"); + }); + } + + @Test(expected = IllegalArgumentException.class) + public void testAliasGetterShouldThrowExceptionWithoutExplicitAliasWhenWrongAliasGiven() { + doInJPA(this::entityManagerFactory, entityManager -> { + List result = getTupleResult(entityManager); + Tuple tuple = result.get(0); + tuple.get("e"); + }); + } + + @Test + public void testAliasGetterWithClassWithoutExplicitAliasShouldWorkProperly() { + doInJPA(this::entityManagerFactory, entityManager -> { + List result = getTupleResult(entityManager); + Tuple tuple = result.get(0); + assertEquals(Long.valueOf(1L), tuple.get("ID", Long.class)); + assertEquals("Arnold", tuple.get("FIRSTNAME", String.class)); + }); + } + + + @Test + public void testAliasGetterWithExplicitAliasShouldWorkProperly() { + doInJPA(this::entityManagerFactory, entityManager -> { + List result = getTupleAliasedResult(entityManager); + Tuple tuple = result.get(0); + assertEquals(1L, tuple.get("ALIAS1")); + assertEquals("Arnold", tuple.get("ALIAS2")); + }); + } + + @Test + public void testAliasGetterWithClassWithExplicitAliasShouldWorkProperly() { + doInJPA(this::entityManagerFactory, entityManager -> { + List result = getTupleAliasedResult(entityManager); + Tuple tuple = result.get(0); + assertEquals(Long.valueOf(1L), tuple.get("ALIAS1", Long.class)); + assertEquals("Arnold", tuple.get("ALIAS2", String.class)); + }); + } + + @Test + public void testToArrayShouldWorkProperly() { + doInJPA(this::entityManagerFactory, entityManager -> { + List tuples = getTupleResult(entityManager); + Object[] result = tuples.get(0).toArray(); + assertArrayEquals(new Object[]{1L, "Arnold"}, result); + }); + } + + @Test + public void testGetElementsShouldWorkProperly() { + doInJPA(this::entityManagerFactory, entityManager -> { + List tuples = getTupleResult(entityManager); + List> result = tuples.get(0).getElements(); + assertEquals(2, result.size()); + assertEquals(Long.class, result.get(0).getJavaType()); + assertEquals("ID", result.get(0).getAlias()); + assertEquals(String.class, result.get(1).getJavaType()); + assertEquals("FIRSTNAME", result.get(1).getAlias()); + }); + } + + @Test + public void testPositionalGetterWithNamedNativeQueryShouldWorkProperly() { + doInJPA(this::entityManagerFactory, entityManager -> { + List result = getTupleNamedResult(entityManager, "standard"); + Tuple tuple = result.get(0); + assertEquals(1L, tuple.get(0)); + assertEquals("Arnold", tuple.get(1)); + }); + } + + @Test + public void testPositionalGetterWithNamedNativeQueryWithClassShouldWorkProperly() { + doInJPA(this::entityManagerFactory, entityManager -> { + List result = getTupleNamedResult(entityManager, "standard"); + Tuple tuple = result.get(0); + assertEquals(Long.valueOf(1L), tuple.get(0, Long.class)); + assertEquals("Arnold", tuple.get(1, String.class)); + }); + } + + + @Test(expected = IllegalArgumentException.class) + public void testPositionalGetterWithNamedNativeQueryShouldThrowExceptionWhenLessThanZeroGiven() { + doInJPA(this::entityManagerFactory, entityManager -> { + List result = getTupleNamedResult(entityManager, "standard"); + Tuple tuple = result.get(0); + tuple.get(-1); + }); + } + + + @Test(expected = IllegalArgumentException.class) + public void testPositionalGetterWithNamedNativeQueryWithClassShouldThrowExceptionWhenLessThanZeroGiven() { + doInJPA(this::entityManagerFactory, entityManager -> { + List result = getTupleNamedResult(entityManager, "standard"); + Tuple tuple = result.get(0); + tuple.get(-1); + }); + } + + + @Test(expected = IllegalArgumentException.class) + public void testPositionalGetterWithNamedNativeQueryShouldThrowExceptionWhenTupleSizePositionGiven() { + doInJPA(this::entityManagerFactory, entityManager -> { + List result = getTupleNamedResult(entityManager, "standard"); + Tuple tuple = result.get(0); + tuple.get(2); + }); + } + + + @Test(expected = IllegalArgumentException.class) + public void testPositionalGetterWithNamedNativeQueryWithClassShouldThrowExceptionWhenTupleSizePositionGiven() { + doInJPA(this::entityManagerFactory, entityManager -> { + List result = getTupleNamedResult(entityManager, "standard"); + Tuple tuple = result.get(0); + tuple.get(2); + }); + } + + + @Test(expected = IllegalArgumentException.class) + public void testPositionalGetterWithNamedNativeQueryShouldThrowExceptionWhenExceedingPositionGiven() { + doInJPA(this::entityManagerFactory, entityManager -> { + List result = getTupleNamedResult(entityManager, "standard"); + Tuple tuple = result.get(0); + tuple.get(3); + }); + } + + + @Test(expected = IllegalArgumentException.class) + public void testPositionalGetterWithNamedNativeQueryWithClassShouldThrowExceptionWhenExceedingPositionGiven() { + doInJPA(this::entityManagerFactory, entityManager -> { + List result = getTupleNamedResult(entityManager, "standard"); + Tuple tuple = result.get(0); + tuple.get(3); + }); + } + + + @Test + public void testAliasGetterWithNamedNativeQueryWithoutExplicitAliasShouldWorkProperly() { + doInJPA(this::entityManagerFactory, entityManager -> { + List result = getTupleNamedResult(entityManager, "standard"); + Tuple tuple = result.get(0); + assertEquals(1L, tuple.get("ID")); + assertEquals("Arnold", tuple.get("FIRSTNAME")); + }); + } + + @Test + public void testAliasGetterWithNamedNativeQueryShouldWorkWithoutExplicitAliasWhenLowerCaseAliasGiven() { + doInJPA(this::entityManagerFactory, entityManager -> { + List result = getTupleNamedResult(entityManager, "standard"); + Tuple tuple = result.get(0); + tuple.get("id"); + }); + } + + @Test(expected = IllegalArgumentException.class) + public void testAliasGetterWithNamedNativeQueryShouldThrowExceptionWithoutExplicitAliasWhenWrongAliasGiven() { + doInJPA(this::entityManagerFactory, entityManager -> { + List result = getTupleNamedResult(entityManager, "standard"); + Tuple tuple = result.get(0); + tuple.get("e"); + }); + } + + @Test + public void testAliasGetterWithNamedNativeQueryWithClassWithoutExplicitAliasShouldWorkProperly() { + doInJPA(this::entityManagerFactory, entityManager -> { + List result = getTupleNamedResult(entityManager, "standard"); + Tuple tuple = result.get(0); + assertEquals(Long.valueOf(1L), tuple.get("ID", Long.class)); + assertEquals("Arnold", tuple.get("FIRSTNAME", String.class)); + }); + } + + + @Test + public void testAliasGetterWithNamedNativeQueryWithExplicitAliasShouldWorkProperly() { + doInJPA(this::entityManagerFactory, entityManager -> { + List result = getTupleNamedResult(entityManager, "standard_with_alias"); + Tuple tuple = result.get(0); + assertEquals(1L, tuple.get("ALIAS1")); + assertEquals("Arnold", tuple.get("ALIAS2")); + }); + } + + @Test + public void testAliasGetterWithNamedNativeQueryWithClassWithExplicitAliasShouldWorkProperly() { + doInJPA(this::entityManagerFactory, entityManager -> { + List result = getTupleNamedResult(entityManager, "standard_with_alias"); + Tuple tuple = result.get(0); + assertEquals(Long.valueOf(1L), tuple.get("ALIAS1", Long.class)); + assertEquals("Arnold", tuple.get("ALIAS2", String.class)); + }); + } + + @Test + public void testToArrayShouldWithNamedNativeQueryWorkProperly() { + doInJPA(this::entityManagerFactory, entityManager -> { + List tuples = getTupleNamedResult(entityManager, "standard"); + Object[] result = tuples.get(0).toArray(); + assertArrayEquals(new Object[]{1L, "Arnold"}, result); + }); + } + + @Test + public void testGetElementsWithNamedNativeQueryShouldWorkProperly() { + doInJPA(this::entityManagerFactory, entityManager -> { + List tuples = getTupleNamedResult(entityManager, "standard"); + List> result = tuples.get(0).getElements(); + assertEquals(2, result.size()); + assertEquals(Long.class, result.get(0).getJavaType()); + assertEquals("ID", result.get(0).getAlias()); + assertEquals(String.class, result.get(1).getJavaType()); + assertEquals("FIRSTNAME", result.get(1).getAlias()); + }); + } + + @Test + public void testStreamedPositionalGetterShouldWorkProperly() { + doInJPA(this::entityManagerFactory, entityManager -> { + List result = getStreamedTupleResult(entityManager); + Tuple tuple = result.get(0); + assertEquals(1L, tuple.get(0)); + assertEquals("Arnold", tuple.get(1)); + }); + } + + @Test + public void testStreamedPositionalGetterWithClassShouldWorkProperly() { + doInJPA(this::entityManagerFactory, entityManager -> { + List result = getStreamedTupleResult(entityManager); + Tuple tuple = result.get(0); + assertEquals(Long.valueOf(1L), tuple.get(0, Long.class)); + assertEquals("Arnold", tuple.get(1, String.class)); + }); + } + + + @Test(expected = IllegalArgumentException.class) + public void testStreamedPositionalGetterShouldThrowExceptionWhenLessThanZeroGiven() { + doInJPA(this::entityManagerFactory, entityManager -> { + List result = getStreamedTupleResult(entityManager); + Tuple tuple = result.get(0); + tuple.get(-1); + }); + } + + + @Test(expected = IllegalArgumentException.class) + public void testStreamedPositionalGetterWithClassShouldThrowExceptionWhenLessThanZeroGiven() { + doInJPA(this::entityManagerFactory, entityManager -> { + List result = getStreamedTupleResult(entityManager); + Tuple tuple = result.get(0); + tuple.get(-1); + }); + } + + + @Test(expected = IllegalArgumentException.class) + public void testStreamedPositionalGetterShouldThrowExceptionWhenTupleSizePositionGiven() { + doInJPA(this::entityManagerFactory, entityManager -> { + List result = getStreamedTupleResult(entityManager); + Tuple tuple = result.get(0); + tuple.get(2); + }); + } + + + @Test(expected = IllegalArgumentException.class) + public void testStreamedPositionalGetterWithClassShouldThrowExceptionWhenTupleSizePositionGiven() { + doInJPA(this::entityManagerFactory, entityManager -> { + List result = getStreamedTupleResult(entityManager); + Tuple tuple = result.get(0); + tuple.get(2); + }); + } + + + @Test(expected = IllegalArgumentException.class) + public void testStreamedPositionalGetterShouldThrowExceptionWhenExceedingPositionGiven() { + doInJPA(this::entityManagerFactory, entityManager -> { + List result = getStreamedTupleResult(entityManager); + Tuple tuple = result.get(0); + tuple.get(3); + }); + } + + + @Test(expected = IllegalArgumentException.class) + public void testStreamedPositionalGetterWithClassShouldThrowExceptionWhenExceedingPositionGiven() { + doInJPA(this::entityManagerFactory, entityManager -> { + List result = getStreamedTupleResult(entityManager); + Tuple tuple = result.get(0); + tuple.get(3); + }); + } + + + @Test + public void testStreamedAliasGetterWithoutExplicitAliasShouldWorkProperly() { + doInJPA(this::entityManagerFactory, entityManager -> { + List result = getStreamedTupleResult(entityManager); + Tuple tuple = result.get(0); + assertEquals(1L, tuple.get("ID")); + assertEquals("Arnold", tuple.get("FIRSTNAME")); + }); + } + + @Test + public void testStreamedAliasGetterShouldWorkWithoutExplicitAliasWhenLowerCaseAliasGiven() { + doInJPA(this::entityManagerFactory, entityManager -> { + List result = getStreamedTupleResult(entityManager); + Tuple tuple = result.get(0); + tuple.get("id"); + }); + } + + @Test(expected = IllegalArgumentException.class) + public void testStreamedAliasGetterShouldThrowExceptionWithoutExplicitAliasWhenWrongAliasGiven() { + doInJPA(this::entityManagerFactory, entityManager -> { + List result = getStreamedTupleResult(entityManager); + Tuple tuple = result.get(0); + tuple.get("e"); + }); + } + + @Test + public void testStreamedAliasGetterWithClassWithoutExplicitAliasShouldWorkProperly() { + doInJPA(this::entityManagerFactory, entityManager -> { + List result = getStreamedTupleResult(entityManager); + Tuple tuple = result.get(0); + assertEquals(Long.valueOf(1L), tuple.get("ID", Long.class)); + assertEquals("Arnold", tuple.get("FIRSTNAME", String.class)); + }); + } + + + @Test + public void testStreamedAliasGetterWithExplicitAliasShouldWorkProperly() { + doInJPA(this::entityManagerFactory, entityManager -> { + List result = getTupleAliasedResult(entityManager); + Tuple tuple = result.get(0); + assertEquals(1L, tuple.get("ALIAS1")); + assertEquals("Arnold", tuple.get("ALIAS2")); + }); + } + + @Test + public void testStreamedAliasGetterWithClassWithExplicitAliasShouldWorkProperly() { + doInJPA(this::entityManagerFactory, entityManager -> { + List result = getTupleAliasedResult(entityManager); + Tuple tuple = result.get(0); + assertEquals(Long.valueOf(1L), tuple.get("ALIAS1", Long.class)); + assertEquals("Arnold", tuple.get("ALIAS2", String.class)); + }); + } + + @Test + public void testStreamedToArrayShouldWorkProperly() { + doInJPA(this::entityManagerFactory, entityManager -> { + List tuples = getStreamedTupleResult(entityManager); + Object[] result = tuples.get(0).toArray(); + assertArrayEquals(new Object[]{1L, "Arnold"}, result); + }); + } + + @Test + public void testStreamedGetElementsShouldWorkProperly() { + doInJPA(this::entityManagerFactory, entityManager -> { + List tuples = getStreamedTupleResult(entityManager); + List> result = tuples.get(0).getElements(); + assertEquals(2, result.size()); + assertEquals(Long.class, result.get(0).getJavaType()); + assertEquals("ID", result.get(0).getAlias()); + assertEquals(String.class, result.get(1).getJavaType()); + assertEquals("FIRSTNAME", result.get(1).getAlias()); + }); + } + + @Test + public void testStreamedPositionalGetterWithNamedNativeQueryShouldWorkProperly() { + doInJPA(this::entityManagerFactory, entityManager -> { + List result = getStreamedNamedTupleResult(entityManager, "standard"); + Tuple tuple = result.get(0); + assertEquals(1L, tuple.get(0)); + assertEquals("Arnold", tuple.get(1)); + }); + } + + @Test + public void testStreamedPositionalGetterWithNamedNativeQueryWithClassShouldWorkProperly() { + doInJPA(this::entityManagerFactory, entityManager -> { + List result = getStreamedNamedTupleResult(entityManager, "standard"); + Tuple tuple = result.get(0); + assertEquals(Long.valueOf(1L), tuple.get(0, Long.class)); + assertEquals("Arnold", tuple.get(1, String.class)); + }); + } + + + @Test(expected = IllegalArgumentException.class) + public void testStreamedPositionalGetterWithNamedNativeQueryShouldThrowExceptionWhenLessThanZeroGiven() { + doInJPA(this::entityManagerFactory, entityManager -> { + List result = getStreamedNamedTupleResult(entityManager, "standard"); + Tuple tuple = result.get(0); + tuple.get(-1); + }); + } + + + @Test(expected = IllegalArgumentException.class) + public void testStreamedPositionalGetterWithNamedNativeQueryWithClassShouldThrowExceptionWhenLessThanZeroGiven() { + doInJPA(this::entityManagerFactory, entityManager -> { + List result = getStreamedNamedTupleResult(entityManager, "standard"); + Tuple tuple = result.get(0); + tuple.get(-1); + }); + } + + + @Test(expected = IllegalArgumentException.class) + public void testStreamedPositionalGetterWithNamedNativeQueryShouldThrowExceptionWhenTupleSizePositionGiven() { + doInJPA(this::entityManagerFactory, entityManager -> { + List result = getStreamedNamedTupleResult(entityManager, "standard"); + Tuple tuple = result.get(0); + tuple.get(2); + }); + } + + + @Test(expected = IllegalArgumentException.class) + public void testStreamedPositionalGetterWithNamedNativeQueryWithClassShouldThrowExceptionWhenTupleSizePositionGiven() { + doInJPA(this::entityManagerFactory, entityManager -> { + List result = getStreamedNamedTupleResult(entityManager, "standard"); + Tuple tuple = result.get(0); + tuple.get(2); + }); + } + + + @Test(expected = IllegalArgumentException.class) + public void testStreamedPositionalGetterWithNamedNativeQueryShouldThrowExceptionWhenExceedingPositionGiven() { + doInJPA(this::entityManagerFactory, entityManager -> { + List result = getStreamedNamedTupleResult(entityManager, "standard"); + Tuple tuple = result.get(0); + tuple.get(3); + }); + } + + + @Test(expected = IllegalArgumentException.class) + public void testStreamedPositionalGetterWithNamedNativeQueryWithClassShouldThrowExceptionWhenExceedingPositionGiven() { + doInJPA(this::entityManagerFactory, entityManager -> { + List result = getStreamedNamedTupleResult(entityManager, "standard"); + Tuple tuple = result.get(0); + tuple.get(3); + }); + } + + + @Test + public void testStreamedAliasGetterWithNamedNativeQueryWithoutExplicitAliasShouldWorkProperly() { + doInJPA(this::entityManagerFactory, entityManager -> { + List result = getStreamedNamedTupleResult(entityManager, "standard"); + Tuple tuple = result.get(0); + assertEquals(1L, tuple.get("ID")); + assertEquals("Arnold", tuple.get("FIRSTNAME")); + }); + } + + @Test + public void testStreamedAliasGetterWithNamedNativeQueryShouldWorkWithoutExplicitAliasWhenLowerCaseAliasGiven() { + doInJPA(this::entityManagerFactory, entityManager -> { + List result = getStreamedNamedTupleResult(entityManager, "standard"); + Tuple tuple = result.get(0); + tuple.get("id"); + }); + } + + @Test(expected = IllegalArgumentException.class) + public void testStreamedAliasGetterWithNamedNativeQueryShouldThrowExceptionWithoutExplicitAliasWhenWrongAliasGiven() { + doInJPA(this::entityManagerFactory, entityManager -> { + List result = getStreamedNamedTupleResult(entityManager, "standard"); + Tuple tuple = result.get(0); + tuple.get("e"); + }); + } + + @Test + public void testStreamedAliasGetterWithNamedNativeQueryWithClassWithoutExplicitAliasShouldWorkProperly() { + doInJPA(this::entityManagerFactory, entityManager -> { + List result = getStreamedNamedTupleResult(entityManager, "standard"); + Tuple tuple = result.get(0); + assertEquals(Long.valueOf(1L), tuple.get("ID", Long.class)); + assertEquals("Arnold", tuple.get("FIRSTNAME", String.class)); + }); + } + + + @Test + public void testStreamedAliasGetterWithNamedNativeQueryWithExplicitAliasShouldWorkProperly() { + doInJPA(this::entityManagerFactory, entityManager -> { + List result = getStreamedNamedTupleResult(entityManager, "standard_with_alias"); + Tuple tuple = result.get(0); + assertEquals(1L, tuple.get("ALIAS1")); + assertEquals("Arnold", tuple.get("ALIAS2")); + }); + } + + @Test + public void testStreamedAliasGetterWithNamedNativeQueryWithClassWithExplicitAliasShouldWorkProperly() { + doInJPA(this::entityManagerFactory, entityManager -> { + List result = getStreamedNamedTupleResult(entityManager, "standard_with_alias"); + Tuple tuple = result.get(0); + assertEquals(Long.valueOf(1L), tuple.get("ALIAS1", Long.class)); + assertEquals("Arnold", tuple.get("ALIAS2", String.class)); + }); + } + + @Test + public void testStreamedToArrayShouldWithNamedNativeQueryWorkProperly() { + doInJPA(this::entityManagerFactory, entityManager -> { + List tuples = getStreamedNamedTupleResult(entityManager, "standard"); + Object[] result = tuples.get(0).toArray(); + assertArrayEquals(new Object[]{1L, "Arnold"}, result); + }); + } + + @Test + public void testStreamedGetElementsWithNamedNativeQueryShouldWorkProperly() { + doInJPA(this::entityManagerFactory, entityManager -> { + List tuples = getStreamedNamedTupleResult(entityManager, "standard"); + List> result = tuples.get(0).getElements(); + assertEquals(2, result.size()); + assertEquals(Long.class, result.get(0).getJavaType()); + assertEquals("ID", result.get(0).getAlias()); + assertEquals(String.class, result.get(1).getJavaType()); + assertEquals("FIRSTNAME", result.get(1).getAlias()); + }); + } + + @Test + @JiraKey(value = "HHH-11897") + public void testGetElementsShouldNotThrowExceptionWhenResultContainsNullValue() { + doInJPA(this::entityManagerFactory, entityManager -> { + User user = entityManager.find(User.class, 1L); + user.firstName = null; + }); + doInJPA(this::entityManagerFactory, entityManager -> { + List tuples = getTupleResult(entityManager); + final Tuple tuple = tuples.get(0); + List> result = tuple.getElements(); + assertEquals(2, result.size()); + final TupleElement firstTupleElement = result.get(0); + assertEquals(Long.class, firstTupleElement.getJavaType()); + assertEquals("ID", firstTupleElement.getAlias()); + assertEquals(1L, tuple.get(firstTupleElement.getAlias())); + final TupleElement secondTupleElement = result.get(1); + assertEquals(Object.class, secondTupleElement.getJavaType()); + assertEquals("FIRSTNAME", secondTupleElement.getAlias()); + assertNull(tuple.get(secondTupleElement.getAlias())); + }); + } + + @SuppressWarnings("unchecked") + private List getTupleAliasedResult(EntityManager entityManager) { + Query query = entityManager.createNativeQuery("SELECT id AS alias1, firstname AS alias2 FROM users", Tuple.class); + return (List) query.getResultList(); + } + + @SuppressWarnings("unchecked") + private List getStreamedTupleAliasedResult(EntityManager entityManager) { + NativeQueryImpl query = (NativeQueryImpl) entityManager.createNativeQuery( + "SELECT id AS alias1, firstname AS alias2 FROM users", + Tuple.class + ); + return (List) query.stream().collect(Collectors.toList()); + } + + @SuppressWarnings("unchecked") + private List getTupleResult(EntityManager entityManager) { + Query query = entityManager.createNativeQuery("SELECT id, firstname FROM users", Tuple.class); + return (List) query.getResultList(); + } + + @SuppressWarnings("unchecked") + private List getTupleNamedResult(EntityManager entityManager, String name) { + return entityManager.createNamedQuery(name, Tuple.class).getResultList(); + } + + @SuppressWarnings("unchecked") + private List getStreamedTupleResult(EntityManager entityManager) { + NativeQueryImplementor query = (NativeQueryImplementor) entityManager.createNativeQuery( "SELECT id, firstname FROM users", Tuple.class); + return (List) query.stream().collect(Collectors.toList()); + } + + @SuppressWarnings("unchecked") + private List getStreamedNamedTupleResult(EntityManager entityManager, String name) { + return (List)((NativeQueryImplementor) entityManager.createNamedQuery(name, Tuple.class)).stream().collect(Collectors.toList()); + } + + @Entity + @Table(name = "users") + @NamedNativeQueries({ + @NamedNativeQuery( + name = "standard", + query = "SELECT id, firstname FROM users" + ), + @NamedNativeQuery( + name = "standard_with_alias", + query = "SELECT id AS alias1, firstname AS alias2 FROM users" + ) + }) + public static class User { + @Id + private long id; + + private String firstName; + + public User() { + } + + public User(String firstName) { + this.id = 1L; + this.firstName = firstName; + } + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/query/TypedValueParametersTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/query/TypedValueParametersTest.java index 00525b887a..46c1080d3f 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/query/TypedValueParametersTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/query/TypedValueParametersTest.java @@ -69,22 +69,22 @@ public class TypedValueParametersTest { @Test public void testNative(EntityManagerFactoryScope scope) { test(scope, - q -> { - final CustomType> customType = new CustomType<>( - TagUserType.INSTANCE, - scope.getEntityManagerFactory().unwrap( SessionFactoryImplementor.class ).getTypeConfiguration() - ); + q -> { + final CustomType> customType = new CustomType<>( + TagUserType.INSTANCE, + scope.getEntityManagerFactory().unwrap( SessionFactoryImplementor.class ).getTypeConfiguration() + ); - org.hibernate.query.Query hibernateQuery = q.unwrap( org.hibernate.query.Query.class ); - hibernateQuery.setParameter( "tags", Arrays.asList( "important", "business" ), customType ); - } + org.hibernate.query.Query hibernateQuery = q.unwrap( org.hibernate.query.Query.class ); + hibernateQuery.setParameter( "tags", Arrays.asList( "important", "business" ), customType ); + } ); } @Test public void testJpa(EntityManagerFactoryScope scope) { test(scope, - q -> { + q -> { final CustomType> customType = new CustomType<>( TagUserType.INSTANCE, scope.getEntityManagerFactory().unwrap( SessionFactoryImplementor.class ).getTypeConfiguration() diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/spi/NativeQueryTupleTransformerTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/spi/NativeQueryTupleTransformerTest.java index d843d2672e..d16c3ab80a 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/spi/NativeQueryTupleTransformerTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/spi/NativeQueryTupleTransformerTest.java @@ -20,24 +20,24 @@ import org.junit.Test; */ public class NativeQueryTupleTransformerTest { - private final NativeQueryTupleTransformer nativeQueryTupleTransformer = new NativeQueryTupleTransformer(); + private final NativeQueryTupleTransformer nativeQueryTupleTransformer = new NativeQueryTupleTransformer(); - @Test - public void nullValueIsExtractedFromTuple() { - final Tuple tuple = (Tuple) nativeQueryTupleTransformer.transformTuple( - new Object[] { 1L, null }, - new String[] { "id", "value" } - ); - assertEquals(1L, tuple.get("id")); - assertNull(tuple.get("value")); - } + @Test + public void nullValueIsExtractedFromTuple() { + final Tuple tuple = (Tuple) nativeQueryTupleTransformer.transformTuple( + new Object[] { 1L, null }, + new String[] { "id", "value" } + ); + assertEquals(1L, tuple.get("id")); + assertNull(tuple.get("value")); + } - @Test(expected = IllegalArgumentException.class) - public void missingAliasCausesExceptionWhenIsExtractedFromTuple() { - final Tuple tuple = (Tuple) nativeQueryTupleTransformer.transformTuple( - new Object[] { 1L, null }, - new String[] { "id", "value" } - ); - tuple.get("unknownAlias"); - } + @Test(expected = IllegalArgumentException.class) + public void missingAliasCausesExceptionWhenIsExtractedFromTuple() { + final Tuple tuple = (Tuple) nativeQueryTupleTransformer.transformTuple( + new Object[] { 1L, null }, + new String[] { "id", "value" } + ); + tuple.get("unknownAlias"); + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/test/components/ComponentCriteriaTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/test/components/ComponentCriteriaTest.java index e562266f55..9a55960780 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/test/components/ComponentCriteriaTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/test/components/ComponentCriteriaTest.java @@ -118,18 +118,18 @@ public class ComponentCriteriaTest extends BaseEntityManagerFunctionalTestCase { @JiraKey(value = "HHH-4586") public void testParameterizedFunctions() { doInJPA( this::entityManagerFactory, em -> { - CriteriaBuilder cb = em.getCriteriaBuilder(); - // lower - CriteriaQuery cq = cb.createQuery( Client.class ); - Root root = cq.from( Client.class ); - cq.where( cb.equal( cb.lower( root.get( Client_.name ).get( Name_.lastName ) ), "test" ) ); - em.createQuery( cq ).getResultList(); - // upper - cq = cb.createQuery( Client.class ); - root = cq.from( Client.class ); - cq.where( cb.equal( cb.upper( root.get( Client_.name ).get( Name_.lastName ) ), "test" ) ); - em.createQuery( cq ).getResultList(); - } + CriteriaBuilder cb = em.getCriteriaBuilder(); + // lower + CriteriaQuery cq = cb.createQuery( Client.class ); + Root root = cq.from( Client.class ); + cq.where( cb.equal( cb.lower( root.get( Client_.name ).get( Name_.lastName ) ), "test" ) ); + em.createQuery( cq ).getResultList(); + // upper + cq = cb.createQuery( Client.class ); + root = cq.from( Client.class ); + cq.where( cb.equal( cb.upper( root.get( Client_.name ).get( Name_.lastName ) ), "test" ) ); + em.createQuery( cq ).getResultList(); + } ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/test/components/Name.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/test/components/Name.java index 0a2e25cf35..526732600c 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/test/components/Name.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/test/components/Name.java @@ -20,10 +20,10 @@ import jakarta.persistence.OneToMany; */ @Embeddable public class Name implements Serializable { - private static final long serialVersionUID = 8381969086665589013L; + private static final long serialVersionUID = 8381969086665589013L; - private String firstName; - private String lastName; + private String firstName; + private String lastName; private Set aliases = new HashSet( ); public Name() { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/version/JpaSpecVersionValueUpdatingTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/version/JpaSpecVersionValueUpdatingTest.java index 896cf69500..17aa7d446a 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/version/JpaSpecVersionValueUpdatingTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/version/JpaSpecVersionValueUpdatingTest.java @@ -115,7 +115,7 @@ public class JpaSpecVersionValueUpdatingTest extends BaseCoreFunctionalTestCase session.beginTransaction(); customer = session.getReference( Customer.class, 1L ); assertEquals( initial, customer.version ); - session.remove( customer ); + session.remove( customer ); session.getTransaction().commit(); session.close(); } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/xml/Employee.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/xml/Employee.java index 8410f2cbc8..87e14b68fb 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/xml/Employee.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/xml/Employee.java @@ -13,58 +13,58 @@ import jakarta.persistence.Id; */ @Entity public class Employee { - @Id + @Id Long id; - String name; + String name; /* - @Embedded - @AttributeOverrides({ - @AttributeOverride(name = "street", column = @Column(name = "HA_street")), - @AttributeOverride(name = "city", column = @Column(name = "HA_city")), - @AttributeOverride(name = "state", column = @Column(name = "HA_state")), - @AttributeOverride(name = "zip", column = @Column(name = "HA_zip")) }) + @Embedded + @AttributeOverrides({ + @AttributeOverride(name = "street", column = @Column(name = "HA_street")), + @AttributeOverride(name = "city", column = @Column(name = "HA_city")), + @AttributeOverride(name = "state", column = @Column(name = "HA_state")), + @AttributeOverride(name = "zip", column = @Column(name = "HA_zip")) }) */ - Address homeAddress; + Address homeAddress; /* - @Embedded - @AttributeOverrides({ - @AttributeOverride(name = "street", column = @Column(name = "MA_street")), - @AttributeOverride(name = "city", column = @Column(name = "MA_city")), - @AttributeOverride(name = "state", column = @Column(name = "MA_state")), - @AttributeOverride(name = "zip", column = @Column(name = "MA_zip")) }) + @Embedded + @AttributeOverrides({ + @AttributeOverride(name = "street", column = @Column(name = "MA_street")), + @AttributeOverride(name = "city", column = @Column(name = "MA_city")), + @AttributeOverride(name = "state", column = @Column(name = "MA_state")), + @AttributeOverride(name = "zip", column = @Column(name = "MA_zip")) }) */ - Address mailAddress; + Address mailAddress; - public Long getId() { - return id; - } + public Long getId() { + return id; + } - public void setId(Long id) { - this.id = id; - } + public void setId(Long id) { + this.id = id; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - public Address getHomeAddress() { - return homeAddress; - } + public Address getHomeAddress() { + return homeAddress; + } - public void setHomeAddress(Address homeAddress) { - this.homeAddress = homeAddress; - } + public void setHomeAddress(Address homeAddress) { + this.homeAddress = homeAddress; + } - public Address getMailAddress() { - return mailAddress; - } + public Address getMailAddress() { + return mailAddress; + } - public void setMailAddress(Address mailAddress) { - this.mailAddress = mailAddress; - } + public void setMailAddress(Address mailAddress) { + this.mailAddress = mailAddress; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/xml/sequences/Employee.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/xml/sequences/Employee.java index e27813bf9f..10d1cfd7a3 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/xml/sequences/Employee.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/xml/sequences/Employee.java @@ -13,58 +13,58 @@ import jakarta.persistence.Id; */ @Entity public class Employee { - @Id + @Id Long id; - String name; + String name; /* - @Embedded - @AttributeOverrides({ - @AttributeOverride(name = "street", column = @Column(name = "HA_street")), - @AttributeOverride(name = "city", column = @Column(name = "HA_city")), - @AttributeOverride(name = "state", column = @Column(name = "HA_state")), - @AttributeOverride(name = "zip", column = @Column(name = "HA_zip")) }) + @Embedded + @AttributeOverrides({ + @AttributeOverride(name = "street", column = @Column(name = "HA_street")), + @AttributeOverride(name = "city", column = @Column(name = "HA_city")), + @AttributeOverride(name = "state", column = @Column(name = "HA_state")), + @AttributeOverride(name = "zip", column = @Column(name = "HA_zip")) }) */ - Address homeAddress; + Address homeAddress; /* - @Embedded - @AttributeOverrides({ - @AttributeOverride(name = "street", column = @Column(name = "MA_street")), - @AttributeOverride(name = "city", column = @Column(name = "MA_city")), - @AttributeOverride(name = "state", column = @Column(name = "MA_state")), - @AttributeOverride(name = "zip", column = @Column(name = "MA_zip")) }) + @Embedded + @AttributeOverrides({ + @AttributeOverride(name = "street", column = @Column(name = "MA_street")), + @AttributeOverride(name = "city", column = @Column(name = "MA_city")), + @AttributeOverride(name = "state", column = @Column(name = "MA_state")), + @AttributeOverride(name = "zip", column = @Column(name = "MA_zip")) }) */ - Address mailAddress; + Address mailAddress; - public Long getId() { - return id; - } + public Long getId() { + return id; + } - public void setId(Long id) { - this.id = id; - } + public void setId(Long id) { + this.id = id; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - public Address getHomeAddress() { - return homeAddress; - } + public Address getHomeAddress() { + return homeAddress; + } - public void setHomeAddress(Address homeAddress) { - this.homeAddress = homeAddress; - } + public void setHomeAddress(Address homeAddress) { + this.homeAddress = homeAddress; + } - public Address getMailAddress() { - return mailAddress; - } + public Address getMailAddress() { + return mailAddress; + } - public void setMailAddress(Address mailAddress) { - this.mailAddress = mailAddress; - } + public void setMailAddress(Address mailAddress) { + this.mailAddress = mailAddress; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/xml/versions/JpaXsdVersionsTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/xml/versions/JpaXsdVersionsTest.java index 9a5b4b8ede..0b179816ca 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/xml/versions/JpaXsdVersionsTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/xml/versions/JpaXsdVersionsTest.java @@ -37,7 +37,7 @@ import org.junit.Test; * @author Steve Ebersole */ public class JpaXsdVersionsTest { - @Test + @Test public void testOrm1() { PersistenceUnitInfoImpl pui = new PersistenceUnitInfoImpl( "orm1-test", "1.0" ) .addMappingFileName( "org/hibernate/orm/test/jpa/xml/versions/valid-orm-1_0.xml" ); @@ -63,7 +63,7 @@ public class JpaXsdVersionsTest { } } - @Test + @Test public void testOrm21() { PersistenceUnitInfoImpl pui = new PersistenceUnitInfoImpl( "orm2-test", "2.1" ) .addMappingFileName( "org/hibernate/orm/test/jpa/xml/versions/valid-orm-2_1.xml" ); @@ -73,7 +73,7 @@ public class JpaXsdVersionsTest { } } - @Test + @Test public void testOrm22() { PersistenceUnitInfoImpl pui = new PersistenceUnitInfoImpl( "orm2-test", "2.2") .addMappingFileName( "org/hibernate/orm/test/jpa/xml/versions/valid-orm-2_2.xml" ); @@ -83,7 +83,7 @@ public class JpaXsdVersionsTest { } } - @Test + @Test public void testInvalidOrm1() { PersistenceUnitInfoImpl pui = new PersistenceUnitInfoImpl( "invalid-orm1-test", "1.0" ) .addMappingFileName( "org/hibernate/orm/test/jpa/xml/versions/invalid-orm-1_0.xml" ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/legacy/ABCTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/legacy/ABCTest.java index b552edb44f..4e08851a61 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/legacy/ABCTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/legacy/ABCTest.java @@ -76,7 +76,7 @@ public class ABCTest { .getDatabase() .getDefaultNamespace() .locateTable( Identifier.toIdentifier( "TA" ) ); - Iterator indexItr = table.getIndexes().values().iterator(); + Iterator indexItr = table.getIndexes().values().iterator(); boolean found = false; while ( indexItr.hasNext() ) { final Index index = indexItr.next(); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/legacy/Company.java b/hibernate-core/src/test/java/org/hibernate/orm/test/legacy/Company.java index f24caaa253..e6217bd042 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/legacy/Company.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/legacy/Company.java @@ -12,25 +12,25 @@ package org.hibernate.orm.test.legacy; */ public class Company extends Party { - String id; - String president; +String id; +String president; - String getId() { - return id; - } +String getId() { + return id; +} - void setId(String newValue) { - id = newValue; - } +void setId(String newValue) { + id = newValue; +} - String getPresident() { - return president; - } +String getPresident() { + return president; +} - void setPresident(String newValue) { - president = newValue; - } +void setPresident(String newValue) { + president = newValue; +} } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/legacy/Component.java b/hibernate-core/src/test/java/org/hibernate/orm/test/legacy/Component.java index 4252c72490..d05fb3b62e 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/legacy/Component.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/legacy/Component.java @@ -13,36 +13,36 @@ package org.hibernate.orm.test.legacy; * @author Emmanuel Bernard */ public class Component { - private String _name; + private String _name; - private SubComponent _subComponent; + private SubComponent _subComponent; - /** - * @return - */ - public String getName() { - return _name; - } + /** + * @return + */ + public String getName() { + return _name; + } - /** - * @param string - */ - public void setName(String string) { - _name = string; - } + /** + * @param string + */ + public void setName(String string) { + _name = string; + } - /** - * @return - */ - public SubComponent getSubComponent() { - return _subComponent; - } + /** + * @return + */ + public SubComponent getSubComponent() { + return _subComponent; + } - /** - * @param component - */ - public void setSubComponent(SubComponent component) { - _subComponent = component; - } + /** + * @param component + */ + public void setSubComponent(SubComponent component) { + _subComponent = component; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/legacy/ComponentNotNull.java b/hibernate-core/src/test/java/org/hibernate/orm/test/legacy/ComponentNotNull.java index 41ba5c78bf..da37a4d146 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/legacy/ComponentNotNull.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/legacy/ComponentNotNull.java @@ -15,8 +15,8 @@ package org.hibernate.orm.test.legacy; public class ComponentNotNull { /* * I've flatten several components in one class, this is kind of ugly but - * I don't have to write tons of classes - */ + * I don't have to write tons of classes + */ private String prop1Nullable; private String prop2Nullable; private ComponentNotNull supercomp; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/legacy/ComponentNotNullRoot.java b/hibernate-core/src/test/java/org/hibernate/orm/test/legacy/ComponentNotNullRoot.java index 612f31e0d8..ec5355315a 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/legacy/ComponentNotNullRoot.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/legacy/ComponentNotNullRoot.java @@ -66,8 +66,8 @@ public class ComponentNotNullRoot { public String toString() { return name + " = " + simple.getCount() + - "/" + ( one==null ? "nil" : one.getKey().toString() ) + - "/" + ( many==null ? "nil" : many.getKey().toString() ); + "/" + ( one==null ? "nil" : one.getKey().toString() ) + + "/" + ( many==null ? "nil" : many.getKey().toString() ); } public One getOne() { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/legacy/Componentizable.java b/hibernate-core/src/test/java/org/hibernate/orm/test/legacy/Componentizable.java index ab9e2e62c0..8bbb708697 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/legacy/Componentizable.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/legacy/Componentizable.java @@ -16,51 +16,51 @@ public class Componentizable { /** surrogate id */ private Integer _id; - public String _nickName; + public String _nickName; /** component */ - private Component _component; + private Component _component; - /** - * @return - */ - public Integer getId() { - return _id; - } + /** + * @return + */ + public Integer getId() { + return _id; + } - /** - * @param integer - */ - public void setId(Integer integer) { - _id = integer; - } + /** + * @param integer + */ + public void setId(Integer integer) { + _id = integer; + } - /** - * @return - */ - public Component getComponent() { - return _component; - } + /** + * @return + */ + public Component getComponent() { + return _component; + } - /** - * @param component - */ - public void setComponent(Component component) { - _component = component; - } + /** + * @param component + */ + public void setComponent(Component component) { + _component = component; + } - /** - * @return - */ - public String getNickName() { - return _nickName; - } + /** + * @return + */ + public String getNickName() { + return _nickName; + } - /** - * @param string - */ - public void setNickName(String string) { - _nickName = string; - } + /** + * @param string + */ + public void setNickName(String string) { + _nickName = string; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/legacy/CompositeIdId.java b/hibernate-core/src/test/java/org/hibernate/orm/test/legacy/CompositeIdId.java index 2cb5e8bbd9..7df4555332 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/legacy/CompositeIdId.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/legacy/CompositeIdId.java @@ -14,44 +14,44 @@ import java.io.Serializable; */ public class CompositeIdId implements Serializable { - String user; - String id; - String name; - CompositeElement composite; + String user; + String id; + String name; + CompositeElement composite; - public String getId() { - return id; - } - public void setId(String id) { - this.id = id; - } - public String getUser() { - return user; - } - public void setUser(String user) { - this.user = user; - } - public String getName() { - return name; - } - public void setName(String name) { - this.name = name; - } + public String getId() { + return id; + } + public void setId(String id) { + this.id = id; + } + public String getUser() { + return user; + } + public void setUser(String user) { + this.user = user; + } + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } - /* (non-Javadoc) - * @see java.lang.Object#equals(java.lang.Object) - */ - public boolean equals(Object obj) { - // not totally NP or type safe equals, but enough for the unittests. - CompositeIdId o = (CompositeIdId) obj; - if(o==null) return false; - return o.getUser().equals( getUser()) && o.getId().equals(getId()); - } - public CompositeElement getComposite() { - return composite; - } - public void setComposite(CompositeElement composite) { - this.composite = composite; - } + /* (non-Javadoc) + * @see java.lang.Object#equals(java.lang.Object) + */ + public boolean equals(Object obj) { + // not totally NP or type safe equals, but enough for the unittests. + CompositeIdId o = (CompositeIdId) obj; + if(o==null) return false; + return o.getUser().equals( getUser()) && o.getId().equals(getId()); + } + public CompositeElement getComposite() { + return composite; + } + public void setComposite(CompositeElement composite) { + this.composite = composite; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/legacy/CustomPersister.java b/hibernate-core/src/test/java/org/hibernate/orm/test/legacy/CustomPersister.java index 09eb6c5a5a..2533cd67bb 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/legacy/CustomPersister.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/legacy/CustomPersister.java @@ -874,10 +874,10 @@ public class CustomPersister implements EntityPersister { return null; } - @Override - public int[] resolveAttributeIndexes(String[] attributeNames) { - return null; - } + @Override + public int[] resolveAttributeIndexes(String[] attributeNames) { + return null; + } @Override public boolean canUseReferenceCacheEntries() { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/legacy/Drug.java b/hibernate-core/src/test/java/org/hibernate/orm/test/legacy/Drug.java index 8082623c00..b5175f3362 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/legacy/Drug.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/legacy/Drug.java @@ -11,16 +11,16 @@ package org.hibernate.orm.test.legacy; */ public class Drug extends Resource { - String id; +String id; - String getId() { - return id; - } +String getId() { + return id; +} - void setId(String newValue) { - id = newValue; - } +void setId(String newValue) { + id = newValue; +} } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/legacy/Intervention.java b/hibernate-core/src/test/java/org/hibernate/orm/test/legacy/Intervention.java index 4aba74d832..518b81d6c0 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/legacy/Intervention.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/legacy/Intervention.java @@ -12,26 +12,26 @@ package org.hibernate.orm.test.legacy; */ public class Intervention { - String id; - long version; +String id; +long version; - String description; +String description; - String getId() { - return id; - } +String getId() { + return id; +} - void setId(String newValue) { - id = newValue; - } +void setId(String newValue) { + id = newValue; +} - long getVersion() { - return version; - } +long getVersion() { + return version; +} - void setVersion(long newValue) { - version = newValue; - } +void setVersion(long newValue) { + version = newValue; +} public String getDescription() { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/legacy/Medication.java b/hibernate-core/src/test/java/org/hibernate/orm/test/legacy/Medication.java index 28ba2fc236..7911f41c15 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/legacy/Medication.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/legacy/Medication.java @@ -12,16 +12,16 @@ package org.hibernate.orm.test.legacy; */ public class Medication extends Intervention { - Drug prescribedDrug; +Drug prescribedDrug; - Drug getPrescribedDrug() { - return prescribedDrug; - } +Drug getPrescribedDrug() { + return prescribedDrug; +} - void setPrescribedDrug(Drug newValue) { - prescribedDrug = newValue; - } +void setPrescribedDrug(Drug newValue) { + prescribedDrug = newValue; +} } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/legacy/Party.java b/hibernate-core/src/test/java/org/hibernate/orm/test/legacy/Party.java index dd50d89107..3a6794d156 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/legacy/Party.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/legacy/Party.java @@ -12,34 +12,34 @@ package org.hibernate.orm.test.legacy; */ public class Party { - String id; - String name; - String address; +String id; +String name; +String address; - String getId() { - return id; - } +String getId() { + return id; +} - void setId(String newValue) { - id = newValue; - } +void setId(String newValue) { + id = newValue; +} - String getName() { - return name; - } +String getName() { + return name; +} - void setName(String newValue) { - name = newValue; - } +void setName(String newValue) { + name = newValue; +} - String getAddress() { - return address; - } +String getAddress() { + return address; +} - void setAddress(String newValue) { - address = newValue; - } +void setAddress(String newValue) { + address = newValue; +} } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/legacy/Person.java b/hibernate-core/src/test/java/org/hibernate/orm/test/legacy/Person.java index e1edd78dd4..bcc419d7d0 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/legacy/Person.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/legacy/Person.java @@ -12,43 +12,43 @@ package org.hibernate.orm.test.legacy; */ public class Person extends Party { - String id; - String givenName; - String lastName; - String nationalID; +String id; +String givenName; +String lastName; +String nationalID; - String getId() { - return id; - } +String getId() { + return id; +} - void setId(String newValue) { - id = newValue; - } +void setId(String newValue) { + id = newValue; +} - String getGivenName() { - return givenName; - } +String getGivenName() { + return givenName; +} - void setGivenName(String newValue) { - givenName = newValue; - } +void setGivenName(String newValue) { + givenName = newValue; +} - String getLastName() { - return lastName; - } +String getLastName() { + return lastName; +} - void setLastName(String newValue) { - lastName = newValue; - } +void setLastName(String newValue) { + lastName = newValue; +} - String getNationalID() { - return nationalID; - } +String getNationalID() { + return nationalID; +} - void setNationalID(String newValue) { - nationalID = newValue; - } +void setNationalID(String newValue) { + nationalID = newValue; +} } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/legacy/Resource.java b/hibernate-core/src/test/java/org/hibernate/orm/test/legacy/Resource.java index 2c2cc45f33..3ef79aed7e 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/legacy/Resource.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/legacy/Resource.java @@ -12,34 +12,34 @@ package org.hibernate.orm.test.legacy; */ public class Resource { - String id; - String name; - String userCode; +String id; +String name; +String userCode; - String getId() { - return id; - } +String getId() { + return id; +} - void setId(String newValue) { - id = newValue; - } +void setId(String newValue) { + id = newValue; +} - String getName() { - return name; - } +String getName() { + return name; +} - void setName(String newValue) { - name = newValue; - } +void setName(String newValue) { + name = newValue; +} - String getUserCode() { - return userCode; - } +String getUserCode() { + return userCode; +} - void setUserCode(String newValue) { - userCode = newValue; - } +void setUserCode(String newValue) { + userCode = newValue; +} } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/legacy/Role.java b/hibernate-core/src/test/java/org/hibernate/orm/test/legacy/Role.java index 6d74c1709d..e8a1562aa3 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/legacy/Role.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/legacy/Role.java @@ -14,40 +14,40 @@ import java.util.Set; */ public class Role { - long id; - String name; - Set interventions = new HashSet(); +long id; +String name; +Set interventions = new HashSet(); private List bunchOfStrings; - long getId() { - return id; - } - - void setId(long newValue) { - id = newValue; - } - - String getName() { - return name; - } - - void setName(String newValue) { - name = newValue; - } - - public Set getInterventions() { - return interventions; - } - - public void setInterventions(Set iv) { - interventions = iv; - } - - List getBunchOfStrings() { - return bunchOfStrings; - } - - void setBunchOfStrings(List s) { - bunchOfStrings = s; - } +long getId() { + return id; +} + +void setId(long newValue) { + id = newValue; +} + +String getName() { + return name; +} + +void setName(String newValue) { + name = newValue; +} + +public Set getInterventions() { + return interventions; +} + +public void setInterventions(Set iv) { + interventions = iv; +} + +List getBunchOfStrings() { + return bunchOfStrings; +} + +void setBunchOfStrings(List s) { + bunchOfStrings = s; +} } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/legacy/SubComponent.java b/hibernate-core/src/test/java/org/hibernate/orm/test/legacy/SubComponent.java index df3cc6388f..6a6b600970 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/legacy/SubComponent.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/legacy/SubComponent.java @@ -12,36 +12,36 @@ package org.hibernate.orm.test.legacy; * @author emmanuel */ public class SubComponent { - private String _subName; + private String _subName; - private String _subName1; + private String _subName1; - /** - * @return - */ - public String getSubName() { - return _subName; - } + /** + * @return + */ + public String getSubName() { + return _subName; + } - /** - * @param string - */ - public void setSubName(String string) { - _subName = string; - } + /** + * @param string + */ + public void setSubName(String string) { + _subName = string; + } - /** - * @return - */ - public String getSubName1() { - return _subName1; - } + /** + * @return + */ + public String getSubName1() { + return _subName1; + } - /** - * @param string - */ - public void setSubName1(String string) { - _subName1 = string; - } + /** + * @param string + */ + public void setSubName1(String string) { + _subName1 = string; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/length/BinaryLengthTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/length/BinaryLengthTest.java index 567633907c..539e77f65d 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/length/BinaryLengthTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/length/BinaryLengthTest.java @@ -16,23 +16,23 @@ import static org.junit.jupiter.api.Assertions.assertArrayEquals; @SessionFactory @DomainModel(annotatedClasses = WithLongByteArrays.class) public class BinaryLengthTest { - @Test - public void testLength(SessionFactoryScope scope) { - WithLongByteArrays arrays = new WithLongByteArrays(); - arrays.longish = "hello world ".repeat(2500).getBytes(); - arrays.long16 = "hello world ".repeat(2700).getBytes(); - arrays.long32 = "hello world ".repeat(20000).getBytes(); - // This is an important test that it's possible to handle - // very long binary types in a way that's portable across - // both Postgres (bytea) and other databases (blob) - arrays.lob = "hello world ".repeat(40000).getBytes(); - scope.inTransaction(s -> s.persist(arrays)); - scope.inTransaction(s -> { - WithLongByteArrays arrs = s.find(WithLongByteArrays.class, arrays.id); - assertArrayEquals(arrs.longish, arrays.longish); - assertArrayEquals(arrs.long16, arrays.long16); - assertArrayEquals(arrs.long32, arrays.long32); - assertArrayEquals(arrs.lob, arrays.lob); - }); - } + @Test + public void testLength(SessionFactoryScope scope) { + WithLongByteArrays arrays = new WithLongByteArrays(); + arrays.longish = "hello world ".repeat(2500).getBytes(); + arrays.long16 = "hello world ".repeat(2700).getBytes(); + arrays.long32 = "hello world ".repeat(20000).getBytes(); + // This is an important test that it's possible to handle + // very long binary types in a way that's portable across + // both Postgres (bytea) and other databases (blob) + arrays.lob = "hello world ".repeat(40000).getBytes(); + scope.inTransaction(s -> s.persist(arrays)); + scope.inTransaction(s -> { + WithLongByteArrays arrs = s.find(WithLongByteArrays.class, arrays.id); + assertArrayEquals(arrs.longish, arrays.longish); + assertArrayEquals(arrs.long16, arrays.long16); + assertArrayEquals(arrs.long32, arrays.long32); + assertArrayEquals(arrs.lob, arrays.lob); + }); + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/length/LengthTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/length/LengthTest.java index 31553d5f6a..c9807c164e 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/length/LengthTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/length/LengthTest.java @@ -21,49 +21,49 @@ import static org.junit.Assert.assertEquals; @SessionFactory @DomainModel(annotatedClasses = {WithLongStrings.class,WithLongTypeStrings.class}) public class LengthTest { - @Test - public void testLength(SessionFactoryScope scope) { - WithLongStrings strings = new WithLongStrings(); - strings.longish = "hello world ".repeat(2500); - strings.long16 = "hello world ".repeat(2700); - strings.long32 = "hello world ".repeat(20000); - strings.clob = "hello world ".repeat(40000); - scope.inTransaction(s -> s.persist(strings)); - scope.inTransaction(s -> { - WithLongStrings strs = s.find(WithLongStrings.class, strings.id); - assertEquals(strs.longish, strings.longish); - assertEquals(strs.long16, strings.long16); - assertEquals(strs.long32, strings.long32); - assertEquals(strs.clob, strings.clob); - }); - } + @Test + public void testLength(SessionFactoryScope scope) { + WithLongStrings strings = new WithLongStrings(); + strings.longish = "hello world ".repeat(2500); + strings.long16 = "hello world ".repeat(2700); + strings.long32 = "hello world ".repeat(20000); + strings.clob = "hello world ".repeat(40000); + scope.inTransaction(s -> s.persist(strings)); + scope.inTransaction(s -> { + WithLongStrings strs = s.find(WithLongStrings.class, strings.id); + assertEquals(strs.longish, strings.longish); + assertEquals(strs.long16, strings.long16); + assertEquals(strs.long32, strings.long32); + assertEquals(strs.clob, strings.clob); + }); + } - @Test - public void testSqlType(SessionFactoryScope scope) { - WithLongTypeStrings strings = new WithLongTypeStrings(); - strings.longish = "hello world ".repeat(2500); - strings.long32 = "hello world ".repeat(20000); - scope.inTransaction(s -> s.persist(strings)); - scope.inTransaction(s -> { - WithLongTypeStrings strs = s.find(WithLongTypeStrings.class, strings.id); - assertEquals(strs.longish, strings.longish); - assertEquals(strs.long32, strings.long32); - }); - } + @Test + public void testSqlType(SessionFactoryScope scope) { + WithLongTypeStrings strings = new WithLongTypeStrings(); + strings.longish = "hello world ".repeat(2500); + strings.long32 = "hello world ".repeat(20000); + scope.inTransaction(s -> s.persist(strings)); + scope.inTransaction(s -> { + WithLongTypeStrings strs = s.find(WithLongTypeStrings.class, strings.id); + assertEquals(strs.longish, strings.longish); + assertEquals(strs.long32, strings.long32); + }); + } - @Test - public void testLong32(SessionFactoryScope scope) { - final Dialect dialect = scope.getSessionFactory().getJdbcServices().getDialect(); - final BasicValuedMapping mapping = (BasicValuedMapping) scope.getSessionFactory() - .getRuntimeMetamodels() - .getMappingMetamodel() - .getEntityDescriptor( WithLongStrings.class ) - .findAttributeMapping( "long32" ); - if ( dialect.useMaterializedLobWhenCapacityExceeded() && Length.LONG32 > dialect.getMaxVarcharCapacity() ) { - assertEquals( SqlTypes.CLOB, mapping.getJdbcMapping().getJdbcType().getJdbcTypeCode() ); - } - else { - assertEquals( SqlTypes.VARCHAR, mapping.getJdbcMapping().getJdbcType().getJdbcTypeCode() ); - } - } + @Test + public void testLong32(SessionFactoryScope scope) { + final Dialect dialect = scope.getSessionFactory().getJdbcServices().getDialect(); + final BasicValuedMapping mapping = (BasicValuedMapping) scope.getSessionFactory() + .getRuntimeMetamodels() + .getMappingMetamodel() + .getEntityDescriptor( WithLongStrings.class ) + .findAttributeMapping( "long32" ); + if ( dialect.useMaterializedLobWhenCapacityExceeded() && Length.LONG32 > dialect.getMaxVarcharCapacity() ) { + assertEquals( SqlTypes.CLOB, mapping.getJdbcMapping().getJdbcType().getJdbcTypeCode() ); + } + else { + assertEquals( SqlTypes.VARCHAR, mapping.getJdbcMapping().getJdbcType().getJdbcTypeCode() ); + } + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/length/WithLongStrings.java b/hibernate-core/src/test/java/org/hibernate/orm/test/length/WithLongStrings.java index 75de1e6f4d..5037e5e462 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/length/WithLongStrings.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/length/WithLongStrings.java @@ -15,19 +15,19 @@ import static org.hibernate.Length.*; @Entity public class WithLongStrings { - @Id - @GeneratedValue - public int id; + @Id + @GeneratedValue + public int id; - @Column(length = LONG) - public String longish; + @Column(length = LONG) + public String longish; - @Column(length = LONG16) - public String long16; + @Column(length = LONG16) + public String long16; - @Column(length = LONG32) - public String long32; + @Column(length = LONG32) + public String long32; - @Column(length = LOB_DEFAULT+1) - public String clob; + @Column(length = LOB_DEFAULT+1) + public String clob; } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/length/WithLongTypeStrings.java b/hibernate-core/src/test/java/org/hibernate/orm/test/length/WithLongTypeStrings.java index 64cea34432..c7411983fa 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/length/WithLongTypeStrings.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/length/WithLongTypeStrings.java @@ -14,13 +14,13 @@ import org.hibernate.type.SqlTypes; @Entity public class WithLongTypeStrings { - @Id - @GeneratedValue - public int id; + @Id + @GeneratedValue + public int id; - @JdbcTypeCode(SqlTypes.LONGVARCHAR) - public String longish; + @JdbcTypeCode(SqlTypes.LONGVARCHAR) + public String longish; - @JdbcTypeCode(SqlTypes.LONG32VARCHAR) - public String long32; + @JdbcTypeCode(SqlTypes.LONG32VARCHAR) + public String long32; } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/loading/multiLoad/FindAllFetchProfileTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/loading/multiLoad/FindAllFetchProfileTest.java index 5bd885b742..5472038e12 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/loading/multiLoad/FindAllFetchProfileTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/loading/multiLoad/FindAllFetchProfileTest.java @@ -29,58 +29,58 @@ import static org.junit.jupiter.api.Assertions.assertTrue; @SessionFactory @DomainModel(annotatedClasses = {FindAllFetchProfileTest.Record.class, FindAllFetchProfileTest.Owner.class}) public class FindAllFetchProfileTest { - @Test void test(SessionFactoryScope scope) { - scope.inTransaction(s-> { - Owner gavin = new Owner("gavin"); - s.persist(gavin); - s.persist(new Record(123L,gavin,"hello earth")); - s.persist(new Record(456L,gavin,"hello mars")); - }); - scope.inTransaction(s-> { - List all = s.findAll(Record.class, List.of(456L, 123L, 2L)); - assertEquals("hello mars",all.get(0).message); - assertEquals("hello earth",all.get(1).message); - assertNull(all.get(2)); - assertFalse(Hibernate.isInitialized(all.get(0).owner)); - assertFalse(Hibernate.isInitialized(all.get(1).owner)); - }); - scope.inTransaction(s-> { - List all = s.findAll(Record.class, List.of(456L, 123L), - new EnabledFetchProfile("withOwner")); - assertEquals("hello mars",all.get(0).message); - assertEquals("hello earth",all.get(1).message); - assertTrue(Hibernate.isInitialized(all.get(0).owner)); - assertTrue(Hibernate.isInitialized(all.get(1).owner)); - }); - } - @Entity - @FetchProfile(name = "withOwner") - static class Record { - @Id Long id; - String message; + @Test void test(SessionFactoryScope scope) { + scope.inTransaction(s-> { + Owner gavin = new Owner("gavin"); + s.persist(gavin); + s.persist(new Record(123L,gavin,"hello earth")); + s.persist(new Record(456L,gavin,"hello mars")); + }); + scope.inTransaction(s-> { + List all = s.findAll(Record.class, List.of(456L, 123L, 2L)); + assertEquals("hello mars",all.get(0).message); + assertEquals("hello earth",all.get(1).message); + assertNull(all.get(2)); + assertFalse(Hibernate.isInitialized(all.get(0).owner)); + assertFalse(Hibernate.isInitialized(all.get(1).owner)); + }); + scope.inTransaction(s-> { + List all = s.findAll(Record.class, List.of(456L, 123L), + new EnabledFetchProfile("withOwner")); + assertEquals("hello mars",all.get(0).message); + assertEquals("hello earth",all.get(1).message); + assertTrue(Hibernate.isInitialized(all.get(0).owner)); + assertTrue(Hibernate.isInitialized(all.get(1).owner)); + }); + } + @Entity + @FetchProfile(name = "withOwner") + static class Record { + @Id Long id; + String message; - @FetchProfileOverride(profile = "withOwner") - @ManyToOne(fetch = FetchType.LAZY) - Owner owner; + @FetchProfileOverride(profile = "withOwner") + @ManyToOne(fetch = FetchType.LAZY) + Owner owner; - Record(Long id, Owner owner, String message) { - this.id = id; - this.owner = owner; - this.message = message; - } + Record(Long id, Owner owner, String message) { + this.id = id; + this.owner = owner; + this.message = message; + } - Record() { - } - } - @Entity - static class Owner { - @Id String name; + Record() { + } + } + @Entity + static class Owner { + @Id String name; - Owner(String name) { - this.name = name; - } + Owner(String name) { + this.name = name; + } - Owner() { - } - } + Owner() { + } + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/loading/multiLoad/FindAllTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/loading/multiLoad/FindAllTest.java index be7a86878f..d0086c1f9c 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/loading/multiLoad/FindAllTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/loading/multiLoad/FindAllTest.java @@ -24,41 +24,41 @@ import static org.junit.jupiter.api.Assertions.assertTrue; @SessionFactory @DomainModel(annotatedClasses = FindAllTest.Record.class) public class FindAllTest { - @Test void test(SessionFactoryScope scope) { - scope.inTransaction(s-> { - s.persist(new Record(123L,"hello earth")); - s.persist(new Record(456L,"hello mars")); - }); - scope.inTransaction(s-> { - List all = s.findAll(Record.class, List.of(456L, 123L, 2L)); - assertEquals("hello mars",all.get(0).message); - assertEquals("hello earth",all.get(1).message); - assertNull(all.get(2)); - }); - scope.inTransaction(s-> { - List all = s.findAll(Record.class, List.of(456L, 123L), READ_ONLY); - assertEquals("hello mars",all.get(0).message); - assertEquals("hello earth",all.get(1).message); - assertTrue(s.isReadOnly(all.get(0))); - assertTrue(s.isReadOnly(all.get(1))); - }); - scope.inTransaction(s-> { - Record record = s.getReference(Record.class, 456L); - List all = s.findAll(Record.class, List.of(456L, 123L)); - assertSame(record, all.get(0)); - }); - } - @Entity - static class Record { - @Id Long id; - String message; + @Test void test(SessionFactoryScope scope) { + scope.inTransaction(s-> { + s.persist(new Record(123L,"hello earth")); + s.persist(new Record(456L,"hello mars")); + }); + scope.inTransaction(s-> { + List all = s.findAll(Record.class, List.of(456L, 123L, 2L)); + assertEquals("hello mars",all.get(0).message); + assertEquals("hello earth",all.get(1).message); + assertNull(all.get(2)); + }); + scope.inTransaction(s-> { + List all = s.findAll(Record.class, List.of(456L, 123L), READ_ONLY); + assertEquals("hello mars",all.get(0).message); + assertEquals("hello earth",all.get(1).message); + assertTrue(s.isReadOnly(all.get(0))); + assertTrue(s.isReadOnly(all.get(1))); + }); + scope.inTransaction(s-> { + Record record = s.getReference(Record.class, 456L); + List all = s.findAll(Record.class, List.of(456L, 123L)); + assertSame(record, all.get(0)); + }); + } + @Entity + static class Record { + @Id Long id; + String message; - Record(Long id, String message) { - this.id = id; - this.message = message; - } + Record(Long id, String message) { + this.id = id; + this.message = message; + } - Record() { - } - } + Record() { + } + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/loading/multiLoad/MultiLoadTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/loading/multiLoad/MultiLoadTest.java index 45aa0a7dab..fd8bc7dace 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/loading/multiLoad/MultiLoadTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/loading/multiLoad/MultiLoadTest.java @@ -645,8 +645,8 @@ public class MultiLoadTest { assertEquals( 56, list.size() ); assertFalse( session.getPersistenceContext() - .getBatchFetchQueue() - .containsEntityKey( entityKey ) ); + .getBatchFetchQueue() + .containsEntityKey( entityKey ) ); } ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/lob/LobEntity.java b/hibernate-core/src/test/java/org/hibernate/orm/test/lob/LobEntity.java index dae0fed7ef..e5b60fa210 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/lob/LobEntity.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/lob/LobEntity.java @@ -20,27 +20,27 @@ import jakarta.persistence.Lob; @Entity public class LobEntity { public static final int BLOB_LENGTH = 100000000; - private Long id; + private Long id; - @Id - @GeneratedValue - public Long getId() { - return id; - } + @Id + @GeneratedValue + public Long getId() { + return id; + } - public void setId(Long id) { - this.id = id; - } + public void setId(Long id) { + this.id = id; + } - @Lob - @Column(length = BLOB_LENGTH) - private Blob blob; + @Lob + @Column(length = BLOB_LENGTH) + private Blob blob; - public Blob getBlob() { - return blob; - } + public Blob getBlob() { + return blob; + } - public void setBlob(Blob blob) { - this.blob = blob; - } + public void setBlob(Blob blob) { + this.blob = blob; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/lob/SerializableData.java b/hibernate-core/src/test/java/org/hibernate/orm/test/lob/SerializableData.java index 91d00ab389..f8f7cd8b04 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/lob/SerializableData.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/lob/SerializableData.java @@ -14,20 +14,20 @@ import java.io.Serializable; */ public class SerializableData implements Serializable { - private String payload; +private String payload; - public SerializableData(String payload) - { - this.payload = payload; - } - - public String getPayload() - { - return payload; - } - - public void setPayload(String payload) - { - this.payload = payload; - } +public SerializableData(String payload) +{ + this.payload = payload; +} + +public String getPayload() +{ + return payload; +} + +public void setPayload(String payload) +{ + this.payload = payload; +} } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/locking/LockModeTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/locking/LockModeTest.java index fe96b777e5..318817f496 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/locking/LockModeTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/locking/LockModeTest.java @@ -221,15 +221,15 @@ public class LockModeTest extends BaseSessionFactoryFunctionalTest { @JiraKey(value = "HHH-12257") public void testRefreshWithExplicitLowerLevelLockMode() { doInHibernate( this::sessionFactory, session -> { - A a = session.get( A.class, id, LockMode.PESSIMISTIC_READ ); - checkLockMode( a, LockMode.PESSIMISTIC_READ, session ); - session.refresh( a, LockMode.READ ); - checkLockMode( a, LockMode.PESSIMISTIC_READ, session ); - session.refresh( a, LockModeType.READ ); - checkLockMode( a, LockMode.PESSIMISTIC_READ, session ); - session.refresh( a, LockModeType.READ, Collections.emptyMap() ); - checkLockMode( a, LockMode.PESSIMISTIC_READ, session ); - } ); + A a = session.get( A.class, id, LockMode.PESSIMISTIC_READ ); + checkLockMode( a, LockMode.PESSIMISTIC_READ, session ); + session.refresh( a, LockMode.READ ); + checkLockMode( a, LockMode.PESSIMISTIC_READ, session ); + session.refresh( a, LockModeType.READ ); + checkLockMode( a, LockMode.PESSIMISTIC_READ, session ); + session.refresh( a, LockModeType.READ, Collections.emptyMap() ); + checkLockMode( a, LockMode.PESSIMISTIC_READ, session ); + } ); } @@ -238,13 +238,13 @@ public class LockModeTest extends BaseSessionFactoryFunctionalTest { @SkipForDialect( dialectClass = CockroachDialect.class ) public void testRefreshWithExplicitHigherLevelLockMode1() { doInHibernate( this::sessionFactory, session -> { - A a = session.get( A.class, id ); - checkLockMode( a, LockMode.READ, session ); - session.refresh( a, LockMode.UPGRADE_NOWAIT ); - checkLockMode( a, LockMode.UPGRADE_NOWAIT, session ); - session.refresh( a, LockModeType.PESSIMISTIC_WRITE, Collections.emptyMap() ); - checkLockMode( a, LockMode.PESSIMISTIC_WRITE, session ); - } ); + A a = session.get( A.class, id ); + checkLockMode( a, LockMode.READ, session ); + session.refresh( a, LockMode.UPGRADE_NOWAIT ); + checkLockMode( a, LockMode.UPGRADE_NOWAIT, session ); + session.refresh( a, LockModeType.PESSIMISTIC_WRITE, Collections.emptyMap() ); + checkLockMode( a, LockMode.PESSIMISTIC_WRITE, session ); + } ); } @Test diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/locking/PessimisticWriteLockTimeoutTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/locking/PessimisticWriteLockTimeoutTest.java index 910518a9e2..9081130a08 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/locking/PessimisticWriteLockTimeoutTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/locking/PessimisticWriteLockTimeoutTest.java @@ -72,7 +72,7 @@ public class PessimisticWriteLockTimeoutTest .unwrap( Query.class ) .setLockOptions( new LockOptions( LockMode.PESSIMISTIC_WRITE ) - .setTimeOut( LockOptions.NO_WAIT ) ) + .setTimeOut( LockOptions.NO_WAIT ) ) .list(); String lockingQuery = sqlStatementInterceptor.getSqlQueries().getLast(); @@ -98,7 +98,7 @@ public class PessimisticWriteLockTimeoutTest .unwrap( Query.class ) .setLockOptions( new LockOptions( LockMode.PESSIMISTIC_WRITE ) - .setTimeOut( LockOptions.SKIP_LOCKED ) ) + .setTimeOut( LockOptions.SKIP_LOCKED ) ) .list(); String lockingQuery = sqlStatementInterceptor.getSqlQueries().getLast(); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/locking/jpa/AdvancedFollowOnLockingTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/locking/jpa/AdvancedFollowOnLockingTest.java index 77107dc4f0..d09c32e02a 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/locking/jpa/AdvancedFollowOnLockingTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/locking/jpa/AdvancedFollowOnLockingTest.java @@ -62,9 +62,9 @@ public class AdvancedFollowOnLockingTest { public void testNoFollowonLockingOnGroupBy(SessionFactoryScope scope) { SQLStatementInspector statementInspector = scope.getCollectingStatementInspector(); scope.inTransaction( session -> { - final Department engineering = new Department( 1, "Engineering" ); - session.persist( engineering ); - } + final Department engineering = new Department( 1, "Engineering" ); + session.persist( engineering ); + } ); scope.inTransaction( diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/manytomany/Advertisement.java b/hibernate-core/src/test/java/org/hibernate/orm/test/manytomany/Advertisement.java index 89c77f0b8f..fd11d1df25 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/manytomany/Advertisement.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/manytomany/Advertisement.java @@ -21,28 +21,28 @@ import java.util.Set; */ @Entity public class Advertisement { - @Id - @GeneratedValue - private Integer id; + @Id + @GeneratedValue + private Integer id; - @SQLRestriction("deleted <> 'true'") - @ManyToMany(fetch = FetchType.EAGER, mappedBy = "advertisements") - @OrderBy("id asc") - private Set attachments; + @SQLRestriction("deleted <> 'true'") + @ManyToMany(fetch = FetchType.EAGER, mappedBy = "advertisements") + @OrderBy("id asc") + private Set attachments; - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public Set getAttachments() { - return attachments; - } + public Set getAttachments() { + return attachments; + } - public void setAttachments(Set attachments) { - this.attachments = attachments; - } + public void setAttachments(Set attachments) { + this.attachments = attachments; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/manytomany/Attachment.java b/hibernate-core/src/test/java/org/hibernate/orm/test/manytomany/Attachment.java index 221eddd75e..c6ca3926ee 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/manytomany/Attachment.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/manytomany/Attachment.java @@ -17,46 +17,46 @@ import java.util.Set; */ @Entity public class Attachment { - @Id - @GeneratedValue - private Integer id; + @Id + @GeneratedValue + private Integer id; - @ManyToMany - private Set advertisements; + @ManyToMany + private Set advertisements; - private String fileName; + private String fileName; - private String deleted = "false"; + private String deleted = "false"; - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public Set getAdvertisements() { - return advertisements; - } + public Set getAdvertisements() { + return advertisements; + } - public void setAdvertisements(Set advertisements) { - this.advertisements = advertisements; - } + public void setAdvertisements(Set advertisements) { + this.advertisements = advertisements; + } - public String getFileName() { - return fileName; - } + public String getFileName() { + return fileName; + } - public void setFileName(String fileName) { - this.fileName = fileName; - } + public void setFileName(String fileName) { + this.fileName = fileName; + } - public String getDeleted() { - return deleted; - } + public String getDeleted() { + return deleted; + } - public void setDeleted(String deleted) { - this.deleted = deleted; - } + public void setDeleted(String deleted) { + this.deleted = deleted; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/manytomany/PageAdvertisement.java b/hibernate-core/src/test/java/org/hibernate/orm/test/manytomany/PageAdvertisement.java index 63454d8c8d..d1563af8a6 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/manytomany/PageAdvertisement.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/manytomany/PageAdvertisement.java @@ -15,15 +15,15 @@ import jakarta.persistence.Id; */ @Entity public class PageAdvertisement extends SubjectAdvertisement { - @Id - @GeneratedValue - private Integer id; + @Id + @GeneratedValue + private Integer id; - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/manytomany/SubjectAdvertisement.java b/hibernate-core/src/test/java/org/hibernate/orm/test/manytomany/SubjectAdvertisement.java index 1656015534..7e45039f9a 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/manytomany/SubjectAdvertisement.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/manytomany/SubjectAdvertisement.java @@ -14,14 +14,14 @@ import jakarta.persistence.OneToOne; */ @MappedSuperclass public class SubjectAdvertisement { - @OneToOne - private Advertisement advertisement; + @OneToOne + private Advertisement advertisement; - public Advertisement getAdvertisement() { - return advertisement; - } + public Advertisement getAdvertisement() { + return advertisement; + } - public void setAdvertisement(Advertisement advertisement) { - this.advertisement = advertisement; - } + public void setAdvertisement(Advertisement advertisement) { + this.advertisement = advertisement; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/manytomanyassociationclass/nestedreference/Item.java b/hibernate-core/src/test/java/org/hibernate/orm/test/manytomanyassociationclass/nestedreference/Item.java index bdf68c5802..3f7c251abc 100755 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/manytomanyassociationclass/nestedreference/Item.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/manytomanyassociationclass/nestedreference/Item.java @@ -33,20 +33,20 @@ public class Item { } public String getDescription() { - return description; - } + return description; + } public void setDescription(String description) { - this.description = description; - } + this.description = description; + } public Long getId() { - return id; - } + return id; + } public void setId(Long id) { - this.id = id; - } + this.id = id; + } public long getVersion() { return version; @@ -57,12 +57,12 @@ public class Item { } public String getName() { - return name; - } + return name; + } public void setName(String name) { - this.name = name; - } + this.name = name; + } public Item getOwner() { return owner; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/EntityTableMappingsTests.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/EntityTableMappingsTests.java index 6c1514f5b2..7c5d66b4bc 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/EntityTableMappingsTests.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/EntityTableMappingsTests.java @@ -132,9 +132,9 @@ public class EntityTableMappingsTests { @Entity( name = "UnionRoot" ) @Inheritance(strategy = InheritanceType.TABLE_PER_CLASS) public static abstract class UnionRoot { - @Id - private Integer id; - @Basic + @Id + private Integer id; + @Basic private String name; private UnionRoot() { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/access/NestedEmbeddableDefaultAccessTests.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/access/NestedEmbeddableDefaultAccessTests.java index 885269d91f..7809338386 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/access/NestedEmbeddableDefaultAccessTests.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/access/NestedEmbeddableDefaultAccessTests.java @@ -79,9 +79,9 @@ public class NestedEmbeddableDefaultAccessTests { @Entity( name = "MyEntity" ) @Table( name = "MyEntity" ) public static class MyEntity { - @Id - private Integer id; - @Basic + @Id + private Integer id; + @Basic private String name; @Embedded private OuterEmbeddable outerEmbeddable; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/BlobByteArrayTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/BlobByteArrayTest.java index 7627ce3292..dff703e202 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/BlobByteArrayTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/BlobByteArrayTest.java @@ -22,71 +22,71 @@ import static org.junit.Assert.assertArrayEquals; */ public class BlobByteArrayTest extends BaseEntityManagerFunctionalTestCase { - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Product.class - }; - } + @Override + protected Class[] getAnnotatedClasses() { + return new Class[] { + Product.class + }; + } - @Test - public void test() { - Integer productId = doInJPA(this::entityManagerFactory, entityManager -> { - final Product product = new Product(); - product.setId(1); - product.setName("Mobile phone"); - product.setImage(new byte[] {1, 2, 3}); + @Test + public void test() { + Integer productId = doInJPA(this::entityManagerFactory, entityManager -> { + final Product product = new Product(); + product.setId(1); + product.setName("Mobile phone"); + product.setImage(new byte[] {1, 2, 3}); - entityManager.persist(product); - return product.getId(); - }); - doInJPA(this::entityManagerFactory, entityManager -> { - Product product = entityManager.find(Product.class, productId); + entityManager.persist(product); + return product.getId(); + }); + doInJPA(this::entityManagerFactory, entityManager -> { + Product product = entityManager.find(Product.class, productId); - assertArrayEquals(new byte[] {1, 2, 3}, product.getImage()); - }); - } + assertArrayEquals(new byte[] {1, 2, 3}, product.getImage()); + }); + } - //tag::basic-blob-byte-array-example[] - @Entity(name = "Product") - public static class Product { + //tag::basic-blob-byte-array-example[] + @Entity(name = "Product") + public static class Product { - @Id - private Integer id; + @Id + private Integer id; - private String name; + private String name; - @Lob - private byte[] image; + @Lob + private byte[] image; - //Getters and setters are omitted for brevity + //Getters and setters are omitted for brevity - //end::basic-blob-byte-array-example[] - public Integer getId() { - return id; - } + //end::basic-blob-byte-array-example[] + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - public byte[] getImage() { - return image; - } + public byte[] getImage() { + return image; + } - public void setImage(byte[] image) { - this.image = image; - } + public void setImage(byte[] image) { + this.image = image; + } - //tag::basic-blob-byte-array-example[] - } - //end::basic-blob-byte-array-example[] + //tag::basic-blob-byte-array-example[] + } + //end::basic-blob-byte-array-example[] } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/BlobTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/BlobTest.java index 63f1939305..1e308cad6a 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/BlobTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/BlobTest.java @@ -30,104 +30,104 @@ import static org.junit.Assert.fail; */ public class BlobTest extends BaseEntityManagerFunctionalTestCase { - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Product.class - }; - } + @Override + protected Class[] getAnnotatedClasses() { + return new Class[] { + Product.class + }; + } - @Test - public void test() { - Integer productId = doInJPA(this::entityManagerFactory, entityManager -> { - Session session = entityManager.unwrap(Session.class); + @Test + public void test() { + Integer productId = doInJPA(this::entityManagerFactory, entityManager -> { + Session session = entityManager.unwrap(Session.class); - //tag::basic-blob-persist-example[] - byte[] image = new byte[] {1, 2, 3}; + //tag::basic-blob-persist-example[] + byte[] image = new byte[] {1, 2, 3}; - final Product product = new Product(); - product.setId(1); - product.setName("Mobile phone"); + final Product product = new Product(); + product.setId(1); + product.setName("Mobile phone"); - product.setImage(BlobProxy.generateProxy(image)); + product.setImage(BlobProxy.generateProxy(image)); - entityManager.persist(product); - //end::basic-blob-persist-example[] + entityManager.persist(product); + //end::basic-blob-persist-example[] - return product.getId(); - }); - doInJPA(this::entityManagerFactory, entityManager -> { - try { - //tag::basic-blob-find-example[] + return product.getId(); + }); + doInJPA(this::entityManagerFactory, entityManager -> { + try { + //tag::basic-blob-find-example[] - Product product = entityManager.find(Product.class, productId); + Product product = entityManager.find(Product.class, productId); - try (InputStream inputStream = product.getImage().getBinaryStream()) { - assertArrayEquals(new byte[] {1, 2, 3}, toBytes(inputStream)); - } - //end::basic-blob-find-example[] - } - catch (Exception e) { - fail(e.getMessage()); - } - }); - } + try (InputStream inputStream = product.getImage().getBinaryStream()) { + assertArrayEquals(new byte[] {1, 2, 3}, toBytes(inputStream)); + } + //end::basic-blob-find-example[] + } + catch (Exception e) { + fail(e.getMessage()); + } + }); + } - private byte[] toBytes(InputStream inputStream) throws IOException { - BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream); - ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); + private byte[] toBytes(InputStream inputStream) throws IOException { + BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream); + ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); - int result = bufferedInputStream.read(); + int result = bufferedInputStream.read(); - while(result != -1) { - byteArrayOutputStream.write((byte) result); - result = bufferedInputStream.read(); - } + while(result != -1) { + byteArrayOutputStream.write((byte) result); + result = bufferedInputStream.read(); + } - return byteArrayOutputStream.toByteArray(); - } + return byteArrayOutputStream.toByteArray(); + } - //tag::basic-blob-example[] - @Entity(name = "Product") - public static class Product { + //tag::basic-blob-example[] + @Entity(name = "Product") + public static class Product { - @Id - private Integer id; + @Id + private Integer id; - private String name; + private String name; - @Lob - private Blob image; + @Lob + private Blob image; - //Getters and setters are omitted for brevity + //Getters and setters are omitted for brevity - //end::basic-blob-example[] - public Integer getId() { - return id; - } + //end::basic-blob-example[] + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - public Blob getImage() { - return image; - } + public Blob getImage() { + return image; + } - public void setImage(Blob image) { - this.image = image; - } + public void setImage(Blob image) { + this.image = image; + } - //tag::basic-blob-example[] - } - //end::basic-blob-example[] + //tag::basic-blob-example[] + } + //end::basic-blob-example[] } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/ClobTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/ClobTest.java index f9c09f8787..f7f68e8336 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/ClobTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/ClobTest.java @@ -30,104 +30,104 @@ import static org.junit.Assert.fail; */ public class ClobTest extends BaseEntityManagerFunctionalTestCase { - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Product.class - }; - } + @Override + protected Class[] getAnnotatedClasses() { + return new Class[] { + Product.class + }; + } - @Test - public void test() { - Integer productId = doInJPA(this::entityManagerFactory, entityManager -> { - Session session = entityManager.unwrap(Session.class); + @Test + public void test() { + Integer productId = doInJPA(this::entityManagerFactory, entityManager -> { + Session session = entityManager.unwrap(Session.class); - //tag::basic-clob-persist-example[] - String warranty = "My product warranty"; + //tag::basic-clob-persist-example[] + String warranty = "My product warranty"; - final Product product = new Product(); - product.setId(1); - product.setName("Mobile phone"); + final Product product = new Product(); + product.setId(1); + product.setName("Mobile phone"); - product.setWarranty(ClobProxy.generateProxy(warranty)); + product.setWarranty(ClobProxy.generateProxy(warranty)); - entityManager.persist(product); - //end::basic-clob-persist-example[] + entityManager.persist(product); + //end::basic-clob-persist-example[] - return product.getId(); - }); - doInJPA(this::entityManagerFactory, entityManager -> { - try { - //tag::basic-clob-find-example[] + return product.getId(); + }); + doInJPA(this::entityManagerFactory, entityManager -> { + try { + //tag::basic-clob-find-example[] - Product product = entityManager.find(Product.class, productId); + Product product = entityManager.find(Product.class, productId); - try (Reader reader = product.getWarranty().getCharacterStream()) { - assertEquals("My product warranty", toString(reader)); - } - //end::basic-clob-find-example[] - } - catch (Exception e) { - fail(e.getMessage()); - } - }); - } + try (Reader reader = product.getWarranty().getCharacterStream()) { + assertEquals("My product warranty", toString(reader)); + } + //end::basic-clob-find-example[] + } + catch (Exception e) { + fail(e.getMessage()); + } + }); + } - private String toString(Reader reader) throws IOException { - BufferedReader bufferedReader = new BufferedReader(reader); - ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); + private String toString(Reader reader) throws IOException { + BufferedReader bufferedReader = new BufferedReader(reader); + ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); - int result = bufferedReader.read(); + int result = bufferedReader.read(); - while(result != -1) { - byteArrayOutputStream.write((byte) result); - result = bufferedReader.read(); - } + while(result != -1) { + byteArrayOutputStream.write((byte) result); + result = bufferedReader.read(); + } - return byteArrayOutputStream.toString(); - } + return byteArrayOutputStream.toString(); + } - //tag::basic-clob-example[] - @Entity(name = "Product") - public static class Product { + //tag::basic-clob-example[] + @Entity(name = "Product") + public static class Product { - @Id - private Integer id; + @Id + private Integer id; - private String name; + private String name; - @Lob - private Clob warranty; + @Lob + private Clob warranty; - //Getters and setters are omitted for brevity + //Getters and setters are omitted for brevity - //end::basic-clob-example[] - public Integer getId() { - return id; - } + //end::basic-clob-example[] + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - public Clob getWarranty() { - return warranty; - } + public Clob getWarranty() { + return warranty; + } - public void setWarranty(Clob warranty) { - this.warranty = warranty; - } + public void setWarranty(Clob warranty) { + this.warranty = warranty; + } - //tag::basic-clob-example[] - } - //end::basic-clob-example[] + //tag::basic-clob-example[] + } + //end::basic-clob-example[] } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/CurrencyMappingTests.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/CurrencyMappingTests.java index b36b43de14..fd437f7418 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/CurrencyMappingTests.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/CurrencyMappingTests.java @@ -193,7 +193,7 @@ public class CurrencyMappingTests { @ElementCollection private Set currencies; - public EntityWithCurrency() { + public EntityWithCurrency() { // } @@ -201,7 +201,7 @@ public class CurrencyMappingTests { this.id = id; this.currency = currency; this.currencies = currencies; - } + } } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/Gender.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/Gender.java index 929e71ee0c..8a0510ac20 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/Gender.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/Gender.java @@ -12,29 +12,29 @@ package org.hibernate.orm.test.mapping.basic; //tag::basic-enums-converter-example[] public enum Gender { - MALE('M'), - FEMALE('F'); + MALE('M'), + FEMALE('F'); - private final char code; + private final char code; - Gender(char code) { - this.code = code; - } + Gender(char code) { + this.code = code; + } - public static Gender fromCode(char code) { - if (code == 'M' || code == 'm') { - return MALE; - } - if (code == 'F' || code == 'f') { - return FEMALE; - } - throw new UnsupportedOperationException( - "The code " + code + " is not supported!" - ); - } + public static Gender fromCode(char code) { + if (code == 'M' || code == 'm') { + return MALE; + } + if (code == 'F' || code == 'f') { + return FEMALE; + } + throw new UnsupportedOperationException( + "The code " + code + " is not supported!" + ); + } - public char getCode() { - return code; - } + public char getCode() { + return code; + } } //end::basic-enums-converter-example[] diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/GenderJavaType.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/GenderJavaType.java index 65bfac56ad..d66cc15901 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/GenderJavaType.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/GenderJavaType.java @@ -16,33 +16,33 @@ import org.hibernate.type.descriptor.java.CharacterJavaType; //tag::basic-enums-custom-type-example[] public class GenderJavaType extends AbstractClassJavaType { - public static final GenderJavaType INSTANCE = - new GenderJavaType(); + public static final GenderJavaType INSTANCE = + new GenderJavaType(); - protected GenderJavaType() { - super(Gender.class); - } + protected GenderJavaType() { + super(Gender.class); + } - public String toString(Gender value) { - return value == null ? null : value.name(); - } + public String toString(Gender value) { + return value == null ? null : value.name(); + } - public Gender fromString(CharSequence string) { - return string == null ? null : Gender.valueOf(string.toString()); - } + public Gender fromString(CharSequence string) { + return string == null ? null : Gender.valueOf(string.toString()); + } - public X unwrap(Gender value, Class type, WrapperOptions options) { - return CharacterJavaType.INSTANCE.unwrap( - value == null ? null : value.getCode(), - type, - options - ); - } + public X unwrap(Gender value, Class type, WrapperOptions options) { + return CharacterJavaType.INSTANCE.unwrap( + value == null ? null : value.getCode(), + type, + options + ); + } - public Gender wrap(X value, WrapperOptions options) { - return Gender.fromCode( + public Gender wrap(X value, WrapperOptions options) { + return Gender.fromCode( CharacterJavaType.INSTANCE.wrap( value, options) - ); - } + ); + } } //end::basic-enums-custom-type-example[] diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/GenderType.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/GenderType.java index 96718d6845..08e6a8b8e7 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/GenderType.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/GenderType.java @@ -15,8 +15,8 @@ import org.hibernate.usertype.UserTypeSupport; */ //tag::basic-enums-custom-type-example[] public class GenderType extends UserTypeSupport { - public GenderType() { - super(Gender.class, Types.CHAR); - } + public GenderType() { + super(Gender.class, Types.CHAR); + } } //end::basic-enums-custom-type-example[] diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/NClobCharArrayTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/NClobCharArrayTest.java index ff2e40b8dd..35668b9a8f 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/NClobCharArrayTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/NClobCharArrayTest.java @@ -23,72 +23,72 @@ import static org.junit.Assert.assertArrayEquals; */ public class NClobCharArrayTest extends BaseEntityManagerFunctionalTestCase { - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Product.class - }; - } + @Override + protected Class[] getAnnotatedClasses() { + return new Class[] { + Product.class + }; + } - @Test - public void test() { - Integer productId = doInJPA(this::entityManagerFactory, entityManager -> { - final Product product = new Product(); - product.setId(1); - product.setName("Mobile phone"); - product.setWarranty("My product warranty".toCharArray()); + @Test + public void test() { + Integer productId = doInJPA(this::entityManagerFactory, entityManager -> { + final Product product = new Product(); + product.setId(1); + product.setName("Mobile phone"); + product.setWarranty("My product warranty".toCharArray()); - entityManager.persist(product); - return product.getId(); - }); - doInJPA(this::entityManagerFactory, entityManager -> { - Product product = entityManager.find(Product.class, productId); + entityManager.persist(product); + return product.getId(); + }); + doInJPA(this::entityManagerFactory, entityManager -> { + Product product = entityManager.find(Product.class, productId); - assertArrayEquals("My product warranty".toCharArray(), product.getWarranty()); - }); - } + assertArrayEquals("My product warranty".toCharArray(), product.getWarranty()); + }); + } - //tag::basic-nclob-char-array-example[] - @Entity(name = "Product") - public static class Product { + //tag::basic-nclob-char-array-example[] + @Entity(name = "Product") + public static class Product { - @Id - private Integer id; + @Id + private Integer id; - private String name; + private String name; - @Lob - @Nationalized - private char[] warranty; + @Lob + @Nationalized + private char[] warranty; - //Getters and setters are omitted for brevity + //Getters and setters are omitted for brevity - //end::basic-nclob-char-array-example[] - public Integer getId() { - return id; - } + //end::basic-nclob-char-array-example[] + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - public char[] getWarranty() { - return warranty; - } + public char[] getWarranty() { + return warranty; + } - public void setWarranty(char[] warranty) { - this.warranty = warranty; - } + public void setWarranty(char[] warranty) { + this.warranty = warranty; + } - //tag::basic-nclob-char-array-example[] - } - //end::basic-nclob-char-array-example[] + //tag::basic-nclob-char-array-example[] + } + //end::basic-nclob-char-array-example[] } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/NClobStringTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/NClobStringTest.java index f55385f695..88a4084295 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/NClobStringTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/NClobStringTest.java @@ -23,72 +23,72 @@ import static org.junit.Assert.assertEquals; */ public class NClobStringTest extends BaseEntityManagerFunctionalTestCase { - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Product.class - }; - } + @Override + protected Class[] getAnnotatedClasses() { + return new Class[] { + Product.class + }; + } - @Test - public void test() { - Integer productId = doInJPA(this::entityManagerFactory, entityManager -> { - final Product product = new Product(); - product.setId(1); - product.setName("Mobile phone"); - product.setWarranty("My product warranty"); + @Test + public void test() { + Integer productId = doInJPA(this::entityManagerFactory, entityManager -> { + final Product product = new Product(); + product.setId(1); + product.setName("Mobile phone"); + product.setWarranty("My product warranty"); - entityManager.persist(product); - return product.getId(); - }); - doInJPA(this::entityManagerFactory, entityManager -> { - Product product = entityManager.find(Product.class, productId); + entityManager.persist(product); + return product.getId(); + }); + doInJPA(this::entityManagerFactory, entityManager -> { + Product product = entityManager.find(Product.class, productId); - assertEquals("My product warranty", product.getWarranty()); - }); - } + assertEquals("My product warranty", product.getWarranty()); + }); + } - //tag::basic-nclob-string-example[] - @Entity(name = "Product") - public static class Product { + //tag::basic-nclob-string-example[] + @Entity(name = "Product") + public static class Product { - @Id - private Integer id; + @Id + private Integer id; - private String name; + private String name; - @Lob - @Nationalized - private String warranty; + @Lob + @Nationalized + private String warranty; - //Getters and setters are omitted for brevity + //Getters and setters are omitted for brevity - //end::basic-nclob-string-example[] - public Integer getId() { - return id; - } + //end::basic-nclob-string-example[] + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - public String getWarranty() { - return warranty; - } + public String getWarranty() { + return warranty; + } - public void setWarranty(String warranty) { - this.warranty = warranty; - } + public void setWarranty(String warranty) { + this.warranty = warranty; + } - //tag::basic-nclob-string-example[] - } - //end::basic-nclob-string-example[] + //tag::basic-nclob-string-example[] + } + //end::basic-nclob-string-example[] } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/NClobTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/NClobTest.java index 7fabfc5b13..9db0dbc534 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/NClobTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/NClobTest.java @@ -32,106 +32,106 @@ import static org.junit.Assert.fail; */ @Jpa(annotatedClasses = NClobTest.Product.class) @RequiresDialectFeature( - feature = DialectFeatureChecks.SupportsNationalizedDataTypes.class, - comment = "This is different from other tests checking generalized nationalization support; " + - "because we explicitly map this attribute to the `NClob` java type the database really" + - " has to support those types" + feature = DialectFeatureChecks.SupportsNationalizedDataTypes.class, + comment = "This is different from other tests checking generalized nationalization support; " + + "because we explicitly map this attribute to the `NClob` java type the database really" + + " has to support those types" ) public class NClobTest { - @Test - public void test(EntityManagerFactoryScope scope) { - scope.inTransaction( - (entityManager) -> { - //tag::basic-nclob-persist-example[] - String warranty = "My product warranty"; + @Test + public void test(EntityManagerFactoryScope scope) { + scope.inTransaction( + (entityManager) -> { + //tag::basic-nclob-persist-example[] + String warranty = "My product warranty"; - final Product product = new Product(); - product.setId(1); - product.setName("Mobile phone"); + final Product product = new Product(); + product.setId(1); + product.setName("Mobile phone"); - product.setWarranty(NClobProxy.generateProxy(warranty)); + product.setWarranty(NClobProxy.generateProxy(warranty)); - entityManager.persist(product); - //end::basic-nclob-persist-example[] - } - ); + entityManager.persist(product); + //end::basic-nclob-persist-example[] + } + ); - scope.inTransaction( - (entityManager) -> { - try { - //tag::basic-nclob-find-example[] - Product product = entityManager.find(Product.class, 1); + scope.inTransaction( + (entityManager) -> { + try { + //tag::basic-nclob-find-example[] + Product product = entityManager.find(Product.class, 1); - try (Reader reader = product.getWarranty().getCharacterStream()) { - assertEquals("My product warranty", toString(reader)); - } - //end::basic-nclob-find-example[] - } - catch (Exception e) { - fail(e.getMessage()); - } - } - ); - } + try (Reader reader = product.getWarranty().getCharacterStream()) { + assertEquals("My product warranty", toString(reader)); + } + //end::basic-nclob-find-example[] + } + catch (Exception e) { + fail(e.getMessage()); + } + } + ); + } - private String toString(Reader reader) throws IOException { - BufferedReader bufferedReader = new BufferedReader(reader); - ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); + private String toString(Reader reader) throws IOException { + BufferedReader bufferedReader = new BufferedReader(reader); + ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); - int result = bufferedReader.read(); + int result = bufferedReader.read(); - while (result != -1) { - byteArrayOutputStream.write((byte) result); - result = bufferedReader.read(); - } + while (result != -1) { + byteArrayOutputStream.write((byte) result); + result = bufferedReader.read(); + } - return byteArrayOutputStream.toString(); - } + return byteArrayOutputStream.toString(); + } - //tag::basic-nclob-example[] - @Entity(name = "Product") - public static class Product { + //tag::basic-nclob-example[] + @Entity(name = "Product") + public static class Product { - @Id - private Integer id; + @Id + private Integer id; - private String name; + private String name; - @Lob - @Nationalized - // Clob also works, because NClob extends Clob. - // The database type is still NCLOB either way and handled as such. - private NClob warranty; + @Lob + @Nationalized + // Clob also works, because NClob extends Clob. + // The database type is still NCLOB either way and handled as such. + private NClob warranty; - //Getters and setters are omitted for brevity + //Getters and setters are omitted for brevity - //end::basic-nclob-example[] - public Integer getId() { - return id; - } + //end::basic-nclob-example[] + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - public NClob getWarranty() { - return warranty; - } + public NClob getWarranty() { + return warranty; + } - public void setWarranty(NClob warranty) { - this.warranty = warranty; - } + public void setWarranty(NClob warranty) { + this.warranty = warranty; + } - //tag::basic-nclob-example[] - } - //end::basic-nclob-example[] + //tag::basic-nclob-example[] + } + //end::basic-nclob-example[] } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/NationalizedTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/NationalizedTest.java index 62db6f631a..476485aebb 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/NationalizedTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/NationalizedTest.java @@ -23,77 +23,77 @@ import static org.junit.Assert.assertEquals; * @author Vlad Mihalcea */ @SkipForDialect(dialectClass = SybaseASEDialect.class, - reason = "Error converting characters into server's character set") + reason = "Error converting characters into server's character set") public class NationalizedTest extends BaseEntityManagerFunctionalTestCase { - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Product.class - }; - } + @Override + protected Class[] getAnnotatedClasses() { + return new Class[] { + Product.class + }; + } - @Test - public void test() { - Integer productId = doInJPA(this::entityManagerFactory, entityManager -> { - //tag::basic-nationalized-persist-example[] - final Product product = new Product(); - product.setId(1); - product.setName("Mobile phone"); - product.setWarranty("My product®™ warranty 😍"); + @Test + public void test() { + Integer productId = doInJPA(this::entityManagerFactory, entityManager -> { + //tag::basic-nationalized-persist-example[] + final Product product = new Product(); + product.setId(1); + product.setName("Mobile phone"); + product.setWarranty("My product®™ warranty 😍"); - entityManager.persist(product); - //end::basic-nationalized-persist-example[] + entityManager.persist(product); + //end::basic-nationalized-persist-example[] - return product.getId(); - }); - doInJPA(this::entityManagerFactory, entityManager -> { - Product product = entityManager.find(Product.class, productId); + return product.getId(); + }); + doInJPA(this::entityManagerFactory, entityManager -> { + Product product = entityManager.find(Product.class, productId); - assertEquals("My product®™ warranty 😍", product.getWarranty()); - }); - } + assertEquals("My product®™ warranty 😍", product.getWarranty()); + }); + } - //tag::basic-nationalized-example[] - @Entity(name = "Product") - public static class Product { + //tag::basic-nationalized-example[] + @Entity(name = "Product") + public static class Product { - @Id - private Integer id; + @Id + private Integer id; - private String name; + private String name; - @Nationalized - private String warranty; + @Nationalized + private String warranty; - //Getters and setters are omitted for brevity + //Getters and setters are omitted for brevity - //end::basic-nationalized-example[] - public Integer getId() { - return id; - } + //end::basic-nationalized-example[] + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - public String getWarranty() { - return warranty; - } + public String getWarranty() { + return warranty; + } - public void setWarranty(String warranty) { - this.warranty = warranty; - } + public void setWarranty(String warranty) { + this.warranty = warranty; + } - //tag::basic-nationalized-example[] - } - //end::basic-nationalized-example[] + //tag::basic-nationalized-example[] + } + //end::basic-nationalized-example[] } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/bitset/BitSetJavaType.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/bitset/BitSetJavaType.java index a743c42ba9..f109c769a8 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/bitset/BitSetJavaType.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/bitset/BitSetJavaType.java @@ -20,65 +20,65 @@ import org.hibernate.type.descriptor.jdbc.JdbcTypeIndicators; */ //tag::basic-bitset-example-java-type[] public class BitSetJavaType extends AbstractClassJavaType { - public static final BitSetJavaType INSTANCE = new BitSetJavaType(); + public static final BitSetJavaType INSTANCE = new BitSetJavaType(); - public BitSetJavaType() { - super(BitSet.class); - } + public BitSetJavaType() { + super(BitSet.class); + } - @Override - public MutabilityPlan getMutabilityPlan() { - return BitSetMutabilityPlan.INSTANCE; - } + @Override + public MutabilityPlan getMutabilityPlan() { + return BitSetMutabilityPlan.INSTANCE; + } - @Override - public JdbcType getRecommendedJdbcType(JdbcTypeIndicators indicators) { - return indicators.getTypeConfiguration() - .getJdbcTypeRegistry() - .getDescriptor(Types.VARCHAR); - } + @Override + public JdbcType getRecommendedJdbcType(JdbcTypeIndicators indicators) { + return indicators.getTypeConfiguration() + .getJdbcTypeRegistry() + .getDescriptor(Types.VARCHAR); + } - @Override - public String toString(BitSet value) { - return BitSetHelper.bitSetToString(value); - } + @Override + public String toString(BitSet value) { + return BitSetHelper.bitSetToString(value); + } - @Override - public BitSet fromString(CharSequence string) { - return BitSetHelper.stringToBitSet(string.toString()); - } + @Override + public BitSet fromString(CharSequence string) { + return BitSetHelper.stringToBitSet(string.toString()); + } - @SuppressWarnings("unchecked") - public X unwrap(BitSet value, Class type, WrapperOptions options) { - if (value == null) { - return null; - } - if (BitSet.class.isAssignableFrom(type)) { - return (X) value; - } - if (String.class.isAssignableFrom(type)) { - return (X) toString(value); - } - if (type.isArray()) { - if (type.getComponentType() == byte.class) { - return (X) value.toByteArray(); - } - } - throw unknownUnwrap(type); - } + @SuppressWarnings("unchecked") + public X unwrap(BitSet value, Class type, WrapperOptions options) { + if (value == null) { + return null; + } + if (BitSet.class.isAssignableFrom(type)) { + return (X) value; + } + if (String.class.isAssignableFrom(type)) { + return (X) toString(value); + } + if (type.isArray()) { + if (type.getComponentType() == byte.class) { + return (X) value.toByteArray(); + } + } + throw unknownUnwrap(type); + } - public BitSet wrap(X value, WrapperOptions options) { - if (value == null) { - return null; - } - if (value instanceof CharSequence) { - return fromString((CharSequence) value); - } - if (value instanceof BitSet) { - return (BitSet) value; - } - throw unknownWrap(value.getClass()); - } + public BitSet wrap(X value, WrapperOptions options) { + if (value == null) { + return null; + } + if (value instanceof CharSequence) { + return fromString((CharSequence) value); + } + if (value instanceof BitSet) { + return (BitSet) value; + } + throw unknownWrap(value.getClass()); + } } //end::basic-bitset-example-java-type[] diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/bitset/BitSetType.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/bitset/BitSetType.java index 18dbfc9ee1..3d13eb436f 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/bitset/BitSetType.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/bitset/BitSetType.java @@ -16,18 +16,18 @@ import org.hibernate.type.descriptor.jdbc.VarcharJdbcType; */ //tag::basic-custom-type-BitSetType-example[] public class BitSetType - extends AbstractSingleColumnStandardBasicType { + extends AbstractSingleColumnStandardBasicType { - public static final BitSetType INSTANCE = new BitSetType(); + public static final BitSetType INSTANCE = new BitSetType(); - public BitSetType() { - super( VarcharJdbcType.INSTANCE, BitSetJavaType.INSTANCE ); - } + public BitSetType() { + super( VarcharJdbcType.INSTANCE, BitSetJavaType.INSTANCE ); + } - @Override - public String getName() { - return "bitset"; - } + @Override + public String getName() { + return "bitset"; + } } //end::basic-custom-type-BitSetType-example[] diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/bitset/BitSetUserType.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/bitset/BitSetUserType.java index 7057889df3..499504abea 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/bitset/BitSetUserType.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/bitset/BitSetUserType.java @@ -25,74 +25,74 @@ import org.jboss.logging.Logger; //tag::basic-custom-type-BitSetUserType-example[] public class BitSetUserType implements UserType { - private static final Logger log = Logger.getLogger(BitSetUserType.class); + private static final Logger log = Logger.getLogger(BitSetUserType.class); - @Override - public int getSqlType() { - return Types.VARCHAR; - } + @Override + public int getSqlType() { + return Types.VARCHAR; + } - @Override - public Class returnedClass() { - return BitSet.class; - } + @Override + public Class returnedClass() { + return BitSet.class; + } - @Override - public boolean equals(BitSet x, BitSet y) { - return Objects.equals(x, y); - } + @Override + public boolean equals(BitSet x, BitSet y) { + return Objects.equals(x, y); + } - @Override - public int hashCode(BitSet x) { - return Objects.hashCode(x); - } + @Override + public int hashCode(BitSet x) { + return Objects.hashCode(x); + } - @Override - public BitSet nullSafeGet(ResultSet rs, int position, - SharedSessionContractImplementor session) - throws SQLException { - String columnValue = rs.getString(position); - if (rs.wasNull()) { - columnValue = null; - } + @Override + public BitSet nullSafeGet(ResultSet rs, int position, + SharedSessionContractImplementor session) + throws SQLException { + String columnValue = rs.getString(position); + if (rs.wasNull()) { + columnValue = null; + } - log.debugv("Result set column {0} value is {1}", position, columnValue); - return BitSetHelper.stringToBitSet(columnValue); - } + log.debugv("Result set column {0} value is {1}", position, columnValue); + return BitSetHelper.stringToBitSet(columnValue); + } - @Override - public void nullSafeSet(PreparedStatement st, BitSet value, int index, - SharedSessionContractImplementor session) - throws SQLException { - if (value == null) { - log.debugv("Binding null to parameter {0} ",index); - st.setNull(index, Types.VARCHAR); - } - else { - String stringValue = BitSetHelper.bitSetToString(value); - log.debugv("Binding {0} to parameter {1} ", stringValue, index); - st.setString(index, stringValue); - } - } + @Override + public void nullSafeSet(PreparedStatement st, BitSet value, int index, + SharedSessionContractImplementor session) + throws SQLException { + if (value == null) { + log.debugv("Binding null to parameter {0} ",index); + st.setNull(index, Types.VARCHAR); + } + else { + String stringValue = BitSetHelper.bitSetToString(value); + log.debugv("Binding {0} to parameter {1} ", stringValue, index); + st.setString(index, stringValue); + } + } - @Override - public BitSet deepCopy(BitSet bitSet) { - return bitSet == null ? null : (BitSet) bitSet.clone(); - } + @Override + public BitSet deepCopy(BitSet bitSet) { + return bitSet == null ? null : (BitSet) bitSet.clone(); + } - @Override - public boolean isMutable() { - return true; - } + @Override + public boolean isMutable() { + return true; + } - @Override - public Serializable disassemble(BitSet value) { - return deepCopy(value); - } + @Override + public Serializable disassemble(BitSet value) { + return deepCopy(value); + } - @Override - public BitSet assemble(Serializable cached, Object owner) { - return deepCopy((BitSet) cached); - } + @Override + public BitSet assemble(Serializable cached, Object owner) { + return deepCopy((BitSet) cached); + } } //end::basic-custom-type-BitSetUserType-example[] diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/cascade/PersistOnLazyCollectionTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/cascade/PersistOnLazyCollectionTest.java index 881486d127..ffa949d79c 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/cascade/PersistOnLazyCollectionTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/cascade/PersistOnLazyCollectionTest.java @@ -108,8 +108,8 @@ public class PersistOnLazyCollectionTest { // load invoice, invoiceLines should not be loaded Invoice invoice = session.get( Invoice.class, _invoice.getId() ); assertEquals( 1, - stats.getEntityCount(), - "Invoice lines should not be initialized while loading the invoice, because of the lazy association." + stats.getEntityCount(), + "Invoice lines should not be initialized while loading the invoice, because of the lazy association." ); Receipt receipt = new Receipt( RECEIPT_A ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/ImplicitListAsBagSemanticsTests.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/ImplicitListAsBagSemanticsTests.java index fdc4845a2c..91a3ea66b2 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/ImplicitListAsBagSemanticsTests.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/ImplicitListAsBagSemanticsTests.java @@ -69,9 +69,9 @@ public class ImplicitListAsBagSemanticsTests { @Entity( name = "AnEntity" ) @Table( name = "t_entity" ) public static class AnEntity { - @Id - private Integer id; - @Basic + @Id + private Integer id; + @Basic private String name; @ElementCollection diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/ImplicitListAsListSemanticsTests.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/ImplicitListAsListSemanticsTests.java index e49cb1a8b6..9307ff49fd 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/ImplicitListAsListSemanticsTests.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/ImplicitListAsListSemanticsTests.java @@ -60,9 +60,9 @@ public class ImplicitListAsListSemanticsTests { @Entity( name = "AnEntity" ) @Table( name = "t_entity" ) public static class AnEntity { - @Id - private Integer id; - @Basic + @Id + private Integer id; + @Basic private String name; @ElementCollection diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/ImplicitListDefaultSemanticsTests.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/ImplicitListDefaultSemanticsTests.java index 531f56d2b3..305baf5a07 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/ImplicitListDefaultSemanticsTests.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/ImplicitListDefaultSemanticsTests.java @@ -66,9 +66,9 @@ public class ImplicitListDefaultSemanticsTests { @Entity( name = "AnEntity" ) @Table( name = "t_entity" ) public static class AnEntity { - @Id - private Integer id; - @Basic + @Id + private Integer id; + @Basic private String name; @ElementCollection diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/SortAndOrderTests.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/SortAndOrderTests.java index 2973bd5776..9508c5b405 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/SortAndOrderTests.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/SortAndOrderTests.java @@ -53,10 +53,10 @@ public class SortAndOrderTests { @Entity( name = "AnEntity" ) @Table( name = "t_entity" ) public static class AnEntity { - @Id - private Integer id; - @Basic - private String name; + @Id + private Integer id; + @Basic + private String name; @ElementCollection @SortNatural diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/asbasic/CommaDelimitedStringsConverterTests.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/asbasic/CommaDelimitedStringsConverterTests.java index d60db8197a..0e0db647b7 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/asbasic/CommaDelimitedStringsConverterTests.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/asbasic/CommaDelimitedStringsConverterTests.java @@ -84,9 +84,9 @@ public class CommaDelimitedStringsConverterTests { //tag::ex-csv-converter-model[] @Entity( name = "Person" ) public static class Person { - @Id - private Integer id; - @Basic + @Id + private Integer id; + @Basic private String name; @Basic @Convert( converter = CommaDelimitedStringsConverter.class ) diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/custom/parameterized/DefaultableList.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/custom/parameterized/DefaultableList.java index fbe5ed9d1a..b5e2b923a4 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/custom/parameterized/DefaultableList.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/custom/parameterized/DefaultableList.java @@ -15,5 +15,5 @@ import java.util.List; * @author Steve Ebersole */ public interface DefaultableList extends List { - public String getDefaultValue(); + public String getDefaultValue(); } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/custom/parameterized/DefaultableListImpl.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/custom/parameterized/DefaultableListImpl.java index ecf9622c4d..21de20eefd 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/custom/parameterized/DefaultableListImpl.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/custom/parameterized/DefaultableListImpl.java @@ -15,7 +15,7 @@ import java.util.ArrayList; * @author Steve Ebersole */ public class DefaultableListImpl extends ArrayList implements DefaultableList { - private String defaultValue; + private String defaultValue; public DefaultableListImpl() { } @@ -25,10 +25,10 @@ public class DefaultableListImpl extends ArrayList implements DefaultableList { } public String getDefaultValue() { - return defaultValue; - } + return defaultValue; + } - public void setDefaultValue(String defaultValue) { - this.defaultValue = defaultValue; - } + public void setDefaultValue(String defaultValue) { + this.defaultValue = defaultValue; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/custom/parameterized/DefaultableListType.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/custom/parameterized/DefaultableListType.java index e8f52e3cd4..4759ecdbb9 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/custom/parameterized/DefaultableListType.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/custom/parameterized/DefaultableListType.java @@ -26,7 +26,7 @@ import org.hibernate.usertype.UserCollectionType; * @author Steve Ebersole */ public class DefaultableListType implements UserCollectionType, ParameterizedType { - private String defaultValue; + private String defaultValue; @Override public CollectionClassification getClassification() { @@ -88,6 +88,6 @@ public class DefaultableListType implements UserCollectionType, ParameterizedTyp @Override public void setParameterValues(Properties parameters) { - defaultValue = parameters.getProperty( "default" ); + defaultValue = parameters.getProperty( "default" ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/custom/parameterized/ParameterizedUserCollectionTypeTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/custom/parameterized/ParameterizedUserCollectionTypeTest.java index 73096e49a0..c3b93fa8e4 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/custom/parameterized/ParameterizedUserCollectionTypeTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/custom/parameterized/ParameterizedUserCollectionTypeTest.java @@ -39,7 +39,7 @@ public abstract class ParameterizedUserCollectionTypeTest extends BaseCoreFuncti entity = s.get( Entity.class, "tester" ); assertTrue( Hibernate.isInitialized( entity.getValues() ) ); assertEquals( 1, entity.getValues().size() ); - assertEquals( "Hello", ( ( DefaultableList ) entity.getValues() ).getDefaultValue() ); + assertEquals( "Hello", ( ( DefaultableList ) entity.getValues() ).getDefaultValue() ); s.remove( entity ); t.commit(); s.close(); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/type/PersistentQueue.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/type/PersistentQueue.java index 3d17c5133f..0fc8a331eb 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/type/PersistentQueue.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/type/PersistentQueue.java @@ -16,43 +16,43 @@ import org.hibernate.engine.spi.SharedSessionContractImplementor; //tag::collections-custom-collection-mapping-example[] public class PersistentQueue extends PersistentBag implements Queue { - public PersistentQueue(SharedSessionContractImplementor session) { - super(session); - } + public PersistentQueue(SharedSessionContractImplementor session) { + super(session); + } - public PersistentQueue(SharedSessionContractImplementor session, List list) { - super(session, list); - } + public PersistentQueue(SharedSessionContractImplementor session, List list) { + super(session, list); + } - @Override - public boolean offer(Object o) { - return add(o); - } + @Override + public boolean offer(Object o) { + return add(o); + } - @Override - public Object remove() { - return poll(); - } + @Override + public Object remove() { + return poll(); + } - @Override - public Object poll() { - int size = size(); - if(size > 0) { - Object first = get(0); - remove(0); - return first; - } - throw new NoSuchElementException(); - } + @Override + public Object poll() { + int size = size(); + if(size > 0) { + Object first = get(0); + remove(0); + return first; + } + throw new NoSuchElementException(); + } - @Override - public Object element() { - return peek(); - } + @Override + public Object element() { + return peek(); + } - @Override - public Object peek() { - return size() > 0 ? get(0) : null; - } + @Override + public Object peek() { + return size() > 0 ? get(0) : null; + } } //end::collections-custom-collection-mapping-example[] diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/type/QueueType.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/type/QueueType.java index d5981daaa4..d1ffe701d9 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/type/QueueType.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/type/QueueType.java @@ -21,65 +21,65 @@ import org.hibernate.usertype.UserCollectionType; //tag::collections-custom-collection-mapping-example[] public class QueueType implements UserCollectionType { - @Override - public CollectionClassification getClassification() { - return CollectionClassification.BAG; - } + @Override + public CollectionClassification getClassification() { + return CollectionClassification.BAG; + } - @Override - public Class getCollectionClass() { - return Queue.class; - } + @Override + public Class getCollectionClass() { + return Queue.class; + } - @Override - public PersistentCollection instantiate( - SharedSessionContractImplementor session, - CollectionPersister persister) throws HibernateException { - return new PersistentQueue(session); - } + @Override + public PersistentCollection instantiate( + SharedSessionContractImplementor session, + CollectionPersister persister) throws HibernateException { + return new PersistentQueue(session); + } - @Override - public PersistentCollection wrap( - SharedSessionContractImplementor session, - Object collection) { - return new PersistentQueue(session, (List) collection); - } + @Override + public PersistentCollection wrap( + SharedSessionContractImplementor session, + Object collection) { + return new PersistentQueue(session, (List) collection); + } - @Override - public Iterator getElementsIterator(Object collection) { - return ((Queue) collection).iterator(); - } + @Override + public Iterator getElementsIterator(Object collection) { + return ((Queue) collection).iterator(); + } - @Override - public boolean contains(Object collection, Object entity) { - return ((Queue) collection).contains(entity); - } + @Override + public boolean contains(Object collection, Object entity) { + return ((Queue) collection).contains(entity); + } - @Override - public Object indexOf(Object collection, Object entity) { - int i = ((List) collection).indexOf(entity); - return (i < 0) ? null : i; - } + @Override + public Object indexOf(Object collection, Object entity) { + int i = ((List) collection).indexOf(entity); + return (i < 0) ? null : i; + } - @Override - public Object replaceElements( - Object original, - Object target, - CollectionPersister persister, - Object owner, - Map copyCache, - SharedSessionContractImplementor session) - throws HibernateException { - Queue result = (Queue) target; - result.clear(); - result.addAll((Queue) original); - return result; - } + @Override + public Object replaceElements( + Object original, + Object target, + CollectionPersister persister, + Object owner, + Map copyCache, + SharedSessionContractImplementor session) + throws HibernateException { + Queue result = (Queue) target; + result.clear(); + result.addAll((Queue) original); + return result; + } - @Override - public Object instantiate(int anticipatedSize) { - return new LinkedList<>(); - } + @Override + public Object instantiate(int anticipatedSize) { + return new LinkedList<>(); + } } //end::collections-custom-collection-mapping-example[] diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/BasicJodaTimeConversionTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/BasicJodaTimeConversionTest.java index 08495b5fbe..d90239badd 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/BasicJodaTimeConversionTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/BasicJodaTimeConversionTest.java @@ -76,7 +76,7 @@ public class BasicJodaTimeConversionTest extends BaseNonConfigCoreFunctionalTest @Test public void testSimpleConvertUsage() throws MalformedURLException { - final EntityPersister ep = sessionFactory().getMappingMetamodel().getEntityDescriptor(TheEntity.class.getName()); + final EntityPersister ep = sessionFactory().getMappingMetamodel().getEntityDescriptor(TheEntity.class.getName()); final Type theDatePropertyType = ep.getPropertyType( "theDate" ); final ConvertedBasicTypeImpl type = assertTyping( ConvertedBasicTypeImpl.class, theDatePropertyType ); final JpaAttributeConverter converter = (JpaAttributeConverter) type.getValueConverter(); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/DirtyCheckingTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/DirtyCheckingTest.java index 6ad3cc3178..2aa52d181b 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/DirtyCheckingTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/DirtyCheckingTest.java @@ -115,7 +115,7 @@ public class DirtyCheckingTest extends BaseNonConfigCoreFunctionalTestCase { @Test public void checkConverterMutabilityPlans() { - final EntityPersister persister = sessionFactory().getMappingMetamodel().getEntityDescriptor(SomeEntity.class.getName()); + final EntityPersister persister = sessionFactory().getMappingMetamodel().getEntityDescriptor(SomeEntity.class.getName()); final AttributeMapping numberMapping = persister.findAttributeMapping( "number" ); final AttributeMapping nameMapping = persister.findAttributeMapping( "name" ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/ExplicitDateConvertersTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/ExplicitDateConvertersTest.java index 1c2a73d6a8..dff9da38c2 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/ExplicitDateConvertersTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/ExplicitDateConvertersTest.java @@ -81,7 +81,7 @@ public class ExplicitDateConvertersTest extends BaseNonConfigCoreFunctionalTestC @Test public void testSimpleConvertUsage() throws MalformedURLException { - final EntityPersister ep = sessionFactory().getMappingMetamodel().getEntityDescriptor(Entity1.class.getName()); + final EntityPersister ep = sessionFactory().getMappingMetamodel().getEntityDescriptor(Entity1.class.getName()); final Type theDatePropertyType = ep.getPropertyType( "theDate" ); final ConvertedBasicTypeImpl type = assertTyping( ConvertedBasicTypeImpl.class, diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/ExplicitEnumConvertersTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/ExplicitEnumConvertersTest.java index 7f17c2f0b5..b8ae042240 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/ExplicitEnumConvertersTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/ExplicitEnumConvertersTest.java @@ -89,7 +89,7 @@ public class ExplicitEnumConvertersTest extends BaseNonConfigCoreFunctionalTestC @Test public void testSimpleConvertUsage() throws MalformedURLException { - final EntityPersister ep = sessionFactory().getMappingMetamodel().getEntityDescriptor(Entity1.class.getName()); + final EntityPersister ep = sessionFactory().getMappingMetamodel().getEntityDescriptor(Entity1.class.getName()); final Type theDatePropertyType = ep.getPropertyType( "mediaType" ); final ConvertedBasicTypeImpl type = assertTyping( ConvertedBasicTypeImpl.class, diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/SimpleConvertAnnotationTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/SimpleConvertAnnotationTest.java index d1b911005e..307be6ac1e 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/SimpleConvertAnnotationTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/SimpleConvertAnnotationTest.java @@ -40,7 +40,7 @@ public class SimpleConvertAnnotationTest extends BaseNonConfigCoreFunctionalTest @Test public void testSimpleConvertUsage() throws MalformedURLException { - final EntityPersister ep = sessionFactory().getMappingMetamodel().getEntityDescriptor(Entity1.class.getName()); + final EntityPersister ep = sessionFactory().getMappingMetamodel().getEntityDescriptor(Entity1.class.getName()); final Type websitePropertyType = ep.getPropertyType( "website" ); final ConvertedBasicTypeImpl type = assertTyping( ConvertedBasicTypeImpl.class, diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/SimpleConvertsAnnotationTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/SimpleConvertsAnnotationTest.java index 23e7b67c8e..e9992f55f5 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/SimpleConvertsAnnotationTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/SimpleConvertsAnnotationTest.java @@ -41,7 +41,7 @@ public class SimpleConvertsAnnotationTest extends BaseNonConfigCoreFunctionalTes @Test public void testSimpleConvertsUsage() throws MalformedURLException { - final EntityPersister ep = sessionFactory().getMappingMetamodel().getEntityDescriptor(Entity1.class.getName()); + final EntityPersister ep = sessionFactory().getMappingMetamodel().getEntityDescriptor(Entity1.class.getName()); final Type websitePropertyType = ep.getPropertyType( "website" ); final ConvertedBasicTypeImpl type = assertTyping( ConvertedBasicTypeImpl.class, diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/SimpleEmbeddableOverriddenConverterTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/SimpleEmbeddableOverriddenConverterTest.java index 0b6d1e810d..b8bdf57561 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/SimpleEmbeddableOverriddenConverterTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/SimpleEmbeddableOverriddenConverterTest.java @@ -47,7 +47,7 @@ public class SimpleEmbeddableOverriddenConverterTest extends BaseNonConfigCoreFu */ @Test public void testSimpleConvertOverrides() { - final EntityPersister ep = sessionFactory().getMappingMetamodel().getEntityDescriptor(Person.class.getName()); + final EntityPersister ep = sessionFactory().getMappingMetamodel().getEntityDescriptor(Person.class.getName()); final JdbcTypeRegistry jdbcTypeRegistry = sessionFactory().getTypeConfiguration() .getJdbcTypeRegistry(); CompositeType homeAddressType = assertTyping( CompositeType.class, ep.getPropertyType( "homeAddress" ) ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/SimpleOverriddenConverterTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/SimpleOverriddenConverterTest.java index 82cb7635ce..d88be08ea0 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/SimpleOverriddenConverterTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/SimpleOverriddenConverterTest.java @@ -44,7 +44,7 @@ public class SimpleOverriddenConverterTest extends BaseNonConfigCoreFunctionalTe */ @Test public void testSimpleConvertOverrides() { - final EntityPersister ep = sessionFactory().getMappingMetamodel().getEntityDescriptor(Sub.class.getName()); + final EntityPersister ep = sessionFactory().getMappingMetamodel().getEntityDescriptor(Sub.class.getName()); final JdbcTypeRegistry jdbcTypeRegistry = sessionFactory().getTypeConfiguration().getJdbcTypeRegistry(); BasicType type = (BasicType) ep.getPropertyType( "it" ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/XmlWithExplicitConvertAnnotationsTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/XmlWithExplicitConvertAnnotationsTest.java index f076bf2e21..b00a0136de 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/XmlWithExplicitConvertAnnotationsTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/XmlWithExplicitConvertAnnotationsTest.java @@ -98,7 +98,7 @@ public class XmlWithExplicitConvertAnnotationsTest extends BaseNonConfigCoreFunc @Test public void testSimpleConvertUsage() throws MalformedURLException { - final EntityPersister ep = sessionFactory().getMappingMetamodel().getEntityDescriptor(Entity1.class.getName()); + final EntityPersister ep = sessionFactory().getMappingMetamodel().getEntityDescriptor(Entity1.class.getName()); final Type theDatePropertyType = ep.getPropertyType( "theDate" ); final ConvertedBasicTypeImpl type = assertTyping( ConvertedBasicTypeImpl.class, diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/registrations/MatchingDuplicateRegistrationTests.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/registrations/MatchingDuplicateRegistrationTests.java index dab333ebbc..c8c0450388 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/registrations/MatchingDuplicateRegistrationTests.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/registrations/MatchingDuplicateRegistrationTests.java @@ -35,8 +35,8 @@ public class MatchingDuplicateRegistrationTests { @ConverterRegistration( converter = Thing1Converter.class ) @ConverterRegistration( converter = Thing1Converter.class ) public static class DupRegEntity { - @Id - private Integer id; + @Id + private Integer id; private String name; private Thing1 thing1; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/registrations/MismatchDuplicateRegistrationTests.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/registrations/MismatchDuplicateRegistrationTests.java index 963f210c05..a31335ecb9 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/registrations/MismatchDuplicateRegistrationTests.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/registrations/MismatchDuplicateRegistrationTests.java @@ -38,8 +38,8 @@ public class MismatchDuplicateRegistrationTests { @ConverterRegistration( converter = Thing1Converter.class ) @ConverterRegistration( converter = Thing1Converter.class, autoApply = false ) public static class TroublesomeEntity { - @Id - private Integer id; + @Id + private Integer id; private String name; private Thing1 thing1; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converter/PeriodStringConverter.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converter/PeriodStringConverter.java index e06e6bca08..5e5be87df1 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converter/PeriodStringConverter.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converter/PeriodStringConverter.java @@ -16,16 +16,16 @@ import jakarta.persistence.Converter; //tag::basic-jpa-convert-period-string-converter-example[] @Converter public class PeriodStringConverter - implements AttributeConverter { + implements AttributeConverter { - @Override - public String convertToDatabaseColumn(Period attribute) { - return attribute.toString(); - } + @Override + public String convertToDatabaseColumn(Period attribute) { + return attribute.toString(); + } - @Override - public Period convertToEntityAttribute(String dbData) { - return Period.parse(dbData); - } + @Override + public Period convertToEntityAttribute(String dbData) { + return Period.parse(dbData); + } } //end::basic-jpa-convert-period-string-converter-example[] diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converter/PeriodStringTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converter/PeriodStringTest.java index c8f989db02..5008b820e3 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converter/PeriodStringTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converter/PeriodStringTest.java @@ -25,73 +25,73 @@ import static org.junit.Assert.assertEquals; */ public class PeriodStringTest extends BaseEntityManagerFunctionalTestCase { - private Period period = Period.ofYears(1).plusMonths(2).plusDays(3); + private Period period = Period.ofYears(1).plusMonths(2).plusDays(3); - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Event.class - }; - } + @Override + protected Class[] getAnnotatedClasses() { + return new Class[] { + Event.class + }; + } - @Test - public void testLifecycle() { - doInJPA(this::entityManagerFactory, entityManager -> { - Event event = new Event(period); - entityManager.persist(event); - }); - doInJPA(this::entityManagerFactory, entityManager -> { - Event event = entityManager.createQuery("from Event", Event.class).getSingleResult(); - assertEquals(period, event.getSpan()); - }); - doInJPA(this::entityManagerFactory, entityManager -> { - //tag::basic-jpa-convert-period-string-converter-immutability-plan-example[] - Event event = entityManager.createQuery("from Event", Event.class).getSingleResult(); - event.setSpan(Period - .ofYears(3) - .plusMonths(2) - .plusDays(1) - ); - //end::basic-jpa-convert-period-string-converter-immutability-plan-example[] - }); - } + @Test + public void testLifecycle() { + doInJPA(this::entityManagerFactory, entityManager -> { + Event event = new Event(period); + entityManager.persist(event); + }); + doInJPA(this::entityManagerFactory, entityManager -> { + Event event = entityManager.createQuery("from Event", Event.class).getSingleResult(); + assertEquals(period, event.getSpan()); + }); + doInJPA(this::entityManagerFactory, entityManager -> { + //tag::basic-jpa-convert-period-string-converter-immutability-plan-example[] + Event event = entityManager.createQuery("from Event", Event.class).getSingleResult(); + event.setSpan(Period + .ofYears(3) + .plusMonths(2) + .plusDays(1) + ); + //end::basic-jpa-convert-period-string-converter-immutability-plan-example[] + }); + } - //tag::basic-jpa-convert-period-string-converter-mapping-example[] - @Entity(name = "Event") - public static class Event { + //tag::basic-jpa-convert-period-string-converter-mapping-example[] + @Entity(name = "Event") + public static class Event { - @Id - @GeneratedValue - private Long id; + @Id + @GeneratedValue + private Long id; - @Convert(converter = PeriodStringConverter.class) - @Column(columnDefinition = "") - private Period span; + @Convert(converter = PeriodStringConverter.class) + @Column(columnDefinition = "") + private Period span; - //Getters and setters are omitted for brevity + //Getters and setters are omitted for brevity - //end::basic-jpa-convert-period-string-converter-mapping-example[] + //end::basic-jpa-convert-period-string-converter-mapping-example[] - public Event() { - } + public Event() { + } - public Event(Period span) { - this.span = span; - } + public Event(Period span) { + this.span = span; + } - public Long getId() { - return id; - } + public Long getId() { + return id; + } - public Period getSpan() { - return span; - } + public Period getSpan() { + return span; + } - public void setSpan(Period span) { - this.span = span; - } + public void setSpan(Period span) { + this.span = span; + } - //tag::basic-jpa-convert-period-string-converter-mapping-example[] - } - //end::basic-jpa-convert-period-string-converter-mapping-example[] + //tag::basic-jpa-convert-period-string-converter-mapping-example[] + } + //end::basic-jpa-convert-period-string-converter-mapping-example[] } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converter/hbm/Account.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converter/hbm/Account.java index 5126166fc3..086af8f174 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converter/hbm/Account.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converter/hbm/Account.java @@ -9,37 +9,37 @@ package org.hibernate.orm.test.mapping.converter.hbm; //tag::basic-hbm-attribute-converter-mapping-account-example[] public class Account { - private Long id; + private Long id; - private String owner; + private String owner; - private Money balance; + private Money balance; - //Getters and setters are omitted for brevity - //end::basic-hbm-attribute-converter-mapping-account-example[] - public Long getId() { - return id; - } + //Getters and setters are omitted for brevity + //end::basic-hbm-attribute-converter-mapping-account-example[] + public Long getId() { + return id; + } - public void setId(Long id) { - this.id = id; - } + public void setId(Long id) { + this.id = id; + } - public String getOwner() { - return owner; - } + public String getOwner() { + return owner; + } - public void setOwner(String owner) { - this.owner = owner; - } + public void setOwner(String owner) { + this.owner = owner; + } - public Money getBalance() { - return balance; - } + public Money getBalance() { + return balance; + } - public void setBalance(Money balance) { - this.balance = balance; - } + public void setBalance(Money balance) { + this.balance = balance; + } //tag::basic-hbm-attribute-converter-mapping-account-example[] } //end::basic-hbm-attribute-converter-mapping-account-example[] diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converter/hbm/Money.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converter/hbm/Money.java index 7f47f2b70c..0eaf74073d 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converter/hbm/Money.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converter/hbm/Money.java @@ -9,18 +9,18 @@ package org.hibernate.orm.test.mapping.converter.hbm; //tag::basic-hbm-attribute-converter-mapping-money-example[] public class Money { - private long cents; + private long cents; - public Money(long cents) { - this.cents = cents; - } + public Money(long cents) { + this.cents = cents; + } - public long getCents() { - return cents; - } + public long getCents() { + return cents; + } - public void setCents(long cents) { - this.cents = cents; - } + public void setCents(long cents) { + this.cents = cents; + } } //end::basic-hbm-attribute-converter-mapping-money-example[] diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converter/hbm/MoneyConverter.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converter/hbm/MoneyConverter.java index 769248f2ab..3426cf4898 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converter/hbm/MoneyConverter.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converter/hbm/MoneyConverter.java @@ -10,16 +10,16 @@ import jakarta.persistence.AttributeConverter; //tag::basic-hbm-attribute-converter-mapping-moneyconverter-example[] public class MoneyConverter - implements AttributeConverter { + implements AttributeConverter { - @Override - public Long convertToDatabaseColumn(Money attribute) { - return attribute == null ? null : attribute.getCents(); - } + @Override + public Long convertToDatabaseColumn(Money attribute) { + return attribute == null ? null : attribute.getCents(); + } - @Override - public Money convertToEntityAttribute(Long dbData) { - return dbData == null ? null : new Money(dbData); - } + @Override + public Money convertToEntityAttribute(Long dbData) { + return dbData == null ? null : new Money(dbData); + } } //end::basic-hbm-attribute-converter-mapping-moneyconverter-example[] diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/fetch/depth/SysModule.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/fetch/depth/SysModule.java index 61a8ab8e82..e36a57bb16 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/fetch/depth/SysModule.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/fetch/depth/SysModule.java @@ -20,19 +20,19 @@ import jakarta.persistence.Table; @Entity @Table(name = "sys_mod") public class SysModule { - @Id - private Integer id; + @Id + private Integer id; - @Column(name = "name") - private String name; + @Column(name = "name") + private String name; // @OneToMany( cascade = CascadeType.PERSIST, fetch = FetchType.EAGER ) // @JoinColumn( name = "target_mod_fk" ) - @ManyToMany( targetEntity = SysModule.class, cascade = { CascadeType.PERSIST }, fetch = FetchType.EAGER ) - @JoinTable( - name = "sys_group_mod", - joinColumns = @JoinColumn(name = "src_fk", referencedColumnName = "id"), - inverseJoinColumns = @JoinColumn(name = "target_fk", referencedColumnName = "id") - ) - private Set targetModules; + @ManyToMany( targetEntity = SysModule.class, cascade = { CascadeType.PERSIST }, fetch = FetchType.EAGER ) + @JoinTable( + name = "sys_group_mod", + joinColumns = @JoinColumn(name = "src_fk", referencedColumnName = "id"), + inverseJoinColumns = @JoinColumn(name = "target_fk", referencedColumnName = "id") + ) + private Set targetModules; } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/fetch/depth/SysModule2.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/fetch/depth/SysModule2.java index 7f9e6a0b9a..39561b37da 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/fetch/depth/SysModule2.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/fetch/depth/SysModule2.java @@ -19,13 +19,13 @@ import jakarta.persistence.Table; @Entity @Table(name = "sys_mod") public class SysModule2 { - @Id - private Integer id; + @Id + private Integer id; - @Column(name = "name") - private String name; + @Column(name = "name") + private String name; - @OneToMany( cascade = CascadeType.PERSIST, fetch = FetchType.EAGER ) - @JoinColumn( name = "target_mod_fk" ) - private Set targetModules; + @OneToMany( cascade = CascadeType.PERSIST, fetch = FetchType.EAGER ) + @JoinColumn( name = "target_mod_fk" ) + private Set targetModules; } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/fetch/subselect/Name.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/fetch/subselect/Name.java index 86b93c0088..beba4a481a 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/fetch/subselect/Name.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/fetch/subselect/Name.java @@ -10,26 +10,26 @@ import java.io.Serializable; import java.util.List; public class Name implements Serializable { - private int id; - private String name; - private int nameLength; - private List values; +private int id; +private String name; +private int nameLength; +private List values; - public int getId() { return id; } - public String getName() { return name; } - public int getNameLength() { return nameLength; } - public List getValues() { return values; } +public int getId() { return id; } +public String getName() { return name; } +public int getNameLength() { return nameLength; } +public List getValues() { return values; } - public void setId(int id) { this.id = id; } - public void setName(String name) { this.name = name; } - public void setNameLength(int nameLength) { this.nameLength = nameLength; } - public void setValues(List values) { this.values = values; } +public void setId(int id) { this.id = id; } +public void setName(String name) { this.name = name; } +public void setNameLength(int nameLength) { this.nameLength = nameLength; } +public void setValues(List values) { this.values = values; } - public boolean equals(Object obj) { - if (!(obj instanceof Name )) return false; - Name other = (Name) obj; - return other.id == this.id; - } - - public int hashCode() { return id; } +public boolean equals(Object obj) { + if (!(obj instanceof Name )) return false; + Name other = (Name) obj; + return other.id == this.id; +} + +public int hashCode() { return id; } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/fetch/subselect/Value.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/fetch/subselect/Value.java index f6265890dd..f9751059dd 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/fetch/subselect/Value.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/fetch/subselect/Value.java @@ -9,23 +9,23 @@ package org.hibernate.orm.test.mapping.fetch.subselect; import java.io.Serializable; public class Value implements Serializable { - private int id; - private Name name; - private String value; +private int id; +private Name name; +private String value; - public int getId() { return id; } - public Name getName() { return name; } - public String getValue() { return value; } +public int getId() { return id; } +public Name getName() { return name; } +public String getValue() { return value; } - public void setId(int id) { this.id = id; } - public void setName(Name name) { this.name = name; } - public void setValue(String value) { this.value = value; } +public void setId(int id) { this.id = id; } +public void setName(Name name) { this.name = name; } +public void setValue(String value) { this.value = value; } - public boolean equals(Object obj) { - if (!(obj instanceof Value )) return false; - Value other = (Value) obj; - return other.id == this.id; - } - - public int hashCode() { return id; } +public boolean equals(Object obj) { + if (!(obj instanceof Value )) return false; + Value other = (Value) obj; + return other.id == this.id; +} + +public int hashCode() { return id; } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/generated/always/GeneratedAlwaysTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/generated/always/GeneratedAlwaysTest.java index d57812a236..59c1c7976f 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/generated/always/GeneratedAlwaysTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/generated/always/GeneratedAlwaysTest.java @@ -41,43 +41,43 @@ import static org.junit.Assert.assertEquals; @SkipForDialect(dialectClass = AltibaseDialect.class, reason = "generated always is not supported in Altibase") public class GeneratedAlwaysTest { - @Test - public void test(SessionFactoryScope scope) { - scope.inTransaction( session -> { - BigDecimal unitPrice = new BigDecimal("12.99"); - OrderLine entity = new OrderLine( unitPrice, 5, 10 ); - session.persist(entity); - session.flush(); - assertEquals( 5, entity.quantity ); - assertEquals( unitPrice, entity.unitPrice ); - assertEquals( unitPrice.multiply( new BigDecimal("5") ), entity.total ); - assertEquals( 58, entity.discounted.intValue() ); - } ); - } + @Test + public void test(SessionFactoryScope scope) { + scope.inTransaction( session -> { + BigDecimal unitPrice = new BigDecimal("12.99"); + OrderLine entity = new OrderLine( unitPrice, 5, 10 ); + session.persist(entity); + session.flush(); + assertEquals( 5, entity.quantity ); + assertEquals( unitPrice, entity.unitPrice ); + assertEquals( unitPrice.multiply( new BigDecimal("5") ), entity.total ); + assertEquals( 58, entity.discounted.intValue() ); + } ); + } - @AfterEach - public void dropTestData(SessionFactoryScope scope) { - scope.inTransaction( session -> session.createQuery( "delete WithGeneratedAlways" ).executeUpdate() ); - } + @AfterEach + public void dropTestData(SessionFactoryScope scope) { + scope.inTransaction( session -> session.createQuery( "delete WithGeneratedAlways" ).executeUpdate() ); + } - @Entity(name="WithGeneratedAlways") - public static class OrderLine { - @Id - private BigDecimal unitPrice; - @Id - private int quantity; - private int discount; - @GeneratedColumn(value = "unitPrice*quantity") - private BigDecimal total; - @Column(name = "discountedTotal") - @GeneratedColumn(value = "unitPrice*quantity*(1.0-discount/100.0)") - private BigDecimal discounted; + @Entity(name="WithGeneratedAlways") + public static class OrderLine { + @Id + private BigDecimal unitPrice; + @Id + private int quantity; + private int discount; + @GeneratedColumn(value = "unitPrice*quantity") + private BigDecimal total; + @Column(name = "discountedTotal") + @GeneratedColumn(value = "unitPrice*quantity*(1.0-discount/100.0)") + private BigDecimal discounted; - public OrderLine() {} - public OrderLine(BigDecimal unitPrice, int quantity, int discount) { - this.unitPrice = unitPrice; - this.quantity = quantity; - this.discount = discount; - } - } + public OrderLine() {} + public OrderLine(BigDecimal unitPrice, int quantity, int discount) { + this.unitPrice = unitPrice; + this.quantity = quantity; + this.discount = discount; + } + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/generated/sqldefault/DefaultTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/generated/sqldefault/DefaultTest.java index 081f8b3985..468a9705af 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/generated/sqldefault/DefaultTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/generated/sqldefault/DefaultTest.java @@ -30,51 +30,51 @@ import static org.junit.Assert.assertEquals; @SessionFactory public class DefaultTest { - @Test - public void test(SessionFactoryScope scope) { - BigDecimal unitPrice = new BigDecimal("12.99"); - scope.inTransaction( session -> { - OrderLine entity = new OrderLine( unitPrice, 5 ); - session.persist(entity); - session.flush(); - assertEquals( "new", entity.status ); - assertEquals( unitPrice, entity.unitPrice ); - assertEquals( 5, entity.quantity ); - } ); - scope.inTransaction( session -> { - OrderLine entity = session.createQuery("from WithDefault", OrderLine.class ).getSingleResult(); - assertEquals( unitPrice, entity.unitPrice ); - assertEquals( 5, entity.quantity ); - assertEquals( "new", entity.status ); - entity.status = "old"; //should be ignored when fetch=true - } ); - scope.inTransaction( session -> { - OrderLine entity = session.createQuery("from WithDefault", OrderLine.class ).getSingleResult(); - assertEquals( unitPrice, entity.unitPrice ); - assertEquals( 5, entity.quantity ); - assertEquals( "new", entity.status ); - } ); - } + @Test + public void test(SessionFactoryScope scope) { + BigDecimal unitPrice = new BigDecimal("12.99"); + scope.inTransaction( session -> { + OrderLine entity = new OrderLine( unitPrice, 5 ); + session.persist(entity); + session.flush(); + assertEquals( "new", entity.status ); + assertEquals( unitPrice, entity.unitPrice ); + assertEquals( 5, entity.quantity ); + } ); + scope.inTransaction( session -> { + OrderLine entity = session.createQuery("from WithDefault", OrderLine.class ).getSingleResult(); + assertEquals( unitPrice, entity.unitPrice ); + assertEquals( 5, entity.quantity ); + assertEquals( "new", entity.status ); + entity.status = "old"; //should be ignored when fetch=true + } ); + scope.inTransaction( session -> { + OrderLine entity = session.createQuery("from WithDefault", OrderLine.class ).getSingleResult(); + assertEquals( unitPrice, entity.unitPrice ); + assertEquals( 5, entity.quantity ); + assertEquals( "new", entity.status ); + } ); + } - @AfterEach - public void dropTestData(SessionFactoryScope scope) { - scope.inTransaction( session -> session.createQuery( "delete WithDefault" ).executeUpdate() ); - } + @AfterEach + public void dropTestData(SessionFactoryScope scope) { + scope.inTransaction( session -> session.createQuery( "delete WithDefault" ).executeUpdate() ); + } - @Entity(name="WithDefault") - public static class OrderLine { - @Id - private BigDecimal unitPrice; - @Id @ColumnDefault(value = "1") - private int quantity; - @Generated - @ColumnDefault(value = "'new'") - private String status; + @Entity(name="WithDefault") + public static class OrderLine { + @Id + private BigDecimal unitPrice; + @Id @ColumnDefault(value = "1") + private int quantity; + @Generated + @ColumnDefault(value = "'new'") + private String status; - public OrderLine() {} - public OrderLine(BigDecimal unitPrice, int quantity) { - this.unitPrice = unitPrice; - this.quantity = quantity; - } - } + public OrderLine() {} + public OrderLine(BigDecimal unitPrice, int quantity) { + this.unitPrice = unitPrice; + this.quantity = quantity; + } + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/generated/sqldefault/DynamicDefaultTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/generated/sqldefault/DynamicDefaultTest.java index 69745e383f..8e724a883e 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/generated/sqldefault/DynamicDefaultTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/generated/sqldefault/DynamicDefaultTest.java @@ -28,78 +28,78 @@ import static org.junit.Assert.assertNull; @SessionFactory public class DynamicDefaultTest { - @Test - public void testWithDefault(SessionFactoryScope scope) { - BigDecimal unitPrice = new BigDecimal("12.99"); - scope.inTransaction( session -> { - OrderLine entity = new OrderLine( unitPrice, 5 ); - session.persist(entity); - session.flush(); - assertNull( entity.status ); - String status = session.createQuery("select status from WithDefault", String.class).getSingleResult(); - assertEquals( "new", status ); - session.refresh(entity); - assertEquals( unitPrice, entity.unitPrice ); - assertEquals( 5, entity.quantity ); + @Test + public void testWithDefault(SessionFactoryScope scope) { + BigDecimal unitPrice = new BigDecimal("12.99"); + scope.inTransaction( session -> { + OrderLine entity = new OrderLine( unitPrice, 5 ); + session.persist(entity); + session.flush(); + assertNull( entity.status ); + String status = session.createQuery("select status from WithDefault", String.class).getSingleResult(); + assertEquals( "new", status ); + session.refresh(entity); + assertEquals( unitPrice, entity.unitPrice ); + assertEquals( 5, entity.quantity ); // assertEquals( "new", entity.status ); //TODO: assertion currently fails; apparent bug in refresh() - } ); - scope.inTransaction( session -> { - OrderLine entity = session.createQuery("from WithDefault", OrderLine.class ).getSingleResult(); - assertEquals( unitPrice, entity.unitPrice ); - assertEquals( 5, entity.quantity ); - assertEquals( "new", entity.status ); - entity.status = "old"; - } ); - scope.inTransaction( session -> { - OrderLine entity = session.createQuery("from WithDefault", OrderLine.class ).getSingleResult(); - assertEquals( unitPrice, entity.unitPrice ); - assertEquals( 5, entity.quantity ); - assertEquals( "old", entity.status ); - } ); - } + } ); + scope.inTransaction( session -> { + OrderLine entity = session.createQuery("from WithDefault", OrderLine.class ).getSingleResult(); + assertEquals( unitPrice, entity.unitPrice ); + assertEquals( 5, entity.quantity ); + assertEquals( "new", entity.status ); + entity.status = "old"; + } ); + scope.inTransaction( session -> { + OrderLine entity = session.createQuery("from WithDefault", OrderLine.class ).getSingleResult(); + assertEquals( unitPrice, entity.unitPrice ); + assertEquals( 5, entity.quantity ); + assertEquals( "old", entity.status ); + } ); + } - @Test - public void testWithExplicit(SessionFactoryScope scope) { - BigDecimal unitPrice = new BigDecimal("12.99"); - scope.inTransaction( session -> { - OrderLine entity = new OrderLine( unitPrice, 5 ); - entity.status = "New"; - session.persist(entity); - session.flush(); - String status = session.createQuery("select status from WithDefault", String.class).getSingleResult(); - assertEquals( "New", status ); - session.refresh(entity); - assertEquals( "New", entity.status ); - assertEquals( unitPrice, entity.unitPrice ); - assertEquals( 5, entity.quantity ); - } ); - scope.inTransaction( session -> { - OrderLine entity = session.createQuery("from WithDefault", OrderLine.class ).getSingleResult(); - assertEquals( unitPrice, entity.unitPrice ); - assertEquals( 5, entity.quantity ); - assertEquals( "New", entity.status ); - } ); - } + @Test + public void testWithExplicit(SessionFactoryScope scope) { + BigDecimal unitPrice = new BigDecimal("12.99"); + scope.inTransaction( session -> { + OrderLine entity = new OrderLine( unitPrice, 5 ); + entity.status = "New"; + session.persist(entity); + session.flush(); + String status = session.createQuery("select status from WithDefault", String.class).getSingleResult(); + assertEquals( "New", status ); + session.refresh(entity); + assertEquals( "New", entity.status ); + assertEquals( unitPrice, entity.unitPrice ); + assertEquals( 5, entity.quantity ); + } ); + scope.inTransaction( session -> { + OrderLine entity = session.createQuery("from WithDefault", OrderLine.class ).getSingleResult(); + assertEquals( unitPrice, entity.unitPrice ); + assertEquals( 5, entity.quantity ); + assertEquals( "New", entity.status ); + } ); + } - @AfterEach - public void dropTestData(SessionFactoryScope scope) { - scope.inTransaction( session -> session.createQuery( "delete WithDefault" ).executeUpdate() ); - } + @AfterEach + public void dropTestData(SessionFactoryScope scope) { + scope.inTransaction( session -> session.createQuery( "delete WithDefault" ).executeUpdate() ); + } - @Entity(name="WithDefault") - @DynamicInsert - public static class OrderLine { - @Id - private BigDecimal unitPrice; - @Id @ColumnDefault(value = "1") - private int quantity; - @ColumnDefault(value = "'new'") - private String status; + @Entity(name="WithDefault") + @DynamicInsert + public static class OrderLine { + @Id + private BigDecimal unitPrice; + @Id @ColumnDefault(value = "1") + private int quantity; + @ColumnDefault(value = "'new'") + private String status; - public OrderLine() {} - public OrderLine(BigDecimal unitPrice, int quantity) { - this.unitPrice = unitPrice; - this.quantity = quantity; - } - } + public OrderLine() {} + public OrderLine(BigDecimal unitPrice, int quantity) { + this.unitPrice = unitPrice; + this.quantity = quantity; + } + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/generated/sqldefault/OverriddenDefaultTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/generated/sqldefault/OverriddenDefaultTest.java index cd91d1b3ee..25c685dc8a 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/generated/sqldefault/OverriddenDefaultTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/generated/sqldefault/OverriddenDefaultTest.java @@ -32,58 +32,58 @@ import static org.junit.Assert.assertEquals; @SessionFactory public class OverriddenDefaultTest { - @Test - public void test(SessionFactoryScope scope) { - BigDecimal unitPrice = new BigDecimal("12.99"); - scope.inTransaction( session -> { - OrderLine entity = new OrderLine( unitPrice, 5 ); - session.persist(entity); - session.flush(); - assertEquals( getDefault(scope), entity.status ); - assertEquals( unitPrice, entity.unitPrice ); - assertEquals( 5, entity.quantity ); - } ); - scope.inTransaction( session -> { - OrderLine entity = session.createQuery("from WithDefault", OrderLine.class ).getSingleResult(); - assertEquals( unitPrice, entity.unitPrice ); - assertEquals( 5, entity.quantity ); - assertEquals( getDefault(scope), entity.status ); - entity.status = "old"; //should be ignored when fetch=true - } ); - scope.inTransaction( session -> { - OrderLine entity = session.createQuery("from WithDefault", OrderLine.class ).getSingleResult(); - assertEquals( unitPrice, entity.unitPrice ); - assertEquals( 5, entity.quantity ); - assertEquals( getDefault(scope), entity.status ); - } ); - } + @Test + public void test(SessionFactoryScope scope) { + BigDecimal unitPrice = new BigDecimal("12.99"); + scope.inTransaction( session -> { + OrderLine entity = new OrderLine( unitPrice, 5 ); + session.persist(entity); + session.flush(); + assertEquals( getDefault(scope), entity.status ); + assertEquals( unitPrice, entity.unitPrice ); + assertEquals( 5, entity.quantity ); + } ); + scope.inTransaction( session -> { + OrderLine entity = session.createQuery("from WithDefault", OrderLine.class ).getSingleResult(); + assertEquals( unitPrice, entity.unitPrice ); + assertEquals( 5, entity.quantity ); + assertEquals( getDefault(scope), entity.status ); + entity.status = "old"; //should be ignored when fetch=true + } ); + scope.inTransaction( session -> { + OrderLine entity = session.createQuery("from WithDefault", OrderLine.class ).getSingleResult(); + assertEquals( unitPrice, entity.unitPrice ); + assertEquals( 5, entity.quantity ); + assertEquals( getDefault(scope), entity.status ); + } ); + } - String getDefault(SessionFactoryScope scope) { - return scope.getMetadataImplementor().getDatabase().getDialect() instanceof H2Dialect ? "NEW" : "new"; - } + String getDefault(SessionFactoryScope scope) { + return scope.getMetadataImplementor().getDatabase().getDialect() instanceof H2Dialect ? "NEW" : "new"; + } - @AfterEach - public void dropTestData(SessionFactoryScope scope) { - scope.inTransaction( session -> session.createQuery( "delete WithDefault" ).executeUpdate() ); - } + @AfterEach + public void dropTestData(SessionFactoryScope scope) { + scope.inTransaction( session -> session.createQuery( "delete WithDefault" ).executeUpdate() ); + } - @Entity(name="WithDefault") - public static class OrderLine { - @Id - private BigDecimal unitPrice; - @Id @ColumnDefault("1") - private int quantity; - @Generated - @ColumnDefault("'new'") - @DialectOverride.ColumnDefault(dialect = H2Dialect.class, - sameOrAfter = @DialectOverride.Version(major=1, minor=4), - override = @ColumnDefault("'NEW'")) - private String status; + @Entity(name="WithDefault") + public static class OrderLine { + @Id + private BigDecimal unitPrice; + @Id @ColumnDefault("1") + private int quantity; + @Generated + @ColumnDefault("'new'") + @DialectOverride.ColumnDefault(dialect = H2Dialect.class, + sameOrAfter = @DialectOverride.Version(major=1, minor=4), + override = @ColumnDefault("'NEW'")) + private String status; - public OrderLine() {} - public OrderLine(BigDecimal unitPrice, int quantity) { - this.unitPrice = unitPrice; - this.quantity = quantity; - } - } + public OrderLine() {} + public OrderLine(BigDecimal unitPrice, int quantity) { + this.unitPrice = unitPrice; + this.quantity = quantity; + } + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/generated/sqldefault/RefreshTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/generated/sqldefault/RefreshTest.java index 549f5066dc..d3a07ba8d2 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/generated/sqldefault/RefreshTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/generated/sqldefault/RefreshTest.java @@ -27,55 +27,55 @@ import static org.junit.Assert.assertEquals; @SessionFactory public class RefreshTest { - @Test - public void test(SessionFactoryScope scope) { - BigDecimal unitPrice = new BigDecimal("12.99"); - scope.inTransaction( session -> { - OrderLine entity = new OrderLine( unitPrice, 5 ); - session.persist(entity); - session.flush(); - assertEquals( null, entity.status ); - assertEquals( unitPrice, entity.unitPrice ); - assertEquals( 5, entity.quantity ); - session.refresh(entity); - assertEquals( "new", entity.status ); - assertEquals( unitPrice, entity.unitPrice ); - assertEquals( 5, entity.quantity ); - } ); - scope.inTransaction( session -> { - OrderLine entity = session.createQuery("from WithDefault", OrderLine.class ).getSingleResult(); - assertEquals( unitPrice, entity.unitPrice ); - assertEquals( 5, entity.quantity ); - assertEquals( "new", entity.status ); - entity.status = "old"; - } ); - scope.inTransaction( session -> { - OrderLine entity = session.createQuery("from WithDefault", OrderLine.class ).getSingleResult(); - assertEquals( unitPrice, entity.unitPrice ); - assertEquals( 5, entity.quantity ); - assertEquals( "old", entity.status ); - } ); - } + @Test + public void test(SessionFactoryScope scope) { + BigDecimal unitPrice = new BigDecimal("12.99"); + scope.inTransaction( session -> { + OrderLine entity = new OrderLine( unitPrice, 5 ); + session.persist(entity); + session.flush(); + assertEquals( null, entity.status ); + assertEquals( unitPrice, entity.unitPrice ); + assertEquals( 5, entity.quantity ); + session.refresh(entity); + assertEquals( "new", entity.status ); + assertEquals( unitPrice, entity.unitPrice ); + assertEquals( 5, entity.quantity ); + } ); + scope.inTransaction( session -> { + OrderLine entity = session.createQuery("from WithDefault", OrderLine.class ).getSingleResult(); + assertEquals( unitPrice, entity.unitPrice ); + assertEquals( 5, entity.quantity ); + assertEquals( "new", entity.status ); + entity.status = "old"; + } ); + scope.inTransaction( session -> { + OrderLine entity = session.createQuery("from WithDefault", OrderLine.class ).getSingleResult(); + assertEquals( unitPrice, entity.unitPrice ); + assertEquals( 5, entity.quantity ); + assertEquals( "old", entity.status ); + } ); + } - @AfterEach - public void dropTestData(SessionFactoryScope scope) { - scope.inTransaction( session -> session.createQuery( "delete WithDefault" ).executeUpdate() ); - } + @AfterEach + public void dropTestData(SessionFactoryScope scope) { + scope.inTransaction( session -> session.createQuery( "delete WithDefault" ).executeUpdate() ); + } - @Entity(name="WithDefault") - @DynamicInsert - public static class OrderLine { - @Id - private BigDecimal unitPrice; - @Id @ColumnDefault(value = "1") - private int quantity; - @ColumnDefault(value = "'new'") - private String status; + @Entity(name="WithDefault") + @DynamicInsert + public static class OrderLine { + @Id + private BigDecimal unitPrice; + @Id @ColumnDefault(value = "1") + private int quantity; + @ColumnDefault(value = "'new'") + private String status; - public OrderLine() {} - public OrderLine(BigDecimal unitPrice, int quantity) { - this.unitPrice = unitPrice; - this.quantity = quantity; - } - } + public OrderLine() {} + public OrderLine(BigDecimal unitPrice, int quantity) { + this.unitPrice = unitPrice; + this.quantity = quantity; + } + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/generated/temporals/GeneratedUuidTests.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/generated/temporals/GeneratedUuidTests.java index 6c11228b78..0ce84ecc87 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/generated/temporals/GeneratedUuidTests.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/generated/temporals/GeneratedUuidTests.java @@ -115,17 +115,17 @@ public class GeneratedUuidTests { @Entity( name = "GeneratedUuidEntity" ) @Table( name = "t_gen_uuid" ) public static class GeneratedUuidEntity { - @Id - public Integer id; - @Basic - public String name; + @Id + public Integer id; + @Basic + public String name; //tag::mapping-generated-custom-ex1[] @GeneratedUuidValue( timing = INSERT ) public UUID createdUuid; @GeneratedUuidValue( timing = {INSERT, UPDATE} ) - public UUID updatedUuid; + public UUID updatedUuid; //end::mapping-generated-custom-ex1[] public GeneratedUuidEntity() { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/hhh14343/entity/NestedPlayerStat.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/hhh14343/entity/NestedPlayerStat.java index 2a2148efe5..d4d2549996 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/hhh14343/entity/NestedPlayerStat.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/hhh14343/entity/NestedPlayerStat.java @@ -23,53 +23,53 @@ import jakarta.persistence.Table; @IdClass(NestedPlayerStatId.class) public class NestedPlayerStat implements Serializable { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; - @Id - @Column(name = "player_id") - private Integer playerId; + @Id + @Column(name = "player_id") + private Integer playerId; - @Basic(optional = false) - @Column(name = "jersey_nbr") - private Integer jerseyNbr; + @Basic(optional = false) + @Column(name = "jersey_nbr") + private Integer jerseyNbr; - @Id - @ManyToOne(optional = false, fetch = FetchType.EAGER) - @JoinColumn(name = "game_id", referencedColumnName = "game_id") - @JoinColumn(name = "is_home", referencedColumnName = "is_home") - private NestedScore score; + @Id + @ManyToOne(optional = false, fetch = FetchType.EAGER) + @JoinColumn(name = "game_id", referencedColumnName = "game_id") + @JoinColumn(name = "is_home", referencedColumnName = "is_home") + private NestedScore score; - public NestedPlayerStat() - { - } + public NestedPlayerStat() + { + } - public Integer getPlayerId() - { - return playerId; - } + public Integer getPlayerId() + { + return playerId; + } - public void setPlayerId(Integer playerId) - { - this.playerId = playerId; - } + public void setPlayerId(Integer playerId) + { + this.playerId = playerId; + } - public Integer getJerseyNbr() - { - return jerseyNbr; - } + public Integer getJerseyNbr() + { + return jerseyNbr; + } - public void setJerseyNbr(Integer jerseyNbr) - { - this.jerseyNbr = jerseyNbr; - } + public void setJerseyNbr(Integer jerseyNbr) + { + this.jerseyNbr = jerseyNbr; + } - public NestedScore getScore() - { - return score; - } + public NestedScore getScore() + { + return score; + } - public void setScore(NestedScore score) - { - this.score = score; - } + public void setScore(NestedScore score) + { + this.score = score; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/hhh14343/entity/NestedPlayerStatId.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/hhh14343/entity/NestedPlayerStatId.java index fad1eb3411..dcd06f9079 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/hhh14343/entity/NestedPlayerStatId.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/hhh14343/entity/NestedPlayerStatId.java @@ -10,33 +10,33 @@ import java.io.Serializable; public class NestedPlayerStatId implements Serializable { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; - private Integer playerId; + private Integer playerId; - private NestedScoreId score; + private NestedScoreId score; - public NestedPlayerStatId() - { - } + public NestedPlayerStatId() + { + } - public Integer getPlayerId() - { - return playerId; - } + public Integer getPlayerId() + { + return playerId; + } - public void setPlayerId(Integer playerId) - { - this.playerId = playerId; - } + public void setPlayerId(Integer playerId) + { + this.playerId = playerId; + } - public NestedScoreId getScore() - { - return score; - } + public NestedScoreId getScore() + { + return score; + } - public void setScore(NestedScoreId score) - { - this.score = score; - } + public void setScore(NestedScoreId score) + { + this.score = score; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/hhh14343/entity/NestedScore.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/hhh14343/entity/NestedScore.java index 4c0f4bfcff..ff2920cbfb 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/hhh14343/entity/NestedScore.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/hhh14343/entity/NestedScore.java @@ -20,65 +20,65 @@ import jakarta.persistence.Table; @IdClass(NestedScoreId.class) public class NestedScore implements Serializable { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; - @Id - @Column(name = "game_id") - private Integer gameId; + @Id + @Column(name = "game_id") + private Integer gameId; - @Id - @Column(name = "is_home") - private Boolean home; + @Id + @Column(name = "is_home") + private Boolean home; - @Basic(optional = false) - @Column(name = "roster_id") - private Integer rosterId; + @Basic(optional = false) + @Column(name = "roster_id") + private Integer rosterId; - @Basic - @Column(name = "final_score") - private Integer finalScore; + @Basic + @Column(name = "final_score") + private Integer finalScore; - public NestedScore() - { - } + public NestedScore() + { + } - public Integer getGameId() - { - return gameId; - } + public Integer getGameId() + { + return gameId; + } - public void setGameId(Integer gameId) - { - this.gameId = gameId; - } + public void setGameId(Integer gameId) + { + this.gameId = gameId; + } - public Boolean getHome() - { - return home; - } + public Boolean getHome() + { + return home; + } - public void setHome(Boolean home) - { - this.home = home; - } + public void setHome(Boolean home) + { + this.home = home; + } - public Integer getRosterId() - { - return rosterId; - } + public Integer getRosterId() + { + return rosterId; + } - public void setRosterId(Integer rosterId) - { - this.rosterId = rosterId; - } + public void setRosterId(Integer rosterId) + { + this.rosterId = rosterId; + } - public Integer getFinalScore() - { - return finalScore; - } + public Integer getFinalScore() + { + return finalScore; + } - public void setFinalScore(Integer finalScore) - { - this.finalScore = finalScore; - } + public void setFinalScore(Integer finalScore) + { + this.finalScore = finalScore; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/hhh14343/entity/NestedScoreId.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/hhh14343/entity/NestedScoreId.java index d83575b014..7786d6cd6a 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/hhh14343/entity/NestedScoreId.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/hhh14343/entity/NestedScoreId.java @@ -10,33 +10,33 @@ import java.io.Serializable; public class NestedScoreId implements Serializable { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; - private Integer gameId; + private Integer gameId; - private Boolean home; + private Boolean home; - public NestedScoreId() - { - } + public NestedScoreId() + { + } - public Integer getGameId() - { - return gameId; - } + public Integer getGameId() + { + return gameId; + } - public void setGameId(Integer gameId) - { - this.gameId = gameId; - } + public void setGameId(Integer gameId) + { + this.gameId = gameId; + } - public Boolean getHome() - { - return home; - } + public Boolean getHome() + { + return home; + } - public void setHome(Boolean home) - { - this.home = home; - } + public void setHome(Boolean home) + { + this.home = home; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/hhh14343/entity/NestedStat.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/hhh14343/entity/NestedStat.java index 44c8acb5c0..dda92fed9a 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/hhh14343/entity/NestedStat.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/hhh14343/entity/NestedStat.java @@ -22,40 +22,40 @@ import jakarta.persistence.Table; @IdClass(NestedStatId.class) public class NestedStat implements Serializable { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; - @Id - @Column - private Integer period; + @Id + @Column + private Integer period; - @Id - @ManyToOne(optional = false, fetch = FetchType.EAGER) - @JoinColumn(name = "game_id", referencedColumnName = "game_id") - @JoinColumn(name = "is_home", referencedColumnName = "is_home") - @JoinColumn(name = "player_id", referencedColumnName = "player_id") - private NestedPlayerStat playerStat; + @Id + @ManyToOne(optional = false, fetch = FetchType.EAGER) + @JoinColumn(name = "game_id", referencedColumnName = "game_id") + @JoinColumn(name = "is_home", referencedColumnName = "is_home") + @JoinColumn(name = "player_id", referencedColumnName = "player_id") + private NestedPlayerStat playerStat; - public NestedStat() - { - } + public NestedStat() + { + } - public Integer getPeriod() - { - return period; - } + public Integer getPeriod() + { + return period; + } - public void setPeriod(Integer period) - { - this.period = period; - } + public void setPeriod(Integer period) + { + this.period = period; + } - public NestedPlayerStat getPlayerStat() - { - return playerStat; - } + public NestedPlayerStat getPlayerStat() + { + return playerStat; + } - public void setPlayerStat(NestedPlayerStat playerStat) - { - this.playerStat = playerStat; - } + public void setPlayerStat(NestedPlayerStat playerStat) + { + this.playerStat = playerStat; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/hhh14343/entity/NestedStatId.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/hhh14343/entity/NestedStatId.java index 0c1b4757d0..7b56e16531 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/hhh14343/entity/NestedStatId.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/hhh14343/entity/NestedStatId.java @@ -10,33 +10,33 @@ import java.io.Serializable; public class NestedStatId implements Serializable { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; - private Integer period; + private Integer period; - private NestedPlayerStatId playerStat; + private NestedPlayerStatId playerStat; - public NestedStatId() - { - } + public NestedStatId() + { + } - public Integer getPeriod() - { - return period; - } + public Integer getPeriod() + { + return period; + } - public void setPeriod(Integer period) - { - this.period = period; - } + public void setPeriod(Integer period) + { + this.period = period; + } - public NestedPlayerStatId getPlayerStat() - { - return playerStat; - } + public NestedPlayerStatId getPlayerStat() + { + return playerStat; + } - public void setPlayerStat(NestedPlayerStatId playerStat) - { - this.playerStat = playerStat; - } + public void setPlayerStat(NestedPlayerStatId playerStat) + { + this.playerStat = playerStat; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/SimpleEntityTableTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/SimpleEntityTableTest.java index 31ffe7d698..bf2369d8b8 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/SimpleEntityTableTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/SimpleEntityTableTest.java @@ -20,61 +20,61 @@ import org.junit.Test; */ public class SimpleEntityTableTest extends BaseEntityManagerFunctionalTestCase { - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Book.class - }; - } + @Override + protected Class[] getAnnotatedClasses() { + return new Class[] { + Book.class + }; + } - @Test - public void test() { + @Test + public void test() { - } + } - //tag::entity-pojo-table-mapping-example[] - @Entity(name = "Book") - @Table( - catalog = "public", - schema = "store", - name = "book" - ) - public static class Book { + //tag::entity-pojo-table-mapping-example[] + @Entity(name = "Book") + @Table( + catalog = "public", + schema = "store", + name = "book" +) + public static class Book { - @Id - private Long id; + @Id + private Long id; - private String title; + private String title; - private String author; + private String author; - //Getters and setters are omitted for brevity - //end::entity-pojo-table-mapping-example[] + //Getters and setters are omitted for brevity + //end::entity-pojo-table-mapping-example[] - public Long getId() { - return id; - } + public Long getId() { + return id; + } - public void setId(Long id) { - this.id = id; - } + public void setId(Long id) { + this.id = id; + } - public String getTitle() { - return title; - } + public String getTitle() { + return title; + } - public void setTitle(String title) { - this.title = title; - } + public void setTitle(String title) { + this.title = title; + } - public String getAuthor() { - return author; - } + public String getAuthor() { + return author; + } - public void setAuthor(String author) { - this.author = author; - } - //tag::entity-pojo-table-mapping-example[] - } - //end::entity-pojo-table-mapping-example[] + public void setAuthor(String author) { + this.author = author; + } + //tag::entity-pojo-table-mapping-example[] + } + //end::entity-pojo-table-mapping-example[] } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/composite/Event.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/composite/Event.java index 269eb8f8b8..f5ea1fce08 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/composite/Event.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/composite/Event.java @@ -17,41 +17,41 @@ import jakarta.persistence.Id; @Entity class Event { - @Id - private EventId id; + @Id + private EventId id; - @Column(name = "event_key") - private String key; + @Column(name = "event_key") + private String key; - @Column(name = "event_value") - private String value; + @Column(name = "event_value") + private String value; - //Getters and setters are omitted for brevity + //Getters and setters are omitted for brevity //end::identifiers-composite-generated-mapping-example[] - public EventId getId() { - return id; - } + public EventId getId() { + return id; + } - public void setId(EventId id) { - this.id = id; - } + public void setId(EventId id) { + this.id = id; + } - public String getKey() { - return key; - } + public String getKey() { + return key; + } - public void setKey(String key) { - this.key = key; - } + public void setKey(String key) { + this.key = key; + } - public String getValue() { - return value; - } + public String getValue() { + return value; + } - public void setValue(String value) { - this.value = value; - } + public void setValue(String value) { + this.value = value; + } //tag::identifiers-composite-generated-mapping-example[] } //end::identifiers-composite-generated-mapping-example[] diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/inheritance/discriminator/MultiInheritanceImplicitDowncastTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/inheritance/discriminator/MultiInheritanceImplicitDowncastTest.java index 46a9e8574e..9ec6a0ef3c 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/inheritance/discriminator/MultiInheritanceImplicitDowncastTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/inheritance/discriminator/MultiInheritanceImplicitDowncastTest.java @@ -68,9 +68,9 @@ public class MultiInheritanceImplicitDowncastTest { } catch (IllegalArgumentException ex) { Assertions.assertTrue( ex.getCause() - .getCause() - .getMessage() - .contains( "Could not resolve attribute 'base' " ) ); + .getCause() + .getMessage() + .contains( "Could not resolve attribute 'base' " ) ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/inheritance/joined/JoinedSubclassTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/inheritance/joined/JoinedSubclassTest.java index aa62e600bc..f354f8ed8c 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/inheritance/joined/JoinedSubclassTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/inheritance/joined/JoinedSubclassTest.java @@ -78,9 +78,9 @@ public class JoinedSubclassTest { assertEquals( s.createQuery( "from Person p where p.class = Customer" ).list().size(), 1 ); assertEquals( s.createQuery( "from Person p where p.class = Person" ).list().size(), 1 ); assertEquals( s.createQuery( "from Person p where type(p) in :who" ) - .setParameter( "who", Customer.class ) - .list() - .size(), 1 ); + .setParameter( "who", Customer.class ) + .list() + .size(), 1 ); assertEquals( s.createQuery( "from Person p where type(p) in :who" ).setParameterList( "who", new Class[] { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/joinformula/ChildEntity.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/joinformula/ChildEntity.java index 616370e372..e80695d4e5 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/joinformula/ChildEntity.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/joinformula/ChildEntity.java @@ -13,13 +13,13 @@ import jakarta.persistence.Id; @Entity public class ChildEntity { - @Id - private Long id; + @Id + private Long id; - @Column(name = "PARENT_ID") - private Long parentId; + @Column(name = "PARENT_ID") + private Long parentId; - @Column - private String name; + @Column + private String name; } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/joinformula/ParentEntity.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/joinformula/ParentEntity.java index d5c9e5a735..a96445a63f 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/joinformula/ParentEntity.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/joinformula/ParentEntity.java @@ -17,17 +17,17 @@ import jakarta.persistence.OneToOne; @Entity public class ParentEntity { - @Id - private Long id; + @Id + private Long id; - @OneToOne(targetEntity = ChildEntity.class, optional = false) - @JoinColumnOrFormula(column = @JoinColumn(name = "ID", referencedColumnName = "PARENT_ID", insertable = false, updatable = false)) - @JoinColumnOrFormula(formula = @JoinFormula(referencedColumnName = "NAME", value = "'Tom'")) - private ChildEntity tom; + @OneToOne(targetEntity = ChildEntity.class, optional = false) + @JoinColumnOrFormula(column = @JoinColumn(name = "ID", referencedColumnName = "PARENT_ID", insertable = false, updatable = false)) + @JoinColumnOrFormula(formula = @JoinFormula(referencedColumnName = "NAME", value = "'Tom'")) + private ChildEntity tom; - @OneToOne(targetEntity = ChildEntity.class, optional = false) - @JoinColumnOrFormula(column = @JoinColumn(name = "ID", referencedColumnName = "PARENT_ID", insertable = false, updatable = false)) - @JoinColumnOrFormula(formula = @JoinFormula(referencedColumnName = "NAME", value = "'Ben'")) - private ChildEntity ben; + @OneToOne(targetEntity = ChildEntity.class, optional = false) + @JoinColumnOrFormula(column = @JoinColumn(name = "ID", referencedColumnName = "PARENT_ID", insertable = false, updatable = false)) + @JoinColumnOrFormula(formula = @JoinFormula(referencedColumnName = "NAME", value = "'Ben'")) + private ChildEntity ben; } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/lazytoone/JoinFetchedManyToOneAllowProxyTests.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/lazytoone/JoinFetchedManyToOneAllowProxyTests.java index 2c5d0888bf..6213178a66 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/lazytoone/JoinFetchedManyToOneAllowProxyTests.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/lazytoone/JoinFetchedManyToOneAllowProxyTests.java @@ -46,7 +46,7 @@ import org.junit.jupiter.api.Test; @DomainModel( annotatedClasses = { JoinFetchedManyToOneAllowProxyTests.Customer.class, - JoinFetchedManyToOneAllowProxyTests.Order.class + JoinFetchedManyToOneAllowProxyTests.Order.class } ) @SessionFactory diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/manytomany/ManyToManyHqlMemberOfQueryTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/manytomany/ManyToManyHqlMemberOfQueryTest.java index d0e4ce87f7..6adcf8ec26 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/manytomany/ManyToManyHqlMemberOfQueryTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/manytomany/ManyToManyHqlMemberOfQueryTest.java @@ -59,7 +59,7 @@ public class ManyToManyHqlMemberOfQueryTest { person1.setNickName( "JD" ); person1.setAddress( "Earth" ); person1.setCreatedOn( Timestamp.from( LocalDateTime.of( 2000, 1, 1, 0, 0, 0 ) - .toInstant( ZoneOffset.UTC ) ) ); + .toInstant( ZoneOffset.UTC ) ) ); person1.getAddresses().put( AddressType.HOME, "Home address" ); person1.getAddresses().put( AddressType.OFFICE, "Office address" ); session.persist( person1 ); @@ -67,7 +67,7 @@ public class ManyToManyHqlMemberOfQueryTest { Person person2 = new Person( "Mrs. John Doe" ); person2.setAddress( "Earth" ); person2.setCreatedOn( Timestamp.from( LocalDateTime.of( 2000, 1, 2, 12, 0, 0 ) - .toInstant( ZoneOffset.UTC ) ) ); + .toInstant( ZoneOffset.UTC ) ) ); session.persist( person2 ); Person person3 = new Person( "Dr_ John Doe" ); @@ -77,19 +77,19 @@ public class ManyToManyHqlMemberOfQueryTest { phone1.setId( 1L ); person1.addPhone( phone1 ); phone1.getRepairTimestamps().add( Timestamp.from( LocalDateTime.of( 2005, 1, 1, 12, 0, 0 ) - .toInstant( ZoneOffset.UTC ) ) ); + .toInstant( ZoneOffset.UTC ) ) ); phone1.getRepairTimestamps().add( Timestamp.from( LocalDateTime.of( 2006, 1, 1, 12, 0, 0 ) - .toInstant( ZoneOffset.UTC ) ) ); + .toInstant( ZoneOffset.UTC ) ) ); Call call11 = new Call(); call11.setDuration( 12 ); call11.setTimestamp( Timestamp.from( LocalDateTime.of( 2000, 1, 1, 0, 0, 0 ) - .toInstant( ZoneOffset.UTC ) ) ); + .toInstant( ZoneOffset.UTC ) ) ); Call call12 = new Call(); call12.setDuration( 33 ); call12.setTimestamp( Timestamp.from( LocalDateTime.of( 2000, 1, 1, 1, 0, 0 ) - .toInstant( ZoneOffset.UTC ) ) ); + .toInstant( ZoneOffset.UTC ) ) ); phone1.addCall( call11 ); phone1.addCall( call12 ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/manytoone/jointable/InverseManyToOneJoinTableSimpleIdTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/manytoone/jointable/InverseManyToOneJoinTableSimpleIdTest.java index 5e7dc1bebf..d234ff8fd5 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/manytoone/jointable/InverseManyToOneJoinTableSimpleIdTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/manytoone/jointable/InverseManyToOneJoinTableSimpleIdTest.java @@ -116,9 +116,9 @@ public class InverseManyToOneJoinTableSimpleIdTest { @Entity( name = "Book" ) @Table( name = "books" ) public static class Book { - @Id - private Integer id; - @Basic + @Id + private Integer id; + @Basic private String name; @ManyToOne @JoinTable(name = "book_authors", @@ -152,9 +152,9 @@ public class InverseManyToOneJoinTableSimpleIdTest { @Entity( name = "Author" ) @Table( name = "authors" ) public static class Author { - @Id - private Integer id; - @Basic + @Id + private Integer id; + @Basic private String name; @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, mappedBy = "author") diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/mutability/attribute/BasicAttributeMutabilityTests.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/mutability/attribute/BasicAttributeMutabilityTests.java index b65313316a..e3979180d6 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/mutability/attribute/BasicAttributeMutabilityTests.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/mutability/attribute/BasicAttributeMutabilityTests.java @@ -227,10 +227,10 @@ public class BasicAttributeMutabilityTests { @Entity( name = "TheEntity" ) @Table( name = "TheEntity" ) public static class TheEntity { - @Id - private Integer id; + @Id + private Integer id; - @Basic + @Basic private String name; //tag::attribute-immutable-example[] diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/mutability/attribute/EntityAttributeMutabilityTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/mutability/attribute/EntityAttributeMutabilityTest.java index bb5e1f807a..5e81b26031 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/mutability/attribute/EntityAttributeMutabilityTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/mutability/attribute/EntityAttributeMutabilityTest.java @@ -66,9 +66,9 @@ public class EntityAttributeMutabilityTest { @Entity( name = "Employee" ) @Table( name = "Employee" ) public static class Employee { - @Id - private Integer id; - @Basic + @Id + private Integer id; + @Basic private String name; @ManyToOne @JoinColumn( name = "manager_fk" ) diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/mutability/converted/ImmutabilityConverterTests.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/mutability/converted/ImmutabilityConverterTests.java index 3e40681e9b..05dcb8261a 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/mutability/converted/ImmutabilityConverterTests.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/mutability/converted/ImmutabilityConverterTests.java @@ -54,9 +54,9 @@ public class ImmutabilityConverterTests { @Entity( name = "TestEntity" ) @Table( name = "TestEntity" ) public static class TestEntity { - @Id - private Integer id; - @Basic + @Id + private Integer id; + @Basic private String name; @Convert( converter = ImmutabilityDateConverter.class ) private Date theDate; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/mutability/converted/ImmutableConvertedBaselineTests.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/mutability/converted/ImmutableConvertedBaselineTests.java index 24e77dab39..4826d2d030 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/mutability/converted/ImmutableConvertedBaselineTests.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/mutability/converted/ImmutableConvertedBaselineTests.java @@ -197,10 +197,10 @@ public class ImmutableConvertedBaselineTests { @Entity( name = "TheEntity" ) @Table( name = "TheEntity" ) public static class TheEntity { - @Id - private Integer id; + @Id + private Integer id; - @Basic + @Basic private String name; @Immutable diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/mutability/converted/ImmutableConverterTests.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/mutability/converted/ImmutableConverterTests.java index 19e4ae9d3a..bd0fd27190 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/mutability/converted/ImmutableConverterTests.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/mutability/converted/ImmutableConverterTests.java @@ -68,9 +68,9 @@ public class ImmutableConverterTests { @Entity( name = "TestEntity" ) @Table( name = "TestEntity" ) public static class TestEntity { - @Id - private Integer id; - @Basic + @Id + private Integer id; + @Basic private String name; @Convert( converter = ImmutableDateConverter.class ) private Date immutableDate; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/naturalid/cid/Account.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/naturalid/cid/Account.java index 3e61543d30..8557351ef1 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/naturalid/cid/Account.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/naturalid/cid/Account.java @@ -19,24 +19,24 @@ import org.hibernate.annotations.NaturalId; @Entity @Table( name = "t_acct" ) public class Account { - @EmbeddedId - private AccountId accountId; + @EmbeddedId + private AccountId accountId; - @Basic( optional = false ) - @NaturalId - private String shortCode; + @Basic( optional = false ) + @NaturalId + private String shortCode; - protected Account() { - } + protected Account() { + } - public Account(AccountId accountId, String shortCode) { - this.accountId = accountId; - this.shortCode = shortCode; - } - public String getShortCode() { - return shortCode; - } - public AccountId getAccountId() { - return accountId; - } + public Account(AccountId accountId, String shortCode) { + this.accountId = accountId; + this.shortCode = shortCode; + } + public String getShortCode() { + return shortCode; + } + public AccountId getAccountId() { + return accountId; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/naturalid/cid/AccountId.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/naturalid/cid/AccountId.java index dfb092126e..bb3c4ab702 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/naturalid/cid/AccountId.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/naturalid/cid/AccountId.java @@ -13,33 +13,33 @@ import jakarta.persistence.Embeddable; */ @Embeddable public class AccountId implements java.io.Serializable { - private final int id; + private final int id; - protected AccountId() { - this.id = 0; - } + protected AccountId() { + this.id = 0; + } - public AccountId(int id) { - this.id = id; - } - public int intValue() { - return id; - } - @Override - public int hashCode() { - return id; - } - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - AccountId other = (AccountId) obj; - if (other != null && id != other.id) - return false; - return true; - } + public AccountId(int id) { + this.id = id; + } + public int intValue() { + return id; + } + @Override + public int hashCode() { + return id; + } + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + AccountId other = (AccountId) obj; + if (other != null && id != other.id) + return false; + return true; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/naturalid/cid/AnnotatedCompositeIdAndNaturalIdTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/naturalid/cid/AnnotatedCompositeIdAndNaturalIdTest.java index 803588c4cb..35b846a9a6 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/naturalid/cid/AnnotatedCompositeIdAndNaturalIdTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/naturalid/cid/AnnotatedCompositeIdAndNaturalIdTest.java @@ -19,11 +19,11 @@ import static org.hibernate.cfg.AvailableSettings.USE_SECOND_LEVEL_CACHE; * @author Donnchadh O Donnabhain */ @ServiceRegistry( - settings = { - @Setting( name = USE_SECOND_LEVEL_CACHE, value = "false" ), - @Setting( name = USE_QUERY_CACHE, value = "false" ), - @Setting( name = GENERATE_STATISTICS, value = "false" ) - } + settings = { + @Setting( name = USE_SECOND_LEVEL_CACHE, value = "false" ), + @Setting( name = USE_QUERY_CACHE, value = "false" ), + @Setting( name = GENERATE_STATISTICS, value = "false" ) + } ) @DomainModel( annotatedClasses = { Account.class, AccountId.class } ) @SessionFactory diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/naturalid/cid/HbmCompositeIdAndNaturalIdTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/naturalid/cid/HbmCompositeIdAndNaturalIdTest.java index 5263241552..93b41f2555 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/naturalid/cid/HbmCompositeIdAndNaturalIdTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/naturalid/cid/HbmCompositeIdAndNaturalIdTest.java @@ -19,11 +19,11 @@ import static org.hibernate.cfg.AvailableSettings.USE_SECOND_LEVEL_CACHE; * @author Donnchadh O Donnabhain */ @ServiceRegistry( - settings = { - @Setting( name = USE_SECOND_LEVEL_CACHE, value = "false" ), - @Setting( name = USE_QUERY_CACHE, value = "false" ), - @Setting( name = GENERATE_STATISTICS, value = "false" ) - } + settings = { + @Setting( name = USE_SECOND_LEVEL_CACHE, value = "false" ), + @Setting( name = USE_QUERY_CACHE, value = "false" ), + @Setting( name = GENERATE_STATISTICS, value = "false" ) + } ) @DomainModel( xmlMappings = "org/hibernate/orm/test/mapping/naturalid/cid/Account.hbm.xml" ) @SessionFactory diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/naturalid/immutable/ImmutableManyToOneNaturalIdAnnotationTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/naturalid/immutable/ImmutableManyToOneNaturalIdAnnotationTest.java index 2252291444..08093a3897 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/naturalid/immutable/ImmutableManyToOneNaturalIdAnnotationTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/naturalid/immutable/ImmutableManyToOneNaturalIdAnnotationTest.java @@ -31,9 +31,9 @@ import static org.junit.Assert.assertTrue; @SessionFactory public class ImmutableManyToOneNaturalIdAnnotationTest { - @Test - @JiraKey( value = "HHH-10360") - public void testNaturalIdNullability(SessionFactoryScope scope) { + @Test + @JiraKey( value = "HHH-10360") + public void testNaturalIdNullability(SessionFactoryScope scope) { // nullability is not specified for either properties making up // the natural ID, so they should be nullable by annotation-specific default diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/naturalid/immutable/ImmutableManyToOneNaturalIdHbmTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/naturalid/immutable/ImmutableManyToOneNaturalIdHbmTest.java index 7727ff43ef..b639d16f21 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/naturalid/immutable/ImmutableManyToOneNaturalIdHbmTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/naturalid/immutable/ImmutableManyToOneNaturalIdHbmTest.java @@ -70,9 +70,9 @@ public class ImmutableManyToOneNaturalIdHbmTest { ); } - @Test - @JiraKey( value = "HHH-10360") - public void checkingMapping(SessionFactoryScope scope) { + @Test + @JiraKey( value = "HHH-10360") + public void checkingMapping(SessionFactoryScope scope) { final RuntimeMetamodels runtimeMetamodels = scope.getSessionFactory().getRuntimeMetamodels(); final EntityMappingType childMapping = runtimeMetamodels.getEntityMappingType( Child.class.getName() ); @@ -130,11 +130,11 @@ public class ImmutableManyToOneNaturalIdHbmTest { } } ); - } + } @Test @SuppressWarnings( {"unchecked"}) - public void testSaveParentWithDetachedChildren(SessionFactoryScope scope) { + public void testSaveParentWithDetachedChildren(SessionFactoryScope scope) { final Parent p = scope.fromTransaction( (session) -> session.createQuery( "from Parent p join fetch p.children where p.name = 'alex'", Parent.class ) .setCacheable( true ) @@ -148,10 +148,10 @@ public class ImmutableManyToOneNaturalIdHbmTest { // todo (6.0) : ^^ this test has nothing to do with (im)mutability... - Child c2 = new Child( 2, "joey", p ); - p.getChildren().add( c2 ); + Child c2 = new Child( 2, "joey", p ); + p.getChildren().add( c2 ); - scope.inTransaction( (session) -> session.merge( p ) ); - } + scope.inTransaction( (session) -> session.merge( p ) ); + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/onetomany/OneToManyBidirectionalTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/onetomany/OneToManyBidirectionalTest.java index e8ea7ea8c9..b7c037d2e1 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/onetomany/OneToManyBidirectionalTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/onetomany/OneToManyBidirectionalTest.java @@ -109,8 +109,8 @@ public class OneToManyBidirectionalTest { /* select l1_0."order_id", l1_0.id - from Item as l1_0 - where l1_0."order_id" = ? + from Item as l1_0 + where l1_0."order_id" = ? */ sqlStatementInterceptor.assertNumberOfJoins( 0, 0 ); @@ -178,10 +178,10 @@ public class OneToManyBidirectionalTest { List results = session.createQuery( "select i from Item i", Item.class ).list(); /* 1) select i1_0.id, i1_0."order_id" - from Item as i1_0 - 2) select o1_0.id, o1_0.name - from "Order" as o1_0 - where o1_0.id = ? + from Item as i1_0 + 2) select o1_0.id, o1_0.name + from "Order" as o1_0 + where o1_0.id = ? */ sqlStatementInterceptor.assertNumberOfJoins( 0, 0 ); @@ -198,8 +198,8 @@ public class OneToManyBidirectionalTest { /* select l1_0."order_id", l1_0.id - from Item as l1_0 - where l1_0."order_id" = ? + from Item as l1_0 + where l1_0."order_id" = ? */ sqlStatementInterceptor.assertNumberOfJoins( 0, 0 ); @@ -221,11 +221,11 @@ public class OneToManyBidirectionalTest { List results = session.createQuery( "select i from Item i join i.order", Item.class ).list(); /* 1) select i1_0.id, i1_0."order_id" - from Item as i1_0 - inner join "Order" as o1_0 on i1_0."order_id" = o1_0.id - 2) select o1_0.id, o1_0.name - from "Order" as o1_0 - where o1_0.id = ? + from Item as i1_0 + inner join "Order" as o1_0 on i1_0."order_id" = o1_0.id + 2) select o1_0.id, o1_0.name + from "Order" as o1_0 + where o1_0.id = ? */ sqlStatementInterceptor.assertNumberOfJoins( 0, SqlAstJoinType.INNER, 1 ); @@ -241,8 +241,8 @@ public class OneToManyBidirectionalTest { /* select l1_0."order_id", l1_0.id - from Item as l1_0 - where l1_0."order_id" = ? + from Item as l1_0 + where l1_0."order_id" = ? */ sqlStatementInterceptor.assertNumberOfJoins( 0, 0 ); @@ -265,8 +265,8 @@ public class OneToManyBidirectionalTest { /* select i1_0.id, o1_0.id, o1_0.name - from Item as i1_0 - inner join "Order" as o1_0 on i1_0."order_id" = o1_0.id + from Item as i1_0 + inner join "Order" as o1_0 on i1_0."order_id" = o1_0.id */ sqlStatementInterceptor.assertNumberOfJoins( 0, SqlAstJoinType.INNER, 1 ); @@ -282,8 +282,8 @@ public class OneToManyBidirectionalTest { /* select l1_0."order_id", l1_0.id - from Item as l1_0 - where l1_0."order_id" = ? + from Item as l1_0 + where l1_0."order_id" = ? */ sqlStatementInterceptor.assertNumberOfJoins( 0, 0 ); @@ -311,10 +311,10 @@ public class OneToManyBidirectionalTest { /* 1) select i1_0.id, i1_0."order_id" - from Item as i1_0 - inner join "Order" as o1_0 on i1_0."order_id" = o1_0.id - inner join Item as l1_0 on l1_0."order_id" = o1_0.id - 2) select o1_0.id, o1_0.name + from Item as i1_0 + inner join "Order" as o1_0 on i1_0."order_id" = o1_0.id + inner join Item as l1_0 on l1_0."order_id" = o1_0.id + 2) select o1_0.id, o1_0.name from "Order" as o1_0 where o1_0.id = ? */ @@ -333,8 +333,8 @@ public class OneToManyBidirectionalTest { /* select l1_0."order_id", l1_0.id - from Item as l1_0 - where l1_0."order_id" = ? + from Item as l1_0 + where l1_0."order_id" = ? */ sqlStatementInterceptor.assertNumberOfJoins( 0, 0 ); @@ -358,9 +358,9 @@ public class OneToManyBidirectionalTest { Order order = session.find( Order.class, 3L ); /* - select o1_0.id, o1_0.name - from "Order" as o1_0 - where o1_0.id = ? + select o1_0.id, o1_0.name + from "Order" as o1_0 + where o1_0.id = ? */ sqlStatementInterceptor.assertNumberOfJoins( 0, 0 ); @@ -374,8 +374,8 @@ public class OneToManyBidirectionalTest { /* select l1_0."order_id", l1_0.id - from Item as l1_0 - where l1_0."order_id" = ? + from Item as l1_0 + where l1_0."order_id" = ? */ sqlStatementInterceptor.assertNumberOfJoins( 0, 0 ); @@ -399,7 +399,7 @@ public class OneToManyBidirectionalTest { /* select o1_0.id, o1_0.name - from "Order" as o1_0 + from "Order" as o1_0 */ sqlStatementInterceptor.assertNumberOfJoins( 0, 0 ); @@ -415,8 +415,8 @@ public class OneToManyBidirectionalTest { /* select l1_0."order_id", l1_0.id - from Item as l1_0 - where l1_0."order_id" = ? + from Item as l1_0 + where l1_0."order_id" = ? */ sqlStatementInterceptor.assertNumberOfJoins( 0, 0 ); @@ -439,8 +439,8 @@ public class OneToManyBidirectionalTest { /* select o1_0.id, o1_0.name - from "Order" as o1_0 - inner join Item as l1_0 on l1_0."order_id" = o1_0.id + from "Order" as o1_0 + inner join Item as l1_0 on l1_0."order_id" = o1_0.id */ sqlStatementInterceptor.assertNumberOfJoins( 0, SqlAstJoinType.INNER, 1 ); @@ -456,8 +456,8 @@ public class OneToManyBidirectionalTest { /* select l1_0."order_id", l1_0.id - from Item as l1_0 - where l1_0."order_id" = ? + from Item as l1_0 + where l1_0."order_id" = ? */ sqlStatementInterceptor.assertNumberOfJoins( 0, 0 ); @@ -481,8 +481,8 @@ public class OneToManyBidirectionalTest { /* select o1_0.id, l1_0."order_id", l1_0.id, o1_0.name - from "Order" as o1_0 - inner join Item as l1_0 on l1_0."order_id" = o1_0.id + from "Order" as o1_0 + inner join Item as l1_0 on l1_0."order_id" = o1_0.id */ sqlStatementInterceptor.assertNumberOfJoins( 0, SqlAstJoinType.INNER, 1 ); @@ -512,10 +512,10 @@ public class OneToManyBidirectionalTest { ).list(); /* - select o1_0.id, l1_0."order_id", l1_0.id, o1_0.name, o2_0.id, o2_0.name - from "Order" as o1_0 - inner join Item as l1_0 on l1_0."order_id" = o1_0.id - inner join "Order" as o2_0 on l1_0."order_id" = o2_0.id + select o1_0.id, l1_0."order_id", l1_0.id, o1_0.name, o2_0.id, o2_0.name + from "Order" as o1_0 + inner join Item as l1_0 on l1_0."order_id" = o1_0.id + inner join "Order" as o2_0 on l1_0."order_id" = o2_0.id */ // todo (6.0): this was originally intended to produce only a single SQL join, @@ -532,8 +532,8 @@ public class OneToManyBidirectionalTest { /* select l1_0."order_id", l1_0.id - from Item as l1_0 - where l1_0."order_id" = ? + from Item as l1_0 + where l1_0."order_id" = ? */ sqlStatementInterceptor.assertNumberOfJoins( 0, 0 ); @@ -557,10 +557,10 @@ public class OneToManyBidirectionalTest { ).list(); /* - select o1_0.id, l1_0."order_id", l1_0.id, o1_0.name, o2_0.id, o2_0.name - from "Order" as o1_0 - inner join Item as l1_0 on l1_0."order_id" = o1_0.id - inner join "Order" as o2_0 on l1_0."order_id" = o2_0.id + select o1_0.id, l1_0."order_id", l1_0.id, o1_0.name, o2_0.id, o2_0.name + from "Order" as o1_0 + inner join Item as l1_0 on l1_0."order_id" = o1_0.id + inner join "Order" as o2_0 on l1_0."order_id" = o2_0.id */ // todo (6.0): this was originally intended to produce only a single SQL join, @@ -597,9 +597,9 @@ public class OneToManyBidirectionalTest { /* select i1_0.id, o1_0.id, l1_0."order_id", l1_0.id, o1_0.name - from Item as i1_0 - inner join "Order" as o1_0 on i1_0."order_id" = o1_0.id - inner join Item as l1_0 on l1_0."order_id" = o1_0.id + from Item as i1_0 + inner join "Order" as o1_0 on i1_0."order_id" = o1_0.id + inner join Item as l1_0 on l1_0."order_id" = o1_0.id */ sqlStatementInterceptor.assertNumberOfJoins( 0, SqlAstJoinType.INNER, 2 ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/onetomany/OneToManyHqlMemberOfQueryTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/onetomany/OneToManyHqlMemberOfQueryTest.java index b6fcce9b0d..0124242e35 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/onetomany/OneToManyHqlMemberOfQueryTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/onetomany/OneToManyHqlMemberOfQueryTest.java @@ -62,7 +62,7 @@ public class OneToManyHqlMemberOfQueryTest { person1.setNickName( "JD" ); person1.setAddress( "Earth" ); person1.setCreatedOn( Timestamp.from( LocalDateTime.of( 2000, 1, 1, 0, 0, 0 ) - .toInstant( ZoneOffset.UTC ) ) ); + .toInstant( ZoneOffset.UTC ) ) ); person1.getAddresses().put( AddressType.HOME, "Home address" ); person1.getAddresses().put( AddressType.OFFICE, "Office address" ); session.persist( person1 ); @@ -70,7 +70,7 @@ public class OneToManyHqlMemberOfQueryTest { Person person2 = new Person( "Mrs. John Doe" ); person2.setAddress( "Earth" ); person2.setCreatedOn( Timestamp.from( LocalDateTime.of( 2000, 1, 2, 12, 0, 0 ) - .toInstant( ZoneOffset.UTC ) ) ); + .toInstant( ZoneOffset.UTC ) ) ); session.persist( person2 ); Person person3 = new Person( "Dr_ John Doe" ); @@ -80,19 +80,19 @@ public class OneToManyHqlMemberOfQueryTest { phone1.setId( 1L ); person1.addPhone( phone1 ); phone1.getRepairTimestamps().add( Timestamp.from( LocalDateTime.of( 2005, 1, 1, 12, 0, 0 ) - .toInstant( ZoneOffset.UTC ) ) ); + .toInstant( ZoneOffset.UTC ) ) ); phone1.getRepairTimestamps().add( Timestamp.from( LocalDateTime.of( 2006, 1, 1, 12, 0, 0 ) - .toInstant( ZoneOffset.UTC ) ) ); + .toInstant( ZoneOffset.UTC ) ) ); Call call11 = new Call(); call11.setDuration( 12 ); call11.setTimestamp( Timestamp.from( LocalDateTime.of( 2000, 1, 1, 0, 0, 0 ) - .toInstant( ZoneOffset.UTC ) ) ); + .toInstant( ZoneOffset.UTC ) ) ); Call call12 = new Call(); call12.setDuration( 33 ); call12.setTimestamp( Timestamp.from( LocalDateTime.of( 2000, 1, 1, 1, 0, 0 ) - .toInstant( ZoneOffset.UTC ) ) ); + .toInstant( ZoneOffset.UTC ) ) ); phone1.addCall( call11 ); phone1.addCall( call12 ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/type/java/BasicCollectionJavaTypeDescriptorTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/type/java/BasicCollectionJavaTypeDescriptorTest.java index e348a9ad67..4ec3eb03c3 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/type/java/BasicCollectionJavaTypeDescriptorTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/type/java/BasicCollectionJavaTypeDescriptorTest.java @@ -26,23 +26,23 @@ import static org.junit.Assert.assertTrue; */ public class BasicCollectionJavaTypeDescriptorTest { - private static final BasicCollectionJavaType, String> stringSetJavaType = createJavaType(); + private static final BasicCollectionJavaType, String> stringSetJavaType = createJavaType(); - @Test - @JiraKey( "HHH-18073" ) - public void wrapShouldRetainOrderOfSet() { - assertTrue("BasicCollectionJavaType.wrap() should retain order of Set", - stringSetJavaType.wrap(Set.of( "foo", "bar" ), null) instanceof LinkedHashSet); - } + @Test + @JiraKey( "HHH-18073" ) + public void wrapShouldRetainOrderOfSet() { + assertTrue("BasicCollectionJavaType.wrap() should retain order of Set", + stringSetJavaType.wrap(Set.of( "foo", "bar" ), null) instanceof LinkedHashSet); + } - @Test - public void deepCopyShouldRetainOrderOfSet() { - assertTrue("BasicCollectionJavaType.getMutabilityPlan().deepCopy() should retain order of Set", - stringSetJavaType.getMutabilityPlan().deepCopy(Set.of( "foo", "bar" )) instanceof LinkedHashSet); - } + @Test + public void deepCopyShouldRetainOrderOfSet() { + assertTrue("BasicCollectionJavaType.getMutabilityPlan().deepCopy() should retain order of Set", + stringSetJavaType.getMutabilityPlan().deepCopy(Set.of( "foo", "bar" )) instanceof LinkedHashSet); + } - @SuppressWarnings("unchecked") - private static BasicCollectionJavaType, String> createJavaType() { + @SuppressWarnings("unchecked") + private static BasicCollectionJavaType, String> createJavaType() { ParameterizedType type; try { type = (ParameterizedType) TestEntity.class.getDeclaredField("tags").getGenericType(); @@ -50,19 +50,19 @@ public class BasicCollectionJavaTypeDescriptorTest { throw new RuntimeException(e); } return new BasicCollectionJavaType<>( - type, - StringJavaType.INSTANCE, - (StandardSetSemantics) StandardSetSemantics.INSTANCE - ); - } + type, + StringJavaType.INSTANCE, + (StandardSetSemantics) StandardSetSemantics.INSTANCE + ); + } - @Entity - static class TestEntity { + @Entity + static class TestEntity { - @Id - @GeneratedValue - Long id; + @Id + @GeneratedValue + Long id; - Set tags; - } + Set tags; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/type/java/BooleanJavaTypeDescriptorTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/type/java/BooleanJavaTypeDescriptorTest.java index b11845a92a..9a8322a326 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/type/java/BooleanJavaTypeDescriptorTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/type/java/BooleanJavaTypeDescriptorTest.java @@ -24,199 +24,199 @@ import org.junit.Test; import static org.junit.Assert.*; public class BooleanJavaTypeDescriptorTest { - private BooleanJavaType underTest = new BooleanJavaType(); + private BooleanJavaType underTest = new BooleanJavaType(); - @Test - @JiraKey( "HHH-17275" ) - public void testCheckConditionShouldReturnCorrectStatementWhenNullXStringGiven() { - // given - // when - String checkCondition = underTest.getCheckCondition("is_active", VarcharJdbcType.INSTANCE, new BooleanXConverter(), new AnyDialect()); - // then - assertEquals("is_active in ('X') or is_active is null", checkCondition); - } + @Test + @JiraKey( "HHH-17275" ) + public void testCheckConditionShouldReturnCorrectStatementWhenNullXStringGiven() { + // given + // when + String checkCondition = underTest.getCheckCondition("is_active", VarcharJdbcType.INSTANCE, new BooleanXConverter(), new AnyDialect()); + // then + assertEquals("is_active in ('X') or is_active is null", checkCondition); + } - @Test - public void testCheckConditionShouldReturnCorrectStatementWhenTFStringGiven() { - // given - // when - String checkCondition = underTest.getCheckCondition("is_active", VarcharJdbcType.INSTANCE, new TrueFalseConverter(), new AnyDialect()); - // then - assertEquals("is_active in ('F','T')", checkCondition); - } + @Test + public void testCheckConditionShouldReturnCorrectStatementWhenTFStringGiven() { + // given + // when + String checkCondition = underTest.getCheckCondition("is_active", VarcharJdbcType.INSTANCE, new TrueFalseConverter(), new AnyDialect()); + // then + assertEquals("is_active in ('F','T')", checkCondition); + } - @Test - public void testCheckConditionShouldReturnCorrectStatementWhen1AndNullIntegerGiven() { - // given - // when - String checkCondition = underTest.getCheckCondition("is_active", IntegerJdbcType.INSTANCE, new OneNullBooleanConverter(), new AnyDialect()); - // then - assertEquals("is_active in (1) or is_active is null", checkCondition); - } + @Test + public void testCheckConditionShouldReturnCorrectStatementWhen1AndNullIntegerGiven() { + // given + // when + String checkCondition = underTest.getCheckCondition("is_active", IntegerJdbcType.INSTANCE, new OneNullBooleanConverter(), new AnyDialect()); + // then + assertEquals("is_active in (1) or is_active is null", checkCondition); + } - @Test - public void testCheckConditionShouldReturnCorrectStatementWhen1And0IntegerGiven() { - // given - // when - String checkCondition = underTest.getCheckCondition("is_active", IntegerJdbcType.INSTANCE, new NumericBooleanConverter(), new AnyDialect()); - // then - assertEquals("is_active in (0,1)", checkCondition); - } + @Test + public void testCheckConditionShouldReturnCorrectStatementWhen1And0IntegerGiven() { + // given + // when + String checkCondition = underTest.getCheckCondition("is_active", IntegerJdbcType.INSTANCE, new NumericBooleanConverter(), new AnyDialect()); + // then + assertEquals("is_active in (0,1)", checkCondition); + } - @Test - public void testCheckConditionShouldReturnCorrectStatementWhen1And0AndNullIntegerGiven() { - // given - // when - String checkCondition = underTest.getCheckCondition("is_active", IntegerJdbcType.INSTANCE, new TriStateBooleanConverter(), new AnyDialect()); - // then - assertEquals("is_active in (0,1,-1)", checkCondition); - } + @Test + public void testCheckConditionShouldReturnCorrectStatementWhen1And0AndNullIntegerGiven() { + // given + // when + String checkCondition = underTest.getCheckCondition("is_active", IntegerJdbcType.INSTANCE, new TriStateBooleanConverter(), new AnyDialect()); + // then + assertEquals("is_active in (0,1,-1)", checkCondition); + } - @Test - public void testWrapShouldReturnTrueWhenYStringGiven() { - // given - // when - Boolean result = underTest.wrap("Y", null); - // then - assertTrue(result); - } + @Test + public void testWrapShouldReturnTrueWhenYStringGiven() { + // given + // when + Boolean result = underTest.wrap("Y", null); + // then + assertTrue(result); + } - @Test - public void testWrapShouldReturnFalseWhenFStringGiven() { - // given - // when - Boolean result = underTest.wrap("N", null); - // then - assertFalse(result); - } + @Test + public void testWrapShouldReturnFalseWhenFStringGiven() { + // given + // when + Boolean result = underTest.wrap("N", null); + // then + assertFalse(result); + } - @Test - public void testWrapShouldReturnFalseWhenRandomStringGiven() { - // given - // when - Boolean result = underTest.wrap("k", null); - // then - assertFalse(result); - } + @Test + public void testWrapShouldReturnFalseWhenRandomStringGiven() { + // given + // when + Boolean result = underTest.wrap("k", null); + // then + assertFalse(result); + } - @Test - public void testWrapShouldReturnNullWhenNullStringGiven() { - // given - // when - Boolean result = underTest.wrap(null, null); - // then - assertNull(result); - } + @Test + public void testWrapShouldReturnNullWhenNullStringGiven() { + // given + // when + Boolean result = underTest.wrap(null, null); + // then + assertNull(result); + } - @Test - public void testWrapShouldReturnFalseWhenEmptyStringGiven() { - // given - // when - Boolean result = underTest.wrap("", null); - // then - assertFalse(result); - } + @Test + public void testWrapShouldReturnFalseWhenEmptyStringGiven() { + // given + // when + Boolean result = underTest.wrap("", null); + // then + assertFalse(result); + } - private static class AnyDialect extends Dialect { + private static class AnyDialect extends Dialect { - } + } - private static class BooleanXConverter implements AttributeConverter, BasicValueConverter { + private static class BooleanXConverter implements AttributeConverter, BasicValueConverter { - @Override - public String convertToDatabaseColumn(Boolean value) { - return value != null && value ? "X" : null; - } + @Override + public String convertToDatabaseColumn(Boolean value) { + return value != null && value ? "X" : null; + } - @Override - public Boolean convertToEntityAttribute(String value) { - return value != null; - } + @Override + public Boolean convertToEntityAttribute(String value) { + return value != null; + } - @Override - public @Nullable Boolean toDomainValue(@Nullable String relationalForm) { - return convertToEntityAttribute(relationalForm); - } + @Override + public @Nullable Boolean toDomainValue(@Nullable String relationalForm) { + return convertToEntityAttribute(relationalForm); + } - @Override - public @Nullable String toRelationalValue(@Nullable Boolean domainForm) { - return convertToDatabaseColumn(domainForm); - } + @Override + public @Nullable String toRelationalValue(@Nullable Boolean domainForm) { + return convertToDatabaseColumn(domainForm); + } - @Override - public JavaType getDomainJavaType() { - return BooleanJavaType.INSTANCE; - } + @Override + public JavaType getDomainJavaType() { + return BooleanJavaType.INSTANCE; + } - @Override - public JavaType getRelationalJavaType() { - return StringJavaType.INSTANCE; - } - } + @Override + public JavaType getRelationalJavaType() { + return StringJavaType.INSTANCE; + } + } - private static class OneNullBooleanConverter implements AttributeConverter, BasicValueConverter { - @Override - public Integer convertToDatabaseColumn(Boolean attribute) { - return attribute != null && attribute ? 1 : null; - } + private static class OneNullBooleanConverter implements AttributeConverter, BasicValueConverter { + @Override + public Integer convertToDatabaseColumn(Boolean attribute) { + return attribute != null && attribute ? 1 : null; + } - @Override - public Boolean convertToEntityAttribute(Integer dbData) { - return dbData != null && dbData == 1; - } + @Override + public Boolean convertToEntityAttribute(Integer dbData) { + return dbData != null && dbData == 1; + } - @Override - public @Nullable Boolean toDomainValue(@Nullable Integer relationalForm) { - return convertToEntityAttribute(relationalForm); - } + @Override + public @Nullable Boolean toDomainValue(@Nullable Integer relationalForm) { + return convertToEntityAttribute(relationalForm); + } - @Override - public @Nullable Integer toRelationalValue(@Nullable Boolean domainForm) { - return convertToDatabaseColumn(domainForm); - } + @Override + public @Nullable Integer toRelationalValue(@Nullable Boolean domainForm) { + return convertToDatabaseColumn(domainForm); + } - @Override - public JavaType getDomainJavaType() { - return BooleanJavaType.INSTANCE; - } + @Override + public JavaType getDomainJavaType() { + return BooleanJavaType.INSTANCE; + } - @Override - public JavaType getRelationalJavaType() { - return IntegerJavaType.INSTANCE; - } - } + @Override + public JavaType getRelationalJavaType() { + return IntegerJavaType.INSTANCE; + } + } - private static class TriStateBooleanConverter implements AttributeConverter, BasicValueConverter { - @Override - public Integer convertToDatabaseColumn(Boolean attribute) { - if (attribute == null) return -1; - return attribute ? 1 : 0; - } + private static class TriStateBooleanConverter implements AttributeConverter, BasicValueConverter { + @Override + public Integer convertToDatabaseColumn(Boolean attribute) { + if (attribute == null) return -1; + return attribute ? 1 : 0; + } - @Override - public Boolean convertToEntityAttribute(Integer dbData) { - if (dbData == null || dbData == -1) return null; - return dbData == 1; - } + @Override + public Boolean convertToEntityAttribute(Integer dbData) { + if (dbData == null || dbData == -1) return null; + return dbData == 1; + } - @Override - public @Nullable Boolean toDomainValue(@Nullable Integer relationalForm) { - return convertToEntityAttribute(relationalForm); - } + @Override + public @Nullable Boolean toDomainValue(@Nullable Integer relationalForm) { + return convertToEntityAttribute(relationalForm); + } - @Override - public @Nullable Integer toRelationalValue(@Nullable Boolean domainForm) { - return convertToDatabaseColumn(domainForm); - } + @Override + public @Nullable Integer toRelationalValue(@Nullable Boolean domainForm) { + return convertToDatabaseColumn(domainForm); + } - @Override - public JavaType getDomainJavaType() { - return BooleanJavaType.INSTANCE; - } + @Override + public JavaType getDomainJavaType() { + return BooleanJavaType.INSTANCE; + } - @Override - public JavaType getRelationalJavaType() { - return IntegerJavaType.INSTANCE; - } - } + @Override + public JavaType getRelationalJavaType() { + return IntegerJavaType.INSTANCE; + } + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/metamodel/wildcardmodel/AbstractOwner.java b/hibernate-core/src/test/java/org/hibernate/orm/test/metamodel/wildcardmodel/AbstractOwner.java index 36b985d8aa..26e4ad3445 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/metamodel/wildcardmodel/AbstractOwner.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/metamodel/wildcardmodel/AbstractOwner.java @@ -25,7 +25,7 @@ public abstract class AbstractOwner { @GeneratedValue private Long id; - @OneToMany(cascade = CascadeType.ALL, mappedBy = "owner", targetEntity = AbstractEntity.class) + @OneToMany(cascade = CascadeType.ALL, mappedBy = "owner", targetEntity = AbstractEntity.class) private List entities = new ArrayList<>(); public Long getId() { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mixed/MixedTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mixed/MixedTest.java index 6a01b2a4fe..c82b780ad5 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mixed/MixedTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mixed/MixedTest.java @@ -66,7 +66,7 @@ public class MixedTest { Long did = doc.getId(); Long d2id = doc2.getId(); - if ( !scope.getSessionFactory().getJdbcServices().getDialect().supportsExpectedLobUsagePattern() ) { + if ( !scope.getSessionFactory().getJdbcServices().getDialect().supportsExpectedLobUsagePattern() ) { SkipLog.reportSkip( "database/driver does not support expected LOB usage pattern", "LOB support" ); return; } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/multitenancy/AbstractMultiTenancyTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/multitenancy/AbstractMultiTenancyTest.java index 25d32fdc02..aa4c36e87b 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/multitenancy/AbstractMultiTenancyTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/multitenancy/AbstractMultiTenancyTest.java @@ -54,263 +54,263 @@ import static org.junit.Assert.assertEquals; */ public abstract class AbstractMultiTenancyTest extends BaseUnitTestCase { - protected static final String FRONT_END_TENANT = "front_end"; - protected static final String BACK_END_TENANT = "back_end"; + protected static final String FRONT_END_TENANT = "front_end"; + protected static final String BACK_END_TENANT = "back_end"; - private Map connectionProviderMap = new HashMap<>(); + private Map connectionProviderMap = new HashMap<>(); - private SessionFactory sessionFactory; + private SessionFactory sessionFactory; - public AbstractMultiTenancyTest() { - init(); - } + public AbstractMultiTenancyTest() { + init(); + } - //tag::multitenacy-hibernate-MultiTenantConnectionProvider-example[] - private void init() { - registerConnectionProvider(FRONT_END_TENANT); - registerConnectionProvider(BACK_END_TENANT); + //tag::multitenacy-hibernate-MultiTenantConnectionProvider-example[] + private void init() { + registerConnectionProvider(FRONT_END_TENANT); + registerConnectionProvider(BACK_END_TENANT); - Map settings = new HashMap<>(); + Map settings = new HashMap<>(); - settings.put(AvailableSettings.MULTI_TENANT_CONNECTION_PROVIDER, - new ConfigurableMultiTenantConnectionProvider(connectionProviderMap)); + settings.put(AvailableSettings.MULTI_TENANT_CONNECTION_PROVIDER, + new ConfigurableMultiTenantConnectionProvider(connectionProviderMap)); - sessionFactory = sessionFactory(settings); - } - //end::multitenacy-hibernate-MultiTenantConnectionProvider-example[] + sessionFactory = sessionFactory(settings); + } + //end::multitenacy-hibernate-MultiTenantConnectionProvider-example[] - @AfterClassOnce - public void destroy() { - sessionFactory.close(); - for (ConnectionProvider connectionProvider : connectionProviderMap.values()) { - if (connectionProvider instanceof Stoppable) { - ((Stoppable) connectionProvider).stop(); - } - } - } + @AfterClassOnce + public void destroy() { + sessionFactory.close(); + for (ConnectionProvider connectionProvider : connectionProviderMap.values()) { + if (connectionProvider instanceof Stoppable) { + ((Stoppable) connectionProvider).stop(); + } + } + } - @After - public void cleanup() { - doInSession(FRONT_END_TENANT, session -> session.createMutationQuery( "delete from Person" ).executeUpdate() ); - doInSession(BACK_END_TENANT, session -> session.createMutationQuery( "delete from Person" ).executeUpdate() ); - } + @After + public void cleanup() { + doInSession(FRONT_END_TENANT, session -> session.createMutationQuery( "delete from Person" ).executeUpdate() ); + doInSession(BACK_END_TENANT, session -> session.createMutationQuery( "delete from Person" ).executeUpdate() ); + } - //tag::multitenacy-hibernate-MultiTenantConnectionProvider-example[] + //tag::multitenacy-hibernate-MultiTenantConnectionProvider-example[] - protected void registerConnectionProvider(String tenantIdentifier) { - Properties properties = properties(); - properties.put(Environment.URL, - tenantUrl(properties.getProperty(Environment.URL), tenantIdentifier)); + protected void registerConnectionProvider(String tenantIdentifier) { + Properties properties = properties(); + properties.put(Environment.URL, + tenantUrl(properties.getProperty(Environment.URL), tenantIdentifier)); - DriverManagerConnectionProviderImpl connectionProvider = - new DriverManagerConnectionProviderImpl(); - connectionProvider.configure( PropertiesHelper.map(properties) ); - connectionProviderMap.put(tenantIdentifier, connectionProvider); - } - //end::multitenacy-hibernate-MultiTenantConnectionProvider-example[] + DriverManagerConnectionProviderImpl connectionProvider = + new DriverManagerConnectionProviderImpl(); + connectionProvider.configure( PropertiesHelper.map(properties) ); + connectionProviderMap.put(tenantIdentifier, connectionProvider); + } + //end::multitenacy-hibernate-MultiTenantConnectionProvider-example[] - @Test - public void testBasicExpectedBehavior() { + @Test + public void testBasicExpectedBehavior() { //tag::multitenacy-multitenacy-hibernate-same-entity-example[] - doInSession(FRONT_END_TENANT, session -> { - Person person = new Person(); - person.setId(1L); - person.setName("John Doe"); - session.persist(person); - }); + doInSession(FRONT_END_TENANT, session -> { + Person person = new Person(); + person.setId(1L); + person.setName("John Doe"); + session.persist(person); + }); - doInSession(BACK_END_TENANT, session -> { - Person person = new Person(); - person.setId(1L); - person.setName("John Doe"); - session.persist(person); - }); + doInSession(BACK_END_TENANT, session -> { + Person person = new Person(); + person.setId(1L); + person.setName("John Doe"); + session.persist(person); + }); //end::multitenacy-multitenacy-hibernate-same-entity-example[] - } + } - @Test - @JiraKey( value = "HHH-17972") - public void testChangeTenantWithoutConnectionReuse() { - Person person = new Person(); - person.setId( 1L ); - person.setName( "John Doe" ); - Person person2 = new Person(); - person2.setId( 2L ); - person2.setName( "Jane Doe" ); + @Test + @JiraKey( value = "HHH-17972") + public void testChangeTenantWithoutConnectionReuse() { + Person person = new Person(); + person.setId( 1L ); + person.setName( "John Doe" ); + Person person2 = new Person(); + person2.setId( 2L ); + person2.setName( "Jane Doe" ); - Transaction t; - Session session = null; - Session newSession = null; - try { - session = sessionFactory.withOptions().tenantIdentifier( FRONT_END_TENANT ).openSession(); - t = session.beginTransaction(); - session.persist( person ); - t.commit(); + Transaction t; + Session session = null; + Session newSession = null; + try { + session = sessionFactory.withOptions().tenantIdentifier( FRONT_END_TENANT ).openSession(); + t = session.beginTransaction(); + session.persist( person ); + t.commit(); - Query sessionQuery = session.createQuery( "from Person", Person.class ); - assertEquals( 1, sessionQuery.getResultList().size() ); - assertEquals( "John Doe", sessionQuery.getResultList().get( 0 ).getName() ); + Query sessionQuery = session.createQuery( "from Person", Person.class ); + assertEquals( 1, sessionQuery.getResultList().size() ); + assertEquals( "John Doe", sessionQuery.getResultList().get( 0 ).getName() ); - newSession = session.sessionWithOptions().tenantIdentifier( BACK_END_TENANT ).openSession(); - t = newSession.beginTransaction(); - newSession.persist( person2 ); - t.commit(); + newSession = session.sessionWithOptions().tenantIdentifier( BACK_END_TENANT ).openSession(); + t = newSession.beginTransaction(); + newSession.persist( person2 ); + t.commit(); - Query newSessionQuery = newSession.createQuery( "from Person", Person.class ); - assertEquals( 1, newSessionQuery.getResultList().size() ); - assertEquals( "Jane Doe", newSessionQuery.getResultList().get( 0 ).getName() ); - } - finally { - if (session != null) { - session.close(); - } - if (newSession != null) { - newSession.close(); - } - } - } + Query newSessionQuery = newSession.createQuery( "from Person", Person.class ); + assertEquals( 1, newSessionQuery.getResultList().size() ); + assertEquals( "Jane Doe", newSessionQuery.getResultList().get( 0 ).getName() ); + } + finally { + if (session != null) { + session.close(); + } + if (newSession != null) { + newSession.close(); + } + } + } - @Test - @JiraKey( value = "HHH-17972") - public void testChangeTenantWithConnectionReuse() { - try (Session session = sessionFactory.withOptions().tenantIdentifier( FRONT_END_TENANT ).openSession()) { - Assert.assertThrows( "Cannot redefine the tenant identifier on a child session if the connection is reused", - SessionException.class, - () -> session.sessionWithOptions().tenantIdentifier( BACK_END_TENANT ).connection().openSession() - ); - Assert.assertThrows( "Cannot redefine the tenant identifier on a child session if the connection is reused", - SessionException.class, - () -> session.sessionWithOptions().connection().tenantIdentifier( BACK_END_TENANT ).openSession() - ); - } - } + @Test + @JiraKey( value = "HHH-17972") + public void testChangeTenantWithConnectionReuse() { + try (Session session = sessionFactory.withOptions().tenantIdentifier( FRONT_END_TENANT ).openSession()) { + Assert.assertThrows( "Cannot redefine the tenant identifier on a child session if the connection is reused", + SessionException.class, + () -> session.sessionWithOptions().tenantIdentifier( BACK_END_TENANT ).connection().openSession() + ); + Assert.assertThrows( "Cannot redefine the tenant identifier on a child session if the connection is reused", + SessionException.class, + () -> session.sessionWithOptions().connection().tenantIdentifier( BACK_END_TENANT ).openSession() + ); + } + } - protected Properties properties() { - Properties properties = new Properties(); - URL propertiesURL = Thread.currentThread().getContextClassLoader().getResource("hibernate.properties"); - try(FileInputStream inputStream = new FileInputStream(propertiesURL.getFile())) { - properties.load(inputStream); - } - catch (IOException e) { - throw new IllegalArgumentException(e); - } - return properties; - } + protected Properties properties() { + Properties properties = new Properties(); + URL propertiesURL = Thread.currentThread().getContextClassLoader().getResource("hibernate.properties"); + try(FileInputStream inputStream = new FileInputStream(propertiesURL.getFile())) { + properties.load(inputStream); + } + catch (IOException e) { + throw new IllegalArgumentException(e); + } + return properties; + } - protected abstract String tenantUrl(String originalUrl, String tenantIdentifier); + protected abstract String tenantUrl(String originalUrl, String tenantIdentifier); - protected SessionFactory sessionFactory(Map settings) { + protected SessionFactory sessionFactory(Map settings) { - ServiceRegistryImplementor serviceRegistry = (ServiceRegistryImplementor) ServiceRegistryUtil.serviceRegistryBuilder() - .applySettings(settings) - .build(); + ServiceRegistryImplementor serviceRegistry = (ServiceRegistryImplementor) ServiceRegistryUtil.serviceRegistryBuilder() + .applySettings(settings) + .build(); - MetadataSources metadataSources = new MetadataSources(serviceRegistry); - for(Class annotatedClasses : getAnnotatedClasses()) { - metadataSources.addAnnotatedClass(annotatedClasses); - } + MetadataSources metadataSources = new MetadataSources(serviceRegistry); + for(Class annotatedClasses : getAnnotatedClasses()) { + metadataSources.addAnnotatedClass(annotatedClasses); + } - Metadata metadata = metadataSources.buildMetadata(); + Metadata metadata = metadataSources.buildMetadata(); - HibernateSchemaManagementTool tool = new HibernateSchemaManagementTool(); - tool.injectServices(serviceRegistry); + HibernateSchemaManagementTool tool = new HibernateSchemaManagementTool(); + tool.injectServices(serviceRegistry); - new SchemaDropperImpl( serviceRegistry ).doDrop( - metadata, - serviceRegistry, - settings, - true, - new GenerationTargetToDatabase( - new DdlTransactionIsolatorTestingImpl( - serviceRegistry, - connectionProviderMap.get( FRONT_END_TENANT ) - ) - ), - new GenerationTargetToDatabase( - new DdlTransactionIsolatorTestingImpl( - serviceRegistry, - connectionProviderMap.get( BACK_END_TENANT ) - ) - ) - ); + new SchemaDropperImpl( serviceRegistry ).doDrop( + metadata, + serviceRegistry, + settings, + true, + new GenerationTargetToDatabase( + new DdlTransactionIsolatorTestingImpl( + serviceRegistry, + connectionProviderMap.get( FRONT_END_TENANT ) + ) + ), + new GenerationTargetToDatabase( + new DdlTransactionIsolatorTestingImpl( + serviceRegistry, + connectionProviderMap.get( BACK_END_TENANT ) + ) + ) + ); - new SchemaCreatorImpl( serviceRegistry ).doCreation( - metadata, - serviceRegistry, - settings, - true, - new GenerationTargetToDatabase( - new DdlTransactionIsolatorTestingImpl( - serviceRegistry, - connectionProviderMap.get( FRONT_END_TENANT ) - ) - ), - new GenerationTargetToDatabase( - new DdlTransactionIsolatorTestingImpl( - serviceRegistry, - connectionProviderMap.get( BACK_END_TENANT ) - ) - ) - ); + new SchemaCreatorImpl( serviceRegistry ).doCreation( + metadata, + serviceRegistry, + settings, + true, + new GenerationTargetToDatabase( + new DdlTransactionIsolatorTestingImpl( + serviceRegistry, + connectionProviderMap.get( FRONT_END_TENANT ) + ) + ), + new GenerationTargetToDatabase( + new DdlTransactionIsolatorTestingImpl( + serviceRegistry, + connectionProviderMap.get( BACK_END_TENANT ) + ) + ) + ); - final SessionFactoryBuilder sessionFactoryBuilder = metadata.getSessionFactoryBuilder(); - return sessionFactoryBuilder.build(); - } + final SessionFactoryBuilder sessionFactoryBuilder = metadata.getSessionFactoryBuilder(); + return sessionFactoryBuilder.build(); + } - protected Class[] getAnnotatedClasses() { - return new Class[] { - Person.class - }; - } + protected Class[] getAnnotatedClasses() { + return new Class[] { + Person.class + }; + } //tag::multitenacy-hibernate-session-example[] - private void doInSession(String tenant, Consumer function) { - Session session = null; - Transaction txn = null; - try { - session = sessionFactory - .withOptions() - .tenantIdentifier(tenant) - .openSession(); - txn = session.getTransaction(); - txn.begin(); - function.accept(session); - txn.commit(); - } catch (Throwable e) { - if (txn != null) txn.rollback(); - throw e; - } finally { - if (session != null) { - session.close(); - } - } - } + private void doInSession(String tenant, Consumer function) { + Session session = null; + Transaction txn = null; + try { + session = sessionFactory + .withOptions() + .tenantIdentifier(tenant) + .openSession(); + txn = session.getTransaction(); + txn.begin(); + function.accept(session); + txn.commit(); + } catch (Throwable e) { + if (txn != null) txn.rollback(); + throw e; + } finally { + if (session != null) { + session.close(); + } + } + } //end::multitenacy-hibernate-session-example[] - @Entity(name = "Person") - public static class Person { + @Entity(name = "Person") + public static class Person { - @Id - private Long id; + @Id + private Long id; - private String name; + private String name; - public Long getId() { - return id; - } + public Long getId() { + return id; + } - public void setId(Long id) { - this.id = id; - } + public void setId(Long id) { + this.id = id; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } - } + public void setName(String name) { + this.name = name; + } + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/multitenancy/ConfigurableMultiTenantConnectionProvider.java b/hibernate-core/src/test/java/org/hibernate/orm/test/multitenancy/ConfigurableMultiTenantConnectionProvider.java index 282898ac75..876fb10183 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/multitenancy/ConfigurableMultiTenantConnectionProvider.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/multitenancy/ConfigurableMultiTenantConnectionProvider.java @@ -17,24 +17,24 @@ import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider; */ //tag::multitenacy-hibernate-ConfigurableMultiTenantConnectionProvider-example[] public class ConfigurableMultiTenantConnectionProvider - extends AbstractMultiTenantConnectionProvider { + extends AbstractMultiTenantConnectionProvider { - private final Map connectionProviderMap = - new HashMap<>(); + private final Map connectionProviderMap = + new HashMap<>(); - public ConfigurableMultiTenantConnectionProvider( - Map connectionProviderMap) { - this.connectionProviderMap.putAll(connectionProviderMap); - } + public ConfigurableMultiTenantConnectionProvider( + Map connectionProviderMap) { + this.connectionProviderMap.putAll(connectionProviderMap); + } - @Override - protected ConnectionProvider getAnyConnectionProvider() { - return connectionProviderMap.values().iterator().next(); - } + @Override + protected ConnectionProvider getAnyConnectionProvider() { + return connectionProviderMap.values().iterator().next(); + } - @Override - protected ConnectionProvider selectConnectionProvider(String tenantIdentifier) { - return connectionProviderMap.get(tenantIdentifier); - } + @Override + protected ConnectionProvider selectConnectionProvider(String tenantIdentifier) { + return connectionProviderMap.get(tenantIdentifier); + } } //end::multitenacy-hibernate-ConfigurableMultiTenantConnectionProvider-example[] diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/multitenancy/DatabaseTimeZoneMultiTenancyTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/multitenancy/DatabaseTimeZoneMultiTenancyTest.java index 534e999564..6e4e335ab9 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/multitenancy/DatabaseTimeZoneMultiTenancyTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/multitenancy/DatabaseTimeZoneMultiTenancyTest.java @@ -57,300 +57,300 @@ import static org.junit.Assert.assertEquals; @RequiresDialect(H2Dialect.class) public class DatabaseTimeZoneMultiTenancyTest extends BaseUnitTestCase { - protected static final String FRONT_END_TENANT = "front_end"; - protected static final String BACK_END_TENANT = "back_end"; + protected static final String FRONT_END_TENANT = "front_end"; + protected static final String BACK_END_TENANT = "back_end"; - //tag::multitenacy-hibernate-timezone-configuration-context-example[] - private Map connectionProviderMap = new HashMap<>(); + //tag::multitenacy-hibernate-timezone-configuration-context-example[] + private Map connectionProviderMap = new HashMap<>(); - private Map timeZoneTenantMap = new HashMap<>(); - //end::multitenacy-hibernate-timezone-configuration-context-example[] + private Map timeZoneTenantMap = new HashMap<>(); + //end::multitenacy-hibernate-timezone-configuration-context-example[] - private SessionFactory sessionFactory; + private SessionFactory sessionFactory; - public DatabaseTimeZoneMultiTenancyTest() { - init(); - } + public DatabaseTimeZoneMultiTenancyTest() { + init(); + } - private void init() { - //tag::multitenacy-hibernate-timezone-configuration-registerConnectionProvider-call-example[] - registerConnectionProvider(FRONT_END_TENANT, TimeZone.getTimeZone("UTC")); - registerConnectionProvider(BACK_END_TENANT, TimeZone.getTimeZone("CST")); - //end::multitenacy-hibernate-timezone-configuration-registerConnectionProvider-call-example[] + private void init() { + //tag::multitenacy-hibernate-timezone-configuration-registerConnectionProvider-call-example[] + registerConnectionProvider(FRONT_END_TENANT, TimeZone.getTimeZone("UTC")); + registerConnectionProvider(BACK_END_TENANT, TimeZone.getTimeZone("CST")); + //end::multitenacy-hibernate-timezone-configuration-registerConnectionProvider-call-example[] - Map settings = new HashMap<>(); + Map settings = new HashMap<>(); - settings.put( - AvailableSettings.MULTI_TENANT_CONNECTION_PROVIDER, - new ConfigurableMultiTenantConnectionProvider(connectionProviderMap) - ); + settings.put( + AvailableSettings.MULTI_TENANT_CONNECTION_PROVIDER, + new ConfigurableMultiTenantConnectionProvider(connectionProviderMap) + ); - sessionFactory = sessionFactory(settings); - } + sessionFactory = sessionFactory(settings); + } - @AfterClassOnce - public void destroy() { - sessionFactory.close(); - for (ConnectionProvider connectionProvider : connectionProviderMap.values()) { - if (connectionProvider instanceof Stoppable) { - ((Stoppable) connectionProvider).stop(); - } - } - } + @AfterClassOnce + public void destroy() { + sessionFactory.close(); + for (ConnectionProvider connectionProvider : connectionProviderMap.values()) { + if (connectionProvider instanceof Stoppable) { + ((Stoppable) connectionProvider).stop(); + } + } + } - //tag::multitenacy-hibernate-timezone-configuration-registerConnectionProvider-example[] - protected void registerConnectionProvider(String tenantIdentifier, TimeZone timeZone) { - Properties properties = properties(); - properties.put( - Environment.URL, - tenantUrl( properties.getProperty(Environment.URL), tenantIdentifier ) - ); + //tag::multitenacy-hibernate-timezone-configuration-registerConnectionProvider-example[] + protected void registerConnectionProvider(String tenantIdentifier, TimeZone timeZone) { + Properties properties = properties(); + properties.put( + Environment.URL, + tenantUrl( properties.getProperty(Environment.URL), tenantIdentifier ) + ); - DriverManagerConnectionProviderImpl connectionProvider = - new DriverManagerConnectionProviderImpl(); - connectionProvider.configure( PropertiesHelper.map(properties) ); + DriverManagerConnectionProviderImpl connectionProvider = + new DriverManagerConnectionProviderImpl(); + connectionProvider.configure( PropertiesHelper.map(properties) ); - connectionProviderMap.put(tenantIdentifier, connectionProvider); + connectionProviderMap.put(tenantIdentifier, connectionProvider); - timeZoneTenantMap.put(tenantIdentifier, timeZone); - } - //end::multitenacy-hibernate-timezone-configuration-registerConnectionProvider-example[] + timeZoneTenantMap.put(tenantIdentifier, timeZone); + } + //end::multitenacy-hibernate-timezone-configuration-registerConnectionProvider-example[] - @Test - public void testBasicExpectedBehavior() { + @Test + public void testBasicExpectedBehavior() { - //tag::multitenacy-hibernate-applying-timezone-configuration-example[] - doInSession(FRONT_END_TENANT, session -> { - Person person = new Person(); - person.setId(1L); - person.setName("John Doe"); - person.setCreatedOn(LocalDateTime.of(2018, 11, 23, 12, 0, 0)); + //tag::multitenacy-hibernate-applying-timezone-configuration-example[] + doInSession(FRONT_END_TENANT, session -> { + Person person = new Person(); + person.setId(1L); + person.setName("John Doe"); + person.setCreatedOn(LocalDateTime.of(2018, 11, 23, 12, 0, 0)); - session.persist(person); - }, true); + session.persist(person); + }, true); - doInSession(BACK_END_TENANT, session -> { - Person person = new Person(); - person.setId(1L); - person.setName("John Doe"); - person.setCreatedOn(LocalDateTime.of(2018, 11, 23, 12, 0, 0)); + doInSession(BACK_END_TENANT, session -> { + Person person = new Person(); + person.setId(1L); + person.setName("John Doe"); + person.setCreatedOn(LocalDateTime.of(2018, 11, 23, 12, 0, 0)); - session.persist(person); - }, true); + session.persist(person); + }, true); - doInSession(FRONT_END_TENANT, session -> { - Timestamp personCreationTimestamp = (Timestamp) session - .createNativeQuery( - "select p.created_on " + - "from Person p " + - "where p.id = :personId", Timestamp.class) - .setParameter("personId", 1L) - .getSingleResult(); + doInSession(FRONT_END_TENANT, session -> { + Timestamp personCreationTimestamp = (Timestamp) session + .createNativeQuery( + "select p.created_on " + + "from Person p " + + "where p.id = :personId", Timestamp.class) + .setParameter("personId", 1L) + .getSingleResult(); - assertEquals( - Timestamp.valueOf(LocalDateTime.of(2018, 11, 23, 12, 0, 0)), - personCreationTimestamp - ); - }, true); + assertEquals( + Timestamp.valueOf(LocalDateTime.of(2018, 11, 23, 12, 0, 0)), + personCreationTimestamp + ); + }, true); - doInSession(BACK_END_TENANT, session -> { - Timestamp personCreationTimestamp = (Timestamp) session - .createNativeQuery( - "select p.created_on " + - "from Person p " + - "where p.id = :personId", Timestamp.class) - .setParameter("personId", 1L) - .getSingleResult(); + doInSession(BACK_END_TENANT, session -> { + Timestamp personCreationTimestamp = (Timestamp) session + .createNativeQuery( + "select p.created_on " + + "from Person p " + + "where p.id = :personId", Timestamp.class) + .setParameter("personId", 1L) + .getSingleResult(); - assertEquals( - Timestamp.valueOf(LocalDateTime.of(2018, 11, 23, 12, 0, 0)), - personCreationTimestamp - ); - }, true); - //end::multitenacy-hibernate-applying-timezone-configuration-example[] + assertEquals( + Timestamp.valueOf(LocalDateTime.of(2018, 11, 23, 12, 0, 0)), + personCreationTimestamp + ); + }, true); + //end::multitenacy-hibernate-applying-timezone-configuration-example[] - //tag::multitenacy-hibernate-not-applying-timezone-configuration-example[] - doInSession(FRONT_END_TENANT, session -> { - Timestamp personCreationTimestamp = (Timestamp) session - .createNativeQuery( - "select p.created_on " + - "from Person p " + - "where p.id = :personId", Timestamp.class) - .setParameter("personId", 1L) - .getSingleResult(); + //tag::multitenacy-hibernate-not-applying-timezone-configuration-example[] + doInSession(FRONT_END_TENANT, session -> { + Timestamp personCreationTimestamp = (Timestamp) session + .createNativeQuery( + "select p.created_on " + + "from Person p " + + "where p.id = :personId", Timestamp.class) + .setParameter("personId", 1L) + .getSingleResult(); - log.infof( - "The created_on timestamp value is: [%s]", - personCreationTimestamp - ); + log.infof( + "The created_on timestamp value is: [%s]", + personCreationTimestamp + ); - long timeZoneOffsetMillis = - Timestamp.valueOf(LocalDateTime.of(2018, 11, 23, 12, 0, 0)).getTime() - - personCreationTimestamp.getTime(); + long timeZoneOffsetMillis = + Timestamp.valueOf(LocalDateTime.of(2018, 11, 23, 12, 0, 0)).getTime() - + personCreationTimestamp.getTime(); - assertEquals( - TimeZone.getTimeZone(ZoneId.systemDefault()).getRawOffset(), - timeZoneOffsetMillis - ); + assertEquals( + TimeZone.getTimeZone(ZoneId.systemDefault()).getRawOffset(), + timeZoneOffsetMillis + ); - log.infof( - "For the current time zone: [%s], the UTC time zone offset is: [%d]", - TimeZone.getDefault().getDisplayName(), timeZoneOffsetMillis - ); - }, false); - //end::multitenacy-hibernate-not-applying-timezone-configuration-example[] - } + log.infof( + "For the current time zone: [%s], the UTC time zone offset is: [%d]", + TimeZone.getDefault().getDisplayName(), timeZoneOffsetMillis + ); + }, false); + //end::multitenacy-hibernate-not-applying-timezone-configuration-example[] + } - protected Properties properties() { - Properties properties = new Properties(); - URL propertiesURL = Thread.currentThread().getContextClassLoader().getResource("hibernate.properties"); - try (FileInputStream inputStream = new FileInputStream(propertiesURL.getFile())) { - properties.load(inputStream); - } - catch (IOException e) { - throw new IllegalArgumentException(e); - } - return properties; - } + protected Properties properties() { + Properties properties = new Properties(); + URL propertiesURL = Thread.currentThread().getContextClassLoader().getResource("hibernate.properties"); + try (FileInputStream inputStream = new FileInputStream(propertiesURL.getFile())) { + properties.load(inputStream); + } + catch (IOException e) { + throw new IllegalArgumentException(e); + } + return properties; + } - protected String tenantUrl(String originalUrl, String tenantIdentifier) { - return originalUrl.replace("db1", tenantIdentifier); - } + protected String tenantUrl(String originalUrl, String tenantIdentifier) { + return originalUrl.replace("db1", tenantIdentifier); + } - protected SessionFactory sessionFactory(Map settings) { + protected SessionFactory sessionFactory(Map settings) { - ServiceRegistryImplementor serviceRegistry = (ServiceRegistryImplementor) ServiceRegistryUtil.serviceRegistryBuilder() - .applySettings(settings) - .build(); + ServiceRegistryImplementor serviceRegistry = (ServiceRegistryImplementor) ServiceRegistryUtil.serviceRegistryBuilder() + .applySettings(settings) + .build(); - MetadataSources metadataSources = new MetadataSources(serviceRegistry); - for (Class annotatedClasses : getAnnotatedClasses()) { - metadataSources.addAnnotatedClass(annotatedClasses); - } + MetadataSources metadataSources = new MetadataSources(serviceRegistry); + for (Class annotatedClasses : getAnnotatedClasses()) { + metadataSources.addAnnotatedClass(annotatedClasses); + } - Metadata metadata = metadataSources.buildMetadata(); + Metadata metadata = metadataSources.buildMetadata(); - HibernateSchemaManagementTool tool = new HibernateSchemaManagementTool(); - tool.injectServices(serviceRegistry); + HibernateSchemaManagementTool tool = new HibernateSchemaManagementTool(); + tool.injectServices(serviceRegistry); - new SchemaDropperImpl( serviceRegistry ).doDrop( - metadata, - serviceRegistry, - settings, - true, - new GenerationTargetToDatabase( - new DdlTransactionIsolatorTestingImpl( - serviceRegistry, - connectionProviderMap.get( FRONT_END_TENANT ) - ) - ), - new GenerationTargetToDatabase( - new DdlTransactionIsolatorTestingImpl( - serviceRegistry, - connectionProviderMap.get( BACK_END_TENANT ) - ) - ) - ); + new SchemaDropperImpl( serviceRegistry ).doDrop( + metadata, + serviceRegistry, + settings, + true, + new GenerationTargetToDatabase( + new DdlTransactionIsolatorTestingImpl( + serviceRegistry, + connectionProviderMap.get( FRONT_END_TENANT ) + ) + ), + new GenerationTargetToDatabase( + new DdlTransactionIsolatorTestingImpl( + serviceRegistry, + connectionProviderMap.get( BACK_END_TENANT ) + ) + ) + ); - new SchemaCreatorImpl( serviceRegistry ).doCreation( - metadata, - serviceRegistry, - settings, - true, - new GenerationTargetToDatabase( - new DdlTransactionIsolatorTestingImpl( - serviceRegistry, - connectionProviderMap.get( FRONT_END_TENANT ) - ) - ), - new GenerationTargetToDatabase( - new DdlTransactionIsolatorTestingImpl( - serviceRegistry, - connectionProviderMap.get( BACK_END_TENANT ) - ) - ) - ); + new SchemaCreatorImpl( serviceRegistry ).doCreation( + metadata, + serviceRegistry, + settings, + true, + new GenerationTargetToDatabase( + new DdlTransactionIsolatorTestingImpl( + serviceRegistry, + connectionProviderMap.get( FRONT_END_TENANT ) + ) + ), + new GenerationTargetToDatabase( + new DdlTransactionIsolatorTestingImpl( + serviceRegistry, + connectionProviderMap.get( BACK_END_TENANT ) + ) + ) + ); - final SessionFactoryBuilder sessionFactoryBuilder = metadata.getSessionFactoryBuilder(); - return sessionFactoryBuilder.build(); - } + final SessionFactoryBuilder sessionFactoryBuilder = metadata.getSessionFactoryBuilder(); + return sessionFactoryBuilder.build(); + } - protected Class[] getAnnotatedClasses() { - return new Class[] { - Person.class - }; - } + protected Class[] getAnnotatedClasses() { + return new Class[] { + Person.class + }; + } - //tag::multitenacy-hibernate-timezone-configuration-session-example[] - private void doInSession(String tenant, Consumer function, boolean useTenantTimeZone) { - Session session = null; - Transaction txn = null; + //tag::multitenacy-hibernate-timezone-configuration-session-example[] + private void doInSession(String tenant, Consumer function, boolean useTenantTimeZone) { + Session session = null; + Transaction txn = null; - try { - SessionBuilder sessionBuilder = sessionFactory - .withOptions() - .tenantIdentifier(tenant); + try { + SessionBuilder sessionBuilder = sessionFactory + .withOptions() + .tenantIdentifier(tenant); - if (useTenantTimeZone) { - sessionBuilder.jdbcTimeZone(timeZoneTenantMap.get(tenant)); - } + if (useTenantTimeZone) { + sessionBuilder.jdbcTimeZone(timeZoneTenantMap.get(tenant)); + } - session = sessionBuilder.openSession(); + session = sessionBuilder.openSession(); - txn = session.getTransaction(); - txn.begin(); + txn = session.getTransaction(); + txn.begin(); - function.accept(session); + function.accept(session); - txn.commit(); - } - catch (Throwable e) { - if (txn != null) { - txn.rollback(); - } - throw e; - } - finally { - if (session != null) { - session.close(); - } - } - } - //end::multitenacy-hibernate-timezone-configuration-session-example[] + txn.commit(); + } + catch (Throwable e) { + if (txn != null) { + txn.rollback(); + } + throw e; + } + finally { + if (session != null) { + session.close(); + } + } + } + //end::multitenacy-hibernate-timezone-configuration-session-example[] - @Entity(name = "Person") - public static class Person { + @Entity(name = "Person") + public static class Person { - @Id - private Long id; + @Id + private Long id; - private String name; + private String name; - @Column(name = "created_on") - private LocalDateTime createdOn; + @Column(name = "created_on") + private LocalDateTime createdOn; - public Long getId() { - return id; - } + public Long getId() { + return id; + } - public void setId(Long id) { - this.id = id; - } + public void setId(Long id) { + this.id = id; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - public LocalDateTime getCreatedOn() { - return createdOn; - } + public LocalDateTime getCreatedOn() { + return createdOn; + } - public void setCreatedOn(LocalDateTime createdOn) { - this.createdOn = createdOn; - } - } + public void setCreatedOn(LocalDateTime createdOn) { + this.createdOn = createdOn; + } + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/namingstrategy/FullyQualifiedEntityNameNamingStrategyTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/namingstrategy/FullyQualifiedEntityNameNamingStrategyTest.java index d0cbf45dd5..1d79b1eec3 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/namingstrategy/FullyQualifiedEntityNameNamingStrategyTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/namingstrategy/FullyQualifiedEntityNameNamingStrategyTest.java @@ -94,7 +94,7 @@ public class FullyQualifiedEntityNameNamingStrategyTest { boolean ownerFKFound = false; boolean inverseFKFound = false; - for (Iterator it = ownerCollectionMapping.getCollectionTable().getForeignKeys().values().iterator(); it.hasNext(); ) { + for (Iterator it = ownerCollectionMapping.getCollectionTable().getForeignKeys().values().iterator(); it.hasNext(); ) { final String fkColumnName = ( (ForeignKey) it.next() ).getColumn( 0 ).getName(); if ( expectedOwnerFK.equals( fkColumnName ) ) { ownerFKFound = true; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/namingstrategy/Item.java b/hibernate-core/src/test/java/org/hibernate/orm/test/namingstrategy/Item.java index 8b829f8ed0..b4929a9aab 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/namingstrategy/Item.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/namingstrategy/Item.java @@ -21,73 +21,73 @@ import jakarta.persistence.Table; @Table(name = "ITEMS") @SecondaryTable(name="ITEMS_SEC") public class Item implements Serializable { - @Id - @GeneratedValue - private Long id; + @Id + @GeneratedValue + private Long id; - @Column(name = "price") - private Double price; + @Column(name = "price") + private Double price; - @Column(name = "price", table = "ITEMS_SEC") - private Double specialPrice; + @Column(name = "price", table = "ITEMS_SEC") + private Double specialPrice; - public Item() { - } + public Item() { + } - public Item(Double price, Double specialPrice) { - this.price = price; - this.specialPrice = specialPrice; - } + public Item(Double price, Double specialPrice) { + this.price = price; + this.specialPrice = specialPrice; + } - public Item(Long id, Double price, Double specialPrice) { - this.id = id; - this.price = price; - this.specialPrice = specialPrice; - } + public Item(Long id, Double price, Double specialPrice) { + this.id = id; + this.price = price; + this.specialPrice = specialPrice; + } - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; - Item item = (Item) o; + Item item = (Item) o; - if (id != null ? !id.equals(item.id) : item.id != null) return false; - if (price != null ? !price.equals(item.price) : item.price != null) return false; - if (specialPrice != null ? !specialPrice.equals(item.specialPrice) : item.specialPrice != null) return false; + if (id != null ? !id.equals(item.id) : item.id != null) return false; + if (price != null ? !price.equals(item.price) : item.price != null) return false; + if (specialPrice != null ? !specialPrice.equals(item.specialPrice) : item.specialPrice != null) return false; - return true; - } + return true; + } - @Override - public int hashCode() { - int result = id != null ? id.hashCode() : 0; - result = 31 * result + (price != null ? price.hashCode() : 0); - result = 31 * result + (specialPrice != null ? specialPrice.hashCode() : 0); - return result; - } + @Override + public int hashCode() { + int result = id != null ? id.hashCode() : 0; + result = 31 * result + (price != null ? price.hashCode() : 0); + result = 31 * result + (specialPrice != null ? specialPrice.hashCode() : 0); + return result; + } - public Long getId() { - return id; - } + public Long getId() { + return id; + } - public void setId(Long id) { - this.id = id; - } + public void setId(Long id) { + this.id = id; + } - public Double getPrice() { - return price; - } + public Double getPrice() { + return price; + } - public void setPrice(Double price) { - this.price = price; - } + public void setPrice(Double price) { + this.price = price; + } - public Double getSpecialPrice() { - return specialPrice; - } + public Double getSpecialPrice() { + return specialPrice; + } - public void setSpecialPrice(Double specialPrice) { - this.specialPrice = specialPrice; - } + public void setSpecialPrice(Double specialPrice) { + this.specialPrice = specialPrice; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/notfound/EagerProxyNotFoundTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/notfound/EagerProxyNotFoundTest.java index f5b2a5024b..717dc0f35a 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/notfound/EagerProxyNotFoundTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/notfound/EagerProxyNotFoundTest.java @@ -157,7 +157,7 @@ public class EagerProxyNotFoundTest { employeeLazy.getId(); employeeLazy.getName(); fail( "ObjectNotFoundException should have been thrown because Task.employeeLazy.location is not found " + - "and is not mapped with @NotFound(IGNORE)" ); + "and is not mapped with @NotFound(IGNORE)" ); } catch (ObjectNotFoundException expected) { } @@ -190,7 +190,7 @@ public class EagerProxyNotFoundTest { session.createQuery( "from Task", Task.class ).getSingleResult(); } ); fail( "EntityNotFoundException should have been thrown because Task.employee.location is not found " + - "and is not mapped with @NotFound(IGNORE)" ); + "and is not mapped with @NotFound(IGNORE)" ); } catch (EntityNotFoundException expected) { } @@ -212,7 +212,7 @@ public class EagerProxyNotFoundTest { try { scope.inTransaction( session -> session.get( Employee.class, 1 ) ); fail( "EntityNotFoundException should have been thrown because Employee.location is not found " + - "and is not mapped with @NotFound(IGNORE)" ); + "and is not mapped with @NotFound(IGNORE)" ); } catch (EntityNotFoundException expected) { } @@ -224,7 +224,7 @@ public class EagerProxyNotFoundTest { Employee.class ).getSingleResult() ); fail( "EntityNotFoundException should have been thrown because Employee.location is not found " + - "and is not mapped with @NotFound(IGNORE)" ); + "and is not mapped with @NotFound(IGNORE)" ); } catch (EntityNotFoundException expected) { } @@ -288,7 +288,7 @@ public class EagerProxyNotFoundTest { session.createQuery( "from Employee", Employee.class ).getSingleResult(); } ); fail( "EntityNotFoundException should have been thrown because Task.employee.location is not found " + - "and is not mapped with @NotFound(IGNORE)" ); + "and is not mapped with @NotFound(IGNORE)" ); } catch (EntityNotFoundException expected) { } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/ondemandload/cache/CacheLazyLoadNoTransTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/ondemandload/cache/CacheLazyLoadNoTransTest.java index a423dfb554..d24df5989f 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/ondemandload/cache/CacheLazyLoadNoTransTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/ondemandload/cache/CacheLazyLoadNoTransTest.java @@ -162,7 +162,7 @@ public class CacheLazyLoadNoTransTest { Object value = scope.fromSession( session -> { final SessionFactoryImplementor sessionFactory = scope.getSessionFactory(); - CollectionPersister persister = sessionFactory.getMappingMetamodel().getCollectionDescriptor( entityClass.getName() + "." + attr); + CollectionPersister persister = sessionFactory.getMappingMetamodel().getCollectionDescriptor( entityClass.getName() + "." + attr); CollectionDataAccess cache = persister.getCacheAccessStrategy(); Object key = cache.generateCacheKey( id, persister, sessionFactory, session.getTenantIdentifier() ); Object cachedValue = cache.get( session, key ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/onetomany/Node.java b/hibernate-core/src/test/java/org/hibernate/orm/test/onetomany/Node.java index e14a7cdacf..683333a3fa 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/onetomany/Node.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/onetomany/Node.java @@ -25,7 +25,7 @@ public class Node implements Serializable { setDescription( description ); } - public Integer getId() { + public Integer getId() { return id; } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/onetoone/basic/OneToOneSchemaTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/onetoone/basic/OneToOneSchemaTest.java index 4539fba888..f53a6c5713 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/onetoone/basic/OneToOneSchemaTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/onetoone/basic/OneToOneSchemaTest.java @@ -36,7 +36,7 @@ public class OneToOneSchemaTest { Table childTable = metadata.getDatabase().getDefaultNamespace().locateTable( Identifier.toIdentifier( "CHILD" ) ); - assertFalse( childTable.getUniqueKeys().values().iterator().hasNext(), "UniqueKey was generated when it should not" ); + assertFalse( childTable.getUniqueKeys().values().iterator().hasNext(), "UniqueKey was generated when it should not" ); } finally { StandardServiceRegistryBuilder.destroy( ssr ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/onetoone/cache/Details.java b/hibernate-core/src/test/java/org/hibernate/orm/test/onetoone/cache/Details.java index af7824246e..2a39f248ed 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/onetoone/cache/Details.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/onetoone/cache/Details.java @@ -9,31 +9,31 @@ package org.hibernate.orm.test.onetoone.cache; import java.io.Serializable; public abstract class Details implements Serializable { - private int id; - private String data; - private Person person; + private int id; + private String data; + private Person person; - public int getId() { - return id; - } + public int getId() { + return id; + } - public void setId(int id) { - this.id = id; - } + public void setId(int id) { + this.id = id; + } - public String getData() { - return data; - } + public String getData() { + return data; + } - public void setData(String data) { - this.data = data; - } + public void setData(String data) { + this.data = data; + } - public Person getPerson() { - return person; - } + public Person getPerson() { + return person; + } - protected void setPerson(Person person) { - this.person = person; - } + protected void setPerson(Person person) { + this.person = person; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/onetoone/cache/Person.java b/hibernate-core/src/test/java/org/hibernate/orm/test/onetoone/cache/Person.java index 5230799365..f28dbc4012 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/onetoone/cache/Person.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/onetoone/cache/Person.java @@ -9,36 +9,36 @@ package org.hibernate.orm.test.onetoone.cache; import java.io.Serializable; public abstract class Person implements Serializable { - private int id; - private String name; - private Details details; + private int id; + private String name; + private Details details; - public int getId() { - return id; - } + public int getId() { + return id; + } - public void setId(int id) { - this.id = id; - } + public void setId(int id) { + this.id = id; + } - public Details getDetails() { - return details; - } + public Details getDetails() { + return details; + } - public void setDetails(Details details) { - if (details != null) { - details.setPerson(this); - } + public void setDetails(Details details) { + if (details != null) { + details.setPerson(this); + } - this.details = details; - } + this.details = details; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/ops/MergeExplicitInitialVersionTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/ops/MergeExplicitInitialVersionTest.java index b2dd3e56cb..a1f023d1be 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/ops/MergeExplicitInitialVersionTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/ops/MergeExplicitInitialVersionTest.java @@ -17,61 +17,61 @@ import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; @Jpa(annotatedClasses = {MergeExplicitInitialVersionTest.E.class, - MergeExplicitInitialVersionTest.F.class, - MergeExplicitInitialVersionTest.G.class}) + MergeExplicitInitialVersionTest.F.class, + MergeExplicitInitialVersionTest.G.class}) public class MergeExplicitInitialVersionTest { - @Test public void testGeneratedId(EntityManagerFactoryScope scope) { - E e = new E(); - scope.inTransaction(s->s.persist(e)); - assertEquals(e.version, 1); - e.text = "hello"; - E e2 = scope.fromTransaction(s->s.merge(e)); - assertEquals(e2.version, 2); - } - @Test public void testAssignedId(EntityManagerFactoryScope scope) { - F f = new F(); - scope.inTransaction(s->s.persist(f)); - assertEquals(f.version, 1); - f.text = "hello"; - F f2 = scope.fromTransaction(s->s.merge(f)); - assertEquals(f2.version, 2); - } - @Test public void testNegativeVersion(EntityManagerFactoryScope scope) { - G g = new G(); - scope.inTransaction(s->s.persist(g)); - assertEquals(g.version, 0); - g.text = "hello"; - G g2 = scope.fromTransaction(s->s.merge(g)); - assertEquals(g2.version, 1); - } + @Test public void testGeneratedId(EntityManagerFactoryScope scope) { + E e = new E(); + scope.inTransaction(s->s.persist(e)); + assertEquals(e.version, 1); + e.text = "hello"; + E e2 = scope.fromTransaction(s->s.merge(e)); + assertEquals(e2.version, 2); + } + @Test public void testAssignedId(EntityManagerFactoryScope scope) { + F f = new F(); + scope.inTransaction(s->s.persist(f)); + assertEquals(f.version, 1); + f.text = "hello"; + F f2 = scope.fromTransaction(s->s.merge(f)); + assertEquals(f2.version, 2); + } + @Test public void testNegativeVersion(EntityManagerFactoryScope scope) { + G g = new G(); + scope.inTransaction(s->s.persist(g)); + assertEquals(g.version, 0); + g.text = "hello"; + G g2 = scope.fromTransaction(s->s.merge(g)); + assertEquals(g2.version, 1); + } - @Entity - static class E { - @Id - @GeneratedValue - long id; - @Version - int version = 1; - String text; - } + @Entity + static class E { + @Id + @GeneratedValue + long id; + @Version + int version = 1; + String text; + } - @Entity - static class F { - @Id - long id = 5; - @Version - int version = 1; - String text; - } + @Entity + static class F { + @Id + long id = 5; + @Version + int version = 1; + String text; + } - @Entity - static class G { - @Id - @GeneratedValue - long id; - @Version - int version = -1; - String text; - } + @Entity + static class G { + @Id + @GeneratedValue + long id; + @Version + int version = -1; + String text; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/orphan/one2one/fk/bidirectional/multilevelcascade/Preisregelung.java b/hibernate-core/src/test/java/org/hibernate/orm/test/orphan/one2one/fk/bidirectional/multilevelcascade/Preisregelung.java index 5bac9d9e64..79e8433d77 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/orphan/one2one/fk/bidirectional/multilevelcascade/Preisregelung.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/orphan/one2one/fk/bidirectional/multilevelcascade/Preisregelung.java @@ -15,27 +15,27 @@ import jakarta.persistence.OneToOne; @Entity public class Preisregelung { - @Id + @Id @GeneratedValue - private Long id; + private Long id; - @OneToOne(mappedBy = "preisregelung", cascade = CascadeType.ALL, fetch = FetchType.LAZY, orphanRemoval = true) - private Tranchenmodell tranchenmodell; + @OneToOne(mappedBy = "preisregelung", cascade = CascadeType.ALL, fetch = FetchType.LAZY, orphanRemoval = true) + private Tranchenmodell tranchenmodell; - public Long getId() { - return id; - } + public Long getId() { + return id; + } public void setId(Long id) { this.id = id; } - public Tranchenmodell getTranchenmodell() { - return tranchenmodell; - } + public Tranchenmodell getTranchenmodell() { + return tranchenmodell; + } - public void setTranchenmodell(Tranchenmodell tranchenmodell) { - this.tranchenmodell = tranchenmodell; - } + public void setTranchenmodell(Tranchenmodell tranchenmodell) { + this.tranchenmodell = tranchenmodell; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/orphan/one2one/fk/bidirectional/multilevelcascade/Tranche.java b/hibernate-core/src/test/java/org/hibernate/orm/test/orphan/one2one/fk/bidirectional/multilevelcascade/Tranche.java index 843225bd9b..42e1528425 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/orphan/one2one/fk/bidirectional/multilevelcascade/Tranche.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/orphan/one2one/fk/bidirectional/multilevelcascade/Tranche.java @@ -11,31 +11,31 @@ import jakarta.persistence.*; @Entity public class Tranche { - @Id + @Id @GeneratedValue private Long id; - @ManyToOne(optional = false, fetch = FetchType.EAGER) - private Tranchenmodell tranchenmodell; + @ManyToOne(optional = false, fetch = FetchType.EAGER) + private Tranchenmodell tranchenmodell; @OneToOne(mappedBy = "tranche", cascade = CascadeType.ALL, fetch = FetchType.LAZY, orphanRemoval = true) private Y y; public Long getId() { - return id; - } + return id; + } public void setId(Long id) { this.id = id; } - public Tranchenmodell getTranchenmodell() { - return tranchenmodell; - } + public Tranchenmodell getTranchenmodell() { + return tranchenmodell; + } - public void setTranchenmodell(Tranchenmodell tranchenmodell) { - this.tranchenmodell = tranchenmodell; - } + public void setTranchenmodell(Tranchenmodell tranchenmodell) { + this.tranchenmodell = tranchenmodell; + } public Y getY() { return y; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/orphan/one2one/fk/bidirectional/multilevelcascade/Tranchenmodell.java b/hibernate-core/src/test/java/org/hibernate/orm/test/orphan/one2one/fk/bidirectional/multilevelcascade/Tranchenmodell.java index b8f5d13277..9208451c86 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/orphan/one2one/fk/bidirectional/multilevelcascade/Tranchenmodell.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/orphan/one2one/fk/bidirectional/multilevelcascade/Tranchenmodell.java @@ -13,39 +13,39 @@ import java.util.List; @Entity public class Tranchenmodell { - @Id + @Id @GeneratedValue private Long id; - @OneToMany(cascade = CascadeType.ALL, mappedBy = "tranchenmodell", fetch = FetchType.LAZY, orphanRemoval = true) + @OneToMany(cascade = CascadeType.ALL, mappedBy = "tranchenmodell", fetch = FetchType.LAZY, orphanRemoval = true) @OrderColumn - private List tranchen = new ArrayList(); + private List tranchen = new ArrayList(); - @OneToOne(optional = true, fetch = FetchType.LAZY) - private Preisregelung preisregelung; + @OneToOne(optional = true, fetch = FetchType.LAZY) + private Preisregelung preisregelung; @OneToOne(mappedBy = "tranchenmodell", cascade = CascadeType.ALL, fetch = FetchType.LAZY, orphanRemoval = true) private X x; - public Long getId() { - return id; - } + public Long getId() { + return id; + } public void setId(Long id) { this.id = id; } - public List getTranchen() { - return tranchen; - } + public List getTranchen() { + return tranchen; + } - public Preisregelung getPreisregelung() { - return preisregelung; - } + public Preisregelung getPreisregelung() { + return preisregelung; + } - public void setPreisregelung(Preisregelung preisregelung) { - this.preisregelung = preisregelung; - } + public void setPreisregelung(Preisregelung preisregelung) { + this.preisregelung = preisregelung; + } public X getX() { return x; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/orphan/one2one/fk/reversed/bidirectional/multilevelcascade/Preisregelung.java b/hibernate-core/src/test/java/org/hibernate/orm/test/orphan/one2one/fk/reversed/bidirectional/multilevelcascade/Preisregelung.java index 4a9084b4da..7261ae95e0 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/orphan/one2one/fk/reversed/bidirectional/multilevelcascade/Preisregelung.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/orphan/one2one/fk/reversed/bidirectional/multilevelcascade/Preisregelung.java @@ -15,25 +15,25 @@ import jakarta.persistence.OneToOne; @Entity public class Preisregelung { - private Long id; + private Long id; - private Tranchenmodell tranchenmodell; + private Tranchenmodell tranchenmodell; - @Id - public Long getId() { - return id; - } + @Id + public Long getId() { + return id; + } public void setId(Long id) { this.id = id; } - @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY, orphanRemoval = true) - public Tranchenmodell getTranchenmodell() { - return tranchenmodell; - } + @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY, orphanRemoval = true) + public Tranchenmodell getTranchenmodell() { + return tranchenmodell; + } - public void setTranchenmodell(Tranchenmodell tranchenmodell) { - this.tranchenmodell = tranchenmodell; - } + public void setTranchenmodell(Tranchenmodell tranchenmodell) { + this.tranchenmodell = tranchenmodell; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/orphan/one2one/fk/reversed/bidirectional/multilevelcascade/Tranche.java b/hibernate-core/src/test/java/org/hibernate/orm/test/orphan/one2one/fk/reversed/bidirectional/multilevelcascade/Tranche.java index 32da35e398..e93d33dc95 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/orphan/one2one/fk/reversed/bidirectional/multilevelcascade/Tranche.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/orphan/one2one/fk/reversed/bidirectional/multilevelcascade/Tranche.java @@ -14,26 +14,26 @@ import jakarta.persistence.ManyToOne; @Entity public class Tranche { - @Id - private Long id; + @Id + private Long id; - @ManyToOne(optional = false, fetch = FetchType.EAGER) - private Tranchenmodell tranchenmodell; + @ManyToOne(optional = false, fetch = FetchType.EAGER) + private Tranchenmodell tranchenmodell; - public Long getId() { - return id; - } + public Long getId() { + return id; + } public void setId(Long id) { this.id = id; } - public Tranchenmodell getTranchenmodell() { - return tranchenmodell; - } + public Tranchenmodell getTranchenmodell() { + return tranchenmodell; + } - public void setTranchenmodell(Tranchenmodell tranchenmodell) { - this.tranchenmodell = tranchenmodell; - } + public void setTranchenmodell(Tranchenmodell tranchenmodell) { + this.tranchenmodell = tranchenmodell; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/orphan/one2one/fk/reversed/bidirectional/multilevelcascade/Tranchenmodell.java b/hibernate-core/src/test/java/org/hibernate/orm/test/orphan/one2one/fk/reversed/bidirectional/multilevelcascade/Tranchenmodell.java index de54ccd1bf..e422a47a76 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/orphan/one2one/fk/reversed/bidirectional/multilevelcascade/Tranchenmodell.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/orphan/one2one/fk/reversed/bidirectional/multilevelcascade/Tranchenmodell.java @@ -19,40 +19,40 @@ import jakarta.persistence.OneToOne; public class Tranchenmodell { - private Long id; + private Long id; - private List tranchen = new ArrayList(); + private List tranchen = new ArrayList(); - private Preisregelung preisregelung; + private Preisregelung preisregelung; - @Id - public Long getId() { - return id; - } + @Id + public Long getId() { + return id; + } public void setId(Long id) { this.id = id; } - @OneToMany(cascade = CascadeType.ALL, mappedBy = "tranchenmodell", fetch = FetchType.LAZY, orphanRemoval = true) - public List getTranchen() { - return tranchen; - } + @OneToMany(cascade = CascadeType.ALL, mappedBy = "tranchenmodell", fetch = FetchType.LAZY, orphanRemoval = true) + public List getTranchen() { + return tranchen; + } - public void setTranchen(List tranchen) { - this.tranchen = tranchen; - } + public void setTranchen(List tranchen) { + this.tranchen = tranchen; + } - @OneToOne(mappedBy="tranchenmodell", optional = true, fetch = FetchType.LAZY) - public Preisregelung getPreisregelung() { - return preisregelung; - } + @OneToOne(mappedBy="tranchenmodell", optional = true, fetch = FetchType.LAZY) + public Preisregelung getPreisregelung() { + return preisregelung; + } - public void setPreisregelung(Preisregelung preisregelung) { - this.preisregelung = preisregelung; - } + public void setPreisregelung(Preisregelung preisregelung) { + this.preisregelung = preisregelung; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/pagination/FetchClausePaginationTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/pagination/FetchClausePaginationTest.java index be81951d45..58e221509b 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/pagination/FetchClausePaginationTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/pagination/FetchClausePaginationTest.java @@ -36,52 +36,52 @@ import static org.hamcrest.MatcherAssert.assertThat; @ServiceRegistry @SessionFactory public class FetchClausePaginationTest { - @BeforeEach - public void createTestData(SessionFactoryScope scope) { - scope.inTransaction( - session -> { - final EntityOfLists entityContainingLists = new EntityOfLists( 1, "first" ); + @BeforeEach + public void createTestData(SessionFactoryScope scope) { + scope.inTransaction( + session -> { + final EntityOfLists entityContainingLists = new EntityOfLists( 1, "first" ); - entityContainingLists.addBasic( "abc" ); - entityContainingLists.addBasic( "def" ); - entityContainingLists.addBasic( "ghi" ); + entityContainingLists.addBasic( "abc" ); + entityContainingLists.addBasic( "def" ); + entityContainingLists.addBasic( "ghi" ); - entityContainingLists.addConvertedEnum( EnumValue.TWO ); + entityContainingLists.addConvertedEnum( EnumValue.TWO ); - entityContainingLists.addEnum( EnumValue.ONE ); - entityContainingLists.addEnum( EnumValue.THREE ); + entityContainingLists.addEnum( EnumValue.ONE ); + entityContainingLists.addEnum( EnumValue.THREE ); - entityContainingLists.addComponent( new SimpleComponent( "first-a1", "first-another-a1" ) ); - entityContainingLists.addComponent( new SimpleComponent( "first-a2", "first-another-a2" ) ); - entityContainingLists.addComponent( new SimpleComponent( "first-a3", "first-another-a2" ) ); + entityContainingLists.addComponent( new SimpleComponent( "first-a1", "first-another-a1" ) ); + entityContainingLists.addComponent( new SimpleComponent( "first-a2", "first-another-a2" ) ); + entityContainingLists.addComponent( new SimpleComponent( "first-a3", "first-another-a2" ) ); - session.persist( entityContainingLists ); - } - ); - } + session.persist( entityContainingLists ); + } + ); + } - @AfterEach - public void dropTestData(SessionFactoryScope scope) { - scope.inTransaction( - session -> { - session.createQuery( "delete from EntityOfLists" ).executeUpdate(); - session.createQuery( "delete from SimpleEntity" ).executeUpdate(); - } - ); - } + @AfterEach + public void dropTestData(SessionFactoryScope scope) { + scope.inTransaction( + session -> { + session.createQuery( "delete from EntityOfLists" ).executeUpdate(); + session.createQuery( "delete from SimpleEntity" ).executeUpdate(); + } + ); + } - @Test - @RequiresDialectFeature(feature = DialectFeatureChecks.SupportsWithTies.class) - @SkipForDialect(dialectClass = DerbyDialect.class, reason = "Derby only supports row_number, but this requires the dense_rank window function") - public void testFetchWithTies(SessionFactoryScope scope) { - scope.inSession( - session -> { - List list = session.createQuery( - "select comp from EntityOfLists e join e.listOfComponents comp order by comp.anotherAttribute desc fetch first 1 row with ties", - SimpleComponent.class - ).list(); - assertThat( list.size(), is( 2 ) ); - } - ); - } + @Test + @RequiresDialectFeature(feature = DialectFeatureChecks.SupportsWithTies.class) + @SkipForDialect(dialectClass = DerbyDialect.class, reason = "Derby only supports row_number, but this requires the dense_rank window function") + public void testFetchWithTies(SessionFactoryScope scope) { + scope.inSession( + session -> { + List list = session.createQuery( + "select comp from EntityOfLists e join e.listOfComponents comp order by comp.anotherAttribute desc fetch first 1 row with ties", + SimpleComponent.class + ).list(); + assertThat( list.size(), is( 2 ) ); + } + ); + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/pagination/SubqueryPaginationTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/pagination/SubqueryPaginationTest.java index f2caa61666..6c405b984b 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/pagination/SubqueryPaginationTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/pagination/SubqueryPaginationTest.java @@ -38,67 +38,67 @@ import static org.hamcrest.MatcherAssert.assertThat; @SessionFactory @RequiresDialectFeature( feature = DialectFeatureChecks.SupportsOrderByInCorrelatedSubquery.class) public class SubqueryPaginationTest { - @BeforeEach - public void createTestData(SessionFactoryScope scope) { - scope.inTransaction( - session -> { - final EntityOfLists entityContainingLists = new EntityOfLists( 1, "first" ); + @BeforeEach + public void createTestData(SessionFactoryScope scope) { + scope.inTransaction( + session -> { + final EntityOfLists entityContainingLists = new EntityOfLists( 1, "first" ); - entityContainingLists.addBasic( "abc" ); - entityContainingLists.addBasic( "def" ); - entityContainingLists.addBasic( "ghi" ); + entityContainingLists.addBasic( "abc" ); + entityContainingLists.addBasic( "def" ); + entityContainingLists.addBasic( "ghi" ); - entityContainingLists.addConvertedEnum( EnumValue.TWO ); + entityContainingLists.addConvertedEnum( EnumValue.TWO ); - entityContainingLists.addEnum( EnumValue.ONE ); - entityContainingLists.addEnum( EnumValue.THREE ); + entityContainingLists.addEnum( EnumValue.ONE ); + entityContainingLists.addEnum( EnumValue.THREE ); - entityContainingLists.addComponent( new SimpleComponent( "first-a1", "first-another-a1" ) ); - entityContainingLists.addComponent( new SimpleComponent( "first-a2", "first-another-a2" ) ); - entityContainingLists.addComponent( new SimpleComponent( "first-a3", "first-another-a2" ) ); + entityContainingLists.addComponent( new SimpleComponent( "first-a1", "first-another-a1" ) ); + entityContainingLists.addComponent( new SimpleComponent( "first-a2", "first-another-a2" ) ); + entityContainingLists.addComponent( new SimpleComponent( "first-a3", "first-another-a2" ) ); - session.persist( entityContainingLists ); - } - ); - } + session.persist( entityContainingLists ); + } + ); + } - @AfterEach - public void dropTestData(SessionFactoryScope scope) { - scope.inTransaction( - session -> { - session.createQuery( "delete from EntityOfLists" ).executeUpdate(); - session.createQuery( "delete from SimpleEntity" ).executeUpdate(); - } - ); - } + @AfterEach + public void dropTestData(SessionFactoryScope scope) { + scope.inTransaction( + session -> { + session.createQuery( "delete from EntityOfLists" ).executeUpdate(); + session.createQuery( "delete from SimpleEntity" ).executeUpdate(); + } + ); + } - @Test - @SkipForDialect(dialectClass = OracleDialect.class, majorVersion = 11, reason = "Generates nested correlated subquery which is not supported in that version") - public void testLimitInSubquery(SessionFactoryScope scope) { - scope.inSession( - session -> { - List list = session.createQuery( - "from EntityOfLists e where 'abc' = (select basic from e.listOfBasics basic order by basic limit 1)", - EntityOfLists.class - ).list(); - assertThat( list.size(), is( 1 ) ); - } - ); - } + @Test + @SkipForDialect(dialectClass = OracleDialect.class, majorVersion = 11, reason = "Generates nested correlated subquery which is not supported in that version") + public void testLimitInSubquery(SessionFactoryScope scope) { + scope.inSession( + session -> { + List list = session.createQuery( + "from EntityOfLists e where 'abc' = (select basic from e.listOfBasics basic order by basic limit 1)", + EntityOfLists.class + ).list(); + assertThat( list.size(), is( 1 ) ); + } + ); + } - @Test - @RequiresDialectFeature(feature = DialectFeatureChecks.SupportsOffsetInSubquery.class) - @SkipForDialect(dialectClass = OracleDialect.class, majorVersion = 11, reason = "Generates nested correlated subquery which is not supported in that version") - @SkipForDialect(dialectClass = DB2Dialect.class, majorVersion = 10, reason = "Generates nested correlated subquery which is not supported in that version") - public void testLimitAndOffsetInSubquery(SessionFactoryScope scope) { - scope.inSession( - session -> { - List list = session.createQuery( - "from EntityOfLists e where 'def' = (select basic from e.listOfBasics basic order by basic limit 1 offset 1)", - EntityOfLists.class - ).list(); - assertThat( list.size(), is( 1 ) ); - } - ); - } + @Test + @RequiresDialectFeature(feature = DialectFeatureChecks.SupportsOffsetInSubquery.class) + @SkipForDialect(dialectClass = OracleDialect.class, majorVersion = 11, reason = "Generates nested correlated subquery which is not supported in that version") + @SkipForDialect(dialectClass = DB2Dialect.class, majorVersion = 10, reason = "Generates nested correlated subquery which is not supported in that version") + public void testLimitAndOffsetInSubquery(SessionFactoryScope scope) { + scope.inSession( + session -> { + List list = session.createQuery( + "from EntityOfLists e where 'def' = (select basic from e.listOfBasics basic order by basic limit 1 offset 1)", + EntityOfLists.class + ).list(); + assertThat( list.size(), is( 1 ) ); + } + ); + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/pagination/hhh9965/HHH9965Test.java b/hibernate-core/src/test/java/org/hibernate/orm/test/pagination/hhh9965/HHH9965Test.java index 529336c9e8..786a302d02 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/pagination/hhh9965/HHH9965Test.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/pagination/hhh9965/HHH9965Test.java @@ -23,37 +23,37 @@ import static org.junit.Assert.fail; @JiraKey(value = "HHH-9965") public class HHH9965Test extends BaseCoreFunctionalTestCase { - @Test - public void testHHH9965() { - Session session = openSession(); - session.beginTransaction(); + @Test + public void testHHH9965() { + Session session = openSession(); + session.beginTransaction(); - String hql = "SELECT s FROM Shop s join fetch s.products"; + String hql = "SELECT s FROM Shop s join fetch s.products"; - try{ - session.createQuery(hql) - .setMaxResults(3) - .list(); - fail("Pagination over collection fetch failure was expected"); - } catch (Exception e){ - log.info(e.getMessage()); - } + try{ + session.createQuery(hql) + .setMaxResults(3) + .list(); + fail("Pagination over collection fetch failure was expected"); + } catch (Exception e){ + log.info(e.getMessage()); + } - session.getTransaction().commit(); - session.close(); - } + session.getTransaction().commit(); + session.close(); + } - @Override - protected void configure(Configuration cfg) { - super.configure(cfg); - cfg.setProperty( Environment.FAIL_ON_PAGINATION_OVER_COLLECTION_FETCH, true ); - } + @Override + protected void configure(Configuration cfg) { + super.configure(cfg); + cfg.setProperty( Environment.FAIL_ON_PAGINATION_OVER_COLLECTION_FETCH, true ); + } - @Override - protected Class[] getAnnotatedClasses() { - return new Class[]{ - Shop.class, - Product.class - }; - } + @Override + protected Class[] getAnnotatedClasses() { + return new Class[]{ + Shop.class, + Product.class + }; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/pagination/hhh9965/Product.java b/hibernate-core/src/test/java/org/hibernate/orm/test/pagination/hhh9965/Product.java index 57f201353b..3967778b77 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/pagination/hhh9965/Product.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/pagination/hhh9965/Product.java @@ -18,16 +18,16 @@ import jakarta.persistence.Id; @Entity public class Product { - @Id - @GeneratedValue - private Long id; + @Id + @GeneratedValue + private Long id; - public Long getId() { - return id; - } + public Long getId() { + return id; + } - public void setId(Long id) { - this.id = id; - } + public void setId(Long id) { + this.id = id; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/pagination/hhh9965/Shop.java b/hibernate-core/src/test/java/org/hibernate/orm/test/pagination/hhh9965/Shop.java index 1950ffa63a..fb32faf2bc 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/pagination/hhh9965/Shop.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/pagination/hhh9965/Shop.java @@ -17,27 +17,27 @@ import java.util.List; @Entity public class Shop { - @Id - @GeneratedValue - private Long id; + @Id + @GeneratedValue + private Long id; - @OneToMany(fetch = FetchType.LAZY) - private List products; + @OneToMany(fetch = FetchType.LAZY) + private List products; - public Long getId() { - return id; - } + public Long getId() { + return id; + } - public void setId(Long id) { - this.id = id; - } + public void setId(Long id) { + this.id = id; + } - public List getProducts() { - return products; - } + public List getProducts() { + return products; + } - public void setProducts(List products) { - this.products = products; - } + public void setProducts(List products) { + this.products = products; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/pc/FilterJoinTableTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/pc/FilterJoinTableTest.java index 1b2bd73be2..ba3796f270 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/pc/FilterJoinTableTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/pc/FilterJoinTableTest.java @@ -33,186 +33,186 @@ import static org.junit.Assert.assertEquals; */ public class FilterJoinTableTest extends BaseEntityManagerFunctionalTestCase { - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Client.class, - Account.class - }; - } + @Override + protected Class[] getAnnotatedClasses() { + return new Class[] { + Client.class, + Account.class + }; + } - @Test - public void testLifecycle() { - doInJPA(this::entityManagerFactory, entityManager -> { - //tag::pc-filter-join-table-persistence-example[] - Client client = new Client() - .setId(1L) - .setName("John Doe"); + @Test + public void testLifecycle() { + doInJPA(this::entityManagerFactory, entityManager -> { + //tag::pc-filter-join-table-persistence-example[] + Client client = new Client() + .setId(1L) + .setName("John Doe"); - client.addAccount( - new Account() - .setId(1L) - .setType(AccountType.CREDIT) - .setAmount(5000d) - .setRate(1.25 / 100) - ); + client.addAccount( + new Account() + .setId(1L) + .setType(AccountType.CREDIT) + .setAmount(5000d) + .setRate(1.25 / 100) + ); - client.addAccount( - new Account() - .setId(2L) - .setType(AccountType.DEBIT) - .setAmount(0d) - .setRate(1.05 / 100) - ); + client.addAccount( + new Account() + .setId(2L) + .setType(AccountType.DEBIT) + .setAmount(0d) + .setRate(1.05 / 100) + ); - client.addAccount( - new Account() - .setType(AccountType.DEBIT) - .setId(3L) - .setAmount(250d) - .setRate(1.05 / 100) - ); + client.addAccount( + new Account() + .setType(AccountType.DEBIT) + .setId(3L) + .setAmount(250d) + .setRate(1.05 / 100) + ); - entityManager.persist(client); - //end::pc-filter-join-table-persistence-example[] - }); + entityManager.persist(client); + //end::pc-filter-join-table-persistence-example[] + }); - doInJPA(this::entityManagerFactory, entityManager -> { - //tag::pc-no-filter-join-table-collection-query-example[] - Client client = entityManager.find(Client.class, 1L); + doInJPA(this::entityManagerFactory, entityManager -> { + //tag::pc-no-filter-join-table-collection-query-example[] + Client client = entityManager.find(Client.class, 1L); - assertEquals(3, client.getAccounts().size()); - //end::pc-no-filter-join-table-collection-query-example[] - }); + assertEquals(3, client.getAccounts().size()); + //end::pc-no-filter-join-table-collection-query-example[] + }); - doInJPA(this::entityManagerFactory, entityManager -> { - log.infof("Activate filter [%s]", "firstAccounts"); + doInJPA(this::entityManagerFactory, entityManager -> { + log.infof("Activate filter [%s]", "firstAccounts"); - //tag::pc-filter-join-table-collection-query-example[] - Client client = entityManager.find(Client.class, 1L); + //tag::pc-filter-join-table-collection-query-example[] + Client client = entityManager.find(Client.class, 1L); - entityManager - .unwrap(Session.class) - .enableFilter("firstAccounts") - .setParameter("maxOrderId", 1); + entityManager + .unwrap(Session.class) + .enableFilter("firstAccounts") + .setParameter("maxOrderId", 1); - assertEquals(2, client.getAccounts().size()); - //end::pc-filter-join-table-collection-query-example[] - }); - } + assertEquals(2, client.getAccounts().size()); + //end::pc-filter-join-table-collection-query-example[] + }); + } - public enum AccountType { - DEBIT, - CREDIT - } + public enum AccountType { + DEBIT, + CREDIT + } - //tag::pc-filter-join-table-example[] - @Entity(name = "Client") - @FilterDef( - name="firstAccounts", - parameters=@ParamDef( - name="maxOrderId", - type=int.class - ) - ) - public static class Client { + //tag::pc-filter-join-table-example[] + @Entity(name = "Client") + @FilterDef( + name="firstAccounts", + parameters=@ParamDef( + name="maxOrderId", + type=int.class + ) +) + public static class Client { - @Id - private Long id; + @Id + private Long id; - private String name; + private String name; - @OneToMany(cascade = CascadeType.ALL) - @OrderColumn(name = "order_id") - @FilterJoinTable( - name="firstAccounts", - condition="order_id <= :maxOrderId" - ) - private List accounts = new ArrayList<>(); + @OneToMany(cascade = CascadeType.ALL) + @OrderColumn(name = "order_id") + @FilterJoinTable( + name="firstAccounts", + condition="order_id <= :maxOrderId" + ) + private List accounts = new ArrayList<>(); - //Getters and setters omitted for brevity - //end::pc-filter-join-table-example[] - public Long getId() { - return id; - } + //Getters and setters omitted for brevity + //end::pc-filter-join-table-example[] + public Long getId() { + return id; + } - public Client setId(Long id) { - this.id = id; - return this; - } + public Client setId(Long id) { + this.id = id; + return this; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public Client setName(String name) { - this.name = name; - return this; - } + public Client setName(String name) { + this.name = name; + return this; + } - public List getAccounts() { - return accounts; - } - //tag::pc-filter-join-table-example[] + public List getAccounts() { + return accounts; + } + //tag::pc-filter-join-table-example[] - public void addAccount(Account account) { - this.accounts.add(account); - } - } + public void addAccount(Account account) { + this.accounts.add(account); + } + } - @Entity(name = "Account") - public static class Account { + @Entity(name = "Account") + public static class Account { - @Id - private Long id; + @Id + private Long id; - @Column(name = "account_type") - @Enumerated(EnumType.STRING) - private AccountType type; + @Column(name = "account_type") + @Enumerated(EnumType.STRING) + private AccountType type; - private Double amount; + private Double amount; - private Double rate; + private Double rate; - //Getters and setters omitted for brevity - //end::pc-filter-join-table-example[] - public Long getId() { - return id; - } + //Getters and setters omitted for brevity + //end::pc-filter-join-table-example[] + public Long getId() { + return id; + } - public Account setId(Long id) { - this.id = id; - return this; - } + public Account setId(Long id) { + this.id = id; + return this; + } - public AccountType getType() { - return type; - } + public AccountType getType() { + return type; + } - public Account setType(AccountType type) { - this.type = type; - return this; - } + public Account setType(AccountType type) { + this.type = type; + return this; + } - public Double getAmount() { - return amount; - } + public Double getAmount() { + return amount; + } - public Account setAmount(Double amount) { - this.amount = amount; - return this; - } + public Account setAmount(Double amount) { + this.amount = amount; + return this; + } - public Double getRate() { - return rate; - } + public Double getRate() { + return rate; + } - public Account setRate(Double rate) { - this.rate = rate; - return this; - } + public Account setRate(Double rate) { + this.rate = rate; + return this; + } - //tag::pc-filter-join-table-example[] - } - //end::pc-filter-join-table-example[] + //tag::pc-filter-join-table-example[] + } + //end::pc-filter-join-table-example[] } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/pc/FilterTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/pc/FilterTest.java index ae14cf301d..3abaf56490 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/pc/FilterTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/pc/FilterTest.java @@ -56,753 +56,753 @@ import static org.junit.Assert.assertTrue; */ public class FilterTest extends BaseEntityManagerFunctionalTestCase { - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Client.class, - Account.class, - AccountEager.class, - AccountNotFound.class, - AccountNotFoundException.class - }; - } - - @Override - protected void addConfigOptions(Map options) { - super.addConfigOptions( options ); - options.put( DEFAULT_LIST_SEMANTICS, CollectionClassification.BAG.name() ); - } - - @Before - public void setup() { - doInJPA(this::entityManagerFactory, entityManager -> { - //tag::pc-filter-persistence-example[] - Client client = new Client() - .setId(1L) - .setName("John Doe") - .setType(AccountType.DEBIT); - - Account account1; - client.addAccount( - account1 = new Account() - .setId(1L) - .setType(AccountType.CREDIT) - .setAmount(5000d) - .setRate(1.25 / 100) - .setActive(true) - ); - - client.addAccount( - new Account() - .setId(2L) - .setType(AccountType.DEBIT) - .setAmount(0d) - .setRate(1.05 / 100) - .setActive(false) - .setParentAccount( account1 ) - ); - - client.addAccount( - new Account() - .setType(AccountType.DEBIT) - .setId(3L) - .setAmount(250d) - .setRate(1.05 / 100) - .setActive(true) - ); - - entityManager.persist(client); - //end::pc-filter-persistence-example[] - entityManager.persist( - new AccountEager() - .setId(2L) - .setParentAccount( account1 ) - ); - entityManager.persist( - new AccountNotFound() - .setId(2L) - .setParentAccount( account1 ) - ); - entityManager.persist( - new AccountNotFoundException() - .setId(2L) - .setParentAccount( account1 ) - ); - }); - } - - @After - public void tearDown() { - doInJPA(this::entityManagerFactory, entityManager -> { - entityManager.createQuery( "update Account set parentAccount = null" ).executeUpdate(); - entityManager.createQuery( "delete from AccountEager" ).executeUpdate(); - entityManager.createQuery( "delete from AccountNotFound" ).executeUpdate(); - entityManager.createQuery( "delete from AccountNotFoundException" ).executeUpdate(); - entityManager.createQuery( "delete from Account" ).executeUpdate(); - entityManager.createQuery( "delete from Client" ).executeUpdate(); - }); - } - - @Test - public void testLifecycle() { - doInJPA(this::entityManagerFactory, entityManager -> { - log.infof("Activate filter [%s]", "activeAccount"); - - entityManager - .unwrap(Session.class) - .enableFilter("activeAccount") - .setParameter("active", true); - - Account account1 = entityManager.find(Account.class, 1L); - Account account2 = entityManager.find(Account.class, 2L); - - assertNotNull(account1); - assertNotNull(account2); - }); - - doInJPA(this::entityManagerFactory, entityManager -> { - log.infof("Activate filter [%s]", "activeAccount"); - - entityManager - .unwrap(Session.class) - .enableFilter("activeAccount") - .setParameter("active", true); - - Account account1 = entityManager.createQuery( - "select a from Account a where a.id = :id", Account.class) - .setParameter("id", 1L) - .getSingleResult(); - assertNotNull(account1); - try { - Account account2 = entityManager.createQuery( - "select a from Account a where a.id = :id", Account.class) - .setParameter("id", 2L) - .getSingleResult(); - } - catch (NoResultException expected) { - } - }); - - doInJPA(this::entityManagerFactory, entityManager -> { - log.infof("Activate filter [%s]", "activeAccount"); - //tag::pc-filter-entity-example[] - entityManager - .unwrap(Session.class) - .enableFilter("activeAccount") - .setParameter("active", true); - - Account account = entityManager.find(Account.class, 2L); - - assertFalse( account.isActive() ); - //end::pc-filter-entity-example[] - }); - - doInJPA(this::entityManagerFactory, entityManager -> { - //tag::pc-no-filter-entity-query-example[] - List accounts = entityManager.createQuery( - "select a from Account a", Account.class) - .getResultList(); - - assertEquals(3, accounts.size()); - //end::pc-no-filter-entity-query-example[] - }); - - doInJPA(this::entityManagerFactory, entityManager -> { - log.infof("Activate filter [%s]", "activeAccount"); - //tag::pc-filter-entity-query-example[] - entityManager - .unwrap(Session.class) - .enableFilter("activeAccount") - .setParameter("active", true); - - List accounts = entityManager.createQuery( - "select a from Account a", Account.class) - .getResultList(); - - assertEquals(2, accounts.size()); - //end::pc-filter-entity-query-example[] - }); - - doInJPA(this::entityManagerFactory, entityManager -> { - //tag::pc-no-filter-collection-query-example[] - Client client = entityManager.find(Client.class, 1L); - - assertEquals(3, client.getAccounts().size()); - //end::pc-no-filter-collection-query-example[] - }); - - doInJPA(this::entityManagerFactory, entityManager -> { - log.infof("Activate filter [%s]", "activeAccount"); - - //tag::pc-filter-collection-query-example[] - entityManager - .unwrap(Session.class) - .enableFilter("activeAccount") - .setParameter("active", true); - - Client client = entityManager.find(Client.class, 1L); - - assertEquals(2, client.getAccounts().size()); - //end::pc-filter-collection-query-example[] - }); - } - - @Test - @JiraKey("HHH-16830") - public void testApplyToLoadByKey() { - doInJPA(this::entityManagerFactory, entityManager -> { - log.infof("Activate filter [%s]", "minimumAmount"); - //tag::pc-filter-entity-example[] - entityManager - .unwrap(Session.class) - .enableFilter("minimumAmount") - .setParameter("amount", 9000d); - - Account account = entityManager.find(Account.class, 1L); - - assertNull( account ); - //end::pc-filter-entity-example[] - }); - - doInJPA(this::entityManagerFactory, entityManager -> { - log.infof("Activate filter [%s]", "minimumAmount"); - //tag::pc-filter-entity-example[] - entityManager - .unwrap(Session.class) - .enableFilter("minimumAmount") - .setParameter("amount", 100d); - - Account account = entityManager.find(Account.class, 1L); - - assertNotNull( account ); - //end::pc-filter-entity-example[] - }); - - doInJPA(this::entityManagerFactory, entityManager -> { - log.infof("Activate filter [%s]", "minimumAmount"); - //tag::pc-filter-entity-query-example[] - entityManager - .unwrap(Session.class) - .enableFilter("minimumAmount") - .setParameter("amount", 500d); - - List accounts = entityManager.createQuery( - "select a from Account a", Account.class) - .getResultList(); - - assertEquals(1, accounts.size()); - //end::pc-filter-entity-query-example[] - }); - } - - @Test - @JiraKey("HHH-16830") - public void testApplyToLoadByKeyAssociationFiltering() { - doInJPA( this::entityManagerFactory, entityManager -> { - Account account = entityManager.find( Account.class, 2L ); - assertNotNull( account.getParentAccount() ); - } ); - } - - @Test - @JiraKey("HHH-16830") - public void testApplyToLoadByKeyAssociationFilteringLazyInitialization() { - doInJPA( this::entityManagerFactory, entityManager -> { - entityManager.unwrap( Session.class ) - .enableFilter( "accountType" ) - .setParameter( "type", "DEBIT" ); - - Account account = entityManager.find( Account.class, 2L ); - EntityNotFoundException exception = assertThrows( - EntityNotFoundException.class, - () -> Hibernate.initialize( account.getParentAccount() ) - ); - // Account with id 1 does not exist - assertTrue( exception.getMessage().endsWith( "#1]" ) ); - } ); - } - - @Test - @JiraKey("HHH-16830") - public void testApplyToLoadByKeyAssociationFilteringAccountLoadGraphInitializer() { - doInJPA( this::entityManagerFactory, entityManager -> { - entityManager.unwrap( Session.class ) - .enableFilter( "accountType" ) - .setParameter( "type", "DEBIT" ); - EntityGraph entityGraph = entityManager.createEntityGraph( Account.class ); - entityGraph.addAttributeNodes( "parentAccount" ); - - EntityFilterException exception = assertThrows( - EntityFilterException.class, - () -> entityManager.find( - Account.class, - 2L, - Map.of( AvailableHints.HINT_SPEC_LOAD_GRAPH, entityGraph ) - ) - ); - // Account with id 1 does not exist - assertTrue( exception.getRole().endsWith( "parentAccount" ) ); - assertEquals( 1L, exception.getIdentifier() ); - } ); - } - - @Test - @JiraKey("HHH-16830") - public void testApplyToLoadByKeyAssociationFilteringAccountJoinInitializer() { - doInJPA( this::entityManagerFactory, entityManager -> { - entityManager.unwrap( Session.class ) - .enableFilter( "accountType" ) - .setParameter( "type", "DEBIT" ); - - EntityFilterException exception = assertThrows( - EntityFilterException.class, - () -> entityManager.createQuery( - "select a from Account a left join fetch a.parentAccount where a.id = 2", - Account.class - ).getResultList() - ); - // Account with id 1 does not exist - assertTrue( exception.getRole().contains( "parentAccount" ) ); - assertEquals( 1L, exception.getIdentifier() ); - } ); - } - - @Test - @JiraKey("HHH-16830") - public void testApplyToLoadByKeyAssociationFilteringAccountSelectInitializer() { - doInJPA( this::entityManagerFactory, entityManager -> { - entityManager.unwrap( Session.class ) - .enableFilter( "accountType" ) - .setParameter( "type", "DEBIT" ); - - EntityFilterException exception = assertThrows( - EntityFilterException.class, - () -> entityManager.createQuery( - "select a from AccountEager a where a.id = 2", - AccountEager.class - ).getResultList() - ); - // Account with id 1 does not exist - assertTrue( exception.getRole().contains( "parentAccount" ) ); - assertEquals( 1L, exception.getIdentifier() ); - } ); - } - - @Test - @JiraKey("HHH-16830") - public void testApplyToLoadByKeyAssociationFilteringAccountNotFoundException() { - doInJPA(this::entityManagerFactory, entityManager -> { - entityManager.unwrap(Session.class) - .enableFilter("accountType") - .setParameter("type", "DEBIT"); - - EntityFilterException exception = assertThrows( - EntityFilterException.class, - () -> entityManager.createQuery( - "select a from AccountNotFoundException a where a.id = 2", - AccountNotFoundException.class - ).getSingleResult() - ); - // Account with id 1 does not exist - assertTrue( exception.getRole().contains( "parentAccount" ) ); - assertEquals( 1L, exception.getIdentifier() ); - }); - doInJPA(this::entityManagerFactory, entityManager -> { - entityManager.unwrap(Session.class) - .enableFilter("accountType") - .setParameter("type", "DEBIT"); - - EntityFilterException exception = assertThrows( - EntityFilterException.class, - () -> entityManager.createQuery( - "select a from AccountNotFoundException a left join fetch a.parentAccount where a.id = 2", - AccountNotFoundException.class - ).getSingleResult() - ); - // Account with id 1 does not exist - assertTrue( exception.getRole().contains( "parentAccount" ) ); - assertEquals( 1L, exception.getIdentifier() ); - }); - } - - @Test - @JiraKey("HHH-16830") - public void testApplyToLoadByKeyAssociationFilteringAccountNotFoundIgnore() { - doInJPA(this::entityManagerFactory, entityManager -> { - entityManager.unwrap(Session.class) - .enableFilter("accountType") - .setParameter("type", "DEBIT"); - - AccountNotFound account = entityManager.createQuery( - "select a from AccountNotFound a where a.id = 2", - AccountNotFound.class - ).getSingleResult(); - // No exception, since we use NotFoundAction.IGNORE - assertNull( account.getParentAccount() ); - }); - doInJPA(this::entityManagerFactory, entityManager -> { - entityManager.unwrap(Session.class) - .enableFilter("accountType") - .setParameter("type", "DEBIT"); - - AccountNotFound account = entityManager.createQuery( - "select a from AccountNotFound a left join fetch a.parentAccount where a.id = 2", - AccountNotFound.class - ).getSingleResult(); - // No exception, since we use NotFoundAction.IGNORE - assertNull( account.getParentAccount() ); - }); - } - - public enum AccountType { - DEBIT, - CREDIT - } - - //tag::pc-filter-Client-example[] - @Entity(name = "Client") - @Table(name = "client") - public static class Client { - - @Id - private Long id; - - private String name; - - private AccountType type; - - @OneToMany( - mappedBy = "client", - cascade = CascadeType.ALL - ) - @Filter( - name="activeAccount", - condition="active_status = :active" - ) - private List accounts = new ArrayList<>(); - - //Getters and setters omitted for brevity - //end::pc-filter-Client-example[] - public Long getId() { - return id; - } - - public Client setId(Long id) { - this.id = id; - return this; - } - - public String getName() { - return name; - } - - public Client setName(String name) { - this.name = name; - return this; - } - - public AccountType getType() { - return type; - } - - public Client setType(AccountType type) { - this.type = type; - return this; - } - - public List getAccounts() { - return accounts; - } - //tag::pc-filter-Client-example[] - - public void addAccount(Account account) { - account.setClient(this); - this.accounts.add(account); - } - } - //end::pc-filter-Client-example[] - - //tag::pc-filter-Account-example[] - @Entity(name = "Account") - @Table(name = "account") - @FilterDef( - name="activeAccount", - parameters = @ParamDef( - name="active", - type=Boolean.class - ) - ) - @Filter( - name="activeAccount", - condition="active_status = :active" - ) - @FilterDef( - name="minimumAmount", - parameters = @ParamDef( - name="amount", - type=Double.class - ), - applyToLoadByKey = true - ) - @Filter( - name="minimumAmount", - condition="amount > :amount" - ) - @FilterDef( - name="accountType", - parameters = @ParamDef( - name="type", - type=String.class - ), - applyToLoadByKey = true - ) - @Filter( - name="accountType", - condition="account_type = :type" - ) - - public static class Account { - - @Id - private Long id; - - @ManyToOne(fetch = FetchType.LAZY) - private Client client; - - @Column(name = "account_type") - @Enumerated(EnumType.STRING) - private AccountType type; - - private Double amount; - - private Double rate; - - @Column(name = "active_status") - private boolean active; - - //Getters and setters omitted for brevity - //end::pc-filter-Account-example[] - - @ManyToOne(fetch = FetchType.LAZY) - private Account parentAccount; - - public Long getId() { - return id; - } - - public Account setId(Long id) { - this.id = id; - return this; - } - - public Client getClient() { - return client; - } - - public Account setClient(Client client) { - this.client = client; - return this; - } - - public AccountType getType() { - return type; - } - - public Account setType(AccountType type) { - this.type = type; - return this; - } - - public Double getAmount() { - return amount; - } - - public Account setAmount(Double amount) { - this.amount = amount; - return this; - } - - public Double getRate() { - return rate; - } - - public Account setRate(Double rate) { - this.rate = rate; - return this; - } - - public boolean isActive() { - return active; - } - - public Account setActive(boolean active) { - this.active = active; - return this; - } - - public Account getParentAccount() { - return parentAccount; - } - - public Account setParentAccount(Account parentAccount) { - this.parentAccount = parentAccount; - return this; - } - //tag::pc-filter-Account-example[] - } - //end::pc-filter-Account-example[] - - - @Entity(name = "AutoFilteredAccount") - @Table(name = "autofilteredaccount") - //tag::pc-filter-auto-enabled-Account-example[] - @FilterDef( - name="activeAccount", - parameters = @ParamDef( - name="active", - type=Boolean.class - ), - autoEnabled = true - ) - //end::pc-filter-auto-enabled-Account-example[] - @Filter( - name="activeAccount", - condition="active_status = :active" - ) - //tag::pc-filter-resolver-Account-example[] - @FilterDef( - name="activeAccountWithResolver", - parameters = @ParamDef( - name="active", - type=Boolean.class, - resolver = AccountIsActiveResolver.class - ), - autoEnabled = true - ) - //end::pc-filter-resolver-Account-example[] - public static class AutoFilteredAccount { - - @Id - private Long id; - - @Column(name = "active_status") - private boolean active; - - public Long getId() { - return id; - } - - public AutoFilteredAccount setId(Long id) { - this.id = id; - return this; - } - - public boolean isActive() { - return active; - } - - public AutoFilteredAccount setActive(boolean active) { - this.active = active; - return this; - } - } - - //tag::pc-filter-resolver-Account-example[] - - public static class AccountIsActiveResolver implements Supplier { - @Override - public Boolean get() { - return true; - } - } - //end::pc-filter-resolver-Account-example[] - - @Entity(name = "AccountEager") - @Table(name = "account_eager") - public static class AccountEager { - - @Id - private Long id; - - @ManyToOne - private Account parentAccount; - - public Long getId() { - return id; - } - - public AccountEager setId(Long id) { - this.id = id; - return this; - } - - public Account getParentAccount() { - return parentAccount; - } - - public AccountEager setParentAccount(Account parentAccount) { - this.parentAccount = parentAccount; - return this; - } - } - - @Entity(name = "AccountNotFound") - @Table(name = "account_not_found") - public static class AccountNotFound { - - @Id - private Long id; - - @ManyToOne - @NotFound(action = NotFoundAction.IGNORE) - private Account parentAccount; - - public Long getId() { - return id; - } - - public AccountNotFound setId(Long id) { - this.id = id; - return this; - } - - public Account getParentAccount() { - return parentAccount; - } - - public AccountNotFound setParentAccount(Account parentAccount) { - this.parentAccount = parentAccount; - return this; - } - } - - @Entity(name = "AccountNotFoundException") - @Table(name = "account_not_found_exception") - public static class AccountNotFoundException { - - @Id - private Long id; - - @ManyToOne - @NotFound - private Account parentAccount; - - public Long getId() { - return id; - } - - public AccountNotFoundException setId(Long id) { - this.id = id; - return this; - } - - public Account getParentAccount() { - return parentAccount; - } - - public AccountNotFoundException setParentAccount(Account parentAccount) { - this.parentAccount = parentAccount; - return this; - } - } + @Override + protected Class[] getAnnotatedClasses() { + return new Class[] { + Client.class, + Account.class, + AccountEager.class, + AccountNotFound.class, + AccountNotFoundException.class + }; + } + + @Override + protected void addConfigOptions(Map options) { + super.addConfigOptions( options ); + options.put( DEFAULT_LIST_SEMANTICS, CollectionClassification.BAG.name() ); + } + + @Before + public void setup() { + doInJPA(this::entityManagerFactory, entityManager -> { + //tag::pc-filter-persistence-example[] + Client client = new Client() + .setId(1L) + .setName("John Doe") + .setType(AccountType.DEBIT); + + Account account1; + client.addAccount( + account1 = new Account() + .setId(1L) + .setType(AccountType.CREDIT) + .setAmount(5000d) + .setRate(1.25 / 100) + .setActive(true) + ); + + client.addAccount( + new Account() + .setId(2L) + .setType(AccountType.DEBIT) + .setAmount(0d) + .setRate(1.05 / 100) + .setActive(false) + .setParentAccount( account1 ) + ); + + client.addAccount( + new Account() + .setType(AccountType.DEBIT) + .setId(3L) + .setAmount(250d) + .setRate(1.05 / 100) + .setActive(true) + ); + + entityManager.persist(client); + //end::pc-filter-persistence-example[] + entityManager.persist( + new AccountEager() + .setId(2L) + .setParentAccount( account1 ) + ); + entityManager.persist( + new AccountNotFound() + .setId(2L) + .setParentAccount( account1 ) + ); + entityManager.persist( + new AccountNotFoundException() + .setId(2L) + .setParentAccount( account1 ) + ); + }); + } + + @After + public void tearDown() { + doInJPA(this::entityManagerFactory, entityManager -> { + entityManager.createQuery( "update Account set parentAccount = null" ).executeUpdate(); + entityManager.createQuery( "delete from AccountEager" ).executeUpdate(); + entityManager.createQuery( "delete from AccountNotFound" ).executeUpdate(); + entityManager.createQuery( "delete from AccountNotFoundException" ).executeUpdate(); + entityManager.createQuery( "delete from Account" ).executeUpdate(); + entityManager.createQuery( "delete from Client" ).executeUpdate(); + }); + } + + @Test + public void testLifecycle() { + doInJPA(this::entityManagerFactory, entityManager -> { + log.infof("Activate filter [%s]", "activeAccount"); + + entityManager + .unwrap(Session.class) + .enableFilter("activeAccount") + .setParameter("active", true); + + Account account1 = entityManager.find(Account.class, 1L); + Account account2 = entityManager.find(Account.class, 2L); + + assertNotNull(account1); + assertNotNull(account2); + }); + + doInJPA(this::entityManagerFactory, entityManager -> { + log.infof("Activate filter [%s]", "activeAccount"); + + entityManager + .unwrap(Session.class) + .enableFilter("activeAccount") + .setParameter("active", true); + + Account account1 = entityManager.createQuery( + "select a from Account a where a.id = :id", Account.class) + .setParameter("id", 1L) + .getSingleResult(); + assertNotNull(account1); + try { + Account account2 = entityManager.createQuery( + "select a from Account a where a.id = :id", Account.class) + .setParameter("id", 2L) + .getSingleResult(); + } + catch (NoResultException expected) { + } + }); + + doInJPA(this::entityManagerFactory, entityManager -> { + log.infof("Activate filter [%s]", "activeAccount"); + //tag::pc-filter-entity-example[] + entityManager + .unwrap(Session.class) + .enableFilter("activeAccount") + .setParameter("active", true); + + Account account = entityManager.find(Account.class, 2L); + + assertFalse( account.isActive() ); + //end::pc-filter-entity-example[] + }); + + doInJPA(this::entityManagerFactory, entityManager -> { + //tag::pc-no-filter-entity-query-example[] + List accounts = entityManager.createQuery( + "select a from Account a", Account.class) + .getResultList(); + + assertEquals(3, accounts.size()); + //end::pc-no-filter-entity-query-example[] + }); + + doInJPA(this::entityManagerFactory, entityManager -> { + log.infof("Activate filter [%s]", "activeAccount"); + //tag::pc-filter-entity-query-example[] + entityManager + .unwrap(Session.class) + .enableFilter("activeAccount") + .setParameter("active", true); + + List accounts = entityManager.createQuery( + "select a from Account a", Account.class) + .getResultList(); + + assertEquals(2, accounts.size()); + //end::pc-filter-entity-query-example[] + }); + + doInJPA(this::entityManagerFactory, entityManager -> { + //tag::pc-no-filter-collection-query-example[] + Client client = entityManager.find(Client.class, 1L); + + assertEquals(3, client.getAccounts().size()); + //end::pc-no-filter-collection-query-example[] + }); + + doInJPA(this::entityManagerFactory, entityManager -> { + log.infof("Activate filter [%s]", "activeAccount"); + + //tag::pc-filter-collection-query-example[] + entityManager + .unwrap(Session.class) + .enableFilter("activeAccount") + .setParameter("active", true); + + Client client = entityManager.find(Client.class, 1L); + + assertEquals(2, client.getAccounts().size()); + //end::pc-filter-collection-query-example[] + }); + } + + @Test + @JiraKey("HHH-16830") + public void testApplyToLoadByKey() { + doInJPA(this::entityManagerFactory, entityManager -> { + log.infof("Activate filter [%s]", "minimumAmount"); + //tag::pc-filter-entity-example[] + entityManager + .unwrap(Session.class) + .enableFilter("minimumAmount") + .setParameter("amount", 9000d); + + Account account = entityManager.find(Account.class, 1L); + + assertNull( account ); + //end::pc-filter-entity-example[] + }); + + doInJPA(this::entityManagerFactory, entityManager -> { + log.infof("Activate filter [%s]", "minimumAmount"); + //tag::pc-filter-entity-example[] + entityManager + .unwrap(Session.class) + .enableFilter("minimumAmount") + .setParameter("amount", 100d); + + Account account = entityManager.find(Account.class, 1L); + + assertNotNull( account ); + //end::pc-filter-entity-example[] + }); + + doInJPA(this::entityManagerFactory, entityManager -> { + log.infof("Activate filter [%s]", "minimumAmount"); + //tag::pc-filter-entity-query-example[] + entityManager + .unwrap(Session.class) + .enableFilter("minimumAmount") + .setParameter("amount", 500d); + + List accounts = entityManager.createQuery( + "select a from Account a", Account.class) + .getResultList(); + + assertEquals(1, accounts.size()); + //end::pc-filter-entity-query-example[] + }); + } + + @Test + @JiraKey("HHH-16830") + public void testApplyToLoadByKeyAssociationFiltering() { + doInJPA( this::entityManagerFactory, entityManager -> { + Account account = entityManager.find( Account.class, 2L ); + assertNotNull( account.getParentAccount() ); + } ); + } + + @Test + @JiraKey("HHH-16830") + public void testApplyToLoadByKeyAssociationFilteringLazyInitialization() { + doInJPA( this::entityManagerFactory, entityManager -> { + entityManager.unwrap( Session.class ) + .enableFilter( "accountType" ) + .setParameter( "type", "DEBIT" ); + + Account account = entityManager.find( Account.class, 2L ); + EntityNotFoundException exception = assertThrows( + EntityNotFoundException.class, + () -> Hibernate.initialize( account.getParentAccount() ) + ); + // Account with id 1 does not exist + assertTrue( exception.getMessage().endsWith( "#1]" ) ); + } ); + } + + @Test + @JiraKey("HHH-16830") + public void testApplyToLoadByKeyAssociationFilteringAccountLoadGraphInitializer() { + doInJPA( this::entityManagerFactory, entityManager -> { + entityManager.unwrap( Session.class ) + .enableFilter( "accountType" ) + .setParameter( "type", "DEBIT" ); + EntityGraph entityGraph = entityManager.createEntityGraph( Account.class ); + entityGraph.addAttributeNodes( "parentAccount" ); + + EntityFilterException exception = assertThrows( + EntityFilterException.class, + () -> entityManager.find( + Account.class, + 2L, + Map.of( AvailableHints.HINT_SPEC_LOAD_GRAPH, entityGraph ) + ) + ); + // Account with id 1 does not exist + assertTrue( exception.getRole().endsWith( "parentAccount" ) ); + assertEquals( 1L, exception.getIdentifier() ); + } ); + } + + @Test + @JiraKey("HHH-16830") + public void testApplyToLoadByKeyAssociationFilteringAccountJoinInitializer() { + doInJPA( this::entityManagerFactory, entityManager -> { + entityManager.unwrap( Session.class ) + .enableFilter( "accountType" ) + .setParameter( "type", "DEBIT" ); + + EntityFilterException exception = assertThrows( + EntityFilterException.class, + () -> entityManager.createQuery( + "select a from Account a left join fetch a.parentAccount where a.id = 2", + Account.class + ).getResultList() + ); + // Account with id 1 does not exist + assertTrue( exception.getRole().contains( "parentAccount" ) ); + assertEquals( 1L, exception.getIdentifier() ); + } ); + } + + @Test + @JiraKey("HHH-16830") + public void testApplyToLoadByKeyAssociationFilteringAccountSelectInitializer() { + doInJPA( this::entityManagerFactory, entityManager -> { + entityManager.unwrap( Session.class ) + .enableFilter( "accountType" ) + .setParameter( "type", "DEBIT" ); + + EntityFilterException exception = assertThrows( + EntityFilterException.class, + () -> entityManager.createQuery( + "select a from AccountEager a where a.id = 2", + AccountEager.class + ).getResultList() + ); + // Account with id 1 does not exist + assertTrue( exception.getRole().contains( "parentAccount" ) ); + assertEquals( 1L, exception.getIdentifier() ); + } ); + } + + @Test + @JiraKey("HHH-16830") + public void testApplyToLoadByKeyAssociationFilteringAccountNotFoundException() { + doInJPA(this::entityManagerFactory, entityManager -> { + entityManager.unwrap(Session.class) + .enableFilter("accountType") + .setParameter("type", "DEBIT"); + + EntityFilterException exception = assertThrows( + EntityFilterException.class, + () -> entityManager.createQuery( + "select a from AccountNotFoundException a where a.id = 2", + AccountNotFoundException.class + ).getSingleResult() + ); + // Account with id 1 does not exist + assertTrue( exception.getRole().contains( "parentAccount" ) ); + assertEquals( 1L, exception.getIdentifier() ); + }); + doInJPA(this::entityManagerFactory, entityManager -> { + entityManager.unwrap(Session.class) + .enableFilter("accountType") + .setParameter("type", "DEBIT"); + + EntityFilterException exception = assertThrows( + EntityFilterException.class, + () -> entityManager.createQuery( + "select a from AccountNotFoundException a left join fetch a.parentAccount where a.id = 2", + AccountNotFoundException.class + ).getSingleResult() + ); + // Account with id 1 does not exist + assertTrue( exception.getRole().contains( "parentAccount" ) ); + assertEquals( 1L, exception.getIdentifier() ); + }); + } + + @Test + @JiraKey("HHH-16830") + public void testApplyToLoadByKeyAssociationFilteringAccountNotFoundIgnore() { + doInJPA(this::entityManagerFactory, entityManager -> { + entityManager.unwrap(Session.class) + .enableFilter("accountType") + .setParameter("type", "DEBIT"); + + AccountNotFound account = entityManager.createQuery( + "select a from AccountNotFound a where a.id = 2", + AccountNotFound.class + ).getSingleResult(); + // No exception, since we use NotFoundAction.IGNORE + assertNull( account.getParentAccount() ); + }); + doInJPA(this::entityManagerFactory, entityManager -> { + entityManager.unwrap(Session.class) + .enableFilter("accountType") + .setParameter("type", "DEBIT"); + + AccountNotFound account = entityManager.createQuery( + "select a from AccountNotFound a left join fetch a.parentAccount where a.id = 2", + AccountNotFound.class + ).getSingleResult(); + // No exception, since we use NotFoundAction.IGNORE + assertNull( account.getParentAccount() ); + }); + } + + public enum AccountType { + DEBIT, + CREDIT + } + + //tag::pc-filter-Client-example[] + @Entity(name = "Client") + @Table(name = "client") + public static class Client { + + @Id + private Long id; + + private String name; + + private AccountType type; + + @OneToMany( + mappedBy = "client", + cascade = CascadeType.ALL + ) + @Filter( + name="activeAccount", + condition="active_status = :active" + ) + private List accounts = new ArrayList<>(); + + //Getters and setters omitted for brevity + //end::pc-filter-Client-example[] + public Long getId() { + return id; + } + + public Client setId(Long id) { + this.id = id; + return this; + } + + public String getName() { + return name; + } + + public Client setName(String name) { + this.name = name; + return this; + } + + public AccountType getType() { + return type; + } + + public Client setType(AccountType type) { + this.type = type; + return this; + } + + public List getAccounts() { + return accounts; + } + //tag::pc-filter-Client-example[] + + public void addAccount(Account account) { + account.setClient(this); + this.accounts.add(account); + } + } + //end::pc-filter-Client-example[] + + //tag::pc-filter-Account-example[] + @Entity(name = "Account") + @Table(name = "account") + @FilterDef( + name="activeAccount", + parameters = @ParamDef( + name="active", + type=Boolean.class + ) +) + @Filter( + name="activeAccount", + condition="active_status = :active" + ) + @FilterDef( + name="minimumAmount", + parameters = @ParamDef( + name="amount", + type=Double.class + ), + applyToLoadByKey = true + ) + @Filter( + name="minimumAmount", + condition="amount > :amount" + ) + @FilterDef( + name="accountType", + parameters = @ParamDef( + name="type", + type=String.class + ), + applyToLoadByKey = true + ) + @Filter( + name="accountType", + condition="account_type = :type" + ) + + public static class Account { + + @Id + private Long id; + + @ManyToOne(fetch = FetchType.LAZY) + private Client client; + + @Column(name = "account_type") + @Enumerated(EnumType.STRING) + private AccountType type; + + private Double amount; + + private Double rate; + + @Column(name = "active_status") + private boolean active; + + //Getters and setters omitted for brevity + //end::pc-filter-Account-example[] + + @ManyToOne(fetch = FetchType.LAZY) + private Account parentAccount; + + public Long getId() { + return id; + } + + public Account setId(Long id) { + this.id = id; + return this; + } + + public Client getClient() { + return client; + } + + public Account setClient(Client client) { + this.client = client; + return this; + } + + public AccountType getType() { + return type; + } + + public Account setType(AccountType type) { + this.type = type; + return this; + } + + public Double getAmount() { + return amount; + } + + public Account setAmount(Double amount) { + this.amount = amount; + return this; + } + + public Double getRate() { + return rate; + } + + public Account setRate(Double rate) { + this.rate = rate; + return this; + } + + public boolean isActive() { + return active; + } + + public Account setActive(boolean active) { + this.active = active; + return this; + } + + public Account getParentAccount() { + return parentAccount; + } + + public Account setParentAccount(Account parentAccount) { + this.parentAccount = parentAccount; + return this; + } + //tag::pc-filter-Account-example[] + } + //end::pc-filter-Account-example[] + + + @Entity(name = "AutoFilteredAccount") + @Table(name = "autofilteredaccount") + //tag::pc-filter-auto-enabled-Account-example[] + @FilterDef( + name="activeAccount", + parameters = @ParamDef( + name="active", + type=Boolean.class + ), + autoEnabled = true + ) + //end::pc-filter-auto-enabled-Account-example[] + @Filter( + name="activeAccount", + condition="active_status = :active" + ) + //tag::pc-filter-resolver-Account-example[] + @FilterDef( + name="activeAccountWithResolver", + parameters = @ParamDef( + name="active", + type=Boolean.class, + resolver = AccountIsActiveResolver.class + ), + autoEnabled = true + ) + //end::pc-filter-resolver-Account-example[] + public static class AutoFilteredAccount { + + @Id + private Long id; + + @Column(name = "active_status") + private boolean active; + + public Long getId() { + return id; + } + + public AutoFilteredAccount setId(Long id) { + this.id = id; + return this; + } + + public boolean isActive() { + return active; + } + + public AutoFilteredAccount setActive(boolean active) { + this.active = active; + return this; + } + } + + //tag::pc-filter-resolver-Account-example[] + + public static class AccountIsActiveResolver implements Supplier { + @Override + public Boolean get() { + return true; + } + } + //end::pc-filter-resolver-Account-example[] + + @Entity(name = "AccountEager") + @Table(name = "account_eager") + public static class AccountEager { + + @Id + private Long id; + + @ManyToOne + private Account parentAccount; + + public Long getId() { + return id; + } + + public AccountEager setId(Long id) { + this.id = id; + return this; + } + + public Account getParentAccount() { + return parentAccount; + } + + public AccountEager setParentAccount(Account parentAccount) { + this.parentAccount = parentAccount; + return this; + } + } + + @Entity(name = "AccountNotFound") + @Table(name = "account_not_found") + public static class AccountNotFound { + + @Id + private Long id; + + @ManyToOne + @NotFound(action = NotFoundAction.IGNORE) + private Account parentAccount; + + public Long getId() { + return id; + } + + public AccountNotFound setId(Long id) { + this.id = id; + return this; + } + + public Account getParentAccount() { + return parentAccount; + } + + public AccountNotFound setParentAccount(Account parentAccount) { + this.parentAccount = parentAccount; + return this; + } + } + + @Entity(name = "AccountNotFoundException") + @Table(name = "account_not_found_exception") + public static class AccountNotFoundException { + + @Id + private Long id; + + @ManyToOne + @NotFound + private Account parentAccount; + + public Long getId() { + return id; + } + + public AccountNotFoundException setId(Long id) { + this.id = id; + return this; + } + + public Account getParentAccount() { + return parentAccount; + } + + public AccountNotFoundException setParentAccount(Account parentAccount) { + this.parentAccount = parentAccount; + return this; + } + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/pc/Person.java b/hibernate-core/src/test/java/org/hibernate/orm/test/pc/Person.java index ab22735617..f5dcc98e51 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/pc/Person.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/pc/Person.java @@ -20,43 +20,43 @@ import jakarta.persistence.OneToMany; @Entity public class Person { - @Id - private Long id; + @Id + private Long id; - private String name; + private String name; - @OneToMany(mappedBy = "owner", cascade = CascadeType.ALL) - private List phones = new ArrayList<>(); + @OneToMany(mappedBy = "owner", cascade = CascadeType.ALL) + private List phones = new ArrayList<>(); - //Getters and setters are omitted for brevity + //Getters and setters are omitted for brevity //end::pc-cascade-domain-model-example[] - public Long getId() { - return id; - } + public Long getId() { + return id; + } - public void setId(Long id) { - this.id = id; - } + public void setId(Long id) { + this.id = id; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - public List getPhones() { - return phones; - } + public List getPhones() { + return phones; + } //tag::pc-cascade-domain-model-example[] - public void addPhone(Phone phone) { - this.phones.add(phone); - phone.setOwner(this); - } + public void addPhone(Phone phone) { + this.phones.add(phone); + phone.setOwner(this); + } } //end::pc-cascade-domain-model-example[] diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/pc/Phone.java b/hibernate-core/src/test/java/org/hibernate/orm/test/pc/Phone.java index 74347f94b5..c12b278f6a 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/pc/Phone.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/pc/Phone.java @@ -19,41 +19,41 @@ import jakarta.persistence.ManyToOne; @Entity public class Phone { - @Id - private Long id; + @Id + private Long id; - @Column(name = "`number`") - private String number; + @Column(name = "`number`") + private String number; - @ManyToOne(fetch = FetchType.LAZY) - private Person owner; + @ManyToOne(fetch = FetchType.LAZY) + private Person owner; - //Getters and setters are omitted for brevity + //Getters and setters are omitted for brevity //end::pc-cascade-domain-model-example[] - public Long getId() { - return id; - } + public Long getId() { + return id; + } - public void setId(Long id) { - this.id = id; - } + public void setId(Long id) { + this.id = id; + } - public String getNumber() { - return number; - } + public String getNumber() { + return number; + } - public void setNumber(String number) { - this.number = number; - } + public void setNumber(String number) { + this.number = number; + } - public Person getOwner() { - return owner; - } + public Person getOwner() { + return owner; + } - public void setOwner(Person owner) { - this.owner = owner; - } + public void setOwner(Person owner) { + this.owner = owner; + } //tag::pc-cascade-domain-model-example[] } //end::pc-cascade-domain-model-example[] diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/persister/entity/CustomSqlSchemaResolvingIdentityTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/persister/entity/CustomSqlSchemaResolvingIdentityTest.java index eb2bdd2f2b..6ff379889e 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/persister/entity/CustomSqlSchemaResolvingIdentityTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/persister/entity/CustomSqlSchemaResolvingIdentityTest.java @@ -46,7 +46,7 @@ public class CustomSqlSchemaResolvingIdentityTest { String className = CustomEntity.class.getName(); - final AbstractEntityPersister persister = (AbstractEntityPersister) scope.getSessionFactory().getMappingMetamodel().getEntityDescriptor(className); + final AbstractEntityPersister persister = (AbstractEntityPersister) scope.getSessionFactory().getMappingMetamodel().getEntityDescriptor(className); String insertQuery = ( (JdbcMutationOperation) persister.getInsertCoordinator().getStaticMutationOperationGroup().getSingleOperation() ).getSqlString(); String updateQuery = ( (JdbcMutationOperation) persister.getUpdateCoordinator().getStaticMutationOperationGroup().getSingleOperation() ).getSqlString(); String deleteQuery = ( (JdbcMutationOperation) persister.getDeleteCoordinator().getStaticMutationOperationGroup().getSingleOperation() ).getSqlString(); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/persister/entity/CustomSqlSchemaResolvingTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/persister/entity/CustomSqlSchemaResolvingTest.java index 8886c57cee..3d5c93c0f2 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/persister/entity/CustomSqlSchemaResolvingTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/persister/entity/CustomSqlSchemaResolvingTest.java @@ -41,7 +41,7 @@ public class CustomSqlSchemaResolvingTest { String className = CustomEntity.class.getName(); - final AbstractEntityPersister persister = (AbstractEntityPersister) scope.getSessionFactory().getMappingMetamodel().getEntityDescriptor(className); + final AbstractEntityPersister persister = (AbstractEntityPersister) scope.getSessionFactory().getMappingMetamodel().getEntityDescriptor(className); String insertQuery = ( (JdbcMutationOperation) persister.getInsertCoordinator().getStaticMutationOperationGroup().getSingleOperation() ).getSqlString(); String updateQuery = ( (JdbcMutationOperation) persister.getUpdateCoordinator().getStaticMutationOperationGroup().getSingleOperation() ).getSqlString(); String deleteQuery = ( (JdbcMutationOperation) persister.getDeleteCoordinator().getStaticMutationOperationGroup().getSingleOperation() ).getSqlString(); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/persister/entity/FormulaTemplateSchemaSubstitutionTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/persister/entity/FormulaTemplateSchemaSubstitutionTest.java index 0929176485..c28e934be7 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/persister/entity/FormulaTemplateSchemaSubstitutionTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/persister/entity/FormulaTemplateSchemaSubstitutionTest.java @@ -28,7 +28,7 @@ public class FormulaTemplateSchemaSubstitutionTest extends AbstractSchemaSubstit @Override void validate(String formula) { assertEquals( "Formula should not contain {} characters", - 4, formula.split( CUSTOM_SCHEMA + ".", -1 ).length - 1 + 4, formula.split( CUSTOM_SCHEMA + ".", -1 ).length - 1 ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/persister/entity/JoinFormulaImplicitJoinTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/persister/entity/JoinFormulaImplicitJoinTest.java index 9eb4faab0f..c763eb553d 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/persister/entity/JoinFormulaImplicitJoinTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/persister/entity/JoinFormulaImplicitJoinTest.java @@ -30,134 +30,134 @@ import org.junit.jupiter.api.Test; @JiraKey(value = "HHH-14223") @Jpa(annotatedClasses = { - JoinFormulaImplicitJoinTest.Person.class, JoinFormulaImplicitJoinTest.PersonVersion.class + JoinFormulaImplicitJoinTest.Person.class, JoinFormulaImplicitJoinTest.PersonVersion.class }, properties = { - @Setting(name = AvailableSettings.GLOBALLY_QUOTED_IDENTIFIERS, value = "true") + @Setting(name = AvailableSettings.GLOBALLY_QUOTED_IDENTIFIERS, value = "true") }) public class JoinFormulaImplicitJoinTest { - @BeforeEach - public void setUp(EntityManagerFactoryScope scope) { - scope.inTransaction(entityManager -> { - final Person person = new Person(); - entityManager.persist(person); + @BeforeEach + public void setUp(EntityManagerFactoryScope scope) { + scope.inTransaction(entityManager -> { + final Person person = new Person(); + entityManager.persist(person); - for (int i = 0; i < 3; i++) { - final PersonVersion personVersion = new PersonVersion(); - personVersion.setName("Name" + i); - personVersion.setVersion(i); - personVersion.setPerson(person); - entityManager.persist(personVersion); - } - }); - } + for (int i = 0; i < 3; i++) { + final PersonVersion personVersion = new PersonVersion(); + personVersion.setName("Name" + i); + personVersion.setVersion(i); + personVersion.setPerson(person); + entityManager.persist(personVersion); + } + }); + } - protected int entityCount() { - return 5; - } + protected int entityCount() { + return 5; + } - @Test - public void testImplicitJoin(EntityManagerFactoryScope scope) { - scope.inTransaction(entityManager -> { - entityManager.createQuery( - "SELECT person\n" + - "FROM Person AS person\n" + - " LEFT JOIN FETCH person.latestPersonVersion\n" + - "order by person.latestPersonVersion.id desc\n" - ); - }); - } + @Test + public void testImplicitJoin(EntityManagerFactoryScope scope) { + scope.inTransaction(entityManager -> { + entityManager.createQuery( + "SELECT person\n" + + "FROM Person AS person\n" + + " LEFT JOIN FETCH person.latestPersonVersion\n" + + "order by person.latestPersonVersion.id desc\n" + ); + }); + } - @Entity(name = "Person") - public static class Person { + @Entity(name = "Person") + public static class Person { - @Id - @GeneratedValue - private Long id; + @Id + @GeneratedValue + private Long id; - @OneToMany(mappedBy = "person", cascade = CascadeType.ALL, orphanRemoval = true) - private List personVersions; + @OneToMany(mappedBy = "person", cascade = CascadeType.ALL, orphanRemoval = true) + private List personVersions; - @ManyToOne - @JoinColumnsOrFormulas({ - @JoinColumnOrFormula( - formula = @JoinFormula( - value = "(SELECT person_version.id FROM person_version WHERE person_version.person_id = id ORDER BY person_version.version DESC LIMIT 1)", - referencedColumnName = "id") - ) - }) - private PersonVersion latestPersonVersion; + @ManyToOne + @JoinColumnsOrFormulas({ + @JoinColumnOrFormula( + formula = @JoinFormula( + value = "(SELECT person_version.id FROM person_version WHERE person_version.person_id = id ORDER BY person_version.version DESC LIMIT 1)", + referencedColumnName = "id") + ) + }) + private PersonVersion latestPersonVersion; - public Long getId() { - return id; - } + public Long getId() { + return id; + } - public void setId(Long id) { - this.id = id; - } + public void setId(Long id) { + this.id = id; + } - public List getPersonVersions() { - return personVersions; - } + public List getPersonVersions() { + return personVersions; + } - public void setPersonVersions(List personVersions) { - this.personVersions = personVersions; - } + public void setPersonVersions(List personVersions) { + this.personVersions = personVersions; + } - public PersonVersion getLatestPersonVersion() { - return latestPersonVersion; - } + public PersonVersion getLatestPersonVersion() { + return latestPersonVersion; + } - public void setLatestPersonVersion(PersonVersion latestPersonVersion) { - this.latestPersonVersion = latestPersonVersion; - } - } + public void setLatestPersonVersion(PersonVersion latestPersonVersion) { + this.latestPersonVersion = latestPersonVersion; + } + } - @Entity(name = "PersonVersion") - public static class PersonVersion { + @Entity(name = "PersonVersion") + public static class PersonVersion { - @Id - @GeneratedValue - private Long id; + @Id + @GeneratedValue + private Long id; - private String name; + private String name; - private Integer version; + private Integer version; - @ManyToOne(fetch = FetchType.LAZY) - @JoinColumn(name = "person_id") - private Person person; + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "person_id") + private Person person; - public Long getId() { - return id; - } + public Long getId() { + return id; + } - public void setId(Long id) { - this.id = id; - } + public void setId(Long id) { + this.id = id; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - public Integer getVersion() { - return version; - } + public Integer getVersion() { + return version; + } - public void setVersion(Integer version) { - this.version = version; - } + public void setVersion(Integer version) { + this.version = version; + } - public Person getPerson() { - return person; - } + public Person getPerson() { + return person; + } - public void setPerson(Person person) { - this.person = person; - } - } + public void setPerson(Person person) { + this.person = person; + } + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/persister/entity/JoinedInheritanceImplicitJoinTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/persister/entity/JoinedInheritanceImplicitJoinTest.java index 86d0173a28..1b63e39aac 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/persister/entity/JoinedInheritanceImplicitJoinTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/persister/entity/JoinedInheritanceImplicitJoinTest.java @@ -33,155 +33,155 @@ import java.util.Set; @JiraKey(value = "HHH-16979") @Jpa(annotatedClasses = { - JoinedInheritanceImplicitJoinTest.MasterEntity.class, - JoinedInheritanceImplicitJoinTest.ChildEntity.class, - JoinedInheritanceImplicitJoinTest.RelatedEntity.class + JoinedInheritanceImplicitJoinTest.MasterEntity.class, + JoinedInheritanceImplicitJoinTest.ChildEntity.class, + JoinedInheritanceImplicitJoinTest.RelatedEntity.class }, properties = { - @Setting(name = AvailableSettings.GLOBALLY_QUOTED_IDENTIFIERS, value = "true") + @Setting(name = AvailableSettings.GLOBALLY_QUOTED_IDENTIFIERS, value = "true") }) public class JoinedInheritanceImplicitJoinTest { - @BeforeEach - public void setup(EntityManagerFactoryScope scope) { - scope.inTransaction(entityManager -> { - final var childEntity = new ChildEntity(); - childEntity.setMasterField("masterValue001"); - childEntity.setChildField("childValue001"); + @BeforeEach + public void setup(EntityManagerFactoryScope scope) { + scope.inTransaction(entityManager -> { + final var childEntity = new ChildEntity(); + childEntity.setMasterField("masterValue001"); + childEntity.setChildField("childValue001"); - RelatedEntity relatedEntity = new RelatedEntity(); - relatedEntity.setRelatedField("relatedValue001"); - relatedEntity.setChildEntity(childEntity); + RelatedEntity relatedEntity = new RelatedEntity(); + relatedEntity.setRelatedField("relatedValue001"); + relatedEntity.setChildEntity(childEntity); - RelatedEntity relatedEntity2 = new RelatedEntity(); - relatedEntity2.setRelatedField("relatedValue002"); - relatedEntity2.setChildEntity(childEntity); + RelatedEntity relatedEntity2 = new RelatedEntity(); + relatedEntity2.setRelatedField("relatedValue002"); + relatedEntity2.setChildEntity(childEntity); - Set relatedEntityHashSet = Set.of(relatedEntity, relatedEntity2); + Set relatedEntityHashSet = Set.of(relatedEntity, relatedEntity2); - childEntity.setRelatedEntitySet(relatedEntityHashSet); + childEntity.setRelatedEntitySet(relatedEntityHashSet); - entityManager.persist(childEntity); - entityManager.persist(relatedEntity); - entityManager.persist(relatedEntity2); - }); - } + entityManager.persist(childEntity); + entityManager.persist(relatedEntity); + entityManager.persist(relatedEntity2); + }); + } - @Test - public void testImplicitJoinWithoutRelatedEntity(EntityManagerFactoryScope scope) { - scope.inTransaction(entityManager -> { - CriteriaBuilder cb = entityManager.getCriteriaBuilder(); - CriteriaQuery query = cb.createQuery(Tuple.class); - Root root = query.from(ChildEntity.class); + @Test + public void testImplicitJoinWithoutRelatedEntity(EntityManagerFactoryScope scope) { + scope.inTransaction(entityManager -> { + CriteriaBuilder cb = entityManager.getCriteriaBuilder(); + CriteriaQuery query = cb.createQuery(Tuple.class); + Root root = query.from(ChildEntity.class); - query.multiselect( - root.get("masterField"), - root.get("childField") - ); + query.multiselect( + root.get("masterField"), + root.get("childField") + ); - TypedQuery result = entityManager.createQuery(query); - List resultList = result.getResultList(); + TypedQuery result = entityManager.createQuery(query); + List resultList = result.getResultList(); - Assertions.assertFalse(resultList.isEmpty()); - }); - } + Assertions.assertFalse(resultList.isEmpty()); + }); + } - @Test - public void testImplicitJoinWithRelatedEntity(EntityManagerFactoryScope scope) { - scope.inTransaction(entityManager -> { - CriteriaBuilder cb = entityManager.getCriteriaBuilder(); - CriteriaQuery query = cb.createQuery(Tuple.class); - Root root = query.from(ChildEntity.class); - Join relatedEntityJoin = root.join("relatedEntitySet"); + @Test + public void testImplicitJoinWithRelatedEntity(EntityManagerFactoryScope scope) { + scope.inTransaction(entityManager -> { + CriteriaBuilder cb = entityManager.getCriteriaBuilder(); + CriteriaQuery query = cb.createQuery(Tuple.class); + Root root = query.from(ChildEntity.class); + Join relatedEntityJoin = root.join("relatedEntitySet"); - query.multiselect( - root.get("masterField"), - root.get("childField"), - relatedEntityJoin.get("relatedField") - ); + query.multiselect( + root.get("masterField"), + root.get("childField"), + relatedEntityJoin.get("relatedField") + ); - TypedQuery result = entityManager.createQuery(query); - List resultList = result.getResultList(); + TypedQuery result = entityManager.createQuery(query); + List resultList = result.getResultList(); - Assertions.assertFalse(resultList.isEmpty()); - }); - } + Assertions.assertFalse(resultList.isEmpty()); + }); + } - @Entity(name = "MasterEntity") - @Inheritance(strategy = InheritanceType.JOINED) - public static class MasterEntity { - @Id - @GeneratedValue - public Long id; + @Entity(name = "MasterEntity") + @Inheritance(strategy = InheritanceType.JOINED) + public static class MasterEntity { + @Id + @GeneratedValue + public Long id; - public String masterField; + public String masterField; - public Long getId() { - return id; - } + public Long getId() { + return id; + } - public String getMasterField() { - return masterField; - } + public String getMasterField() { + return masterField; + } - public void setMasterField(final String masterField) { - this.masterField = masterField; - } - } + public void setMasterField(final String masterField) { + this.masterField = masterField; + } + } - @Entity(name = "ChildEntity") - public static class ChildEntity extends MasterEntity { - private String childField; + @Entity(name = "ChildEntity") + public static class ChildEntity extends MasterEntity { + private String childField; - @OneToMany(mappedBy = "childEntity") - public Set relatedEntitySet; + @OneToMany(mappedBy = "childEntity") + public Set relatedEntitySet; - public String getChildField() { - return childField; - } + public String getChildField() { + return childField; + } - public void setChildField(final String childField) { - this.childField = childField; - } + public void setChildField(final String childField) { + this.childField = childField; + } - public Set getRelatedEntitySet() { - return relatedEntitySet; - } + public Set getRelatedEntitySet() { + return relatedEntitySet; + } - public void setRelatedEntitySet(final Set relatedEntitySet) { - this.relatedEntitySet = relatedEntitySet; - } - } + public void setRelatedEntitySet(final Set relatedEntitySet) { + this.relatedEntitySet = relatedEntitySet; + } + } - @Entity(name = "RelatedEntity") - public static class RelatedEntity { - @Id - @GeneratedValue - public Long id; + @Entity(name = "RelatedEntity") + public static class RelatedEntity { + @Id + @GeneratedValue + public Long id; - public String relatedField; + public String relatedField; - @ManyToOne - public ChildEntity childEntity; + @ManyToOne + public ChildEntity childEntity; - public Long getId() { - return id; - } + public Long getId() { + return id; + } - public String getRelatedField() { - return relatedField; - } + public String getRelatedField() { + return relatedField; + } - public void setRelatedField(final String relatedField) { - this.relatedField = relatedField; - } + public void setRelatedField(final String relatedField) { + this.relatedField = relatedField; + } - public ChildEntity getChildEntity() { - return childEntity; - } + public ChildEntity getChildEntity() { + return childEntity; + } - public void setChildEntity(final ChildEntity childEntity) { - this.childEntity = childEntity; - } - } + public void setChildEntity(final ChildEntity childEntity) { + this.childEntity = childEntity; + } + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/procedure/MySQLStoredProcedureTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/procedure/MySQLStoredProcedureTest.java index 718ee472ac..7e63e7592d 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/procedure/MySQLStoredProcedureTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/procedure/MySQLStoredProcedureTest.java @@ -131,7 +131,7 @@ public class MySQLStoredProcedureTest { person1.setNickName( "JD" ); person1.setAddress( "Earth" ); person1.setCreatedOn( Timestamp.from( LocalDateTime.of( 2000, 1, 1, 0, 0, 0 ) - .toInstant( ZoneOffset.UTC ) ) ); + .toInstant( ZoneOffset.UTC ) ) ); em.persist( person1 ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/procedure/Person.java b/hibernate-core/src/test/java/org/hibernate/orm/test/procedure/Person.java index c46064b50c..1aec10cbd6 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/procedure/Person.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/procedure/Person.java @@ -34,142 +34,142 @@ import static org.hibernate.jpa.HibernateHints.HINT_CALLABLE_FUNCTION; * @author Vlad Mihalcea */ @NamedStoredProcedureQuery( - name = "personAndPhonesFunction", - procedureName = "fn_person_and_phones", - resultSetMappings = "personWithPhonesMapping", - parameters = @StoredProcedureParameter(type = Long.class), - hints = @QueryHint(name = HINT_CALLABLE_FUNCTION, value = "true") + name = "personAndPhonesFunction", + procedureName = "fn_person_and_phones", + resultSetMappings = "personWithPhonesMapping", + parameters = @StoredProcedureParameter(type = Long.class), + hints = @QueryHint(name = HINT_CALLABLE_FUNCTION, value = "true") ) @NamedNativeQuery( - name = "fn_person_and_phones_hana", - query = "select \"pr.id\", \"pr.name\", \"pr.nickName\", \"pr.address\", \"pr.createdOn\", \"pr.version\", \"ph.id\", \"ph.person_id\", \"ph.phone_number\", \"ph.valid\" from fn_person_and_phones( ? )", - resultSetMapping = "person_with_phones_hana" + name = "fn_person_and_phones_hana", + query = "select \"pr.id\", \"pr.name\", \"pr.nickName\", \"pr.address\", \"pr.createdOn\", \"pr.version\", \"ph.id\", \"ph.person_id\", \"ph.phone_number\", \"ph.valid\" from fn_person_and_phones( ? )", + resultSetMapping = "person_with_phones_hana" ) @SqlResultSetMappings({ - @SqlResultSetMapping( - name = "personWithPhonesMapping", - entities = { - @EntityResult( - entityClass = Person.class, - fields = { - @FieldResult( name = "id", column = "pr.id" ), - @FieldResult( name = "name", column = "pr.name" ), - @FieldResult( name = "nickName", column = "pr.nickName" ), - @FieldResult( name = "address", column = "pr.address" ), - @FieldResult( name = "createdOn", column = "pr.createdOn" ), - @FieldResult( name = "version", column = "pr.version" ), - } - ), - @EntityResult( - entityClass = Phone.class, - fields = { - @FieldResult( name = "id", column = "ph.id" ), - @FieldResult( name = "person", column = "ph.person_id" ), - @FieldResult( name = "number", column = "ph.phone_number" ), - @FieldResult( name = "valid", column = "ph.valid" ) - } - ) - } - ), - @SqlResultSetMapping( - name = "person_with_phones_hana", - entities = { - @EntityResult( - entityClass = Person.class, - fields = { - @FieldResult( name = "id", column = "pr.id" ), - @FieldResult( name = "name", column = "pr.name" ), - @FieldResult( name = "nickName", column = "pr.nickName" ), - @FieldResult( name = "address", column = "pr.address" ), - @FieldResult( name = "createdOn", column = "pr.createdOn" ), - @FieldResult( name = "version", column = "pr.version" ), - } - ), - @EntityResult( - entityClass = Phone.class, - fields = { - @FieldResult( name = "id", column = "ph.id" ), - @FieldResult( name = "person", column = "ph.person_id" ), - @FieldResult( name = "number", column = "ph.phone_number" ), - @FieldResult( name = "valid", column = "ph.valid" ) - } - ) - } - ), + @SqlResultSetMapping( + name = "personWithPhonesMapping", + entities = { + @EntityResult( + entityClass = Person.class, + fields = { + @FieldResult( name = "id", column = "pr.id" ), + @FieldResult( name = "name", column = "pr.name" ), + @FieldResult( name = "nickName", column = "pr.nickName" ), + @FieldResult( name = "address", column = "pr.address" ), + @FieldResult( name = "createdOn", column = "pr.createdOn" ), + @FieldResult( name = "version", column = "pr.version" ), + } + ), + @EntityResult( + entityClass = Phone.class, + fields = { + @FieldResult( name = "id", column = "ph.id" ), + @FieldResult( name = "person", column = "ph.person_id" ), + @FieldResult( name = "number", column = "ph.phone_number" ), + @FieldResult( name = "valid", column = "ph.valid" ) + } + ) + } + ), + @SqlResultSetMapping( + name = "person_with_phones_hana", + entities = { + @EntityResult( + entityClass = Person.class, + fields = { + @FieldResult( name = "id", column = "pr.id" ), + @FieldResult( name = "name", column = "pr.name" ), + @FieldResult( name = "nickName", column = "pr.nickName" ), + @FieldResult( name = "address", column = "pr.address" ), + @FieldResult( name = "createdOn", column = "pr.createdOn" ), + @FieldResult( name = "version", column = "pr.version" ), + } + ), + @EntityResult( + entityClass = Phone.class, + fields = { + @FieldResult( name = "id", column = "ph.id" ), + @FieldResult( name = "person", column = "ph.person_id" ), + @FieldResult( name = "number", column = "ph.phone_number" ), + @FieldResult( name = "valid", column = "ph.valid" ) + } + ) + } + ), }) @Entity public class Person { - @Id - private Long id; + @Id + private Long id; - private String name; + private String name; - private String nickName; + private String nickName; - private String address; + private String address; - @Temporal(TemporalType.TIMESTAMP ) - private Date createdOn; + @Temporal(TemporalType.TIMESTAMP ) + private Date createdOn; - @OneToMany(mappedBy = "person", cascade = CascadeType.ALL) - @OrderColumn(name = "order_id") - private List phones = new ArrayList<>(); + @OneToMany(mappedBy = "person", cascade = CascadeType.ALL) + @OrderColumn(name = "order_id") + private List phones = new ArrayList<>(); - @Version - private int version; + @Version + private int version; - //Getters and setters are omitted for brevity + //Getters and setters are omitted for brevity //end::hql-examples-domain-model-example[] - public Person() {} + public Person() {} - public Person(Long id, String name) { - this.id = id; - this.name = name; - } + public Person(Long id, String name) { + this.id = id; + this.name = name; + } - public Long getId() { - return id; - } + public Long getId() { + return id; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public String getNickName() { - return nickName; - } + public String getNickName() { + return nickName; + } - public void setNickName(String nickName) { - this.nickName = nickName; - } + public void setNickName(String nickName) { + this.nickName = nickName; + } - public String getAddress() { - return address; - } + public String getAddress() { + return address; + } - public void setAddress(String address) { - this.address = address; - } + public void setAddress(String address) { + this.address = address; + } - public Date getCreatedOn() { - return createdOn; - } + public Date getCreatedOn() { + return createdOn; + } - public void setCreatedOn(Date createdOn) { - this.createdOn = createdOn; - } + public void setCreatedOn(Date createdOn) { + this.createdOn = createdOn; + } - public List getPhones() { - return phones; - } + public List getPhones() { + return phones; + } - public void addPhone(Phone phone) { - phones.add( phone ); - phone.setPerson( this ); - } + public void addPhone(Phone phone) { + phones.add( phone ); + phone.setPerson( this ); + } //tag::hql-examples-domain-model-example[] } //end::hql-examples-domain-model-example[] diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/procedure/Phone.java b/hibernate-core/src/test/java/org/hibernate/orm/test/procedure/Phone.java index b170537de6..8ba986fab2 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/procedure/Phone.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/procedure/Phone.java @@ -22,51 +22,51 @@ import jakarta.persistence.ManyToOne; @Entity public class Phone { - @Id - private Long id; + @Id + private Long id; - @ManyToOne(fetch = FetchType.LAZY) - private Person person; + @ManyToOne(fetch = FetchType.LAZY) + private Person person; - @Column(name = "phone_number") - private String number; + @Column(name = "phone_number") + private String number; - private boolean valid; + private boolean valid; - @ElementCollection - private List repairTimestamps = new ArrayList<>( ); + @ElementCollection + private List repairTimestamps = new ArrayList<>( ); - public Phone() {} + public Phone() {} - public Phone(String number) { - this.number = number; - } + public Phone(String number) { + this.number = number; + } - public Long getId() { - return id; - } + public Long getId() { + return id; + } - public void setId(Long id) { - this.id = id; - } + public void setId(Long id) { + this.id = id; + } - public String getNumber() { - return number; - } + public String getNumber() { + return number; + } - public Person getPerson() { - return person; - } + public Person getPerson() { + return person; + } - public void setPerson(Person person) { - this.person = person; - } + public void setPerson(Person person) { + this.person = person; + } - public boolean isValid() { - return valid; - } + public boolean isValid() { + return valid; + } - public void setValid(boolean valid) { - this.valid = valid; - } + public void setValid(boolean valid) { + this.valid = valid; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/procedure/PostgreSQLFunctionProcedureTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/procedure/PostgreSQLFunctionProcedureTest.java index 173f804325..ce12ca988f 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/procedure/PostgreSQLFunctionProcedureTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/procedure/PostgreSQLFunctionProcedureTest.java @@ -153,7 +153,7 @@ public class PostgreSQLFunctionProcedureTest extends BaseEntityManagerFunctional person1.setNickName( "JD" ); person1.setAddress( "Earth" ); person1.setCreatedOn( Timestamp.from( LocalDateTime.of( 2000, 1, 1, 0, 0, 0 ) - .toInstant( ZoneOffset.UTC ) ) ); + .toInstant( ZoneOffset.UTC ) ) ); entityManager.persist( person1 ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/procedure/PostgreSQLStoredProcedureTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/procedure/PostgreSQLStoredProcedureTest.java index 696125dd75..50672450f2 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/procedure/PostgreSQLStoredProcedureTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/procedure/PostgreSQLStoredProcedureTest.java @@ -434,7 +434,7 @@ public class PostgreSQLStoredProcedureTest { person1.setNickName( "JD" ); person1.setAddress( "Earth" ); person1.setCreatedOn( Timestamp.from( LocalDateTime.of( 2000, 1, 1, 0, 0, 0 ) - .toInstant( ZoneOffset.UTC ) ) ); + .toInstant( ZoneOffset.UTC ) ) ); entityManager.persist( person1 ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/procedure/SQLServerStoredProcedureForcePositionalTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/procedure/SQLServerStoredProcedureForcePositionalTest.java index 34195e99af..933c7d5fc9 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/procedure/SQLServerStoredProcedureForcePositionalTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/procedure/SQLServerStoredProcedureForcePositionalTest.java @@ -69,7 +69,7 @@ public class SQLServerStoredProcedureForcePositionalTest { person1.setNickName( "JD" ); person1.setAddress( "Earth" ); person1.setCreatedOn( Timestamp.from( LocalDateTime.of( 2000, 1, 1, 0, 0, 0 ) - .toInstant( ZoneOffset.UTC ) ) ); + .toInstant( ZoneOffset.UTC ) ) ); entityManager.persist( person1 ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/procedure/SQLServerStoredProcedureTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/procedure/SQLServerStoredProcedureTest.java index ef4cb25f0e..f280e063d6 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/procedure/SQLServerStoredProcedureTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/procedure/SQLServerStoredProcedureTest.java @@ -131,7 +131,7 @@ public class SQLServerStoredProcedureTest { person1.setNickName( "JD" ); person1.setAddress( "Earth" ); person1.setCreatedOn( Timestamp.from( LocalDateTime.of( 2000, 1, 1, 0, 0, 0 ) - .toInstant( ZoneOffset.UTC ) ) ); + .toInstant( ZoneOffset.UTC ) ) ); entityManager.persist( person1 ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/procedure/SybaseStoredProcedureTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/procedure/SybaseStoredProcedureTest.java index 260c74abbf..9297f7da31 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/procedure/SybaseStoredProcedureTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/procedure/SybaseStoredProcedureTest.java @@ -78,7 +78,7 @@ public class SybaseStoredProcedureTest { person1.setNickName( "JD" ); person1.setAddress( "Earth" ); person1.setCreatedOn( Timestamp.from( LocalDateTime.of( 2000, 1, 1, 0, 0, 0 ) - .toInstant( ZoneOffset.UTC ) ) ); + .toInstant( ZoneOffset.UTC ) ) ); entityManager.persist( person1 ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/procedure/Vote.java b/hibernate-core/src/test/java/org/hibernate/orm/test/procedure/Vote.java index d272c04103..6cb07a80f8 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/procedure/Vote.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/procedure/Vote.java @@ -21,26 +21,26 @@ import jakarta.persistence.Table; @Table(name = "vote") public class Vote { - @Id - private Long id; + @Id + private Long id; - @Column(name = "vote_choice") - @Convert( converter = YesNoConverter.class ) - private boolean voteChoice; + @Column(name = "vote_choice") + @Convert( converter = YesNoConverter.class ) + private boolean voteChoice; - public Long getId() { - return id; - } + public Long getId() { + return id; + } - public void setId(Long id) { - this.id = id; - } + public void setId(Long id) { + this.id = id; + } - public boolean isVoteChoice() { - return voteChoice; - } + public boolean isVoteChoice() { + return voteChoice; + } - public void setVoteChoice(boolean voteChoice) { - this.voteChoice = voteChoice; - } + public void setVoteChoice(boolean voteChoice) { + this.voteChoice = voteChoice; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/propertyref/basic/PropertyRefTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/propertyref/basic/PropertyRefTest.java index 34d1eb903d..09e2c6c82f 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/propertyref/basic/PropertyRefTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/propertyref/basic/PropertyRefTest.java @@ -269,7 +269,7 @@ public class PropertyRefTest { public void testForeignKeyCreation(SessionFactoryScope scope) { PersistentClass classMapping = scope.getMetadataImplementor().getEntityBinding( Account.class.getName() ); - Iterator foreignKeyIterator = classMapping.getTable().getForeignKeys().values().iterator(); + Iterator foreignKeyIterator = classMapping.getTable().getForeignKeys().values().iterator(); boolean found = false; while ( foreignKeyIterator.hasNext() ) { ForeignKey element = (ForeignKey) foreignKeyIterator.next(); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/proxy/HibernateUnproxyTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/proxy/HibernateUnproxyTest.java index 84e47c55a0..24b146e71f 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/proxy/HibernateUnproxyTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/proxy/HibernateUnproxyTest.java @@ -50,7 +50,7 @@ public class HibernateUnproxyTest { p.setChild( c ); scope.inTransaction( entityManager -> - entityManager.persist( p ) + entityManager.persist( p ) ); scope.inTransaction( entityManager -> { @@ -84,7 +84,7 @@ public class HibernateUnproxyTest { p.setChild( c ); scope.inTransaction( entityManager -> - entityManager.persist( p ) + entityManager.persist( p ) ); scope.inTransaction( entityManager -> { @@ -121,7 +121,7 @@ public class HibernateUnproxyTest { p.setChild( c ); scope.inTransaction( entityManager -> - entityManager.persist( p ) + entityManager.persist( p ) ); scope.inTransaction( entityManager -> { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/proxy/MissingSetterWithEnhancementTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/proxy/MissingSetterWithEnhancementTest.java index 8747ef66aa..2d66ab4731 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/proxy/MissingSetterWithEnhancementTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/proxy/MissingSetterWithEnhancementTest.java @@ -37,25 +37,25 @@ import static org.junit.jupiter.api.Assertions.fail; @JiraKey("HHH-14460") @BytecodeEnhanced public class MissingSetterWithEnhancementTest { - private ServiceRegistry serviceRegistry; + private ServiceRegistry serviceRegistry; - @BeforeEach - public void setUp() { + @BeforeEach + public void setUp() { final BootstrapServiceRegistryBuilder builder = new BootstrapServiceRegistryBuilder(); builder.applyClassLoader( getClass().getClassLoader() ); serviceRegistry = ServiceRegistryUtil.serviceRegistryBuilder( builder.build() ) .applySettings( Environment.getProperties() ) .build(); - } + } - @AfterEach - public void tearDown() { - if ( serviceRegistry != null ) { - ServiceRegistryBuilder.destroy( serviceRegistry ); - } - } + @AfterEach + public void tearDown() { + if ( serviceRegistry != null ) { + ServiceRegistryBuilder.destroy( serviceRegistry ); + } + } - @Test + @Test public void testEnhancedClassMissesSetterForProperty() { Configuration cfg = new Configuration(); cfg.addAnnotatedClass( EntityWithMissingSetter.class ); @@ -74,12 +74,12 @@ public class MissingSetterWithEnhancementTest { @Entity @Access(AccessType.PROPERTY) public static class EntityWithMissingSetter { - private Long id; - @Column + private Long id; + @Column @Access(AccessType.FIELD) private int someInt; - @Id + @Id public Long getId() { return id; } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/proxy/ProxyTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/proxy/ProxyTest.java index ce637290bf..37b717b0af 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/proxy/ProxyTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/proxy/ProxyTest.java @@ -483,9 +483,9 @@ public class ProxyTest extends BaseCoreFunctionalTestCase { s.remove( container ); // force a snapshot retrieval of the proxied container SessionImpl sImpl = ( SessionImpl ) s; - sImpl.getPersistenceContext().getDatabaseSnapshot( + sImpl.getPersistenceContext().getDatabaseSnapshot( lastContainerId, - sImpl.getFactory().getMappingMetamodel().getEntityDescriptor(Container.class.getName()) + sImpl.getFactory().getMappingMetamodel().getEntityDescriptor(Container.class.getName()) ); assertFalse( Hibernate.isInitialized( proxy ) ); t.commit(); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/query/ImplicitJoinInSubqueryTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/query/ImplicitJoinInSubqueryTest.java index 0e01774c0b..dd2cf3e12d 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/query/ImplicitJoinInSubqueryTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/query/ImplicitJoinInSubqueryTest.java @@ -22,66 +22,66 @@ import jakarta.persistence.ManyToOne; import static org.assertj.core.api.Assertions.assertThat; @DomainModel(annotatedClasses = { - ImplicitJoinInSubqueryTest.A.class, - ImplicitJoinInSubqueryTest.B.class, - ImplicitJoinInSubqueryTest.C.class + ImplicitJoinInSubqueryTest.A.class, + ImplicitJoinInSubqueryTest.B.class, + ImplicitJoinInSubqueryTest.C.class }) @SessionFactory(useCollectingStatementInspector = true) public class ImplicitJoinInSubqueryTest { - @Test - @JiraKey("HHH-16721") - public void testImplicitJoinInSubquery(SessionFactoryScope scope) { - SQLStatementInspector statementInspector = scope.getCollectingStatementInspector(); - statementInspector.clear(); - scope.inTransaction( - entityManager -> { - entityManager.createSelectionQuery( - "select 1 from A a where exists (select 1 from B b where a.b.c.id = 5)" - ).getResultList(); - assertThat( statementInspector.getSqlQueries().get( 0 ) ).contains( "b2_0.id=a1_0.b_id" ); - } - ); - } + @Test + @JiraKey("HHH-16721") + public void testImplicitJoinInSubquery(SessionFactoryScope scope) { + SQLStatementInspector statementInspector = scope.getCollectingStatementInspector(); + statementInspector.clear(); + scope.inTransaction( + entityManager -> { + entityManager.createSelectionQuery( + "select 1 from A a where exists (select 1 from B b where a.b.c.id = 5)" + ).getResultList(); + assertThat( statementInspector.getSqlQueries().get( 0 ) ).contains( "b2_0.id=a1_0.b_id" ); + } + ); + } - @Test - @JiraKey("HHH-17445") - public void testImplicitJoinInSubquery2(SessionFactoryScope scope) { - SQLStatementInspector statementInspector = scope.getCollectingStatementInspector(); - statementInspector.clear(); - scope.inTransaction( - entityManager -> { - entityManager.createSelectionQuery( - "select a from A a where exists (select 1 from B b where a.b.c is null)" - ).getResultList(); - assertThat( statementInspector.getSqlQueries().get( 0 ) ).contains( "b1_0.c_id is null" ); - assertThat( statementInspector.getSqlQueries().get( 0 ) ).doesNotContain( ".id=b1_0.c_id" ); - } - ); - } + @Test + @JiraKey("HHH-17445") + public void testImplicitJoinInSubquery2(SessionFactoryScope scope) { + SQLStatementInspector statementInspector = scope.getCollectingStatementInspector(); + statementInspector.clear(); + scope.inTransaction( + entityManager -> { + entityManager.createSelectionQuery( + "select a from A a where exists (select 1 from B b where a.b.c is null)" + ).getResultList(); + assertThat( statementInspector.getSqlQueries().get( 0 ) ).contains( "b1_0.c_id is null" ); + assertThat( statementInspector.getSqlQueries().get( 0 ) ).doesNotContain( ".id=b1_0.c_id" ); + } + ); + } - @Entity(name = "A") - public static class A { - @Id - @GeneratedValue - Long id; - @ManyToOne(fetch = FetchType.LAZY) - B b; - } + @Entity(name = "A") + public static class A { + @Id + @GeneratedValue + Long id; + @ManyToOne(fetch = FetchType.LAZY) + B b; + } - @Entity(name = "B") - public static class B { - @Id - @GeneratedValue - Long id; - @ManyToOne(fetch = FetchType.LAZY) - C c; - } + @Entity(name = "B") + public static class B { + @Id + @GeneratedValue + Long id; + @ManyToOne(fetch = FetchType.LAZY) + C c; + } - @Entity(name = "C") - public static class C { - @Id - @GeneratedValue - Long id; - } + @Entity(name = "C") + public static class C { + @Id + @GeneratedValue + Long id; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/query/TupleInListAlternativeTests.java b/hibernate-core/src/test/java/org/hibernate/orm/test/query/TupleInListAlternativeTests.java index f7040d71ba..dc4a14c70f 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/query/TupleInListAlternativeTests.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/query/TupleInListAlternativeTests.java @@ -75,8 +75,8 @@ public class TupleInListAlternativeTests { .setParameter( "subs", Arrays.asList( new EntityWithEmbeddedSubEntity.Sub( "ZH2", "HDS" ), - new EntityWithEmbeddedSubEntity.Sub( "GXZ", "HDS" ), - new EntityWithEmbeddedSubEntity.Sub( "KAZ", "TST" ) + new EntityWithEmbeddedSubEntity.Sub( "GXZ", "HDS" ), + new EntityWithEmbeddedSubEntity.Sub( "KAZ", "TST" ) ) ) .setParameter( "present", "Y" ).list(); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/query/count/CountTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/query/count/CountTest.java index 7c6635509d..f0c9d6e5c0 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/query/count/CountTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/query/count/CountTest.java @@ -29,130 +29,130 @@ import static org.junit.jupiter.api.Assertions.assertEquals; @DomainModel(annotatedClasses = {CountTest.Book.class, CountTest.Author.class, CountTest.Publisher.class}) public class CountTest { - @Test void testCount(SessionFactoryScope scope) { - scope.inTransaction(session -> session.createMutationQuery("delete Book").executeUpdate()); - scope.inTransaction(session -> { - session.persist(new Book("9781932394153", "Hibernate in Action")); - session.persist(new Book("9781617290459", "Java Persistence with Hibernate")); - }); - scope.inSession(session -> { - assertEquals(1L, - session.createSelectionQuery("from Book where title like 'Hibernate%'", Book.class) - .getResultCount()); - assertEquals(2L, - session.createSelectionQuery("from Book where title like '%Hibernate%'", Book.class) - .getResultCount()); - assertEquals(1L, - session.createSelectionQuery("select isbn, title from Book where title like 'Hibernate%'", String.class) - .getResultCount()); - assertEquals(1L, - session.createSelectionQuery("from Book where title like :title", Book.class) - .setParameter("title", "Hibernate%") - .getResultCount()); - assertEquals(0L, - session.createSelectionQuery("from Book where title like :title", Book.class) - .setParameter("title", "Jibernate%") - .getResultCount()); - assertEquals(2L, - session.createSelectionQuery("select title from Book where title like '%Hibernate' union select title from Book where title like 'Hibernate%'", String.class) - .getResultCount()); - assertEquals(2L, - session.createSelectionQuery("from Book left join fetch authors left join fetch publisher", Book.class) - .getResultCount()); - assertEquals(0L, - session.createSelectionQuery("from Book join fetch publisher", Book.class) - .getResultCount()); - }); - } + @Test void testCount(SessionFactoryScope scope) { + scope.inTransaction(session -> session.createMutationQuery("delete Book").executeUpdate()); + scope.inTransaction(session -> { + session.persist(new Book("9781932394153", "Hibernate in Action")); + session.persist(new Book("9781617290459", "Java Persistence with Hibernate")); + }); + scope.inSession(session -> { + assertEquals(1L, + session.createSelectionQuery("from Book where title like 'Hibernate%'", Book.class) + .getResultCount()); + assertEquals(2L, + session.createSelectionQuery("from Book where title like '%Hibernate%'", Book.class) + .getResultCount()); + assertEquals(1L, + session.createSelectionQuery("select isbn, title from Book where title like 'Hibernate%'", String.class) + .getResultCount()); + assertEquals(1L, + session.createSelectionQuery("from Book where title like :title", Book.class) + .setParameter("title", "Hibernate%") + .getResultCount()); + assertEquals(0L, + session.createSelectionQuery("from Book where title like :title", Book.class) + .setParameter("title", "Jibernate%") + .getResultCount()); + assertEquals(2L, + session.createSelectionQuery("select title from Book where title like '%Hibernate' union select title from Book where title like 'Hibernate%'", String.class) + .getResultCount()); + assertEquals(2L, + session.createSelectionQuery("from Book left join fetch authors left join fetch publisher", Book.class) + .getResultCount()); + assertEquals(0L, + session.createSelectionQuery("from Book join fetch publisher", Book.class) + .getResultCount()); + }); + } - @Test void testCountNative(SessionFactoryScope scope) { - scope.inTransaction(session -> session.createMutationQuery("delete Book").executeUpdate()); - scope.inTransaction(session -> { - session.persist(new Book("9781932394153", "Hibernate in Action")); - session.persist(new Book("9781617290459", "Java Persistence with Hibernate")); - }); - scope.inSession(session -> { - assertEquals(2L, - session.createNativeQuery("select title from books", String.class) - .setMaxResults(1) - .getResultCount()); - assertEquals(1L, - session.createNativeQuery("select title from books where title like :title", String.class) - .setParameter("title", "Hibernate%") - .getResultCount()); - assertEquals(2L, - session.createNativeQuery("select title from books", String.class) - .setMaxResults(1) - .getResultCount()); - }); - } + @Test void testCountNative(SessionFactoryScope scope) { + scope.inTransaction(session -> session.createMutationQuery("delete Book").executeUpdate()); + scope.inTransaction(session -> { + session.persist(new Book("9781932394153", "Hibernate in Action")); + session.persist(new Book("9781617290459", "Java Persistence with Hibernate")); + }); + scope.inSession(session -> { + assertEquals(2L, + session.createNativeQuery("select title from books", String.class) + .setMaxResults(1) + .getResultCount()); + assertEquals(1L, + session.createNativeQuery("select title from books where title like :title", String.class) + .setParameter("title", "Hibernate%") + .getResultCount()); + assertEquals(2L, + session.createNativeQuery("select title from books", String.class) + .setMaxResults(1) + .getResultCount()); + }); + } - @Test void testCountCriteria(SessionFactoryScope scope) { - scope.inTransaction(session -> session.createMutationQuery("delete Book").executeUpdate()); - scope.inTransaction(session -> { - session.persist(new Book("9781932394153", "Hibernate in Action")); - session.persist(new Book("9781617290459", "Java Persistence with Hibernate")); - }); - CriteriaBuilder builder = scope.getSessionFactory().getCriteriaBuilder(); - scope.inSession(session -> { - CriteriaQuery query1 = builder.createQuery(Book.class); - query1.where( builder.like( query1.from(Book.class).get("title"), "Hibernate%" ) ); - assertEquals(1L, - session.createQuery(query1) - .getResultCount()); - CriteriaQuery query2 = builder.createQuery(Book.class); - query2.from(Book.class); - assertEquals(2L, - session.createQuery(query2) - .setMaxResults(1) - .getResultCount()); - CriteriaQuery query3 = builder.createQuery(Book.class); - ParameterExpression parameter = builder.parameter(String.class); - query3.where( builder.like( query3.from(Book.class).get("title"), parameter ) ); - assertEquals(1L, - session.createQuery(query3) - .setParameter(parameter, "Hibernate%") - .getResultCount()); - CriteriaQuery query4 = builder.createQuery(Book.class); - Root book = query4.from(Book.class); - book.fetch("authors", JoinType.INNER); - assertEquals(0L, - session.createQuery(query4) - .getResultCount()); - }); - } + @Test void testCountCriteria(SessionFactoryScope scope) { + scope.inTransaction(session -> session.createMutationQuery("delete Book").executeUpdate()); + scope.inTransaction(session -> { + session.persist(new Book("9781932394153", "Hibernate in Action")); + session.persist(new Book("9781617290459", "Java Persistence with Hibernate")); + }); + CriteriaBuilder builder = scope.getSessionFactory().getCriteriaBuilder(); + scope.inSession(session -> { + CriteriaQuery query1 = builder.createQuery(Book.class); + query1.where( builder.like( query1.from(Book.class).get("title"), "Hibernate%" ) ); + assertEquals(1L, + session.createQuery(query1) + .getResultCount()); + CriteriaQuery query2 = builder.createQuery(Book.class); + query2.from(Book.class); + assertEquals(2L, + session.createQuery(query2) + .setMaxResults(1) + .getResultCount()); + CriteriaQuery query3 = builder.createQuery(Book.class); + ParameterExpression parameter = builder.parameter(String.class); + query3.where( builder.like( query3.from(Book.class).get("title"), parameter ) ); + assertEquals(1L, + session.createQuery(query3) + .setParameter(parameter, "Hibernate%") + .getResultCount()); + CriteriaQuery query4 = builder.createQuery(Book.class); + Root book = query4.from(Book.class); + book.fetch("authors", JoinType.INNER); + assertEquals(0L, + session.createQuery(query4) + .getResultCount()); + }); + } - @Entity(name="Book") - @Table(name = "books") - static class Book { - @Id String isbn; - String title; + @Entity(name="Book") + @Table(name = "books") + static class Book { + @Id String isbn; + String title; - @ManyToMany - List authors; + @ManyToMany + List authors; - @ManyToOne - Publisher publisher; + @ManyToOne + Publisher publisher; - Book(String isbn, String title) { - this.isbn = isbn; - this.title = title; - } + Book(String isbn, String title) { + this.isbn = isbn; + this.title = title; + } - Book() { - } - } + Book() { + } + } - @Entity(name="Author") - @Table(name = "authors") - static class Author { - @Id String ssn; - String name; - } + @Entity(name="Author") + @Table(name = "authors") + static class Author { + @Id String ssn; + String name; + } - @Entity(name="Publisher") - @Table(name = "pubs") - static class Publisher { - @Id String name; - } + @Entity(name="Publisher") + @Table(name = "pubs") + static class Publisher { + @Id String name; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/query/criteria/CriteriaGetJoinsTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/query/criteria/CriteriaGetJoinsTest.java index c9fd51da10..2a0e3eb429 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/query/criteria/CriteriaGetJoinsTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/query/criteria/CriteriaGetJoinsTest.java @@ -50,8 +50,8 @@ public class CriteriaGetJoinsTest { root.join( MyEntity.class, SqmJoinType.LEFT ); Set> joins = root.getJoins(); /* - SqmEntityJoin does not implement jakarta.persistence.criteria.Join, iterating through the - result would cause a ClassCastException + SqmEntityJoin does not implement jakarta.persistence.criteria.Join, iterating through the + result would cause a ClassCastException */ assertThat( joins.size() ).isEqualTo( 1 ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/query/criteria/CriteriaInheritanceJoinTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/query/criteria/CriteriaInheritanceJoinTest.java index 97a39b6006..9d4fd45e83 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/query/criteria/CriteriaInheritanceJoinTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/query/criteria/CriteriaInheritanceJoinTest.java @@ -79,8 +79,8 @@ public class CriteriaInheritanceJoinTest { final Root
addressRoot = cq.from( Address.class ); cq.select( addressRoot ).where( cb.equal( cb.treat( addressRoot, StreetAddress.class ) - .get( "street" ) - .get( "name" ), "Via Roma" ) + .get( "street" ) + .get( "name" ), "Via Roma" ) ); final Address result = session.createQuery( cq ).getSingleResult(); assertThat( result ).isInstanceOf( StreetAddress.class ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/query/criteria/CriteriaStringInlineLiteralTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/query/criteria/CriteriaStringInlineLiteralTest.java index e81f38edce..2cfcb52a09 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/query/criteria/CriteriaStringInlineLiteralTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/query/criteria/CriteriaStringInlineLiteralTest.java @@ -41,7 +41,7 @@ public class CriteriaStringInlineLiteralTest extends BaseEntityManagerFunctional CriteriaBuilder.Case sCase = cb.selectCase(); Expression caseSelect = sCase.when( cb.equal( animalRoot.get( "name" ), cb.literal( "kitty" ) ), cb.literal( "Cat" ) ) - .otherwise("escapez'moi" ); + .otherwise("escapez'moi" ); criteriaQuery.multiselect( caseSelect ); criteriaQuery.where( cb.equal( animalRoot.get( "name" ), "myFavoriteAnimal" ) ); entityManager.createQuery( criteriaQuery); // would throw exception for unescaped otherwise literal in HHH-13889 diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/query/criteria/CriteriaTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/query/criteria/CriteriaTest.java index 00204b00a6..750447c4ad 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/query/criteria/CriteriaTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/query/criteria/CriteriaTest.java @@ -53,7 +53,7 @@ public class CriteriaTest extends BaseEntityManagerFunctionalTestCase { return new Class[] { Person.class, Partner.class, - Phone.class, + Phone.class, Call.class, CreditCardPayment.class, WireTransferPayment.class, @@ -131,7 +131,7 @@ public class CriteriaTest extends BaseEntityManagerFunctionalTestCase { @Test public void test_criteria_typedquery_entity_example() { - doInJPA(this::entityManagerFactory, entityManager -> { + doInJPA(this::entityManagerFactory, entityManager -> { //tag::criteria-typedquery-entity-example[] CriteriaBuilder builder = entityManager.getCriteriaBuilder(); @@ -149,7 +149,7 @@ public class CriteriaTest extends BaseEntityManagerFunctionalTestCase { @Test public void test_criteria_typedquery_expression_example() { - doInJPA(this::entityManagerFactory, entityManager -> { + doInJPA(this::entityManagerFactory, entityManager -> { //tag::criteria-typedquery-expression-example[] CriteriaBuilder builder = entityManager.getCriteriaBuilder(); @@ -167,7 +167,7 @@ public class CriteriaTest extends BaseEntityManagerFunctionalTestCase { @Test public void test_criteria_typedquery_multiselect_explicit_array_example() { - doInJPA(this::entityManagerFactory, entityManager -> { + doInJPA(this::entityManagerFactory, entityManager -> { //tag::criteria-typedquery-multiselect-array-explicit-example[] CriteriaBuilder builder = entityManager.getCriteriaBuilder(); @@ -189,7 +189,7 @@ public class CriteriaTest extends BaseEntityManagerFunctionalTestCase { @Test public void test_criteria_typedquery_multiselect_implicit_array_example() { - doInJPA(this::entityManagerFactory, entityManager -> { + doInJPA(this::entityManagerFactory, entityManager -> { //tag::criteria-typedquery-multiselect-array-implicit-example[] CriteriaBuilder builder = entityManager.getCriteriaBuilder(); @@ -211,7 +211,7 @@ public class CriteriaTest extends BaseEntityManagerFunctionalTestCase { @Test public void test_criteria_typedquery_wrapper_example() { - doInJPA(this::entityManagerFactory, entityManager -> { + doInJPA(this::entityManagerFactory, entityManager -> { //tag::criteria-typedquery-wrapper-example[] CriteriaBuilder builder = entityManager.getCriteriaBuilder(); @@ -234,7 +234,7 @@ public class CriteriaTest extends BaseEntityManagerFunctionalTestCase { @Test public void test_criteria_tuple_example() { - doInJPA(this::entityManagerFactory, entityManager -> { + doInJPA(this::entityManagerFactory, entityManager -> { //tag::criteria-tuple-example[] CriteriaBuilder builder = entityManager.getCriteriaBuilder(); @@ -267,7 +267,7 @@ public class CriteriaTest extends BaseEntityManagerFunctionalTestCase { @Test public void test_criteria_from_root_example() { - doInJPA(this::entityManagerFactory, entityManager -> { + doInJPA(this::entityManagerFactory, entityManager -> { //tag::criteria-from-root-example[] CriteriaBuilder builder = entityManager.getCriteriaBuilder(); @@ -280,7 +280,7 @@ public class CriteriaTest extends BaseEntityManagerFunctionalTestCase { @Test public void test_criteria_from_multiple_root_example() { - doInJPA(this::entityManagerFactory, entityManager -> { + doInJPA(this::entityManagerFactory, entityManager -> { String address = "Earth"; String prefix = "J%"; //tag::criteria-from-multiple-root-example[] diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/query/criteria/InsertSelectTests.java b/hibernate-core/src/test/java/org/hibernate/orm/test/query/criteria/InsertSelectTests.java index 5ef4756848..4ff26db10f 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/query/criteria/InsertSelectTests.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/query/criteria/InsertSelectTests.java @@ -48,10 +48,10 @@ public class InsertSelectTests { @Entity( name = "AnEntity" ) @Table( name = "AnEntity" ) public static class AnEntity { - @Id + @Id @GeneratedValue - private Integer id; - @Basic + private Integer id; + @Basic private String name; private AnEntity() { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/query/criteria/PersonWrapper.java b/hibernate-core/src/test/java/org/hibernate/orm/test/query/criteria/PersonWrapper.java index 4855428c09..0eb34de3f0 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/query/criteria/PersonWrapper.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/query/criteria/PersonWrapper.java @@ -12,21 +12,21 @@ package org.hibernate.orm.test.query.criteria; //tag::criteria-typedquery-wrapper-example[] public class PersonWrapper { - private final Long id; + private final Long id; - private final String nickName; + private final String nickName; - public PersonWrapper(Long id, String nickName) { - this.id = id; - this.nickName = nickName; - } + public PersonWrapper(Long id, String nickName) { + this.id = id; + this.nickName = nickName; + } - public Long getId() { - return id; - } + public Long getId() { + return id; + } - public String getNickName() { - return nickName; - } + public String getNickName() { + return nickName; + } } //end::criteria-typedquery-wrapper-example[] diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/query/criteria/internal/expression/SearchedCaseExpressionTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/query/criteria/internal/expression/SearchedCaseExpressionTest.java index 797cd33d53..a5e2fb7055 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/query/criteria/internal/expression/SearchedCaseExpressionTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/query/criteria/internal/expression/SearchedCaseExpressionTest.java @@ -33,7 +33,7 @@ import static org.junit.Assert.assertEquals; */ public class SearchedCaseExpressionTest extends BaseCoreFunctionalTestCase { - @Test + @Test public void testCaseClause() { doInHibernate( this::sessionFactory, session -> { CriteriaBuilder cb = session.getCriteriaBuilder(); @@ -55,10 +55,10 @@ public class SearchedCaseExpressionTest extends BaseCoreFunctionalTestCase { Assert.assertNotNull(resultList); } ); - } + } - @Test - public void testEqualClause() { + @Test + public void testEqualClause() { doInHibernate( this::sessionFactory, session -> { CriteriaBuilder cb = session.getCriteriaBuilder(); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/query/criteria/internal/hhh13058/HHH13058Test.java b/hibernate-core/src/test/java/org/hibernate/orm/test/query/criteria/internal/hhh13058/HHH13058Test.java index 08ca3cfb47..6a3bb9f0d4 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/query/criteria/internal/hhh13058/HHH13058Test.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/query/criteria/internal/hhh13058/HHH13058Test.java @@ -120,8 +120,8 @@ public class HHH13058Test extends BaseEntityManagerFunctionalTestCase { subquery.select( subtask ) .where( builder.or( - patient.isNull(), - site.in( validSites ) + patient.isNull(), + site.in( validSites ) ) ) ) diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/query/hhh13670/HHH13670Test.java b/hibernate-core/src/test/java/org/hibernate/orm/test/query/hhh13670/HHH13670Test.java index 860a8e9bab..a6f8ddea6a 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/query/hhh13670/HHH13670Test.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/query/hhh13670/HHH13670Test.java @@ -31,186 +31,186 @@ import static org.junit.Assert.assertNull; @JiraKey(value = "HHH-13670") public class HHH13670Test extends BaseCoreFunctionalTestCase { - @Before - public void setUp() { - doInJPA(this::sessionFactory, em -> { - SubA a_1 = new SubA(1L); - SubA a_2 = new SubA(2L); - SubA a_3 = new SubA(3L); - SubA a_14 = em.getReference(SubA.class, 10L); - SubB b_4 = new SubB(4L, null); - SubB b_5 = new SubB(5L, a_3); - SubB b_6 = new SubB(6L, b_4); - SubB b_7 = new SubB(7L, a_14); + @Before + public void setUp() { + doInJPA(this::sessionFactory, em -> { + SubA a_1 = new SubA(1L); + SubA a_2 = new SubA(2L); + SubA a_3 = new SubA(3L); + SubA a_14 = em.getReference(SubA.class, 10L); + SubB b_4 = new SubB(4L, null); + SubB b_5 = new SubB(5L, a_3); + SubB b_6 = new SubB(6L, b_4); + SubB b_7 = new SubB(7L, a_14); - em.merge(a_1); - em.merge(a_2); - em.merge(a_3); - em.merge(b_4); - em.merge(b_5); - em.merge(b_6); - em.merge(b_7); - }); - } + em.merge(a_1); + em.merge(a_2); + em.merge(a_3); + em.merge(b_4); + em.merge(b_5); + em.merge(b_6); + em.merge(b_7); + }); + } - @Test - public void testDereferenceSuperClassAttributeInWithClause() { - doInJPA(this::sessionFactory, em -> { - em.createQuery("SELECT subB_0.id FROM SubB subB_0 LEFT JOIN subB_0.other subA_0 ON subA_0.id = subB_0.parent.id", Tuple.class).getResultList(); - }); - } + @Test + public void testDereferenceSuperClassAttributeInWithClause() { + doInJPA(this::sessionFactory, em -> { + em.createQuery("SELECT subB_0.id FROM SubB subB_0 LEFT JOIN subB_0.other subA_0 ON subA_0.id = subB_0.parent.id", Tuple.class).getResultList(); + }); + } - @Test - public void testRootTypeJoinWithGroupJoins() { - doInJPA(this::sessionFactory, em -> { - List resultList = em.createQuery("SELECT subB_0.id, subA_0.id, subB_0.id, subA_0.id FROM SubB subB_0 LEFT JOIN Super subA_0 ON subA_0.id = subB_0.parent.id ORDER BY subB_0.id ASC, subA_0.id ASC", Tuple.class) - .getResultList(); + @Test + public void testRootTypeJoinWithGroupJoins() { + doInJPA(this::sessionFactory, em -> { + List resultList = em.createQuery("SELECT subB_0.id, subA_0.id, subB_0.id, subA_0.id FROM SubB subB_0 LEFT JOIN Super subA_0 ON subA_0.id = subB_0.parent.id ORDER BY subB_0.id ASC, subA_0.id ASC", Tuple.class) + .getResultList(); - assertEquals("Rows omitted despite optional association should have rendered a left join", 4, resultList.size()); + assertEquals("Rows omitted despite optional association should have rendered a left join", 4, resultList.size()); - assertEquals((Long) 4L , resultList.get(0).get(0)); - assertEquals((Long) 5L , resultList.get(1).get(0)); - assertEquals((Long) 6L , resultList.get(2).get(0)); - assertEquals((Long) 7L , resultList.get(3).get(0)); + assertEquals((Long) 4L , resultList.get(0).get(0)); + assertEquals((Long) 5L , resultList.get(1).get(0)); + assertEquals((Long) 6L , resultList.get(2).get(0)); + assertEquals((Long) 7L , resultList.get(3).get(0)); - assertNull(resultList.get(0).get(1, Long.class)); - assertEquals((Long) 3L , resultList.get(1).get(1, Long.class)); - assertEquals((Long) 4L , resultList.get(2).get(1, Long.class)); - assertNull("Missing entry in foreign table should not be returned", resultList.get(3).get(1, Long.class)); - }); - } + assertNull(resultList.get(0).get(1, Long.class)); + assertEquals((Long) 3L , resultList.get(1).get(1, Long.class)); + assertEquals((Long) 4L , resultList.get(2).get(1, Long.class)); + assertNull("Missing entry in foreign table should not be returned", resultList.get(3).get(1, Long.class)); + }); + } - @Test - public void testSubTypeJoinWithTableGroupJoins() { - doInJPA(this::sessionFactory, em -> { - List resultList = em.createQuery("SELECT subB_0.id, subA_0.id, subB_0.id, subA_0.id FROM SubB subB_0 LEFT JOIN SubA subA_0 ON subA_0.id = subB_0.parent.id ORDER BY subB_0.id ASC, subA_0.id ASC", Tuple.class) - .getResultList(); + @Test + public void testSubTypeJoinWithTableGroupJoins() { + doInJPA(this::sessionFactory, em -> { + List resultList = em.createQuery("SELECT subB_0.id, subA_0.id, subB_0.id, subA_0.id FROM SubB subB_0 LEFT JOIN SubA subA_0 ON subA_0.id = subB_0.parent.id ORDER BY subB_0.id ASC, subA_0.id ASC", Tuple.class) + .getResultList(); - assertEquals("Rows omitted despite optional association should have rendered a left join", 4, resultList.size()); + assertEquals("Rows omitted despite optional association should have rendered a left join", 4, resultList.size()); - assertEquals((Long) 4L, resultList.get(0).get(0)); - assertEquals((Long) 5L, resultList.get(1).get(0)); - assertEquals((Long) 6L, resultList.get(2).get(0)); - assertEquals((Long) 7L, resultList.get(3).get(0)); + assertEquals((Long) 4L, resultList.get(0).get(0)); + assertEquals((Long) 5L, resultList.get(1).get(0)); + assertEquals((Long) 6L, resultList.get(2).get(0)); + assertEquals((Long) 7L, resultList.get(3).get(0)); - assertNull(resultList.get(0).get(1, Long.class)); - assertEquals((Long) 3L, resultList.get(1).get(1, Long.class)); - assertNull("Another subtype than queried for was returned", resultList.get(2).get(1)); - assertNull("Missing entry in foreign table should not be returned", resultList.get(3).get(1, Long.class)); - }); - } + assertNull(resultList.get(0).get(1, Long.class)); + assertEquals((Long) 3L, resultList.get(1).get(1, Long.class)); + assertNull("Another subtype than queried for was returned", resultList.get(2).get(1)); + assertNull("Missing entry in foreign table should not be returned", resultList.get(3).get(1, Long.class)); + }); + } - @Test - public void testSubTypePropertyReferencedFromEntityJoinInSyntheticSubquery() { - doInJPA(this::sessionFactory, em -> { - List resultList = em.createQuery( - "SELECT subB_0.id, subA_0.id, subB_0.id, subA_0.id FROM SubB subB_0 INNER JOIN SubA subA_0 ON 1=1 WHERE (EXISTS (SELECT 1 FROM subB_0.parent _synth_subquery_0 WHERE subA_0.id = _synth_subquery_0.id)) ORDER BY subB_0.id ASC, subA_0.id ASC", Tuple.class) - .getResultList(); + @Test + public void testSubTypePropertyReferencedFromEntityJoinInSyntheticSubquery() { + doInJPA(this::sessionFactory, em -> { + List resultList = em.createQuery( + "SELECT subB_0.id, subA_0.id, subB_0.id, subA_0.id FROM SubB subB_0 INNER JOIN SubA subA_0 ON 1=1 WHERE (EXISTS (SELECT 1 FROM subB_0.parent _synth_subquery_0 WHERE subA_0.id = _synth_subquery_0.id)) ORDER BY subB_0.id ASC, subA_0.id ASC", Tuple.class) + .getResultList(); - assertEquals(1, resultList.size()); - }); - } + assertEquals(1, resultList.size()); + }); + } - @Test - public void testSubTypePropertyReferencedFromEntityJoinInSyntheticSubquery2() { - doInJPA(this::sessionFactory, em -> { - List resultList = em.createQuery( - "SELECT subB_0.id, subA_0.id, subB_0.id, subA_0.id FROM SubB subB_0 INNER JOIN SubA subA_0 ON 1=1 WHERE (EXISTS (SELECT 1 FROM Super s WHERE subA_0.id = s.parent.id)) ORDER BY subB_0.id ASC, subA_0.id ASC", Tuple.class) - .getResultList(); + @Test + public void testSubTypePropertyReferencedFromEntityJoinInSyntheticSubquery2() { + doInJPA(this::sessionFactory, em -> { + List resultList = em.createQuery( + "SELECT subB_0.id, subA_0.id, subB_0.id, subA_0.id FROM SubB subB_0 INNER JOIN SubA subA_0 ON 1=1 WHERE (EXISTS (SELECT 1 FROM Super s WHERE subA_0.id = s.parent.id)) ORDER BY subB_0.id ASC, subA_0.id ASC", Tuple.class) + .getResultList(); - assertEquals(4, resultList.size()); - }); - } + assertEquals(4, resultList.size()); + }); + } - @Test - public void testSubTypePropertyReferencedFromEntityJoinInSyntheticSubquery3() { - doInJPA(this::sessionFactory, em -> { - List resultList = em.createQuery( - "SELECT subB_0.id, subA_0.id, subB_0.id, subA_0.id FROM SubB subB_0 INNER JOIN SubA subA_0 ON 1=1 WHERE (EXISTS (SELECT 1 FROM Super s WHERE s.id = subB_0.parent.id)) ORDER BY subB_0.id ASC, subA_0.id ASC", Tuple.class) - .getResultList(); + @Test + public void testSubTypePropertyReferencedFromEntityJoinInSyntheticSubquery3() { + doInJPA(this::sessionFactory, em -> { + List resultList = em.createQuery( + "SELECT subB_0.id, subA_0.id, subB_0.id, subA_0.id FROM SubB subB_0 INNER JOIN SubA subA_0 ON 1=1 WHERE (EXISTS (SELECT 1 FROM Super s WHERE s.id = subB_0.parent.id)) ORDER BY subB_0.id ASC, subA_0.id ASC", Tuple.class) + .getResultList(); - assertEquals(6, resultList.size()); - }); - } + assertEquals(6, resultList.size()); + }); + } - @Test - public void testSubTypePropertyReferencedFromEntityJoinInSyntheticSubquery4() { - doInJPA(this::sessionFactory, em -> { - List resultList = em.createQuery( - "SELECT subB_0.id, subA_0.id, subB_0.id, subA_0.id FROM SubB subB_0 INNER JOIN SubA subA_0 ON 1=1 WHERE (EXISTS (SELECT 1 FROM Super s WHERE s.id = subA_0.parent.id)) ORDER BY subB_0.id ASC, subA_0.id ASC", Tuple.class) - .getResultList(); + @Test + public void testSubTypePropertyReferencedFromEntityJoinInSyntheticSubquery4() { + doInJPA(this::sessionFactory, em -> { + List resultList = em.createQuery( + "SELECT subB_0.id, subA_0.id, subB_0.id, subA_0.id FROM SubB subB_0 INNER JOIN SubA subA_0 ON 1=1 WHERE (EXISTS (SELECT 1 FROM Super s WHERE s.id = subA_0.parent.id)) ORDER BY subB_0.id ASC, subA_0.id ASC", Tuple.class) + .getResultList(); - assertEquals(0, resultList.size()); - }); - } + assertEquals(0, resultList.size()); + }); + } - @Test - public void testSubTypePropertyReferencedFromWhereClause() { - doInJPA(this::sessionFactory, em -> { - List resultList = em.createQuery("SELECT subB_0.id FROM SubB subB_0 WHERE subB_0.parent.id IS NOT NULL", Tuple.class) - .getResultList(); - }); - } + @Test + public void testSubTypePropertyReferencedFromWhereClause() { + doInJPA(this::sessionFactory, em -> { + List resultList = em.createQuery("SELECT subB_0.id FROM SubB subB_0 WHERE subB_0.parent.id IS NOT NULL", Tuple.class) + .getResultList(); + }); + } - @Test - public void testSubTypePropertyReferencedFromGroupByClause() { - doInJPA(this::sessionFactory, em -> { - List resultList = em.createQuery("SELECT subB_0.id FROM SubB subB_0 GROUP BY subB_0.id , subB_0.parent.id", Tuple.class) - .getResultList(); - }); - } + @Test + public void testSubTypePropertyReferencedFromGroupByClause() { + doInJPA(this::sessionFactory, em -> { + List resultList = em.createQuery("SELECT subB_0.id FROM SubB subB_0 GROUP BY subB_0.id , subB_0.parent.id", Tuple.class) + .getResultList(); + }); + } - @Test - public void testSubTypePropertyReferencedFromOrderByClause() { - doInJPA(this::sessionFactory, em -> { - List resultList = em.createQuery("SELECT subB_0.id FROM SubB subB_0 ORDER BY subB_0.id , subB_0.parent.id", Tuple.class) - .getResultList(); - }); - } + @Test + public void testSubTypePropertyReferencedFromOrderByClause() { + doInJPA(this::sessionFactory, em -> { + List resultList = em.createQuery("SELECT subB_0.id FROM SubB subB_0 ORDER BY subB_0.id , subB_0.parent.id", Tuple.class) + .getResultList(); + }); + } - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { Super.class, SubA.class, SubB.class }; - } + @Override + protected Class[] getAnnotatedClasses() { + return new Class[] { Super.class, SubA.class, SubB.class }; + } - @Entity(name = "Super") - @Inheritance(strategy = InheritanceType.JOINED) - public static class Super { + @Entity(name = "Super") + @Inheritance(strategy = InheritanceType.JOINED) + public static class Super { - @Id - @Column - Long id; + @Id + @Column + Long id; - @JoinColumn(foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT)) - @ManyToOne(targetEntity = Super.class, fetch = FetchType.LAZY) - SubType parent; + @JoinColumn(foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT)) + @ManyToOne(targetEntity = Super.class, fetch = FetchType.LAZY) + SubType parent; - } + } - @Entity(name = "SubA") - public static class SubA extends Super { + @Entity(name = "SubA") + public static class SubA extends Super { - SubA() {} + SubA() {} - SubA(Long id) { - this.id = id; - } + SubA(Long id) { + this.id = id; + } - } + } - @Entity(name = "SubB") - public static class SubB extends Super { + @Entity(name = "SubB") + public static class SubB extends Super { - @ManyToOne(fetch = FetchType.LAZY) - Super other; + @ManyToOne(fetch = FetchType.LAZY) + Super other; - SubB() {} + SubB() {} - SubB(Long id, Super parent) { - this.id = id; - ((Super) this).parent = parent; - } + SubB(Long id, Super parent) { + this.id = id; + ((Super) this).parent = parent; + } - } + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/query/hhh14116/HHH14116Test.java b/hibernate-core/src/test/java/org/hibernate/orm/test/query/hhh14116/HHH14116Test.java index de51e39fd4..9e0e26607e 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/query/hhh14116/HHH14116Test.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/query/hhh14116/HHH14116Test.java @@ -39,10 +39,10 @@ public class HHH14116Test extends BaseCoreFunctionalTestCase { @Test public void testNoExceptionThrown() { doInJPA( this::sessionFactory, em -> { - em.createQuery( - "SELECT g FROM User u JOIN u.groups g JOIN FETCH g.permissions JOIN FETCH g.tenant where u.id = ?1", Group.class ) - .setParameter(1, 1L ) - .getResultList(); + em.createQuery( + "SELECT g FROM User u JOIN u.groups g JOIN FETCH g.permissions JOIN FETCH g.tenant where u.id = ?1", Group.class ) + .setParameter(1, 1L ) + .getResultList(); } ); } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/query/hhh18291/InvoiceBE.java b/hibernate-core/src/test/java/org/hibernate/orm/test/query/hhh18291/InvoiceBE.java index e1d392c56c..79e38c5f62 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/query/hhh18291/InvoiceBE.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/query/hhh18291/InvoiceBE.java @@ -15,20 +15,20 @@ import jakarta.persistence.Table; @Table(name = "invoice") public class InvoiceBE { - @Id +@Id // @GeneratedValue - private long id; +private long id; - @Column(name = "removed", nullable = false) - private boolean removed; +@Column(name = "removed", nullable = false) +private boolean removed; - public InvoiceBE setId(long id) { - this.id = id; - return this; - } - - public InvoiceBE setRemoved(boolean removed) { - this.removed = removed; - return this; - } +public InvoiceBE setId(long id) { + this.id = id; + return this; +} + +public InvoiceBE setRemoved(boolean removed) { + this.removed = removed; + return this; +} } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/query/hhh18291/PaidInvoiceBE.java b/hibernate-core/src/test/java/org/hibernate/orm/test/query/hhh18291/PaidInvoiceBE.java index 4ac685aaf6..dc91445945 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/query/hhh18291/PaidInvoiceBE.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/query/hhh18291/PaidInvoiceBE.java @@ -14,23 +14,23 @@ import jakarta.persistence.Table; @Entity @Table( - name = "paid_invoice") + name = "paid_invoice") public class PaidInvoiceBE { - @Id +@Id // @GeneratedValue - private long id; +private long id; - @ManyToOne(optional = false, fetch = FetchType.LAZY) - private InvoiceBE invoice; +@ManyToOne(optional = false, fetch = FetchType.LAZY) +private InvoiceBE invoice; - public PaidInvoiceBE setId(long id) { - this.id = id; - return this; - } - - public PaidInvoiceBE setInvoice(InvoiceBE invoice) { - this.invoice = invoice; - return this; - } +public PaidInvoiceBE setId(long id) { + this.id = id; + return this; +} + +public PaidInvoiceBE setInvoice(InvoiceBE invoice) { + this.invoice = invoice; + return this; +} } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/query/hql/AvgFunctionTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/query/hql/AvgFunctionTest.java index cb501c08b7..c11d46a257 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/query/hql/AvgFunctionTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/query/hql/AvgFunctionTest.java @@ -20,38 +20,38 @@ import static org.hamcrest.MatcherAssert.assertThat; @SessionFactory public class AvgFunctionTest { - @Test - public void test(SessionFactoryScope scope) { - scope.inTransaction( - session -> { - session.persist( new Score(0) ); - session.persist( new Score(1) ); - session.persist( new Score(2) ); - session.persist( new Score(3) ); - assertThat( - session.createQuery("select avg(doubleValue) from ScoreForAvg", Double.class) - .getSingleResult(), - is(1.5) - ); - assertThat( - session.createQuery("select avg(integerValue) from ScoreForAvg", Double.class) - .getSingleResult(), - is(1.5) - ); - } - ); - } + @Test + public void test(SessionFactoryScope scope) { + scope.inTransaction( + session -> { + session.persist( new Score(0) ); + session.persist( new Score(1) ); + session.persist( new Score(2) ); + session.persist( new Score(3) ); + assertThat( + session.createQuery("select avg(doubleValue) from ScoreForAvg", Double.class) + .getSingleResult(), + is(1.5) + ); + assertThat( + session.createQuery("select avg(integerValue) from ScoreForAvg", Double.class) + .getSingleResult(), + is(1.5) + ); + } + ); + } - @Entity(name="ScoreForAvg") - public static class Score { - public Score() {} - public Score(int value) { - this.doubleValue = value; - this.integerValue = value; - } - @Id - double doubleValue; - int integerValue; - } + @Entity(name="ScoreForAvg") + public static class Score { + public Score() {} + public Score(int value) { + this.doubleValue = value; + this.integerValue = value; + } + @Id + double doubleValue; + int integerValue; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/query/hql/EntityJoinTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/query/hql/EntityJoinTest.java index 9959fbe2c3..7fee4b74a5 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/query/hql/EntityJoinTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/query/hql/EntityJoinTest.java @@ -57,26 +57,26 @@ import static org.junit.Assert.fail; @SessionFactory public class EntityJoinTest { - @Test - public void testInnerEntityJoins(SessionFactoryScope scope) { - scope.inTransaction( - (session) -> { - // this should get financial records which have a lastUpdateBy user set - List result = session.createQuery( - "select r.id, c.name, u.id, u.username " + - "from FinancialRecord r " + - " inner join r.customer c " + - " inner join User u on r.lastUpdateBy = u.username", - Object[].class - ).list(); + @Test + public void testInnerEntityJoins(SessionFactoryScope scope) { + scope.inTransaction( + (session) -> { + // this should get financial records which have a lastUpdateBy user set + List result = session.createQuery( + "select r.id, c.name, u.id, u.username " + + "from FinancialRecord r " + + " inner join r.customer c " + + " inner join User u on r.lastUpdateBy = u.username", + Object[].class + ).list(); - assertThat( result.size(), is( 1 ) ); - Object[] steveAndAcme = result.get( 0 ); - assertThat( steveAndAcme[0], is( 1 ) ); - assertThat( steveAndAcme[1], is( "Acme" ) ); - assertThat( steveAndAcme[3], is( "steve" ) ); + assertThat( result.size(), is( 1 ) ); + Object[] steveAndAcme = result.get( 0 ); + assertThat( steveAndAcme[0], is( 1 ) ); + assertThat( steveAndAcme[1], is( "Acme" ) ); + assertThat( steveAndAcme[3], is( "steve" ) ); - // NOTE that this leads to not really valid SQL, although some databases might support it / + // NOTE that this leads to not really valid SQL, although some databases might support it / // result = session.createQuery( // "select r.id, r.customer.name, u.id, u.username " + // "from FinancialRecord r " + @@ -84,352 +84,352 @@ public class EntityJoinTest { // ).list(); // assertThat( result.size(), is( 1 ) ); - } - ); - } + } + ); + } - @Test - public void testLeftOuterEntityJoins(SessionFactoryScope scope) { - scope.inTransaction( - (session) -> { - // this should get all financial records even if their lastUpdateBy user is null - List result = session.createQuery( - "select r.id, u.id, u.username " + - "from FinancialRecord r " + - " left join User u on r.lastUpdateBy = u.username" + - " order by r.id", - Object[].class - ).list(); - assertThat( result.size(), is( 2 ) ); + @Test + public void testLeftOuterEntityJoins(SessionFactoryScope scope) { + scope.inTransaction( + (session) -> { + // this should get all financial records even if their lastUpdateBy user is null + List result = session.createQuery( + "select r.id, u.id, u.username " + + "from FinancialRecord r " + + " left join User u on r.lastUpdateBy = u.username" + + " order by r.id", + Object[].class + ).list(); + assertThat( result.size(), is( 2 ) ); - Object[] stevesRecord = result.get( 0 ); - assertThat( stevesRecord[0], is( 1 ) ); - assertThat( stevesRecord[2], is( "steve" ) ); + Object[] stevesRecord = result.get( 0 ); + assertThat( stevesRecord[0], is( 1 ) ); + assertThat( stevesRecord[2], is( "steve" ) ); - Object[] noOnesRecord = result.get( 1 ); - assertThat( noOnesRecord[0], is( 2 ) ); - assertNull( noOnesRecord[2] ); - } - ); - } + Object[] noOnesRecord = result.get( 1 ); + assertThat( noOnesRecord[0], is( 2 ) ); + assertNull( noOnesRecord[2] ); + } + ); + } - @Test - @JiraKey(value = "HHH-11337") - @SkipForDialect(dialectClass = SybaseDialect.class) - public void testLeftOuterEntityJoinsWithImplicitInnerJoinInSelectClause(SessionFactoryScope scope) { - scope.inTransaction( - (session) -> { - // this should get all financial records even if their lastUpdateBy user is null - List result = session.createQuery( - "select r.id, u.id, u.username, r.customer.name " + - "from FinancialRecord r " + - " left join User u on r.lastUpdateBy = u.username" + - " order by r.id", - Object[].class - ).list(); - assertThat( result.size(), is( 2 ) ); + @Test + @JiraKey(value = "HHH-11337") + @SkipForDialect(dialectClass = SybaseDialect.class) + public void testLeftOuterEntityJoinsWithImplicitInnerJoinInSelectClause(SessionFactoryScope scope) { + scope.inTransaction( + (session) -> { + // this should get all financial records even if their lastUpdateBy user is null + List result = session.createQuery( + "select r.id, u.id, u.username, r.customer.name " + + "from FinancialRecord r " + + " left join User u on r.lastUpdateBy = u.username" + + " order by r.id", + Object[].class + ).list(); + assertThat( result.size(), is( 2 ) ); - Object[] stevesRecord = result.get( 0 ); - assertThat( stevesRecord[0], is( 1 ) ); - assertThat( stevesRecord[2], is( "steve" ) ); + Object[] stevesRecord = result.get( 0 ); + assertThat( stevesRecord[0], is( 1 ) ); + assertThat( stevesRecord[2], is( "steve" ) ); - Object[] noOnesRecord = result.get( 1 ); - assertThat( noOnesRecord[0], is( 2 ) ); - assertNull( noOnesRecord[2] ); - } - ); - } + Object[] noOnesRecord = result.get( 1 ); + assertThat( noOnesRecord[0], is( 2 ) ); + assertNull( noOnesRecord[2] ); + } + ); + } - @Test - @JiraKey(value = "HHH-11340") - public void testJoinOnEntityJoinNode(SessionFactoryScope scope) { - scope.inTransaction( - (session) -> { - // this should get all financial records even if their lastUpdateBy user is null - List result = session.createQuery( - "select u.username, c.name " + - "from FinancialRecord r " + - " left join User u on r.lastUpdateBy = u.username " + - " left join u.customer c " + - " order by r.id", - Object[].class - ).list(); - assertThat( result.size(), is( 2 ) ); + @Test + @JiraKey(value = "HHH-11340") + public void testJoinOnEntityJoinNode(SessionFactoryScope scope) { + scope.inTransaction( + (session) -> { + // this should get all financial records even if their lastUpdateBy user is null + List result = session.createQuery( + "select u.username, c.name " + + "from FinancialRecord r " + + " left join User u on r.lastUpdateBy = u.username " + + " left join u.customer c " + + " order by r.id", + Object[].class + ).list(); + assertThat( result.size(), is( 2 ) ); - Object[] stevesRecord = result.get( 0 ); - assertThat( stevesRecord[0], is( "steve" ) ); - assertThat( stevesRecord[1], is( "Acme" ) ); + Object[] stevesRecord = result.get( 0 ); + assertThat( stevesRecord[0], is( "steve" ) ); + assertThat( stevesRecord[1], is( "Acme" ) ); - Object[] noOnesRecord = result.get( 1 ); - assertNull( noOnesRecord[0] ); - assertNull( noOnesRecord[1] ); - } - ); - } + Object[] noOnesRecord = result.get( 1 ); + assertNull( noOnesRecord[0] ); + assertNull( noOnesRecord[1] ); + } + ); + } - @Test - @JiraKey(value = "HHH-11538") - public void testNoImpliedJoinGeneratedForEqualityComparison(SessionFactoryScope scope) { - final String qry = "select r.id, cust.name " + - "from FinancialRecord r " + - " join Customer cust on r.customer = cust" + - " order by r.id"; + @Test + @JiraKey(value = "HHH-11538") + public void testNoImpliedJoinGeneratedForEqualityComparison(SessionFactoryScope scope) { + final String qry = "select r.id, cust.name " + + "from FinancialRecord r " + + " join Customer cust on r.customer = cust" + + " order by r.id"; - scope.inTransaction( - (session) -> { - final SessionFactoryImplementor factory = scope.getSessionFactory(); + scope.inTransaction( + (session) -> { + final SessionFactoryImplementor factory = scope.getSessionFactory(); - final EntityMappingType customerEntityDescriptor = factory.getRuntimeMetamodels() - .getMappingMetamodel() - .findEntityDescriptor( Customer.class ); + final EntityMappingType customerEntityDescriptor = factory.getRuntimeMetamodels() + .getMappingMetamodel() + .findEntityDescriptor( Customer.class ); - final QueryEngine queryEngine = factory.getQueryEngine(); + final QueryEngine queryEngine = factory.getQueryEngine(); - final SqmStatement sqm = - queryEngine.getHqlTranslator().translate( qry, null ); + final SqmStatement sqm = + queryEngine.getHqlTranslator().translate( qry, null ); - final SqmTranslation sqmTranslation = - queryEngine.getSqmTranslatorFactory() - .createSelectTranslator( - (SqmSelectStatement) sqm, - QueryOptions.NONE, - DomainParameterXref.EMPTY, - QueryParameterBindingsImpl.EMPTY, - new LoadQueryInfluencers( factory ), - factory, - true - ) - .translate(); + final SqmTranslation sqmTranslation = + queryEngine.getSqmTranslatorFactory() + .createSelectTranslator( + (SqmSelectStatement) sqm, + QueryOptions.NONE, + DomainParameterXref.EMPTY, + QueryParameterBindingsImpl.EMPTY, + new LoadQueryInfluencers( factory ), + factory, + true + ) + .translate(); - final SelectStatement sqlAst = sqmTranslation.getSqlAst(); - final List roots = sqlAst.getQuerySpec().getFromClause().getRoots(); - assertThat( roots.size(), is( 1 ) ); + final SelectStatement sqlAst = sqmTranslation.getSqlAst(); + final List roots = sqlAst.getQuerySpec().getFromClause().getRoots(); + assertThat( roots.size(), is( 1 ) ); - final TableGroup rootTableGroup = roots.get( 0 ); - assertThat( rootTableGroup.getTableGroupJoins().size(), is( 1 ) ); - assertThat( rootTableGroup.getNestedTableGroupJoins().size(), is( 1 ) ); + final TableGroup rootTableGroup = roots.get( 0 ); + assertThat( rootTableGroup.getTableGroupJoins().size(), is( 1 ) ); + assertThat( rootTableGroup.getNestedTableGroupJoins().size(), is( 1 ) ); - // An uninitialized lazy table group for the path in the on clause - final TableGroupJoin nestedTableGroupJoin = rootTableGroup.getNestedTableGroupJoins().get( 0 ); - assertThat( nestedTableGroupJoin.getJoinedGroup(), instanceOf( LazyTableGroup.class ) ); - assertThat( ((LazyTableGroup) nestedTableGroupJoin.getJoinedGroup()).getUnderlyingTableGroup(), is( CoreMatchers.nullValue() ) ); + // An uninitialized lazy table group for the path in the on clause + final TableGroupJoin nestedTableGroupJoin = rootTableGroup.getNestedTableGroupJoins().get( 0 ); + assertThat( nestedTableGroupJoin.getJoinedGroup(), instanceOf( LazyTableGroup.class ) ); + assertThat( ((LazyTableGroup) nestedTableGroupJoin.getJoinedGroup()).getUnderlyingTableGroup(), is( CoreMatchers.nullValue() ) ); - final TableGroupJoin tableGroupJoin = rootTableGroup.getTableGroupJoins().get( 0 ); - assertThat( tableGroupJoin.getJoinedGroup().getModelPart(), is( customerEntityDescriptor ) ); - } - ); - } + final TableGroupJoin tableGroupJoin = rootTableGroup.getTableGroupJoins().get( 0 ); + assertThat( tableGroupJoin.getJoinedGroup().getModelPart(), is( customerEntityDescriptor ) ); + } + ); + } - @Test - public void testRightOuterEntityJoins(SessionFactoryScope scope) { - scope.inTransaction( - (session) -> { - // this should get all users even if they have no financial records - List result = session.createQuery( - "select r.id, u.id, u.username " + - "from FinancialRecord r " + - " right join User u on r.lastUpdateBy = u.username" + - " order by u.id", - Object[].class - ).list(); + @Test + public void testRightOuterEntityJoins(SessionFactoryScope scope) { + scope.inTransaction( + (session) -> { + // this should get all users even if they have no financial records + List result = session.createQuery( + "select r.id, u.id, u.username " + + "from FinancialRecord r " + + " right join User u on r.lastUpdateBy = u.username" + + " order by u.id", + Object[].class + ).list(); - assertThat( result.size(), is( 2 ) ); + assertThat( result.size(), is( 2 ) ); - Object[] steveAndAcme = result.get( 0 ); - assertThat( steveAndAcme[ 0 ], is( 1 ) ); - assertThat( steveAndAcme[ 2 ], is( "steve" ) ); + Object[] steveAndAcme = result.get( 0 ); + assertThat( steveAndAcme[ 0 ], is( 1 ) ); + assertThat( steveAndAcme[ 2 ], is( "steve" ) ); - Object[] janeAndNull = result.get( 1 ); - assertNull( janeAndNull[ 0 ] ); - assertThat( janeAndNull[ 2 ], is( "jane" ) ); - } - ); - } + Object[] janeAndNull = result.get( 1 ); + assertNull( janeAndNull[ 0 ] ); + assertThat( janeAndNull[ 2 ], is( "jane" ) ); + } + ); + } - @Test - @Jira( "https://hibernate.atlassian.net/browse/HHH-16495" ) - public void testEntityJoinWithoutPredicate(SessionFactoryScope scope) { - scope.inTransaction( (session) -> { - try { - // this should throw an exception since it's not a cross join - final List result = session.createQuery( - "select r.id, u.id, u.username " + - "from FinancialRecord r join User u", - Object[].class - ).getResultList(); - fail( "Should've thrown SemanticException" ); - } - catch (Exception expected) { - assertThat( expected.getCause(), instanceOf( SemanticException.class ) ); - assertThat( expected.getMessage(), CoreMatchers.containsString( "Entity join did not specify a join condition" ) ); - } - } ); - } + @Test + @Jira( "https://hibernate.atlassian.net/browse/HHH-16495" ) + public void testEntityJoinWithoutPredicate(SessionFactoryScope scope) { + scope.inTransaction( (session) -> { + try { + // this should throw an exception since it's not a cross join + final List result = session.createQuery( + "select r.id, u.id, u.username " + + "from FinancialRecord r join User u", + Object[].class + ).getResultList(); + fail( "Should've thrown SemanticException" ); + } + catch (Exception expected) { + assertThat( expected.getCause(), instanceOf( SemanticException.class ) ); + assertThat( expected.getMessage(), CoreMatchers.containsString( "Entity join did not specify a join condition" ) ); + } + } ); + } - @Test - @Jira( "https://hibernate.atlassian.net/browse/HHH-16495" ) - public void testEntityCrossJoinWithoutPredicate(SessionFactoryScope scope) { - scope.inTransaction( - (session) -> { - final List result = session.createQuery( - "select r.id, u.id, u.username " + - "from FinancialRecord r cross join User u", - Object[].class - ).getResultList(); - assertThat( result.size(), is( 4 ) ); - } - ); - } + @Test + @Jira( "https://hibernate.atlassian.net/browse/HHH-16495" ) + public void testEntityCrossJoinWithoutPredicate(SessionFactoryScope scope) { + scope.inTransaction( + (session) -> { + final List result = session.createQuery( + "select r.id, u.id, u.username " + + "from FinancialRecord r cross join User u", + Object[].class + ).getResultList(); + assertThat( result.size(), is( 4 ) ); + } + ); + } - @BeforeEach - public void createTestData(SessionFactoryScope scope) { - scope.inTransaction( - (session) -> { - final Customer customer = new Customer( 1, "Acme" ); - session.persist( customer ); - session.persist( new User( 1, "steve", customer ) ); - session.persist( new User( 2, "jane" ) ); - session.persist( new FinancialRecord( 1, customer, "steve" ) ); - session.persist( new FinancialRecord( 2, customer, null ) ); - } - ); - } + @BeforeEach + public void createTestData(SessionFactoryScope scope) { + scope.inTransaction( + (session) -> { + final Customer customer = new Customer( 1, "Acme" ); + session.persist( customer ); + session.persist( new User( 1, "steve", customer ) ); + session.persist( new User( 2, "jane" ) ); + session.persist( new FinancialRecord( 1, customer, "steve" ) ); + session.persist( new FinancialRecord( 2, customer, null ) ); + } + ); + } - @AfterEach - public void dropTestData(SessionFactoryScope scope) { - scope.inTransaction( - (session) -> { - session.createQuery( "delete FinancialRecord" ).executeUpdate(); - session.createQuery( "delete User" ).executeUpdate(); - session.createQuery( "delete Customer" ).executeUpdate(); - } - ); - } + @AfterEach + public void dropTestData(SessionFactoryScope scope) { + scope.inTransaction( + (session) -> { + session.createQuery( "delete FinancialRecord" ).executeUpdate(); + session.createQuery( "delete User" ).executeUpdate(); + session.createQuery( "delete Customer" ).executeUpdate(); + } + ); + } - @Entity(name = "Customer") - @Table(name = "`a:customer`") - public static class Customer { - private Integer id; - private String name; + @Entity(name = "Customer") + @Table(name = "`a:customer`") + public static class Customer { + private Integer id; + private String name; - public Customer() { - } + public Customer() { + } - public Customer(Integer id, String name) { - this.id = id; - this.name = name; - } + public Customer(Integer id, String name) { + this.id = id; + this.name = name; + } - @Id - public Integer getId() { - return id; - } + @Id + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } - } + public void setName(String name) { + this.name = name; + } + } - @Entity(name = "FinancialRecord") - @Table(name = "`a:financial_record`") - public static class FinancialRecord { - private Integer id; - private Customer customer; - private String lastUpdateBy; + @Entity(name = "FinancialRecord") + @Table(name = "`a:financial_record`") + public static class FinancialRecord { + private Integer id; + private Customer customer; + private String lastUpdateBy; - public FinancialRecord() { - } + public FinancialRecord() { + } - public FinancialRecord(Integer id, Customer customer, String lastUpdateBy) { - this.id = id; - this.customer = customer; - this.lastUpdateBy = lastUpdateBy; - } + public FinancialRecord(Integer id, Customer customer, String lastUpdateBy) { + this.id = id; + this.customer = customer; + this.lastUpdateBy = lastUpdateBy; + } - @Id - public Integer getId() { - return id; - } + @Id + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - @ManyToOne - @JoinColumn - public Customer getCustomer() { - return customer; - } + @ManyToOne + @JoinColumn + public Customer getCustomer() { + return customer; + } - public void setCustomer(Customer customer) { - this.customer = customer; - } + public void setCustomer(Customer customer) { + this.customer = customer; + } - public String getLastUpdateBy() { - return lastUpdateBy; - } + public String getLastUpdateBy() { + return lastUpdateBy; + } - public void setLastUpdateBy(String lastUpdateBy) { - this.lastUpdateBy = lastUpdateBy; - } - } + public void setLastUpdateBy(String lastUpdateBy) { + this.lastUpdateBy = lastUpdateBy; + } + } - @Entity(name = "User") - @Table(name = "`a:user`") - public static class User { - private Integer id; - private String username; - private Customer customer; + @Entity(name = "User") + @Table(name = "`a:user`") + public static class User { + private Integer id; + private String username; + private Customer customer; - public User() { - } + public User() { + } - public User(Integer id, String username) { - this.id = id; - this.username = username; - } + public User(Integer id, String username) { + this.id = id; + this.username = username; + } - public User(Integer id, String username, Customer customer) { - this.id = id; - this.username = username; - this.customer = customer; - } + public User(Integer id, String username, Customer customer) { + this.id = id; + this.username = username; + this.customer = customer; + } - @Id - public Integer getId() { - return id; - } + @Id + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - @NaturalId - public String getUsername() { - return username; - } + @NaturalId + public String getUsername() { + return username; + } - public void setUsername(String username) { - this.username = username; - } + public void setUsername(String username) { + this.username = username; + } - @ManyToOne(fetch = FetchType.LAZY) - public Customer getCustomer() { - return customer; - } + @ManyToOne(fetch = FetchType.LAZY) + public Customer getCustomer() { + return customer; + } - public void setCustomer(Customer customer) { - this.customer = customer; - } - } + public void setCustomer(Customer customer) { + this.customer = customer; + } + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/query/hql/EnumComparisonTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/query/hql/EnumComparisonTest.java index 29e4800dfe..7c38434e65 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/query/hql/EnumComparisonTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/query/hql/EnumComparisonTest.java @@ -23,62 +23,62 @@ import static org.junit.jupiter.api.Assertions.fail; @SessionFactory @DomainModel(annotatedClasses = EnumComparisonTest.WithEnum.class) public class EnumComparisonTest { - @Test - void test(SessionFactoryScope scope) { - scope.inTransaction(session -> { - session.createMutationQuery("delete WithEnum").executeUpdate(); - session.persist(new WithEnum()); - assertEquals(1, - session.createSelectionQuery("from WithEnum where stringEnum > X").getResultList().size()); - assertEquals(1, - session.createSelectionQuery("from WithEnum where ordinalEnum > X").getResultList().size()); - assertEquals(1, - session.createSelectionQuery("from WithEnum where stringEnum > 'X'").getResultList().size()); - assertEquals(1, - session.createSelectionQuery("from WithEnum where ordinalEnum > 1").getResultList().size()); - try { - session.createSelectionQuery("from WithEnum where ordinalEnum > 'X'").getResultList(); - fail(); - } - catch (SemanticException se) { - } - try { - session.createSelectionQuery("from WithEnum where stringEnum > 1").getResultList(); - fail(); - } - catch (SemanticException se) { - } - session.createSelectionQuery("select max(ordinalEnum) from WithEnum").getSingleResult(); - session.createSelectionQuery("select max(stringEnum) from WithEnum").getSingleResult(); - }); - } + @Test + void test(SessionFactoryScope scope) { + scope.inTransaction(session -> { + session.createMutationQuery("delete WithEnum").executeUpdate(); + session.persist(new WithEnum()); + assertEquals(1, + session.createSelectionQuery("from WithEnum where stringEnum > X").getResultList().size()); + assertEquals(1, + session.createSelectionQuery("from WithEnum where ordinalEnum > X").getResultList().size()); + assertEquals(1, + session.createSelectionQuery("from WithEnum where stringEnum > 'X'").getResultList().size()); + assertEquals(1, + session.createSelectionQuery("from WithEnum where ordinalEnum > 1").getResultList().size()); + try { + session.createSelectionQuery("from WithEnum where ordinalEnum > 'X'").getResultList(); + fail(); + } + catch (SemanticException se) { + } + try { + session.createSelectionQuery("from WithEnum where stringEnum > 1").getResultList(); + fail(); + } + catch (SemanticException se) { + } + session.createSelectionQuery("select max(ordinalEnum) from WithEnum").getSingleResult(); + session.createSelectionQuery("select max(stringEnum) from WithEnum").getSingleResult(); + }); + } - @Test - void testCase(SessionFactoryScope scope) { - scope.inTransaction(session -> { - session.createMutationQuery("delete WithEnum").executeUpdate(); - session.persist(new WithEnum()); - assertEquals(2, - session.createSelectionQuery("select case stringEnum when X then 1 when Y then 2 when Z then 3 else -1 end from WithEnum", Integer.class) - .getSingleResult()); - assertEquals(3, - session.createSelectionQuery("select case ordinalEnum when X then 1 when Y then 2 when Z then 3 else -1 end from WithEnum", Integer.class) - .getSingleResult()); - }); - } + @Test + void testCase(SessionFactoryScope scope) { + scope.inTransaction(session -> { + session.createMutationQuery("delete WithEnum").executeUpdate(); + session.persist(new WithEnum()); + assertEquals(2, + session.createSelectionQuery("select case stringEnum when X then 1 when Y then 2 when Z then 3 else -1 end from WithEnum", Integer.class) + .getSingleResult()); + assertEquals(3, + session.createSelectionQuery("select case ordinalEnum when X then 1 when Y then 2 when Z then 3 else -1 end from WithEnum", Integer.class) + .getSingleResult()); + }); + } - enum Enum { X, Y, Z } + enum Enum { X, Y, Z } - @Entity(name = "WithEnum") - static class WithEnum { - @Id - @GeneratedValue - long id; + @Entity(name = "WithEnum") + static class WithEnum { + @Id + @GeneratedValue + long id; - @Enumerated(EnumType.STRING) - Enum stringEnum = Enum.Y; + @Enumerated(EnumType.STRING) + Enum stringEnum = Enum.Y; - @Enumerated(EnumType.ORDINAL) - Enum ordinalEnum = Enum.Z; - } + @Enumerated(EnumType.ORDINAL) + Enum ordinalEnum = Enum.Z; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/query/hql/FunctionTests.java b/hibernate-core/src/test/java/org/hibernate/orm/test/query/hql/FunctionTests.java index 5ec7be2b9e..30cb8beda9 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/query/hql/FunctionTests.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/query/hql/FunctionTests.java @@ -1666,30 +1666,30 @@ public class FunctionTests { session.createQuery("select local date + 1 week", LocalDate.class) .getSingleResult() ); assertEquals( LocalDate.now().plus(1, ChronoUnit.MONTHS), - session.createQuery("select local date + 1 month", LocalDate.class) - .getSingleResult() ); + session.createQuery("select local date + 1 month", LocalDate.class) + .getSingleResult() ); assertEquals( LocalDate.now().plus(1, ChronoUnit.YEARS), - session.createQuery("select local date + 1 year", LocalDate.class) - .getSingleResult() ); + session.createQuery("select local date + 1 year", LocalDate.class) + .getSingleResult() ); assertEquals( LocalDate.now().plus(3, ChronoUnit.MONTHS), - session.createQuery("select local date + 1 quarter", LocalDate.class) - .getSingleResult() ); + session.createQuery("select local date + 1 quarter", LocalDate.class) + .getSingleResult() ); // Some explicit 'special' cases: assertEquals( LocalDate.of(2024, 02, 29), - session.createQuery("select {2024-01-31} + 1 month", LocalDate.class) - .getSingleResult() ); + session.createQuery("select {2024-01-31} + 1 month", LocalDate.class) + .getSingleResult() ); assertEquals( LocalDate.of(2025, 02, 28), - session.createQuery("select {2024-02-29} + 1 year", LocalDate.class) - .getSingleResult() ); + session.createQuery("select {2024-02-29} + 1 year", LocalDate.class) + .getSingleResult() ); assertEquals( LocalDate.of(2028, 02, 29), - session.createQuery("select {2024-02-29} + 4 year", LocalDate.class) - .getSingleResult() ); + session.createQuery("select {2024-02-29} + 4 year", LocalDate.class) + .getSingleResult() ); assertEquals( LocalDate.of(2025, 03, 29), - session.createQuery("select {2024-02-29} + 13 month", LocalDate.class) - .getSingleResult() ); + session.createQuery("select {2024-02-29} + 13 month", LocalDate.class) + .getSingleResult() ); assertEquals( LocalDate.of(2024, 02, 29), - session.createQuery("select {2023-11-30} + 1 quarter", LocalDate.class) - .getSingleResult() ); + session.createQuery("select {2023-11-30} + 1 quarter", LocalDate.class) + .getSingleResult() ); session.createQuery("select e.theTimestamp - 21 second from EntityOfBasics e", java.util.Date.class) .getSingleResult(); @@ -1714,7 +1714,7 @@ public class FunctionTests { @SkipForDialect( dialectClass = TiDBDialect.class, reason = "Bug in the TiDB timestampadd function (https://github.com/pingcap/tidb/issues/41052)") @SkipForDialect( dialectClass = AltibaseDialect.class, - reason = "exceeds timestampadd limit in Altibase") + reason = "exceeds timestampadd limit in Altibase") public void testDurationArithmeticOverflowing(SessionFactoryScope scope) { scope.inTransaction( session -> { @@ -2488,7 +2488,7 @@ public class FunctionTests { s.createQuery("select coalesce(:word, null)", String.class) .setParameter("word", "hello") .getSingleResultOrNull()); - }); + }); } @Test diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/query/hql/ImplicitJoinInOnClauseTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/query/hql/ImplicitJoinInOnClauseTest.java index 9f4aec1cfa..64b54e019b 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/query/hql/ImplicitJoinInOnClauseTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/query/hql/ImplicitJoinInOnClauseTest.java @@ -22,81 +22,81 @@ import jakarta.persistence.ManyToOne; * @author Christian Beikov */ @DomainModel( annotatedClasses = { - ImplicitJoinInOnClauseTest.RootEntity.class, - ImplicitJoinInOnClauseTest.FirstLevelReferencedEntity.class, - ImplicitJoinInOnClauseTest.SecondLevelReferencedEntityA.class, - ImplicitJoinInOnClauseTest.SecondLevelReferencedEntityB.class, - ImplicitJoinInOnClauseTest.ThirdLevelReferencedEntity.class, - ImplicitJoinInOnClauseTest.UnrelatedEntity.class + ImplicitJoinInOnClauseTest.RootEntity.class, + ImplicitJoinInOnClauseTest.FirstLevelReferencedEntity.class, + ImplicitJoinInOnClauseTest.SecondLevelReferencedEntityA.class, + ImplicitJoinInOnClauseTest.SecondLevelReferencedEntityB.class, + ImplicitJoinInOnClauseTest.ThirdLevelReferencedEntity.class, + ImplicitJoinInOnClauseTest.UnrelatedEntity.class }) @SessionFactory @JiraKey( "HHH-17033" ) public class ImplicitJoinInOnClauseTest { - @Test - public void testImplicitJoinInEntityJoinPredicate(SessionFactoryScope scope) { - scope.inTransaction( - (session) -> { - // this should get financial records which have a lastUpdateBy user set - List result = session.createQuery( - "select r.id, flr.id, ur1.id, ur2.id, ur3.id from RootEntity r " + - "inner join r.firstLevelReference as flr " + - "left join UnrelatedEntity ur1 on ur1.id = flr.secondLevelReferenceA.id " + - "left join UnrelatedEntity ur2 on ur2.id = flr.secondLevelReferenceB.id " + - "left join UnrelatedEntity ur3 on ur3.id = flr.secondLevelReferenceB.thirdLevelReference.id", - Object[].class - ).list(); - } - ); - } + @Test + public void testImplicitJoinInEntityJoinPredicate(SessionFactoryScope scope) { + scope.inTransaction( + (session) -> { + // this should get financial records which have a lastUpdateBy user set + List result = session.createQuery( + "select r.id, flr.id, ur1.id, ur2.id, ur3.id from RootEntity r " + + "inner join r.firstLevelReference as flr " + + "left join UnrelatedEntity ur1 on ur1.id = flr.secondLevelReferenceA.id " + + "left join UnrelatedEntity ur2 on ur2.id = flr.secondLevelReferenceB.id " + + "left join UnrelatedEntity ur3 on ur3.id = flr.secondLevelReferenceB.thirdLevelReference.id", + Object[].class + ).list(); + } + ); + } - @Entity(name = "RootEntity") - public static class RootEntity { - @Id - private Long id; - @ManyToOne - private FirstLevelReferencedEntity firstLevelReference; + @Entity(name = "RootEntity") + public static class RootEntity { + @Id + private Long id; + @ManyToOne + private FirstLevelReferencedEntity firstLevelReference; - } + } - @Entity(name = "FirstLevelReferencedEntity") - public static class FirstLevelReferencedEntity { - @Id - private Long id; - @ManyToOne - private SecondLevelReferencedEntityA secondLevelReferenceA; - @ManyToOne - private SecondLevelReferencedEntityB secondLevelReferenceB; + @Entity(name = "FirstLevelReferencedEntity") + public static class FirstLevelReferencedEntity { + @Id + private Long id; + @ManyToOne + private SecondLevelReferencedEntityA secondLevelReferenceA; + @ManyToOne + private SecondLevelReferencedEntityB secondLevelReferenceB; - } - @Entity(name = "SecondLevelReferencedEntityA") - public static class SecondLevelReferencedEntityA { - @Id - private Long id; - private String name; - } + } + @Entity(name = "SecondLevelReferencedEntityA") + public static class SecondLevelReferencedEntityA { + @Id + private Long id; + private String name; + } - @Entity(name = "SecondLevelReferencedEntityB") - public static class SecondLevelReferencedEntityB { - @Id - private Long id; - @ManyToOne - private ThirdLevelReferencedEntity thirdLevelReference; - } + @Entity(name = "SecondLevelReferencedEntityB") + public static class SecondLevelReferencedEntityB { + @Id + private Long id; + @ManyToOne + private ThirdLevelReferencedEntity thirdLevelReference; + } - @Entity(name = "ThirdLevelReferencedEntity") - public static class ThirdLevelReferencedEntity { - @Id - private Long id; - private String name; + @Entity(name = "ThirdLevelReferencedEntity") + public static class ThirdLevelReferencedEntity { + @Id + private Long id; + private String name; - } - @Entity(name = "UnrelatedEntity") - public static class UnrelatedEntity { - @Id - private Long id; - private String name; - } + } + @Entity(name = "UnrelatedEntity") + public static class UnrelatedEntity { + @Id + private Long id; + private String name; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/query/hql/IntegerDivisionTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/query/hql/IntegerDivisionTest.java index 77d51cfccf..c2e126af91 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/query/hql/IntegerDivisionTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/query/hql/IntegerDivisionTest.java @@ -21,13 +21,13 @@ import static org.junit.jupiter.api.Assertions.assertFalse; @SessionFactory @ServiceRegistry(settings = @Setting(name = PORTABLE_INTEGER_DIVISION, value = "true")) public class IntegerDivisionTest { - @Test - public void testIntegerDivision(SessionFactoryScope scope) { - scope.inTransaction(s -> { - assertFalse( s.createQuery("select 1 where 1/2 = 0 and 4/3 = 1", Integer.class) - .getResultList().isEmpty() ); - assertEquals( 1, s.createQuery("select 4/3", Integer.class) - .getSingleResult() ); - }); - } + @Test + public void testIntegerDivision(SessionFactoryScope scope) { + scope.inTransaction(s -> { + assertFalse( s.createQuery("select 1 where 1/2 = 0 and 4/3 = 1", Integer.class) + .getResultList().isEmpty() ); + assertEquals( 1, s.createQuery("select 4/3", Integer.class) + .getSingleResult() ); + }); + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/query/hql/OrderByTests.java b/hibernate-core/src/test/java/org/hibernate/orm/test/query/hql/OrderByTests.java index c3ceb98909..d888c2d52a 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/query/hql/OrderByTests.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/query/hql/OrderByTests.java @@ -71,7 +71,7 @@ public class OrderByTests extends BaseCoreFunctionalTestCase { stateProvince = new StateProvince(); stateProvince.setName( "IL" ); - zoo1 = new Zoo(); + zoo1 = new Zoo(); zoo1.setName( "Zoo" ); Address address1 = new Address(); address1.setStreet( "1313 Mockingbird Lane" ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/query/hql/WithClauseJoinRewriteTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/query/hql/WithClauseJoinRewriteTest.java index ee1add3e9a..e931896712 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/query/hql/WithClauseJoinRewriteTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/query/hql/WithClauseJoinRewriteTest.java @@ -34,103 +34,103 @@ import java.util.Set; */ public class WithClauseJoinRewriteTest extends BaseCoreFunctionalTestCase { - @Override - protected Class[] getAnnotatedClasses() { - return new Class[]{ - AbstractObject.class, - AbstractConfigurationObject.class, - ConfigurationObject.class - }; - } + @Override + protected Class[] getAnnotatedClasses() { + return new Class[]{ + AbstractObject.class, + AbstractConfigurationObject.class, + ConfigurationObject.class + }; + } - @Test - @JiraKey(value = "HHH-11230") - public void testInheritanceReAliasing() { - Session s = openSession(); - Transaction tx = s.beginTransaction(); + @Test + @JiraKey(value = "HHH-11230") + public void testInheritanceReAliasing() { + Session s = openSession(); + Transaction tx = s.beginTransaction(); - // Just assert that the query is successful - List results = s.createQuery( - "SELECT usedBy.id, usedBy.name, COUNT(inverse.id) " + - "FROM " + AbstractConfigurationObject.class.getName() + " config " + - "INNER JOIN config.usedBy usedBy " + - "LEFT JOIN usedBy.uses inverse ON inverse.id = config.id " + - "WHERE config.id = 0 " + - "GROUP BY usedBy.id, usedBy.name", - Object[].class - ).getResultList(); + // Just assert that the query is successful + List results = s.createQuery( + "SELECT usedBy.id, usedBy.name, COUNT(inverse.id) " + + "FROM " + AbstractConfigurationObject.class.getName() + " config " + + "INNER JOIN config.usedBy usedBy " + + "LEFT JOIN usedBy.uses inverse ON inverse.id = config.id " + + "WHERE config.id = 0 " + + "GROUP BY usedBy.id, usedBy.name", + Object[].class + ).getResultList(); - tx.commit(); - s.close(); - } + tx.commit(); + s.close(); + } - @Entity - @Table( name = "config" ) - @Inheritance( strategy = InheritanceType.JOINED ) - public static abstract class AbstractConfigurationObject extends AbstractObject { + @Entity + @Table( name = "config" ) + @Inheritance( strategy = InheritanceType.JOINED ) + public static abstract class AbstractConfigurationObject extends AbstractObject { - private String name; - private Set uses = new HashSet<>(); - private Set usedBy = new HashSet<>(); + private String name; + private Set uses = new HashSet<>(); + private Set usedBy = new HashSet<>(); - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - @ManyToMany( targetEntity = AbstractConfigurationObject.class, fetch = FetchType.LAZY, cascade = {} ) - public Set getUses () { - return uses; - } + @ManyToMany( targetEntity = AbstractConfigurationObject.class, fetch = FetchType.LAZY, cascade = {} ) + public Set getUses () { + return uses; + } - public void setUses(Set uses) { - this.uses = uses; - } + public void setUses(Set uses) { + this.uses = uses; + } - @ManyToMany ( targetEntity = AbstractConfigurationObject.class, fetch = FetchType.LAZY, mappedBy = "uses", cascade = {} ) - public Set getUsedBy () { - return usedBy; - } + @ManyToMany ( targetEntity = AbstractConfigurationObject.class, fetch = FetchType.LAZY, mappedBy = "uses", cascade = {} ) + public Set getUsedBy () { + return usedBy; + } - public void setUsedBy(Set usedBy) { - this.usedBy = usedBy; - } - } + public void setUsedBy(Set usedBy) { + this.usedBy = usedBy; + } + } - @Entity - @Table( name = "config_config" ) - public static class ConfigurationObject extends AbstractConfigurationObject { + @Entity + @Table( name = "config_config" ) + public static class ConfigurationObject extends AbstractConfigurationObject { - } + } - @MappedSuperclass - public static class AbstractObject { + @MappedSuperclass + public static class AbstractObject { - private Long id; - private Long version; + private Long id; + private Long version; - @Id - @GeneratedValue - public Long getId () { - return id; - } + @Id + @GeneratedValue + public Long getId () { + return id; + } - public void setId(Long id) { - this.id = id; - } + public void setId(Long id) { + this.id = id; + } - @Version - @Column( nullable = false ) - public Long getVersion () { - return version; - } + @Version + @Column( nullable = false ) + public Long getVersion () { + return version; + } - public void setVersion(Long version) { - this.version = version; - } - } + public void setVersion(Long version) { + this.version = version; + } + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/query/hql/instantiation/InstantiationWithCollectionTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/query/hql/instantiation/InstantiationWithCollectionTest.java index 67c99ad0a5..b738efe6ae 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/query/hql/instantiation/InstantiationWithCollectionTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/query/hql/instantiation/InstantiationWithCollectionTest.java @@ -27,102 +27,102 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; @SessionFactory @DomainModel(annotatedClasses = {InstantiationWithCollectionTest.Entity.class, - InstantiationWithCollectionTest.ChildEntity.class}) + InstantiationWithCollectionTest.ChildEntity.class}) public class InstantiationWithCollectionTest { @Test void testElements(SessionFactoryScope scope) { - scope.getSessionFactory().getSchemaManager().truncateMappedObjects(); + scope.getSessionFactory().getSchemaManager().truncateMappedObjects(); - Entity entity = new Entity("hello", "world"); - scope.inTransaction(s -> s.persist(entity)); + Entity entity = new Entity("hello", "world"); + scope.inTransaction(s -> s.persist(entity)); List tuples = - // this kind of query is currently not documented to work, but it does, and I guess I don't see why it's terrible + // this kind of query is currently not documented to work, but it does, and I guess I don't see why it's terrible scope.fromSession(s -> s.createSelectionQuery("select id, names from Entity", Object[].class).getResultList()); assertEquals(2, tuples.size()); tuples.forEach(tuple -> assertNotNull(tuple[0])); tuples.forEach(tuple -> assertNotNull(tuple[1])); - List tuples2 = - scope.fromSession(s -> s.createSelectionQuery("select id, element(names) from Entity", Object[].class).getResultList()); - assertEquals(2, tuples2.size()); - tuples2.forEach(tuple -> assertNotNull(tuple[0])); - tuples2.forEach(tuple -> assertNotNull(tuple[1])); + List tuples2 = + scope.fromSession(s -> s.createSelectionQuery("select id, element(names) from Entity", Object[].class).getResultList()); + assertEquals(2, tuples2.size()); + tuples2.forEach(tuple -> assertNotNull(tuple[0])); + tuples2.forEach(tuple -> assertNotNull(tuple[1])); - List copies = - // this kind of query is currently not documented to work, but it does, and I guess I don't see why it's terrible + List copies = + // this kind of query is currently not documented to work, but it does, and I guess I don't see why it's terrible scope.fromSession(s -> s.createSelectionQuery("select id, names from Entity", EntityCopy.class).getResultList()); assertEquals(2, copies.size()); copies.forEach(Assertions::assertNotNull); copies.forEach(copy -> assertNotNull(copy.id)); copies.forEach(copy -> assertNotNull(copy.name)); - List copies2 = - scope.fromSession(s -> s.createSelectionQuery("select id, element(names) from Entity", EntityCopy.class).getResultList()); - assertEquals(2, copies2.size()); - copies2.forEach(Assertions::assertNotNull); - copies2.forEach(copy -> assertNotNull(copy.id)); - copies2.forEach(copy -> assertNotNull(copy.name)); + List copies2 = + scope.fromSession(s -> s.createSelectionQuery("select id, element(names) from Entity", EntityCopy.class).getResultList()); + assertEquals(2, copies2.size()); + copies2.forEach(Assertions::assertNotNull); + copies2.forEach(copy -> assertNotNull(copy.id)); + copies2.forEach(copy -> assertNotNull(copy.name)); - List newCopies = - // this kind of query is currently not documented to work, but it does, and I guess I don't see why it's terrible + List newCopies = + // this kind of query is currently not documented to work, but it does, and I guess I don't see why it's terrible scope.fromSession(s -> s.createSelectionQuery("select new EntityCopy(id, names) from Entity", EntityCopy.class).getResultList()); assertEquals(2, newCopies.size()); newCopies.forEach(Assertions::assertNotNull); newCopies.forEach(copy -> assertNotNull(copy.id)); newCopies.forEach(copy -> assertNotNull(copy.name)); - List newCopies2 = - scope.fromSession(s -> s.createSelectionQuery("select new EntityCopy(id, element(names)) from Entity", EntityCopy.class).getResultList()); - assertEquals(2, newCopies.size()); - newCopies2.forEach(Assertions::assertNotNull); - newCopies2.forEach(copy -> assertNotNull(copy.id)); - newCopies2.forEach(copy -> assertNotNull(copy.name)); + List newCopies2 = + scope.fromSession(s -> s.createSelectionQuery("select new EntityCopy(id, element(names)) from Entity", EntityCopy.class).getResultList()); + assertEquals(2, newCopies.size()); + newCopies2.forEach(Assertions::assertNotNull); + newCopies2.forEach(copy -> assertNotNull(copy.id)); + newCopies2.forEach(copy -> assertNotNull(copy.name)); } - @Test - void testAssociation(SessionFactoryScope scope) { - scope.getSessionFactory().getSchemaManager().truncateMappedObjects(); + @Test + void testAssociation(SessionFactoryScope scope) { + scope.getSessionFactory().getSchemaManager().truncateMappedObjects(); - Entity entity = new Entity("hello", "world"); - entity.children.add(new ChildEntity(entity, "goodbye")); - entity.children.add(new ChildEntity(entity, "gavin")); - scope.inTransaction(s -> s.persist(entity)); + Entity entity = new Entity("hello", "world"); + entity.children.add(new ChildEntity(entity, "goodbye")); + entity.children.add(new ChildEntity(entity, "gavin")); + scope.inTransaction(s -> s.persist(entity)); - List tuples = - // this kind of query is currently not documented to work, but it does, and I guess I don't see why it's terrible - scope.fromSession(s -> s.createSelectionQuery("select id, children from Entity", Object[].class).getResultList()); - assertEquals(2, tuples.size()); - tuples.forEach(tuple -> assertNotNull(tuple[0])); - tuples.forEach(tuple -> assertNotNull(tuple[1])); + List tuples = + // this kind of query is currently not documented to work, but it does, and I guess I don't see why it's terrible + scope.fromSession(s -> s.createSelectionQuery("select id, children from Entity", Object[].class).getResultList()); + assertEquals(2, tuples.size()); + tuples.forEach(tuple -> assertNotNull(tuple[0])); + tuples.forEach(tuple -> assertNotNull(tuple[1])); - List tuples2 = - scope.fromSession(s -> s.createSelectionQuery("select id, element(children) from Entity", Object[].class).getResultList()); - assertEquals(2, tuples2.size()); - tuples2.forEach(tuple -> assertNotNull(tuple[0])); - tuples2.forEach(tuple -> assertNotNull(tuple[1])); + List tuples2 = + scope.fromSession(s -> s.createSelectionQuery("select id, element(children) from Entity", Object[].class).getResultList()); + assertEquals(2, tuples2.size()); + tuples2.forEach(tuple -> assertNotNull(tuple[0])); + tuples2.forEach(tuple -> assertNotNull(tuple[1])); - List tuples3 = - scope.fromSession(s -> s.createSelectionQuery("select id, element(children).name from Entity", Object[].class).getResultList()); - assertEquals(2, tuples3.size()); - tuples3.forEach(tuple -> assertNotNull(tuple[0])); - tuples3.forEach(tuple -> assertNotNull(tuple[1])); + List tuples3 = + scope.fromSession(s -> s.createSelectionQuery("select id, element(children).name from Entity", Object[].class).getResultList()); + assertEquals(2, tuples3.size()); + tuples3.forEach(tuple -> assertNotNull(tuple[0])); + tuples3.forEach(tuple -> assertNotNull(tuple[1])); - List copies = - scope.fromSession(s -> s.createSelectionQuery("select id, element(children).name from Entity", EntityCopy.class).getResultList()); - assertEquals(2, copies.size()); - copies.forEach(Assertions::assertNotNull); - copies.forEach(copy -> assertNotNull(copy.id)); - copies.forEach(copy -> assertNotNull(copy.name)); + List copies = + scope.fromSession(s -> s.createSelectionQuery("select id, element(children).name from Entity", EntityCopy.class).getResultList()); + assertEquals(2, copies.size()); + copies.forEach(Assertions::assertNotNull); + copies.forEach(copy -> assertNotNull(copy.id)); + copies.forEach(copy -> assertNotNull(copy.name)); - List newCopies = - scope.fromSession(s -> s.createSelectionQuery("select new EntityCopy(id, element(children).name) from Entity", EntityCopy.class).getResultList()); - assertEquals(2, newCopies.size()); - newCopies.forEach(Assertions::assertNotNull); - newCopies.forEach(copy -> assertNotNull(copy.id)); - newCopies.forEach(copy -> assertNotNull(copy.name)); - } + List newCopies = + scope.fromSession(s -> s.createSelectionQuery("select new EntityCopy(id, element(children).name) from Entity", EntityCopy.class).getResultList()); + assertEquals(2, newCopies.size()); + newCopies.forEach(Assertions::assertNotNull); + newCopies.forEach(copy -> assertNotNull(copy.id)); + newCopies.forEach(copy -> assertNotNull(copy.name)); + } static class EntityCopy { Long id; @@ -137,35 +137,35 @@ public class InstantiationWithCollectionTest { @jakarta.persistence.Entity(name="Entity") static class Entity { @GeneratedValue @Id - Long id; + Long id; @ElementCollection Set names; - @OneToMany(mappedBy = "parent", cascade = CascadeType.PERSIST) - Set children; + @OneToMany(mappedBy = "parent", cascade = CascadeType.PERSIST) + Set children; Entity(String... names) { this.names = Set.of(names); - this.children = new HashSet<>(); + this.children = new HashSet<>(); } Entity() { names = new HashSet<>(); - children = new HashSet<>(); + children = new HashSet<>(); } } @jakarta.persistence.Entity(name="ChildEntity") static class ChildEntity { @GeneratedValue @Id Long id; - String name; - @ManyToOne Entity parent; + String name; + @ManyToOne Entity parent; - ChildEntity(Entity parent, String name) { - this.parent = parent; - this.name = name; - } + ChildEntity(Entity parent, String name) { + this.parent = parent; + this.name = name; + } - ChildEntity() { - } - } + ChildEntity() { + } + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/query/hql/set/SetOperationTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/query/hql/set/SetOperationTest.java index bf3f15be8b..f7cdfba8a8 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/query/hql/set/SetOperationTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/query/hql/set/SetOperationTest.java @@ -40,243 +40,243 @@ import static org.hamcrest.MatcherAssert.assertThat; @ServiceRegistry @SessionFactory public class SetOperationTest { - @BeforeEach - public void createTestData(SessionFactoryScope scope) { - scope.inTransaction( - session -> { - session.persist( new EntityOfLists( 1, "first" ) ); - session.persist( new EntityOfLists( 2, "second" ) ); - session.persist( new EntityOfLists( 3, "third" ) ); - EntityWithManyToOneSelfReference first = new EntityWithManyToOneSelfReference( 1, "first", 123 ); - EntityWithManyToOneSelfReference second = new EntityWithManyToOneSelfReference( 2, "second", 123 ); - session.persist( first ); - first.setOther( first ); - session.persist( second ); - second.setOther( second ); - } - ); - } + @BeforeEach + public void createTestData(SessionFactoryScope scope) { + scope.inTransaction( + session -> { + session.persist( new EntityOfLists( 1, "first" ) ); + session.persist( new EntityOfLists( 2, "second" ) ); + session.persist( new EntityOfLists( 3, "third" ) ); + EntityWithManyToOneSelfReference first = new EntityWithManyToOneSelfReference( 1, "first", 123 ); + EntityWithManyToOneSelfReference second = new EntityWithManyToOneSelfReference( 2, "second", 123 ); + session.persist( first ); + first.setOther( first ); + session.persist( second ); + second.setOther( second ); + } + ); + } - @AfterEach - public void dropTestData(SessionFactoryScope scope) { - scope.inTransaction( - session -> { - // Because, why not MySQL/MariaDB... https://bugs.mysql.com/bug.php?id=7412 - session.createQuery( "update EntityWithManyToOneSelfReference set other = null" ).executeUpdate(); - session.createQuery( "delete from EntityWithManyToOneSelfReference" ).executeUpdate(); - session.createQuery( "delete from EntityOfLists" ).executeUpdate(); - session.createQuery( "delete from SimpleEntity" ).executeUpdate(); - } - ); - } + @AfterEach + public void dropTestData(SessionFactoryScope scope) { + scope.inTransaction( + session -> { + // Because, why not MySQL/MariaDB... https://bugs.mysql.com/bug.php?id=7412 + session.createQuery( "update EntityWithManyToOneSelfReference set other = null" ).executeUpdate(); + session.createQuery( "delete from EntityWithManyToOneSelfReference" ).executeUpdate(); + session.createQuery( "delete from EntityOfLists" ).executeUpdate(); + session.createQuery( "delete from SimpleEntity" ).executeUpdate(); + } + ); + } - @Test - @JiraKey( value = "HHH-14704") - @RequiresDialectFeature(feature = DialectFeatureChecks.SupportsUnion.class) - public void testUnionAllWithManyToOne(SessionFactoryScope scope) { - scope.inSession( - session -> { - List list = session.createQuery( - "from EntityWithManyToOneSelfReference e where e.id = 1 " + - "union all " + - "from EntityWithManyToOneSelfReference e where e.id = 2", - EntityWithManyToOneSelfReference.class - ).list(); - assertThat( list.size(), is( 2 ) ); - } - ); - } + @Test + @JiraKey( value = "HHH-14704") + @RequiresDialectFeature(feature = DialectFeatureChecks.SupportsUnion.class) + public void testUnionAllWithManyToOne(SessionFactoryScope scope) { + scope.inSession( + session -> { + List list = session.createQuery( + "from EntityWithManyToOneSelfReference e where e.id = 1 " + + "union all " + + "from EntityWithManyToOneSelfReference e where e.id = 2", + EntityWithManyToOneSelfReference.class + ).list(); + assertThat( list.size(), is( 2 ) ); + } + ); + } - @Test - @JiraKey( value = "HHH-14704") - @RequiresDialectFeature(feature = DialectFeatureChecks.SupportsUnion.class) - public void testUnionAllWithManyToOneFetch(SessionFactoryScope scope) { - scope.inSession( - session -> { - List list = session.createQuery( - "from EntityWithManyToOneSelfReference e join fetch e.other where e.id = 1 " + - "union all " + - "from EntityWithManyToOneSelfReference e join fetch e.other where e.id = 2", - EntityWithManyToOneSelfReference.class - ).list(); - assertThat( list.size(), is( 2 ) ); - } - ); - } + @Test + @JiraKey( value = "HHH-14704") + @RequiresDialectFeature(feature = DialectFeatureChecks.SupportsUnion.class) + public void testUnionAllWithManyToOneFetch(SessionFactoryScope scope) { + scope.inSession( + session -> { + List list = session.createQuery( + "from EntityWithManyToOneSelfReference e join fetch e.other where e.id = 1 " + + "union all " + + "from EntityWithManyToOneSelfReference e join fetch e.other where e.id = 2", + EntityWithManyToOneSelfReference.class + ).list(); + assertThat( list.size(), is( 2 ) ); + } + ); + } - @Test - @RequiresDialectFeature(feature = DialectFeatureChecks.SupportsUnion.class) - public void testUnionAllWithManyToOneFetchJustOne(SessionFactoryScope scope) { - scope.inSession( - session -> { - try { - session.createQuery( - "from EntityWithManyToOneSelfReference e join fetch e.other where e.id = 1 " + - "union all " + - "from EntityWithManyToOneSelfReference e where e.id = 2", - EntityWithManyToOneSelfReference.class - ); - Assertions.fail( "Expected exception to be thrown!" ); - } - catch (Exception e) { - Assertions.assertEquals( IllegalArgumentException.class, e.getClass() ); - Assertions.assertEquals( SemanticException.class, e.getCause().getClass() ); - } - } - ); - } + @Test + @RequiresDialectFeature(feature = DialectFeatureChecks.SupportsUnion.class) + public void testUnionAllWithManyToOneFetchJustOne(SessionFactoryScope scope) { + scope.inSession( + session -> { + try { + session.createQuery( + "from EntityWithManyToOneSelfReference e join fetch e.other where e.id = 1 " + + "union all " + + "from EntityWithManyToOneSelfReference e where e.id = 2", + EntityWithManyToOneSelfReference.class + ); + Assertions.fail( "Expected exception to be thrown!" ); + } + catch (Exception e) { + Assertions.assertEquals( IllegalArgumentException.class, e.getClass() ); + Assertions.assertEquals( SemanticException.class, e.getCause().getClass() ); + } + } + ); + } - @Test - @RequiresDialectFeature(feature = DialectFeatureChecks.SupportsUnion.class) - public void testUnionAllWithManyToOneFetchDifferentAttributes(SessionFactoryScope scope) { - scope.inSession( - session -> { - try { - session.createQuery( - "from EntityOfLists e join fetch e.listOfOneToMany where e.id = 1 " + - "union all " + - "from EntityOfLists e join fetch e.listOfManyToMany where e.id = 2", - EntityOfLists.class - ); - Assertions.fail( "Expected exception to be thrown!" ); - } - catch (Exception e) { - Assertions.assertEquals( IllegalArgumentException.class, e.getClass() ); - Assertions.assertEquals( SemanticException.class, e.getCause().getClass() ); - } - } - ); - } + @Test + @RequiresDialectFeature(feature = DialectFeatureChecks.SupportsUnion.class) + public void testUnionAllWithManyToOneFetchDifferentAttributes(SessionFactoryScope scope) { + scope.inSession( + session -> { + try { + session.createQuery( + "from EntityOfLists e join fetch e.listOfOneToMany where e.id = 1 " + + "union all " + + "from EntityOfLists e join fetch e.listOfManyToMany where e.id = 2", + EntityOfLists.class + ); + Assertions.fail( "Expected exception to be thrown!" ); + } + catch (Exception e) { + Assertions.assertEquals( IllegalArgumentException.class, e.getClass() ); + Assertions.assertEquals( SemanticException.class, e.getCause().getClass() ); + } + } + ); + } - @Test - @RequiresDialectFeature(feature = DialectFeatureChecks.SupportsUnion.class) - public void testUnionAllWithManyToOneFetchDifferentOrder(SessionFactoryScope scope) { - scope.inSession( - session -> { - try { - session.createQuery( - "from EntityOfLists e join fetch e.listOfOneToMany join fetch e.listOfManyToMany where e.id = 1 " + - "union all " + - "from EntityOfLists e join fetch e.listOfManyToMany join fetch e.listOfOneToMany where e.id = 2", - EntityOfLists.class - ); - Assertions.fail( "Expected exception to be thrown!" ); - } - catch (Exception e) { - Assertions.assertEquals( IllegalArgumentException.class, e.getClass() ); - Assertions.assertEquals( SemanticException.class, e.getCause().getClass() ); - } - } - ); - } + @Test + @RequiresDialectFeature(feature = DialectFeatureChecks.SupportsUnion.class) + public void testUnionAllWithManyToOneFetchDifferentOrder(SessionFactoryScope scope) { + scope.inSession( + session -> { + try { + session.createQuery( + "from EntityOfLists e join fetch e.listOfOneToMany join fetch e.listOfManyToMany where e.id = 1 " + + "union all " + + "from EntityOfLists e join fetch e.listOfManyToMany join fetch e.listOfOneToMany where e.id = 2", + EntityOfLists.class + ); + Assertions.fail( "Expected exception to be thrown!" ); + } + catch (Exception e) { + Assertions.assertEquals( IllegalArgumentException.class, e.getClass() ); + Assertions.assertEquals( SemanticException.class, e.getCause().getClass() ); + } + } + ); + } - @Test - @RequiresDialectFeature(feature = DialectFeatureChecks.SupportsUnion.class) - public void testUnionAll(SessionFactoryScope scope) { - scope.inSession( - session -> { - List list = session.createQuery( - "select e from EntityOfLists e where e.id = 1 " + - "union all " + - "select e from EntityOfLists e where e.id = 2", - EntityOfLists.class - ).list(); - assertThat( list.size(), is( 2 ) ); - } - ); - } + @Test + @RequiresDialectFeature(feature = DialectFeatureChecks.SupportsUnion.class) + public void testUnionAll(SessionFactoryScope scope) { + scope.inSession( + session -> { + List list = session.createQuery( + "select e from EntityOfLists e where e.id = 1 " + + "union all " + + "select e from EntityOfLists e where e.id = 2", + EntityOfLists.class + ).list(); + assertThat( list.size(), is( 2 ) ); + } + ); + } - @Test - @RequiresDialectFeature(feature = DialectFeatureChecks.SupportsUnion.class) - public void testUnionAllLimit(SessionFactoryScope scope) { - scope.inSession( - session -> { - List list = session.createQuery( - "(select e.id, e from EntityOfLists e where e.id = 1 " + - "union all " + - "select e.id, e from EntityOfLists e where e.id = 2) " + - "order by 1 fetch first 1 row only", - Tuple.class - ).list(); - assertThat( list.size(), is( 1 ) ); - } - ); - } + @Test + @RequiresDialectFeature(feature = DialectFeatureChecks.SupportsUnion.class) + public void testUnionAllLimit(SessionFactoryScope scope) { + scope.inSession( + session -> { + List list = session.createQuery( + "(select e.id, e from EntityOfLists e where e.id = 1 " + + "union all " + + "select e.id, e from EntityOfLists e where e.id = 2) " + + "order by 1 fetch first 1 row only", + Tuple.class + ).list(); + assertThat( list.size(), is( 1 ) ); + } + ); + } - @Test - @RequiresDialectFeature(feature = DialectFeatureChecks.SupportsUnion.class) - @RequiresDialectFeature(feature = DialectFeatureChecks.SupportsOrderByInSubquery.class) - public void testUnionAllLimitSubquery(SessionFactoryScope scope) { - scope.inSession( - session -> { - List list = session.createQuery( - "select e.id, e from EntityOfLists e where e.id = 1 " + - "union all " + - "select e.id, e from EntityOfLists e where e.id = 2 " + - "order by 1 fetch first 1 row only", - Tuple.class - ).list(); - assertThat( list.size(), is( 2 ) ); - } - ); - } + @Test + @RequiresDialectFeature(feature = DialectFeatureChecks.SupportsUnion.class) + @RequiresDialectFeature(feature = DialectFeatureChecks.SupportsOrderByInSubquery.class) + public void testUnionAllLimitSubquery(SessionFactoryScope scope) { + scope.inSession( + session -> { + List list = session.createQuery( + "select e.id, e from EntityOfLists e where e.id = 1 " + + "union all " + + "select e.id, e from EntityOfLists e where e.id = 2 " + + "order by 1 fetch first 1 row only", + Tuple.class + ).list(); + assertThat( list.size(), is( 2 ) ); + } + ); + } - @Test - @RequiresDialectFeature(feature = DialectFeatureChecks.SupportsUnion.class) - @RequiresDialectFeature(feature = DialectFeatureChecks.SupportsOrderByInSubquery.class) - public void testUnionAllLimitNested(SessionFactoryScope scope) { - scope.inSession( - session -> { - List list = session.createQuery( - "(select e.id, e from EntityOfLists e where e.id = 1 " + - "union all " + - "(select e.id, e from EntityOfLists e where e.id = 2 order by 1 fetch first 1 row only)) " + - "order by 1 fetch first 1 row only", - Tuple.class - ).list(); - assertThat( list.size(), is( 1 ) ); - } - ); - } + @Test + @RequiresDialectFeature(feature = DialectFeatureChecks.SupportsUnion.class) + @RequiresDialectFeature(feature = DialectFeatureChecks.SupportsOrderByInSubquery.class) + public void testUnionAllLimitNested(SessionFactoryScope scope) { + scope.inSession( + session -> { + List list = session.createQuery( + "(select e.id, e from EntityOfLists e where e.id = 1 " + + "union all " + + "(select e.id, e from EntityOfLists e where e.id = 2 order by 1 fetch first 1 row only)) " + + "order by 1 fetch first 1 row only", + Tuple.class + ).list(); + assertThat( list.size(), is( 1 ) ); + } + ); + } - @Test - @RequiresDialectFeature(feature = DialectFeatureChecks.SupportsUnion.class) - @RequiresDialectFeature(feature = DialectFeatureChecks.SupportsOrderByInSubquery.class) - @SkipForDialect(dialectClass = OracleDialect.class, reason = "Bug in BasicFormatterImpl causes exception during formatting of the SQL string") - public void testAlternatingSetOperator(SessionFactoryScope scope) { - scope.inSession( - session -> { - List list = session.createQuery( - "(SELECT e.id FROM EntityOfLists e WHERE e.id = 1\n" - + "UNION\n" - + "SELECT e.id FROM EntityOfLists e WHERE e.id = 2\n" - + "UNION ALL\n" - + "SELECT e.id FROM EntityOfLists e WHERE e.id = 3)\n" - + "ORDER BY 1 DESC" - + " LIMIT 1", - Integer.class - ).list(); - assertThat( list.size(), is( 1 ) ); - } - ); - } + @Test + @RequiresDialectFeature(feature = DialectFeatureChecks.SupportsUnion.class) + @RequiresDialectFeature(feature = DialectFeatureChecks.SupportsOrderByInSubquery.class) + @SkipForDialect(dialectClass = OracleDialect.class, reason = "Bug in BasicFormatterImpl causes exception during formatting of the SQL string") + public void testAlternatingSetOperator(SessionFactoryScope scope) { + scope.inSession( + session -> { + List list = session.createQuery( + "(SELECT e.id FROM EntityOfLists e WHERE e.id = 1\n" + + "UNION\n" + + "SELECT e.id FROM EntityOfLists e WHERE e.id = 2\n" + + "UNION ALL\n" + + "SELECT e.id FROM EntityOfLists e WHERE e.id = 3)\n" + + "ORDER BY 1 DESC" + + " LIMIT 1", + Integer.class + ).list(); + assertThat( list.size(), is( 1 ) ); + } + ); + } - @Test - @RequiresDialectFeature(feature = DialectFeatureChecks.SupportsUnion.class) - @RequiresDialectFeature(feature = DialectFeatureChecks.SupportsOrderByInSubquery.class) - public void testUnionAllOrderByAttribute(SessionFactoryScope scope) { - scope.inSession( - session -> { - List list = session.createQuery( - "(SELECT e FROM EntityOfLists e WHERE e.id = 1\n" - + "UNION ALL\n" - + "SELECT e FROM EntityOfLists e WHERE e.id = 2)\n" - + "ORDER BY name DESC" - + " LIMIT 1", - EntityOfLists.class - ).list(); - assertThat( list.size(), is( 1 ) ); - } - ); - } + @Test + @RequiresDialectFeature(feature = DialectFeatureChecks.SupportsUnion.class) + @RequiresDialectFeature(feature = DialectFeatureChecks.SupportsOrderByInSubquery.class) + public void testUnionAllOrderByAttribute(SessionFactoryScope scope) { + scope.inSession( + session -> { + List list = session.createQuery( + "(SELECT e FROM EntityOfLists e WHERE e.id = 1\n" + + "UNION ALL\n" + + "SELECT e FROM EntityOfLists e WHERE e.id = 2)\n" + + "ORDER BY name DESC" + + " LIMIT 1", + EntityOfLists.class + ).list(); + assertThat( list.size(), is( 1 ) ); + } + ); + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/query/order/OrderTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/query/order/OrderTest.java index 40dd07d86e..015c72f60e 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/query/order/OrderTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/query/order/OrderTest.java @@ -30,47 +30,47 @@ import static org.junit.jupiter.api.Assertions.assertEquals; @DomainModel(annotatedClasses = OrderTest.Book.class) public class OrderTest { - @Test void testAscendingDescending(SessionFactoryScope scope) { - scope.inTransaction( session -> session.createMutationQuery("delete Book").executeUpdate() ); - scope.inTransaction( session -> { - session.persist(new Book("9781932394153", "Hibernate in Action")); - session.persist(new Book("9781617290459", "Java Persistence with Hibernate")); - }); - EntityDomainType bookType = scope.getSessionFactory().getJpaMetamodel().findEntityType(Book.class); - SingularAttribute title = bookType.findSingularAttribute("title"); - SingularAttribute isbn = bookType.findSingularAttribute("isbn"); - scope.inSession(session -> { - List titlesAsc = session.createSelectionQuery("from Book", Book.class) - .setOrder(asc(title)) - .getResultList() - .stream().map(book -> book.title) - .collect(toList()); - assertEquals("Hibernate in Action", titlesAsc.get(0)); - assertEquals("Java Persistence with Hibernate", titlesAsc.get(1)); + @Test void testAscendingDescending(SessionFactoryScope scope) { + scope.inTransaction( session -> session.createMutationQuery("delete Book").executeUpdate() ); + scope.inTransaction( session -> { + session.persist(new Book("9781932394153", "Hibernate in Action")); + session.persist(new Book("9781617290459", "Java Persistence with Hibernate")); + }); + EntityDomainType bookType = scope.getSessionFactory().getJpaMetamodel().findEntityType(Book.class); + SingularAttribute title = bookType.findSingularAttribute("title"); + SingularAttribute isbn = bookType.findSingularAttribute("isbn"); + scope.inSession(session -> { + List titlesAsc = session.createSelectionQuery("from Book", Book.class) + .setOrder(asc(title)) + .getResultList() + .stream().map(book -> book.title) + .collect(toList()); + assertEquals("Hibernate in Action", titlesAsc.get(0)); + assertEquals("Java Persistence with Hibernate", titlesAsc.get(1)); - List titlesDesc = session.createSelectionQuery("from Book", Book.class) - .setOrder(desc(title)) - .getResultList() - .stream().map(book -> book.title) - .collect(toList()); - assertEquals("Hibernate in Action", titlesDesc.get(1)); - assertEquals("Java Persistence with Hibernate", titlesDesc.get(0)); + List titlesDesc = session.createSelectionQuery("from Book", Book.class) + .setOrder(desc(title)) + .getResultList() + .stream().map(book -> book.title) + .collect(toList()); + assertEquals("Hibernate in Action", titlesDesc.get(1)); + assertEquals("Java Persistence with Hibernate", titlesDesc.get(0)); - List isbnAsc = session.createSelectionQuery("from Book", Book.class) - .setOrder(List.of(asc(isbn), desc(title))) - .getResultList() - .stream().map(book -> book.title) - .collect(toList()); - assertEquals("Hibernate in Action", isbnAsc.get(1)); - assertEquals("Java Persistence with Hibernate", isbnAsc.get(0)); + List isbnAsc = session.createSelectionQuery("from Book", Book.class) + .setOrder(List.of(asc(isbn), desc(title))) + .getResultList() + .stream().map(book -> book.title) + .collect(toList()); + assertEquals("Hibernate in Action", isbnAsc.get(1)); + assertEquals("Java Persistence with Hibernate", isbnAsc.get(0)); - List isbnDesc = session.createSelectionQuery("from Book", Book.class) - .setOrder(List.of(desc(isbn), desc(title))) - .getResultList() - .stream().map(book -> book.title) - .collect(toList()); - assertEquals("Hibernate in Action", isbnDesc.get(0)); - assertEquals("Java Persistence with Hibernate", isbnDesc.get(1)); + List isbnDesc = session.createSelectionQuery("from Book", Book.class) + .setOrder(List.of(desc(isbn), desc(title))) + .getResultList() + .stream().map(book -> book.title) + .collect(toList()); + assertEquals("Hibernate in Action", isbnDesc.get(0)); + assertEquals("Java Persistence with Hibernate", isbnDesc.get(1)); // titlesAsc = session.createSelectionQuery("from Book order by isbn asc", Book.class) // .setOrder(asc(title)) @@ -79,62 +79,62 @@ public class OrderTest { // .collect(toList()); // assertEquals("Hibernate in Action", titlesAsc.get(1)); // assertEquals("Java Persistence with Hibernate", titlesAsc.get(0)); - titlesAsc = session.createSelectionQuery("from Book order by isbn asc", Book.class) + titlesAsc = session.createSelectionQuery("from Book order by isbn asc", Book.class) // .setOrder(emptyList()) - .setOrder(asc(title)) - .getResultList() - .stream().map(book -> book.title) - .collect(toList()); - assertEquals("Hibernate in Action", titlesAsc.get(0)); - assertEquals("Java Persistence with Hibernate", titlesAsc.get(1)); - }); - } + .setOrder(asc(title)) + .getResultList() + .stream().map(book -> book.title) + .collect(toList()); + assertEquals("Hibernate in Action", titlesAsc.get(0)); + assertEquals("Java Persistence with Hibernate", titlesAsc.get(1)); + }); + } - @Test void testAscendingDescendingWithPositionalParam(SessionFactoryScope scope) { - scope.inTransaction( session -> session.createMutationQuery("delete Book").executeUpdate() ); - scope.inTransaction( session -> { - session.persist(new Book("9781932394153", "Hibernate in Action")); - session.persist(new Book("9781617290459", "Java Persistence with Hibernate")); - }); - EntityDomainType bookType = scope.getSessionFactory().getJpaMetamodel().findEntityType(Book.class); - SingularAttribute title = bookType.findSingularAttribute("title"); - SingularAttribute isbn = bookType.findSingularAttribute("isbn"); - scope.inSession(session -> { - List titlesAsc = session.createSelectionQuery("from Book where title like ?1", Book.class) - .setParameter(1, "%Hibernate%") - .setOrder(asc(title)) - .getResultList() - .stream().map(book -> book.title) - .collect(toList()); - assertEquals("Hibernate in Action", titlesAsc.get(0)); - assertEquals("Java Persistence with Hibernate", titlesAsc.get(1)); + @Test void testAscendingDescendingWithPositionalParam(SessionFactoryScope scope) { + scope.inTransaction( session -> session.createMutationQuery("delete Book").executeUpdate() ); + scope.inTransaction( session -> { + session.persist(new Book("9781932394153", "Hibernate in Action")); + session.persist(new Book("9781617290459", "Java Persistence with Hibernate")); + }); + EntityDomainType bookType = scope.getSessionFactory().getJpaMetamodel().findEntityType(Book.class); + SingularAttribute title = bookType.findSingularAttribute("title"); + SingularAttribute isbn = bookType.findSingularAttribute("isbn"); + scope.inSession(session -> { + List titlesAsc = session.createSelectionQuery("from Book where title like ?1", Book.class) + .setParameter(1, "%Hibernate%") + .setOrder(asc(title)) + .getResultList() + .stream().map(book -> book.title) + .collect(toList()); + assertEquals("Hibernate in Action", titlesAsc.get(0)); + assertEquals("Java Persistence with Hibernate", titlesAsc.get(1)); - List titlesDesc = session.createSelectionQuery("from Book where title like ?1", Book.class) - .setParameter(1, "%Hibernate%") - .setOrder(Order.desc(title)) - .getResultList() - .stream().map(book -> book.title) - .collect(toList()); - assertEquals("Hibernate in Action", titlesDesc.get(1)); - assertEquals("Java Persistence with Hibernate", titlesDesc.get(0)); + List titlesDesc = session.createSelectionQuery("from Book where title like ?1", Book.class) + .setParameter(1, "%Hibernate%") + .setOrder(Order.desc(title)) + .getResultList() + .stream().map(book -> book.title) + .collect(toList()); + assertEquals("Hibernate in Action", titlesDesc.get(1)); + assertEquals("Java Persistence with Hibernate", titlesDesc.get(0)); - List isbnAsc = session.createSelectionQuery("from Book where title like ?1", Book.class) - .setParameter(1, "%Hibernate%") - .setOrder(List.of(asc(isbn), desc(title))) - .getResultList() - .stream().map(book -> book.title) - .collect(toList()); - assertEquals("Hibernate in Action", isbnAsc.get(1)); - assertEquals("Java Persistence with Hibernate", isbnAsc.get(0)); + List isbnAsc = session.createSelectionQuery("from Book where title like ?1", Book.class) + .setParameter(1, "%Hibernate%") + .setOrder(List.of(asc(isbn), desc(title))) + .getResultList() + .stream().map(book -> book.title) + .collect(toList()); + assertEquals("Hibernate in Action", isbnAsc.get(1)); + assertEquals("Java Persistence with Hibernate", isbnAsc.get(0)); - List isbnDesc = session.createSelectionQuery("from Book where title like ?1", Book.class) - .setParameter(1, "%Hibernate%") - .setOrder(List.of(desc(isbn), desc(title))) - .getResultList() - .stream().map(book -> book.title) - .collect(toList()); - assertEquals("Hibernate in Action", isbnDesc.get(0)); - assertEquals("Java Persistence with Hibernate", isbnDesc.get(1)); + List isbnDesc = session.createSelectionQuery("from Book where title like ?1", Book.class) + .setParameter(1, "%Hibernate%") + .setOrder(List.of(desc(isbn), desc(title))) + .getResultList() + .stream().map(book -> book.title) + .collect(toList()); + assertEquals("Hibernate in Action", isbnDesc.get(0)); + assertEquals("Java Persistence with Hibernate", isbnDesc.get(1)); // titlesAsc = session.createSelectionQuery("from Book where title like ?1 order by isbn asc", Book.class) // .setParameter(1, "%Hibernate%") @@ -144,63 +144,63 @@ public class OrderTest { // .collect(toList()); // assertEquals("Hibernate in Action", titlesAsc.get(1)); // assertEquals("Java Persistence with Hibernate", titlesAsc.get(0)); - titlesAsc = session.createSelectionQuery("from Book where title like ?1 order by isbn asc", Book.class) - .setParameter(1, "%Hibernate%") + titlesAsc = session.createSelectionQuery("from Book where title like ?1 order by isbn asc", Book.class) + .setParameter(1, "%Hibernate%") // .setOrder(emptyList()) - .setOrder(asc(title)) - .getResultList() - .stream().map(book -> book.title) - .collect(toList()); - assertEquals("Hibernate in Action", titlesAsc.get(0)); - assertEquals("Java Persistence with Hibernate", titlesAsc.get(1)); - }); - } + .setOrder(asc(title)) + .getResultList() + .stream().map(book -> book.title) + .collect(toList()); + assertEquals("Hibernate in Action", titlesAsc.get(0)); + assertEquals("Java Persistence with Hibernate", titlesAsc.get(1)); + }); + } - @Test void testAscendingDescendingWithNamedParam(SessionFactoryScope scope) { - scope.inTransaction( session -> session.createMutationQuery("delete Book").executeUpdate() ); - scope.inTransaction( session -> { - session.persist(new Book("9781932394153", "Hibernate in Action")); - session.persist(new Book("9781617290459", "Java Persistence with Hibernate")); - }); - EntityDomainType bookType = scope.getSessionFactory().getJpaMetamodel().findEntityType(Book.class); - SingularAttribute title = bookType.findSingularAttribute("title"); - SingularAttribute isbn = bookType.findSingularAttribute("isbn"); - scope.inSession(session -> { - List titlesAsc = session.createSelectionQuery("from Book where title like :title", Book.class) - .setParameter("title", "%Hibernate%") - .setOrder(asc(title)) - .getResultList() - .stream().map(book -> book.title) - .collect(toList()); - assertEquals("Hibernate in Action", titlesAsc.get(0)); - assertEquals("Java Persistence with Hibernate", titlesAsc.get(1)); + @Test void testAscendingDescendingWithNamedParam(SessionFactoryScope scope) { + scope.inTransaction( session -> session.createMutationQuery("delete Book").executeUpdate() ); + scope.inTransaction( session -> { + session.persist(new Book("9781932394153", "Hibernate in Action")); + session.persist(new Book("9781617290459", "Java Persistence with Hibernate")); + }); + EntityDomainType bookType = scope.getSessionFactory().getJpaMetamodel().findEntityType(Book.class); + SingularAttribute title = bookType.findSingularAttribute("title"); + SingularAttribute isbn = bookType.findSingularAttribute("isbn"); + scope.inSession(session -> { + List titlesAsc = session.createSelectionQuery("from Book where title like :title", Book.class) + .setParameter("title", "%Hibernate%") + .setOrder(asc(title)) + .getResultList() + .stream().map(book -> book.title) + .collect(toList()); + assertEquals("Hibernate in Action", titlesAsc.get(0)); + assertEquals("Java Persistence with Hibernate", titlesAsc.get(1)); - List titlesDesc = session.createSelectionQuery("from Book where title like :title", Book.class) - .setParameter("title", "%Hibernate%") - .setOrder(desc(title)) - .getResultList() - .stream().map(book -> book.title) - .collect(toList()); - assertEquals("Hibernate in Action", titlesDesc.get(1)); - assertEquals("Java Persistence with Hibernate", titlesDesc.get(0)); + List titlesDesc = session.createSelectionQuery("from Book where title like :title", Book.class) + .setParameter("title", "%Hibernate%") + .setOrder(desc(title)) + .getResultList() + .stream().map(book -> book.title) + .collect(toList()); + assertEquals("Hibernate in Action", titlesDesc.get(1)); + assertEquals("Java Persistence with Hibernate", titlesDesc.get(0)); - List isbnAsc = session.createSelectionQuery("from Book where title like :title", Book.class) - .setParameter("title", "%Hibernate%") - .setOrder(List.of(asc(isbn), desc(title))) - .getResultList() - .stream().map(book -> book.title) - .collect(toList()); - assertEquals("Hibernate in Action", isbnAsc.get(1)); - assertEquals("Java Persistence with Hibernate", isbnAsc.get(0)); + List isbnAsc = session.createSelectionQuery("from Book where title like :title", Book.class) + .setParameter("title", "%Hibernate%") + .setOrder(List.of(asc(isbn), desc(title))) + .getResultList() + .stream().map(book -> book.title) + .collect(toList()); + assertEquals("Hibernate in Action", isbnAsc.get(1)); + assertEquals("Java Persistence with Hibernate", isbnAsc.get(0)); - List isbnDesc = session.createSelectionQuery("from Book where title like :title", Book.class) - .setParameter("title", "%Hibernate%") - .setOrder(List.of(desc(isbn), desc(title))) - .getResultList() - .stream().map(book -> book.title) - .collect(toList()); - assertEquals("Hibernate in Action", isbnDesc.get(0)); - assertEquals("Java Persistence with Hibernate", isbnDesc.get(1)); + List isbnDesc = session.createSelectionQuery("from Book where title like :title", Book.class) + .setParameter("title", "%Hibernate%") + .setOrder(List.of(desc(isbn), desc(title))) + .getResultList() + .stream().map(book -> book.title) + .collect(toList()); + assertEquals("Hibernate in Action", isbnDesc.get(0)); + assertEquals("Java Persistence with Hibernate", isbnDesc.get(1)); // titlesAsc = session.createSelectionQuery("from Book where title like :title order by isbn asc", Book.class) // .setParameter("title", "%Hibernate%") @@ -210,100 +210,100 @@ public class OrderTest { // .collect(toList()); // assertEquals("Hibernate in Action", titlesAsc.get(1)); // assertEquals("Java Persistence with Hibernate", titlesAsc.get(0)); - titlesAsc = session.createSelectionQuery("from Book where title like :title order by isbn asc", Book.class) - .setParameter("title", "%Hibernate%") + titlesAsc = session.createSelectionQuery("from Book where title like :title order by isbn asc", Book.class) + .setParameter("title", "%Hibernate%") // .setOrder(emptyList()) - .setOrder(asc(title)) - .getResultList() - .stream().map(book -> book.title) - .collect(toList()); - assertEquals("Hibernate in Action", titlesAsc.get(0)); - assertEquals("Java Persistence with Hibernate", titlesAsc.get(1)); - }); - } + .setOrder(asc(title)) + .getResultList() + .stream().map(book -> book.title) + .collect(toList()); + assertEquals("Hibernate in Action", titlesAsc.get(0)); + assertEquals("Java Persistence with Hibernate", titlesAsc.get(1)); + }); + } - @Test void testAscendingDescendingBySelectElement(SessionFactoryScope scope) { - scope.inTransaction( session -> session.createMutationQuery("delete Book").executeUpdate() ); - scope.inTransaction( session -> { - session.persist(new Book("9781932394153", "Hibernate in Action")); - session.persist(new Book("9781617290459", "Java Persistence with Hibernate")); - }); - scope.inSession(session -> { - List titlesAsc = session.createSelectionQuery("select isbn, title from Book", Object[].class) - .setOrder(asc(2)) - .getResultList() - .stream().map(book -> book[1]) - .collect(toList()); - assertEquals("Hibernate in Action", titlesAsc.get(0)); - assertEquals("Java Persistence with Hibernate", titlesAsc.get(1)); + @Test void testAscendingDescendingBySelectElement(SessionFactoryScope scope) { + scope.inTransaction( session -> session.createMutationQuery("delete Book").executeUpdate() ); + scope.inTransaction( session -> { + session.persist(new Book("9781932394153", "Hibernate in Action")); + session.persist(new Book("9781617290459", "Java Persistence with Hibernate")); + }); + scope.inSession(session -> { + List titlesAsc = session.createSelectionQuery("select isbn, title from Book", Object[].class) + .setOrder(asc(2)) + .getResultList() + .stream().map(book -> book[1]) + .collect(toList()); + assertEquals("Hibernate in Action", titlesAsc.get(0)); + assertEquals("Java Persistence with Hibernate", titlesAsc.get(1)); - List titlesDesc = session.createSelectionQuery("select isbn, title from Book", Object[].class) - .setOrder(desc(2)) - .getResultList() - .stream().map(book -> book[1]) - .collect(toList()); - assertEquals("Hibernate in Action", titlesDesc.get(1)); - assertEquals("Java Persistence with Hibernate", titlesDesc.get(0)); + List titlesDesc = session.createSelectionQuery("select isbn, title from Book", Object[].class) + .setOrder(desc(2)) + .getResultList() + .stream().map(book -> book[1]) + .collect(toList()); + assertEquals("Hibernate in Action", titlesDesc.get(1)); + assertEquals("Java Persistence with Hibernate", titlesDesc.get(0)); - List isbnAsc = session.createSelectionQuery("select isbn, title from Book", Object[].class) - .setOrder(List.of(asc(1), desc(2))) - .getResultList() - .stream().map(book -> book[1]) - .collect(toList()); - assertEquals("Hibernate in Action", isbnAsc.get(1)); - assertEquals("Java Persistence with Hibernate", isbnAsc.get(0)); + List isbnAsc = session.createSelectionQuery("select isbn, title from Book", Object[].class) + .setOrder(List.of(asc(1), desc(2))) + .getResultList() + .stream().map(book -> book[1]) + .collect(toList()); + assertEquals("Hibernate in Action", isbnAsc.get(1)); + assertEquals("Java Persistence with Hibernate", isbnAsc.get(0)); - List isbnDesc = session.createSelectionQuery("select isbn, title from Book", Object[].class) - .setOrder(List.of(desc(1), desc(2))) - .getResultList() - .stream().map(book -> book[1]) - .collect(toList()); - assertEquals("Hibernate in Action", isbnDesc.get(0)); - assertEquals("Java Persistence with Hibernate", isbnDesc.get(1)); - }); - } + List isbnDesc = session.createSelectionQuery("select isbn, title from Book", Object[].class) + .setOrder(List.of(desc(1), desc(2))) + .getResultList() + .stream().map(book -> book[1]) + .collect(toList()); + assertEquals("Hibernate in Action", isbnDesc.get(0)); + assertEquals("Java Persistence with Hibernate", isbnDesc.get(1)); + }); + } - @Test void testAscendingDescendingCaseInsensitive(SessionFactoryScope scope) { - scope.inTransaction( session -> session.createMutationQuery("delete Book").executeUpdate() ); - scope.inTransaction( session -> { - session.persist(new Book("9781932394153", "Hibernate in Action")); - session.persist(new Book("9781617290459", "Java Persistence with Hibernate")); - }); - EntityDomainType bookType = scope.getSessionFactory().getJpaMetamodel().findEntityType(Book.class); - SingularAttribute title = bookType.findSingularAttribute("title"); - SingularAttribute isbn = bookType.findSingularAttribute("isbn"); - scope.inSession(session -> { - List titlesAsc = session.createSelectionQuery("from Book", Book.class) - .setOrder(asc(title).ignoringCase()) - .getResultList() - .stream().map(book -> book.title) - .collect(toList()); - assertEquals("Hibernate in Action", titlesAsc.get(0)); - assertEquals("Java Persistence with Hibernate", titlesAsc.get(1)); + @Test void testAscendingDescendingCaseInsensitive(SessionFactoryScope scope) { + scope.inTransaction( session -> session.createMutationQuery("delete Book").executeUpdate() ); + scope.inTransaction( session -> { + session.persist(new Book("9781932394153", "Hibernate in Action")); + session.persist(new Book("9781617290459", "Java Persistence with Hibernate")); + }); + EntityDomainType bookType = scope.getSessionFactory().getJpaMetamodel().findEntityType(Book.class); + SingularAttribute title = bookType.findSingularAttribute("title"); + SingularAttribute isbn = bookType.findSingularAttribute("isbn"); + scope.inSession(session -> { + List titlesAsc = session.createSelectionQuery("from Book", Book.class) + .setOrder(asc(title).ignoringCase()) + .getResultList() + .stream().map(book -> book.title) + .collect(toList()); + assertEquals("Hibernate in Action", titlesAsc.get(0)); + assertEquals("Java Persistence with Hibernate", titlesAsc.get(1)); - List titlesDesc = session.createSelectionQuery("from Book", Book.class) - .setOrder(desc(title).ignoringCase()) - .getResultList() - .stream().map(book -> book.title) - .collect(toList()); - assertEquals("Hibernate in Action", titlesDesc.get(1)); - assertEquals("Java Persistence with Hibernate", titlesDesc.get(0)); + List titlesDesc = session.createSelectionQuery("from Book", Book.class) + .setOrder(desc(title).ignoringCase()) + .getResultList() + .stream().map(book -> book.title) + .collect(toList()); + assertEquals("Hibernate in Action", titlesDesc.get(1)); + assertEquals("Java Persistence with Hibernate", titlesDesc.get(0)); - List isbnAsc = session.createSelectionQuery("from Book", Book.class) - .setOrder(List.of(asc(isbn).ignoringCase(), desc(title).ignoringCase())) - .getResultList() - .stream().map(book -> book.title) - .collect(toList()); - assertEquals("Hibernate in Action", isbnAsc.get(1)); - assertEquals("Java Persistence with Hibernate", isbnAsc.get(0)); + List isbnAsc = session.createSelectionQuery("from Book", Book.class) + .setOrder(List.of(asc(isbn).ignoringCase(), desc(title).ignoringCase())) + .getResultList() + .stream().map(book -> book.title) + .collect(toList()); + assertEquals("Hibernate in Action", isbnAsc.get(1)); + assertEquals("Java Persistence with Hibernate", isbnAsc.get(0)); - List isbnDesc = session.createSelectionQuery("from Book", Book.class) - .setOrder(List.of(desc(isbn).ignoringCase(), desc(title).ignoringCase())) - .getResultList() - .stream().map(book -> book.title) - .collect(toList()); - assertEquals("Hibernate in Action", isbnDesc.get(0)); - assertEquals("Java Persistence with Hibernate", isbnDesc.get(1)); + List isbnDesc = session.createSelectionQuery("from Book", Book.class) + .setOrder(List.of(desc(isbn).ignoringCase(), desc(title).ignoringCase())) + .getResultList() + .stream().map(book -> book.title) + .collect(toList()); + assertEquals("Hibernate in Action", isbnDesc.get(0)); + assertEquals("Java Persistence with Hibernate", isbnDesc.get(1)); // titlesAsc = session.createSelectionQuery("from Book order by isbn asc", Book.class) // .setOrder(asc(title)) @@ -312,58 +312,58 @@ public class OrderTest { // .collect(toList()); // assertEquals("Hibernate in Action", titlesAsc.get(1)); // assertEquals("Java Persistence with Hibernate", titlesAsc.get(0)); - titlesAsc = session.createSelectionQuery("from Book order by isbn asc", Book.class) + titlesAsc = session.createSelectionQuery("from Book order by isbn asc", Book.class) // .setOrder(emptyList()) - .setOrder(asc(title).ignoringCase()) - .getResultList() - .stream().map(book -> book.title) - .collect(toList()); - assertEquals("Hibernate in Action", titlesAsc.get(0)); - assertEquals("Java Persistence with Hibernate", titlesAsc.get(1)); - }); - } + .setOrder(asc(title).ignoringCase()) + .getResultList() + .stream().map(book -> book.title) + .collect(toList()); + assertEquals("Hibernate in Action", titlesAsc.get(0)); + assertEquals("Java Persistence with Hibernate", titlesAsc.get(1)); + }); + } - @Test void testAscendingDescendingCaseInsensitiveLongForm(SessionFactoryScope scope) { - scope.inTransaction( session -> session.createMutationQuery("delete Book").executeUpdate() ); - scope.inTransaction( session -> { - session.persist(new Book("9781932394153", "Hibernate in Action")); - session.persist(new Book("9781617290459", "Java Persistence with Hibernate")); - }); - EntityDomainType bookType = scope.getSessionFactory().getJpaMetamodel().findEntityType(Book.class); - SingularAttribute title = bookType.findSingularAttribute("title"); - SingularAttribute isbn = bookType.findSingularAttribute("isbn"); - scope.inSession(session -> { - List titlesAsc = session.createSelectionQuery("from Book", Book.class) - .setOrder(by(title, ASCENDING, true)) - .getResultList() - .stream().map(book -> book.title) - .collect(toList()); - assertEquals("Hibernate in Action", titlesAsc.get(0)); - assertEquals("Java Persistence with Hibernate", titlesAsc.get(1)); + @Test void testAscendingDescendingCaseInsensitiveLongForm(SessionFactoryScope scope) { + scope.inTransaction( session -> session.createMutationQuery("delete Book").executeUpdate() ); + scope.inTransaction( session -> { + session.persist(new Book("9781932394153", "Hibernate in Action")); + session.persist(new Book("9781617290459", "Java Persistence with Hibernate")); + }); + EntityDomainType bookType = scope.getSessionFactory().getJpaMetamodel().findEntityType(Book.class); + SingularAttribute title = bookType.findSingularAttribute("title"); + SingularAttribute isbn = bookType.findSingularAttribute("isbn"); + scope.inSession(session -> { + List titlesAsc = session.createSelectionQuery("from Book", Book.class) + .setOrder(by(title, ASCENDING, true)) + .getResultList() + .stream().map(book -> book.title) + .collect(toList()); + assertEquals("Hibernate in Action", titlesAsc.get(0)); + assertEquals("Java Persistence with Hibernate", titlesAsc.get(1)); - List titlesDesc = session.createSelectionQuery("from Book", Book.class) - .setOrder(by(title, DESCENDING, true)) - .getResultList() - .stream().map(book -> book.title) - .collect(toList()); - assertEquals("Hibernate in Action", titlesDesc.get(1)); - assertEquals("Java Persistence with Hibernate", titlesDesc.get(0)); + List titlesDesc = session.createSelectionQuery("from Book", Book.class) + .setOrder(by(title, DESCENDING, true)) + .getResultList() + .stream().map(book -> book.title) + .collect(toList()); + assertEquals("Hibernate in Action", titlesDesc.get(1)); + assertEquals("Java Persistence with Hibernate", titlesDesc.get(0)); - List isbnAsc = session.createSelectionQuery("from Book", Book.class) - .setOrder(List.of(by(isbn, ASCENDING, true), by(title, DESCENDING, true))) - .getResultList() - .stream().map(book -> book.title) - .collect(toList()); - assertEquals("Hibernate in Action", isbnAsc.get(1)); - assertEquals("Java Persistence with Hibernate", isbnAsc.get(0)); + List isbnAsc = session.createSelectionQuery("from Book", Book.class) + .setOrder(List.of(by(isbn, ASCENDING, true), by(title, DESCENDING, true))) + .getResultList() + .stream().map(book -> book.title) + .collect(toList()); + assertEquals("Hibernate in Action", isbnAsc.get(1)); + assertEquals("Java Persistence with Hibernate", isbnAsc.get(0)); - List isbnDesc = session.createSelectionQuery("from Book", Book.class) - .setOrder(List.of(by(isbn, DESCENDING, true), by(title, DESCENDING, true))) - .getResultList() - .stream().map(book -> book.title) - .collect(toList()); - assertEquals("Hibernate in Action", isbnDesc.get(0)); - assertEquals("Java Persistence with Hibernate", isbnDesc.get(1)); + List isbnDesc = session.createSelectionQuery("from Book", Book.class) + .setOrder(List.of(by(isbn, DESCENDING, true), by(title, DESCENDING, true))) + .getResultList() + .stream().map(book -> book.title) + .collect(toList()); + assertEquals("Hibernate in Action", isbnDesc.get(0)); + assertEquals("Java Persistence with Hibernate", isbnDesc.get(1)); // titlesAsc = session.createSelectionQuery("from Book order by isbn asc", Book.class) // .setOrder(asc(title)) @@ -372,110 +372,110 @@ public class OrderTest { // .collect(toList()); // assertEquals("Hibernate in Action", titlesAsc.get(1)); // assertEquals("Java Persistence with Hibernate", titlesAsc.get(0)); - titlesAsc = session.createSelectionQuery("from Book order by isbn asc", Book.class) + titlesAsc = session.createSelectionQuery("from Book order by isbn asc", Book.class) // .setOrder(emptyList()) - .setOrder(by(title, ASCENDING, true)) - .getResultList() - .stream().map(book -> book.title) - .collect(toList()); - assertEquals("Hibernate in Action", titlesAsc.get(0)); - assertEquals("Java Persistence with Hibernate", titlesAsc.get(1)); - }); - } + .setOrder(by(title, ASCENDING, true)) + .getResultList() + .stream().map(book -> book.title) + .collect(toList()); + assertEquals("Hibernate in Action", titlesAsc.get(0)); + assertEquals("Java Persistence with Hibernate", titlesAsc.get(1)); + }); + } - @Test void testAscendingDescendingBySelectElementCaseInsensitive(SessionFactoryScope scope) { - scope.inTransaction( session -> session.createMutationQuery("delete Book").executeUpdate() ); - scope.inTransaction( session -> { - session.persist(new Book("9781932394153", "Hibernate in Action")); - session.persist(new Book("9781617290459", "Java Persistence with Hibernate")); - }); - scope.inSession(session -> { - List titlesAsc = session.createSelectionQuery("select isbn, title from Book", Object[].class) - .setOrder(asc(2).ignoringCase()) - .getResultList() - .stream().map(book -> book[1]) - .collect(toList()); - assertEquals("Hibernate in Action", titlesAsc.get(0)); - assertEquals("Java Persistence with Hibernate", titlesAsc.get(1)); + @Test void testAscendingDescendingBySelectElementCaseInsensitive(SessionFactoryScope scope) { + scope.inTransaction( session -> session.createMutationQuery("delete Book").executeUpdate() ); + scope.inTransaction( session -> { + session.persist(new Book("9781932394153", "Hibernate in Action")); + session.persist(new Book("9781617290459", "Java Persistence with Hibernate")); + }); + scope.inSession(session -> { + List titlesAsc = session.createSelectionQuery("select isbn, title from Book", Object[].class) + .setOrder(asc(2).ignoringCase()) + .getResultList() + .stream().map(book -> book[1]) + .collect(toList()); + assertEquals("Hibernate in Action", titlesAsc.get(0)); + assertEquals("Java Persistence with Hibernate", titlesAsc.get(1)); - List titlesDesc = session.createSelectionQuery("select isbn, title from Book", Object[].class) - .setOrder(desc(2).ignoringCase()) - .getResultList() - .stream().map(book -> book[1]) - .collect(toList()); - assertEquals("Hibernate in Action", titlesDesc.get(1)); - assertEquals("Java Persistence with Hibernate", titlesDesc.get(0)); + List titlesDesc = session.createSelectionQuery("select isbn, title from Book", Object[].class) + .setOrder(desc(2).ignoringCase()) + .getResultList() + .stream().map(book -> book[1]) + .collect(toList()); + assertEquals("Hibernate in Action", titlesDesc.get(1)); + assertEquals("Java Persistence with Hibernate", titlesDesc.get(0)); - List isbnAsc = session.createSelectionQuery("select isbn, title from Book", Object[].class) - .setOrder(List.of(asc(1).ignoringCase(), desc(2).ignoringCase())) - .getResultList() - .stream().map(book -> book[1]) - .collect(toList()); - assertEquals("Hibernate in Action", isbnAsc.get(1)); - assertEquals("Java Persistence with Hibernate", isbnAsc.get(0)); + List isbnAsc = session.createSelectionQuery("select isbn, title from Book", Object[].class) + .setOrder(List.of(asc(1).ignoringCase(), desc(2).ignoringCase())) + .getResultList() + .stream().map(book -> book[1]) + .collect(toList()); + assertEquals("Hibernate in Action", isbnAsc.get(1)); + assertEquals("Java Persistence with Hibernate", isbnAsc.get(0)); - List isbnDesc = session.createSelectionQuery("select isbn, title from Book", Object[].class) - .setOrder(List.of(desc(1).ignoringCase(), desc(2).ignoringCase())) - .getResultList() - .stream().map(book -> book[1]) - .collect(toList()); - assertEquals("Hibernate in Action", isbnDesc.get(0)); - assertEquals("Java Persistence with Hibernate", isbnDesc.get(1)); - }); - } + List isbnDesc = session.createSelectionQuery("select isbn, title from Book", Object[].class) + .setOrder(List.of(desc(1).ignoringCase(), desc(2).ignoringCase())) + .getResultList() + .stream().map(book -> book[1]) + .collect(toList()); + assertEquals("Hibernate in Action", isbnDesc.get(0)); + assertEquals("Java Persistence with Hibernate", isbnDesc.get(1)); + }); + } - @Test void testAscendingDescendingBySelectElementCaseInsensitiveLongForm(SessionFactoryScope scope) { - scope.inTransaction( session -> session.createMutationQuery("delete Book").executeUpdate() ); - scope.inTransaction( session -> { - session.persist(new Book("9781932394153", "Hibernate in Action")); - session.persist(new Book("9781617290459", "Java Persistence with Hibernate")); - }); - scope.inSession(session -> { - List titlesAsc = session.createSelectionQuery("select isbn, title from Book", Object[].class) - .setOrder(by(2, ASCENDING, true)) - .getResultList() - .stream().map(book -> book[1]) - .collect(toList()); - assertEquals("Hibernate in Action", titlesAsc.get(0)); - assertEquals("Java Persistence with Hibernate", titlesAsc.get(1)); + @Test void testAscendingDescendingBySelectElementCaseInsensitiveLongForm(SessionFactoryScope scope) { + scope.inTransaction( session -> session.createMutationQuery("delete Book").executeUpdate() ); + scope.inTransaction( session -> { + session.persist(new Book("9781932394153", "Hibernate in Action")); + session.persist(new Book("9781617290459", "Java Persistence with Hibernate")); + }); + scope.inSession(session -> { + List titlesAsc = session.createSelectionQuery("select isbn, title from Book", Object[].class) + .setOrder(by(2, ASCENDING, true)) + .getResultList() + .stream().map(book -> book[1]) + .collect(toList()); + assertEquals("Hibernate in Action", titlesAsc.get(0)); + assertEquals("Java Persistence with Hibernate", titlesAsc.get(1)); - List titlesDesc = session.createSelectionQuery("select isbn, title from Book", Object[].class) - .setOrder(by(2, DESCENDING, true)) - .getResultList() - .stream().map(book -> book[1]) - .collect(toList()); - assertEquals("Hibernate in Action", titlesDesc.get(1)); - assertEquals("Java Persistence with Hibernate", titlesDesc.get(0)); + List titlesDesc = session.createSelectionQuery("select isbn, title from Book", Object[].class) + .setOrder(by(2, DESCENDING, true)) + .getResultList() + .stream().map(book -> book[1]) + .collect(toList()); + assertEquals("Hibernate in Action", titlesDesc.get(1)); + assertEquals("Java Persistence with Hibernate", titlesDesc.get(0)); - List isbnAsc = session.createSelectionQuery("select isbn, title from Book", Object[].class) - .setOrder(List.of(by(1, ASCENDING, true), by(2, DESCENDING, true))) - .getResultList() - .stream().map(book -> book[1]) - .collect(toList()); - assertEquals("Hibernate in Action", isbnAsc.get(1)); - assertEquals("Java Persistence with Hibernate", isbnAsc.get(0)); + List isbnAsc = session.createSelectionQuery("select isbn, title from Book", Object[].class) + .setOrder(List.of(by(1, ASCENDING, true), by(2, DESCENDING, true))) + .getResultList() + .stream().map(book -> book[1]) + .collect(toList()); + assertEquals("Hibernate in Action", isbnAsc.get(1)); + assertEquals("Java Persistence with Hibernate", isbnAsc.get(0)); - List isbnDesc = session.createSelectionQuery("select isbn, title from Book", Object[].class) - .setOrder(List.of(by(1, DESCENDING, true), by(2, DESCENDING, true))) - .getResultList() - .stream().map(book -> book[1]) - .collect(toList()); - assertEquals("Hibernate in Action", isbnDesc.get(0)); - assertEquals("Java Persistence with Hibernate", isbnDesc.get(1)); - }); - } + List isbnDesc = session.createSelectionQuery("select isbn, title from Book", Object[].class) + .setOrder(List.of(by(1, DESCENDING, true), by(2, DESCENDING, true))) + .getResultList() + .stream().map(book -> book[1]) + .collect(toList()); + assertEquals("Hibernate in Action", isbnDesc.get(0)); + assertEquals("Java Persistence with Hibernate", isbnDesc.get(1)); + }); + } - @Entity(name="Book") - static class Book { - @Id String isbn; - String title; + @Entity(name="Book") + static class Book { + @Id String isbn; + String title; - Book(String isbn, String title) { - this.isbn = isbn; - this.title = title; - } + Book(String isbn, String title) { + this.isbn = isbn; + this.title = title; + } - Book() { - } - } + Book() { + } + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/query/sqm/BasicSelectionQueryTests.java b/hibernate-core/src/test/java/org/hibernate/orm/test/query/sqm/BasicSelectionQueryTests.java index 0c9a63345b..bd7bbcec73 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/query/sqm/BasicSelectionQueryTests.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/query/sqm/BasicSelectionQueryTests.java @@ -191,9 +191,9 @@ public class BasicSelectionQueryTests { @Entity( name = "DummyEntity" ) @Table( name = "DummyEntity" ) public static class DummyEntity { - @Id - private Integer id; - @Basic + @Id + private Integer id; + @Basic private String name; private DummyEntity() { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/query/sqm/ConcurrentQueriesByIdsTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/query/sqm/ConcurrentQueriesByIdsTest.java index c144879374..1cc1cf1876 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/query/sqm/ConcurrentQueriesByIdsTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/query/sqm/ConcurrentQueriesByIdsTest.java @@ -69,7 +69,7 @@ public class ConcurrentQueriesByIdsTest extends BaseCoreFunctionalTestCase { .setParameter( "ids", Arrays.asList( base + 0, base + 1, base + 2, base + 3, base + 4, base + 5, - base + 6, base + 7, base + 8, base + 9 + base + 6, base + 7, base + 8, base + 9 ) ) .list(); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/query/sqm/exec/SubQueryImplicitJoinReferenceTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/query/sqm/exec/SubQueryImplicitJoinReferenceTest.java index 89525ccadd..9e0613ec1a 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/query/sqm/exec/SubQueryImplicitJoinReferenceTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/query/sqm/exec/SubQueryImplicitJoinReferenceTest.java @@ -29,152 +29,152 @@ import org.hibernate.testing.orm.junit.SessionFactoryScope; * @author Chris Cranford */ @DomainModel(annotatedClasses = { - SubQueryImplicitJoinReferenceTest.TheEntity.class, - SubQueryImplicitJoinReferenceTest.RevisionInfoEntity.class }) + SubQueryImplicitJoinReferenceTest.TheEntity.class, + SubQueryImplicitJoinReferenceTest.RevisionInfoEntity.class }) @SessionFactory @JiraKey(value = "HHH-14482") public class SubQueryImplicitJoinReferenceTest { - @Test - public void performDataPreparation(SessionFactoryScope scope) { - // Simulate creating revision 1 - final RevisionInfoEntity revEntity = new RevisionInfoEntity(); - revEntity.setId( 1 ); + @Test + public void performDataPreparation(SessionFactoryScope scope) { + // Simulate creating revision 1 + final RevisionInfoEntity revEntity = new RevisionInfoEntity(); + revEntity.setId( 1 ); - // Simulate creating the audit record - final TheEntity entity = new TheEntity(); - entity.setOriginalId( OriginalId.from( revEntity, 1 ) ); - entity.setData( "Test" ); + // Simulate creating the audit record + final TheEntity entity = new TheEntity(); + entity.setOriginalId( OriginalId.from( revEntity, 1 ) ); + entity.setData( "Test" ); - // Persist the entities - scope.inTransaction( session -> { session.persist( revEntity ); session.persist( entity ); } ); - } + // Persist the entities + scope.inTransaction( session -> { session.persist( revEntity ); session.persist( entity ); } ); + } - @Test - public void performHqlTest(SessionFactoryScope scope) { - // Now simulate running an audit query - scope.inSession( session -> { - session.createQuery( "select e__ FROM TheEntity e__ " - + "WHERE e__.originalId.rev.id = (select max(e2__.originalId.rev.id) FROM " - + "TheEntity e2__ WHERE " + - "e2__.originalId.rev.id <= 2 and e__.originalId.id = e2__.originalId.id)" ).list(); - } ); - } + @Test + public void performHqlTest(SessionFactoryScope scope) { + // Now simulate running an audit query + scope.inSession( session -> { + session.createQuery( "select e__ FROM TheEntity e__ " + + "WHERE e__.originalId.rev.id = (select max(e2__.originalId.rev.id) FROM " + + "TheEntity e2__ WHERE " + + "e2__.originalId.rev.id <= 2 and e__.originalId.id = e2__.originalId.id)" ).list(); + } ); + } - @Test - public void performHqlIsNullTest(SessionFactoryScope scope) { - // Now simulate running an audit query - scope.inSession( session -> { - session.createQuery( "select e__ FROM TheEntity e__ " - + "WHERE e__.originalId.rev.id = (select max(e2__.originalId.rev.id) FROM " - + "TheEntity e2__ WHERE " + - "e2__.originalId.rev is null)" ).list(); - } ); - } + @Test + public void performHqlIsNullTest(SessionFactoryScope scope) { + // Now simulate running an audit query + scope.inSession( session -> { + session.createQuery( "select e__ FROM TheEntity e__ " + + "WHERE e__.originalId.rev.id = (select max(e2__.originalId.rev.id) FROM " + + "TheEntity e2__ WHERE " + + "e2__.originalId.rev is null)" ).list(); + } ); + } - @Test - public void performHqlTest2(SessionFactoryScope scope) { - // Now simulate running an audit query - scope.inSession( session -> { - session.createQuery( "select e__ FROM TheEntity e__ " - + "WHERE e__.originalId.id = (select max(e2__.originalId.id) FROM " - + "TheEntity e2__ WHERE " + - "e__.originalId.id = e2__.originalId.id and e2__.originalId.rev.id <= 2)" ).list(); - } ); - } + @Test + public void performHqlTest2(SessionFactoryScope scope) { + // Now simulate running an audit query + scope.inSession( session -> { + session.createQuery( "select e__ FROM TheEntity e__ " + + "WHERE e__.originalId.id = (select max(e2__.originalId.id) FROM " + + "TheEntity e2__ WHERE " + + "e__.originalId.id = e2__.originalId.id and e2__.originalId.rev.id <= 2)" ).list(); + } ); + } - @Test - public void performHqlTest3(SessionFactoryScope scope) { - // Now simulate running an audit query - scope.inSession( session -> { - session.createQuery( "select e2__.originalId.id, e2__.originalId.rev.id FROM " - + "TheEntity e2__ WHERE " + - " e2__.originalId.rev.id <= 2" ).list(); - } ); - } + @Test + public void performHqlTest3(SessionFactoryScope scope) { + // Now simulate running an audit query + scope.inSession( session -> { + session.createQuery( "select e2__.originalId.id, e2__.originalId.rev.id FROM " + + "TheEntity e2__ WHERE " + + " e2__.originalId.rev.id <= 2" ).list(); + } ); + } - @Entity(name = "TheEntity") - public static class TheEntity { - @EmbeddedId - private OriginalId originalId; - private String data; + @Entity(name = "TheEntity") + public static class TheEntity { + @EmbeddedId + private OriginalId originalId; + private String data; - public OriginalId getOriginalId() { - return originalId; - } + public OriginalId getOriginalId() { + return originalId; + } - public void setOriginalId(OriginalId originalId) { - this.originalId = originalId; - } + public void setOriginalId(OriginalId originalId) { + this.originalId = originalId; + } - public String getData() { - return data; - } + public String getData() { + return data; + } - public void setData(String data) { - this.data = data; - } - } + public void setData(String data) { + this.data = data; + } + } - @Entity(name="RevisionInfoEntity") - public static class RevisionInfoEntity { - @Id - private Integer id; + @Entity(name="RevisionInfoEntity") + public static class RevisionInfoEntity { + @Id + private Integer id; - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } - } + public void setId(Integer id) { + this.id = id; + } + } - @Embeddable - public static class OriginalId implements Serializable { - @ManyToOne - private RevisionInfoEntity rev; - private Integer id; + @Embeddable + public static class OriginalId implements Serializable { + @ManyToOne + private RevisionInfoEntity rev; + private Integer id; - public RevisionInfoEntity getRev() { - return rev; - } + public RevisionInfoEntity getRev() { + return rev; + } - public void setRev(RevisionInfoEntity rev) { - this.rev = rev; - } + public void setRev(RevisionInfoEntity rev) { + this.rev = rev; + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public static OriginalId from(RevisionInfoEntity rev, Integer id) { - OriginalId oId = new OriginalId(); - oId.rev = rev; - oId.id = id; - return oId; - } + public static OriginalId from(RevisionInfoEntity rev, Integer id) { + OriginalId oId = new OriginalId(); + oId.rev = rev; + oId.id = id; + return oId; + } - @Override - public int hashCode() { - return Objects.hash(rev, id); - } + @Override + public int hashCode() { + return Objects.hash(rev, id); + } - @Override - public boolean equals(Object obj) { - if ( obj == null ) { - return false; - } - if ( obj.getClass() != this.getClass() ) { - return false; - } + @Override + public boolean equals(Object obj) { + if ( obj == null ) { + return false; + } + if ( obj.getClass() != this.getClass() ) { + return false; + } - final OriginalId other = (OriginalId) obj; - return Objects.equals( rev, other.rev ) && Objects.equals( id, other.id ); - } - } + final OriginalId other = (OriginalId) obj; + return Objects.equals( rev, other.rev ) && Objects.equals( id, other.id ); + } + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/query/sqm/mutation/BasicMutationQueryTests.java b/hibernate-core/src/test/java/org/hibernate/orm/test/query/sqm/mutation/BasicMutationQueryTests.java index 6be2fa533e..ffaf70d61b 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/query/sqm/mutation/BasicMutationQueryTests.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/query/sqm/mutation/BasicMutationQueryTests.java @@ -112,9 +112,9 @@ public class BasicMutationQueryTests { resultClass = BasicMutationQueryTests.SillyEntity.class ) public static class SillyEntity { - @Id - private Integer id; - @Basic + @Id + private Integer id; + @Basic private String name; private SillyEntity() { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/query/sqm/param/EmptyEntityCollectionParameterTests.java b/hibernate-core/src/test/java/org/hibernate/orm/test/query/sqm/param/EmptyEntityCollectionParameterTests.java index 912d9e30ed..1d0943a95e 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/query/sqm/param/EmptyEntityCollectionParameterTests.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/query/sqm/param/EmptyEntityCollectionParameterTests.java @@ -35,9 +35,9 @@ class EmptyEntityCollectionParameterTests { // Converting `org.hibernate.type.descriptor.java.spi.JdbcTypeRecommendationException` to JPA `PersistenceException` : // Could not determine recommended JdbcType for `org.hibernate.orm.test.query.sqm.param.EmptyEntityCollectionParameterTests$ContentEntry` scope.inTransaction( session -> - session.createQuery( "FROM DbEntity WHERE content IN (:vals)", DbEntity.class ) - .setParameter( "vals", Collections.emptyList() ) - .list() + session.createQuery( "FROM DbEntity WHERE content IN (:vals)", DbEntity.class ) + .setParameter( "vals", Collections.emptyList() ) + .list() ); } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/querycache/StringCompositeKey.java b/hibernate-core/src/test/java/org/hibernate/orm/test/querycache/StringCompositeKey.java index f79f81cb04..0f20b70163 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/querycache/StringCompositeKey.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/querycache/StringCompositeKey.java @@ -13,21 +13,21 @@ import jakarta.persistence.Embeddable; @Embeddable public class StringCompositeKey implements Serializable { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; - private String substation; +private String substation; - private String deviceType; + private String deviceType; - private String device; + private String device; - private String analog; + private String analog; - // For some dialects, the sum of a primary key column lengths cannot - // be larger than 255 (DB2). Restrict them to a sufficiently - // small size. See HHH-8085. + // For some dialects, the sum of a primary key column lengths cannot + // be larger than 255 (DB2). Restrict them to a sufficiently + // small size. See HHH-8085. - @Column( length = 50 ) + @Column( length = 50 ) public String getSubstation() { return substation; } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/quote/Phone.java b/hibernate-core/src/test/java/org/hibernate/orm/test/quote/Phone.java index e23e14b53e..b1af839523 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/quote/Phone.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/quote/Phone.java @@ -17,35 +17,35 @@ import jakarta.persistence.Table; @Table(name = "PHONE") public class Phone implements java.io.Serializable { - private Integer id; - private String brandName; - private float price; + private Integer id; + private String brandName; + private float price; - public Phone() { - } + public Phone() { + } @Id - @Column(name="ID") - public Integer getId() { - return id; - } - public void setId(Integer id) { - this.id = id; - } + @Column(name="ID") + public Integer getId() { + return id; + } + public void setId(Integer id) { + this.id = id; + } - @Column(name="BRANDNAME") - public String getBrandName() { - return brandName; - } - public void setBrandName(String bName) { - this.brandName = bName; - } + @Column(name="BRANDNAME") + public String getBrandName() { + return brandName; + } + public void setBrandName(String bName) { + this.brandName = bName; + } - @Column(name="PRICE") - public float getPrice() { - return price; - } - public void setPrice(float price) { - this.price = price; - } + @Column(name="PRICE") + public float getPrice() { + return price; + } + public void setPrice(float price) { + this.price = price; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/quote/QuoteGlobalTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/quote/QuoteGlobalTest.java index 23db99b877..bd75750831 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/quote/QuoteGlobalTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/quote/QuoteGlobalTest.java @@ -50,8 +50,8 @@ public class QuoteGlobalTest { @Test @JiraKey(value = "HHH-7890") public void testQuotedUniqueConstraint(SessionFactoryScope scope) { - Iterator itr = scope.getMetadataImplementor().getEntityBinding(Person.class.getName()) - .getTable().getUniqueKeys().values().iterator(); + Iterator itr = scope.getMetadataImplementor().getEntityBinding(Person.class.getName()) + .getTable().getUniqueKeys().values().iterator(); while ( itr.hasNext() ) { UniqueKey uk = itr.next(); assertEquals( 1, uk.getColumns().size() ); @@ -106,7 +106,7 @@ public class QuoteGlobalTest { private void doTestHbmQuoting(Class clazz, MetadataImplementor metadataImplementor) { Table table = metadataImplementor.getEntityBinding( clazz.getName() ).getTable(); assertTrue( table.isQuoted() ); - Iterator itr = table.getColumns().iterator(); + Iterator itr = table.getColumns().iterator(); while ( itr.hasNext() ) { Column column = (Column) itr.next(); assertTrue( column.isQuoted() ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/quote/Role.java b/hibernate-core/src/test/java/org/hibernate/orm/test/quote/Role.java index 37139c94f7..fca8e8bb8b 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/quote/Role.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/quote/Role.java @@ -19,8 +19,8 @@ import jakarta.persistence.Table; @Table(name = "`Role`") public class Role implements Serializable { - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - private long id; +@Id +@GeneratedValue(strategy = GenerationType.AUTO) +private long id; } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/readonly/ReadOnlySessionLazyNonLazyTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/readonly/ReadOnlySessionLazyNonLazyTest.java index 1f169696b3..8c391da18a 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/readonly/ReadOnlySessionLazyNonLazyTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/readonly/ReadOnlySessionLazyNonLazyTest.java @@ -335,7 +335,7 @@ public class ReadOnlySessionLazyNonLazyTest extends AbstractReadOnlyTest { @SuppressWarnings( {"unchecked"}) @Test - public void testExistingReadOnlyAfterSetSessionModifiableExistingEntityReadOnly(SessionFactoryScope scope) { + public void testExistingReadOnlyAfterSetSessionModifiableExistingEntityReadOnly(SessionFactoryScope scope) { Container cOrig = createContainer(); Set expectedInitializedObjects = new HashSet( Arrays.asList( diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/records/EmbeddableInstantiatorTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/records/EmbeddableInstantiatorTest.java index 3da8ebf230..ce0d472b6c 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/records/EmbeddableInstantiatorTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/records/EmbeddableInstantiatorTest.java @@ -86,7 +86,7 @@ public class EmbeddableInstantiatorTest { @Override public Object instantiate(ValueAccess valueAccess, SessionFactoryImplementor sessionFactory) { return new MyRecord( valueAccess.getValue( 2, Integer.class ), valueAccess.getValue( 1, String.class ), - valueAccess.getValue( 0, LocalDate.class ) + valueAccess.getValue( 0, LocalDate.class ) ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/records/GenericEnbeddedIdRecordTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/records/GenericEnbeddedIdRecordTest.java index c21c2f65e2..87e36c5928 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/records/GenericEnbeddedIdRecordTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/records/GenericEnbeddedIdRecordTest.java @@ -33,47 +33,47 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; @DomainModel(annotatedClasses = {GenericEnbeddedIdRecordTest.MainEntity.class, GenericEnbeddedIdRecordTest.ReferencedEntity.class}) class GenericEnbeddedIdRecordTest { - @Test - void testOverrideJoinColumn(SessionFactoryScope scope) { - scope.inTransaction(entityManager -> { - MainEntity mainEntity = new MainEntity(); - ReferencedEntity referencedEntity = new ReferencedEntity(); - mainEntity.id = new GenericEmbeddedId<>(referencedEntity); - referencedEntity.entities = Collections.singleton(mainEntity); - entityManager.persist(referencedEntity); - assertNotNull(mainEntity); - }); - } + @Test + void testOverrideJoinColumn(SessionFactoryScope scope) { + scope.inTransaction(entityManager -> { + MainEntity mainEntity = new MainEntity(); + ReferencedEntity referencedEntity = new ReferencedEntity(); + mainEntity.id = new GenericEmbeddedId<>(referencedEntity); + referencedEntity.entities = Collections.singleton(mainEntity); + entityManager.persist(referencedEntity); + assertNotNull(mainEntity); + }); + } - @Embeddable - public record GenericEmbeddedId(@ManyToOne(fetch = FetchType.EAGER) - @JoinColumn(name = "REFERENCED_ENTITY_ID") - T referencedEntity) { - } + @Embeddable + public record GenericEmbeddedId(@ManyToOne(fetch = FetchType.EAGER) + @JoinColumn(name = "REFERENCED_ENTITY_ID") + T referencedEntity) { + } - @Entity - public static class MainEntity { + @Entity + public static class MainEntity { - @EmbeddedId - private GenericEmbeddedId id; + @EmbeddedId + private GenericEmbeddedId id; - @Column(name = "DESCRIPTION") - private String description; + @Column(name = "DESCRIPTION") + private String description; - } + } - @Entity - public static class ReferencedEntity { + @Entity + public static class ReferencedEntity { - @Id - @GeneratedValue(strategy = GenerationType.SEQUENCE, - generator = "REFERENCED_ENTITY_ID_GEN") - @SequenceGenerator(name = "REFERENCED_ENTITY_ID_GEN") - @Column(name = "REFERENCED_ENTITY_ID") - private Long id; + @Id + @GeneratedValue(strategy = GenerationType.SEQUENCE, + generator = "REFERENCED_ENTITY_ID_GEN") + @SequenceGenerator(name = "REFERENCED_ENTITY_ID_GEN") + @Column(name = "REFERENCED_ENTITY_ID") + private Long id; - @OneToMany(mappedBy = "id.referencedEntity", cascade = CascadeType.ALL) - private Collection entities; + @OneToMany(mappedBy = "id.referencedEntity", cascade = CascadeType.ALL) + private Collection entities; - } + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/rowid/RowIdTest2.java b/hibernate-core/src/test/java/org/hibernate/orm/test/rowid/RowIdTest2.java index 607ab409ab..b583f9915f 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/rowid/RowIdTest2.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/rowid/RowIdTest2.java @@ -51,7 +51,7 @@ public class RowIdTest2 { st, "create table Point (\"x\" number(19,2) not null, \"y\" number(19,2) not null, description varchar2(255) )" ); - session.getJdbcCoordinator().getLogicalConnection().getResourceRegistry().release( st ); + session.getJdbcCoordinator().getLogicalConnection().getResourceRegistry().release( st ); } ) ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/schema/ColumnDefaultTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/schema/ColumnDefaultTest.java index 5f4cd681ea..85897ea765 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/schema/ColumnDefaultTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/schema/ColumnDefaultTest.java @@ -23,71 +23,71 @@ import static org.junit.Assert.assertEquals; */ public class ColumnDefaultTest extends BaseEntityManagerFunctionalTestCase { - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Person.class, - }; - } + @Override + protected Class[] getAnnotatedClasses() { + return new Class[] { + Person.class, + }; + } - @Test - public void test() { + @Test + public void test() { //tag::schema-generation-column-default-value-persist-example[] - doInJPA(this::entityManagerFactory, entityManager -> { - Person person = new Person(); - person.setId(1L); - entityManager.persist(person); - }); - doInJPA(this::entityManagerFactory, entityManager -> { - Person person = entityManager.find(Person.class, 1L); - assertEquals("N/A", person.getName()); - assertEquals(Long.valueOf(-1L), person.getClientId()); - }); + doInJPA(this::entityManagerFactory, entityManager -> { + Person person = new Person(); + person.setId(1L); + entityManager.persist(person); + }); + doInJPA(this::entityManagerFactory, entityManager -> { + Person person = entityManager.find(Person.class, 1L); + assertEquals("N/A", person.getName()); + assertEquals(Long.valueOf(-1L), person.getClientId()); + }); //end::schema-generation-column-default-value-persist-example[] - } + } - //tag::schema-generation-column-default-value-mapping-example[] - @Entity(name = "Person") - @DynamicInsert - public static class Person { + //tag::schema-generation-column-default-value-mapping-example[] + @Entity(name = "Person") + @DynamicInsert + public static class Person { - @Id - private Long id; + @Id + private Long id; - @ColumnDefault("'N/A'") - private String name; + @ColumnDefault("'N/A'") + private String name; - @ColumnDefault("-1") - private Long clientId; + @ColumnDefault("-1") + private Long clientId; - //Getter and setters omitted for brevity + //Getter and setters omitted for brevity - //end::schema-generation-column-default-value-mapping-example[] + //end::schema-generation-column-default-value-mapping-example[] - public Long getId() { - return id; - } + public Long getId() { + return id; + } - public void setId(Long id) { - this.id = id; - } + public void setId(Long id) { + this.id = id; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - public Long getClientId() { - return clientId; - } + public Long getClientId() { + return clientId; + } - public void setClientId(Long clientId) { - this.clientId = clientId; - } - //tag::schema-generation-column-default-value-mapping-example[] - } - //end::schema-generation-column-default-value-mapping-example[] + public void setClientId(Long clientId) { + this.clientId = clientId; + } + //tag::schema-generation-column-default-value-mapping-example[] + } + //end::schema-generation-column-default-value-mapping-example[] } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/schema/IndexTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/schema/IndexTest.java index 5475d1c72a..8e5b722a66 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/schema/IndexTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/schema/IndexTest.java @@ -25,73 +25,73 @@ import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; public class IndexTest extends BaseEntityManagerFunctionalTestCase { - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Author.class, - }; - } + @Override + protected Class[] getAnnotatedClasses() { + return new Class[] { + Author.class, + }; + } - @Test - public void test() { - doInJPA(this::entityManagerFactory, entityManager -> { - Author author = new Author(); - author.setFirstName("Vlad"); - author.setLastName("Mihalcea"); - entityManager.persist(author); - }); - } + @Test + public void test() { + doInJPA(this::entityManagerFactory, entityManager -> { + Author author = new Author(); + author.setFirstName("Vlad"); + author.setLastName("Mihalcea"); + entityManager.persist(author); + }); + } - //tag::schema-generation-columns-index-mapping-example[] - @Entity - @Table( - name = "author", - indexes = @Index( - name = "idx_author_first_last_name", - columnList = "first_name, last_name", - unique = false - ) - ) - public static class Author { + //tag::schema-generation-columns-index-mapping-example[] + @Entity + @Table( + name = "author", + indexes = @Index( + name = "idx_author_first_last_name", + columnList = "first_name, last_name", + unique = false + ) +) + public static class Author { - @Id - @GeneratedValue - private Long id; + @Id + @GeneratedValue + private Long id; - @Column(name = "first_name") - private String firstName; + @Column(name = "first_name") + private String firstName; - @Column(name = "last_name") - private String lastName; + @Column(name = "last_name") + private String lastName; - //Getter and setters omitted for brevity - //end::schema-generation-columns-index-mapping-example[] + //Getter and setters omitted for brevity + //end::schema-generation-columns-index-mapping-example[] - public Long getId() { - return id; - } + public Long getId() { + return id; + } - public void setId(Long id) { - this.id = id; - } + public void setId(Long id) { + this.id = id; + } - public String getFirstName() { - return firstName; - } + public String getFirstName() { + return firstName; + } - public void setFirstName(String firstName) { - this.firstName = firstName; - } + public void setFirstName(String firstName) { + this.firstName = firstName; + } - public String getLastName() { - return lastName; - } + public String getLastName() { + return lastName; + } - public void setLastName(String lastName) { - this.lastName = lastName; - } + public void setLastName(String lastName) { + this.lastName = lastName; + } - //tag::schema-generation-columns-index-mapping-example[] - } - //end::schema-generation-columns-index-mapping-example[] + //tag::schema-generation-columns-index-mapping-example[] + } + //end::schema-generation-columns-index-mapping-example[] } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/schema/UniqueConstraintTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/schema/UniqueConstraintTest.java index 9e0c0e2704..f21c916561 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/schema/UniqueConstraintTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/schema/UniqueConstraintTest.java @@ -32,144 +32,144 @@ import static org.junit.Assert.assertNotNull; public class UniqueConstraintTest extends BaseEntityManagerFunctionalTestCase { - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Book.class, - Author.class, - }; - } + @Override + protected Class[] getAnnotatedClasses() { + return new Class[] { + Book.class, + Author.class, + }; + } - @Test - public void test() { - //tag::schema-generation-columns-unique-constraint-persist-example[] - Author _author = doInJPA(this::entityManagerFactory, entityManager -> { - Author author = new Author(); - author.setFirstName("Vlad"); - author.setLastName("Mihalcea"); - entityManager.persist(author); + @Test + public void test() { + //tag::schema-generation-columns-unique-constraint-persist-example[] + Author _author = doInJPA(this::entityManagerFactory, entityManager -> { + Author author = new Author(); + author.setFirstName("Vlad"); + author.setLastName("Mihalcea"); + entityManager.persist(author); - Book book = new Book(); - book.setTitle("High-Performance Java Persistence"); - book.setAuthor(author); - entityManager.persist(book); + Book book = new Book(); + book.setTitle("High-Performance Java Persistence"); + book.setAuthor(author); + entityManager.persist(book); - return author; - }); + return author; + }); - try { - doInJPA(this::entityManagerFactory, entityManager -> { + try { + doInJPA(this::entityManagerFactory, entityManager -> { Book book = new Book(); book.setTitle("High-Performance Java Persistence"); book.setAuthor(_author); entityManager.persist(book); }); - } - catch (Exception expected) { - assertNotNull(ExceptionUtil.findCause(expected, ConstraintViolationException.class)); - } - //end::schema-generation-columns-unique-constraint-persist-example[] - } + } + catch (Exception expected) { + assertNotNull(ExceptionUtil.findCause(expected, ConstraintViolationException.class)); + } + //end::schema-generation-columns-unique-constraint-persist-example[] + } - //tag::schema-generation-columns-unique-constraint-mapping-example[] - @Entity - @Table( - name = "book", - uniqueConstraints = @UniqueConstraint( - name = "uk_book_title_author", - columnNames = { - "title", - "author_id" - } - ) - ) - public static class Book { + //tag::schema-generation-columns-unique-constraint-mapping-example[] + @Entity + @Table( + name = "book", + uniqueConstraints = @UniqueConstraint( + name = "uk_book_title_author", + columnNames = { + "title", + "author_id" + } + ) +) + public static class Book { - @Id - @GeneratedValue - private Long id; + @Id + @GeneratedValue + private Long id; - private String title; + private String title; - @ManyToOne(fetch = FetchType.LAZY) - @JoinColumn( - name = "author_id", - foreignKey = @ForeignKey(name = "fk_book_author_id") - ) - private Author author; + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn( + name = "author_id", + foreignKey = @ForeignKey(name = "fk_book_author_id") + ) + private Author author; - //Getter and setters omitted for brevity - //end::schema-generation-columns-unique-constraint-mapping-example[] + //Getter and setters omitted for brevity + //end::schema-generation-columns-unique-constraint-mapping-example[] - public Long getId() { - return id; - } + public Long getId() { + return id; + } - public void setId(Long id) { - this.id = id; - } + public void setId(Long id) { + this.id = id; + } - public String getTitle() { - return title; - } + public String getTitle() { + return title; + } - public void setTitle(String title) { - this.title = title; - } + public void setTitle(String title) { + this.title = title; + } - public Author getAuthor() { - return author; - } + public Author getAuthor() { + return author; + } - public void setAuthor(Author author) { - this.author = author; - } + public void setAuthor(Author author) { + this.author = author; + } - //tag::schema-generation-columns-unique-constraint-mapping-example[] - } + //tag::schema-generation-columns-unique-constraint-mapping-example[] + } - @Entity - @Table(name = "author") - public static class Author { + @Entity + @Table(name = "author") + public static class Author { - @Id - @GeneratedValue - private Long id; + @Id + @GeneratedValue + private Long id; - @Column(name = "first_name") - private String firstName; + @Column(name = "first_name") + private String firstName; - @Column(name = "last_name") - private String lastName; + @Column(name = "last_name") + private String lastName; - //Getter and setters omitted for brevity - //end::schema-generation-columns-unique-constraint-mapping-example[] + //Getter and setters omitted for brevity + //end::schema-generation-columns-unique-constraint-mapping-example[] - public Long getId() { - return id; - } + public Long getId() { + return id; + } - public void setId(Long id) { - this.id = id; - } + public void setId(Long id) { + this.id = id; + } - public String getFirstName() { - return firstName; - } + public String getFirstName() { + return firstName; + } - public void setFirstName(String firstName) { - this.firstName = firstName; - } + public void setFirstName(String firstName) { + this.firstName = firstName; + } - public String getLastName() { - return lastName; - } + public String getLastName() { + return lastName; + } - public void setLastName(String lastName) { - this.lastName = lastName; - } + public void setLastName(String lastName) { + this.lastName = lastName; + } - //tag::schema-generation-columns-unique-constraint-mapping-example[] - } - //end::schema-generation-columns-unique-constraint-mapping-example[] + //tag::schema-generation-columns-unique-constraint-mapping-example[] + } + //end::schema-generation-columns-unique-constraint-mapping-example[] } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/schemamanager/SchemaManagerLoadScriptTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/schemamanager/SchemaManagerLoadScriptTest.java index e96776ee11..85b616ceb6 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/schemamanager/SchemaManagerLoadScriptTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/schemamanager/SchemaManagerLoadScriptTest.java @@ -34,7 +34,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; @DomainModel(annotatedClasses = {SchemaManagerLoadScriptTest.Book.class, SchemaManagerLoadScriptTest.Author.class}) @SessionFactory(exportSchema = false) @ServiceRegistry(settings = @Setting(name = JAKARTA_HBM2DDL_LOAD_SCRIPT_SOURCE, - value = "org/hibernate/orm/test/schemamanager/data.sql")) + value = "org/hibernate/orm/test/schemamanager/data.sql")) @RequiresDialectFeature(feature= DialectFeatureChecks.SupportsTruncateTable.class) public class SchemaManagerLoadScriptTest { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/schematools/EnumCheckColumnDefinitionTests.java b/hibernate-core/src/test/java/org/hibernate/orm/test/schematools/EnumCheckColumnDefinitionTests.java index 987bc58ac3..741f31f21f 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/schematools/EnumCheckColumnDefinitionTests.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/schematools/EnumCheckColumnDefinitionTests.java @@ -137,9 +137,9 @@ public class EnumCheckColumnDefinitionTests { @Entity( name = "SimpleEntity" ) @Table( name = "SimpleEntity" ) public static class SimpleEntity { - @Id - private Integer id; - @Basic + @Id + private Integer id; + @Basic private String name; @Column(columnDefinition = "enum ('SOURCE','CLASS','RUNTIME')") @Enumerated(EnumType.STRING) diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/schematools/EnumCheckTests.java b/hibernate-core/src/test/java/org/hibernate/orm/test/schematools/EnumCheckTests.java index a08c39699c..2fac79645d 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/schematools/EnumCheckTests.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/schematools/EnumCheckTests.java @@ -143,9 +143,9 @@ public class EnumCheckTests { @Entity( name = "SimpleEntity" ) @Table( name = "SimpleEntity" ) public static class SimpleEntity { - @Id - private Integer id; - @Basic + @Id + private Integer id; + @Basic private String name; @Enumerated(EnumType.STRING) RetentionPolicy retentionPolicy; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/schematools/FallbackSchemaManagementToolTests.java b/hibernate-core/src/test/java/org/hibernate/orm/test/schematools/FallbackSchemaManagementToolTests.java index 187f771fb1..f39bb270d6 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/schematools/FallbackSchemaManagementToolTests.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/schematools/FallbackSchemaManagementToolTests.java @@ -136,9 +136,9 @@ public class FallbackSchemaManagementToolTests { @Entity( name = "SimpleEntity" ) @Table( name = "SimpleEntity" ) public static class SimpleEntity { - @Id - private Integer id; - @Basic + @Id + private Integer id; + @Basic private String name; private SimpleEntity() { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/schematools/PrimaryKeyColumnOrderTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/schematools/PrimaryKeyColumnOrderTest.java index 3ae163de62..50848754ce 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/schematools/PrimaryKeyColumnOrderTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/schematools/PrimaryKeyColumnOrderTest.java @@ -110,8 +110,8 @@ public class PrimaryKeyColumnOrderTest extends BaseSessionFactoryFunctionalTest List pkColumnNames = new ArrayList<>(); primaryKey.getColumns().forEach( columnInformation -> { pkColumnNames.add( columnInformation.getColumnIdentifier() - .getCanonicalName() - .toLowerCase( Locale.ROOT ) ); + .getCanonicalName() + .toLowerCase( Locale.ROOT ) ); } ); assertThat( pkColumnNames.size() ).isEqualTo( 2 ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/PostgreSQLMultipleSchemaSequenceTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/PostgreSQLMultipleSchemaSequenceTest.java index ea7fe00470..50eeb9425b 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/PostgreSQLMultipleSchemaSequenceTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/PostgreSQLMultipleSchemaSequenceTest.java @@ -155,10 +155,10 @@ public class PostgreSQLMultipleSchemaSequenceTest extends BaseUnitTestCase { final List sqlLines = Files.readAllLines( output.toPath(), Charset.defaultCharset() ); assertEquals( 2 , - sqlLines - .stream() - .filter( s -> s.equalsIgnoreCase( "create sequence SEQ_TEST start with 1 increment by 1;" ) ) - .count() + sqlLines + .stream() + .filter( s -> s.equalsIgnoreCase( "create sequence SEQ_TEST start with 1 increment by 1;" ) ) + .count() ); } catch (IOException e) { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/SchemaExportTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/SchemaExportTest.java index 6010e847e6..2b16f1e983 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/SchemaExportTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/SchemaExportTest.java @@ -38,22 +38,22 @@ import static org.junit.Assert.assertTrue; * @author Gail Badner */ public class SchemaExportTest extends BaseUnitTestCase { - private boolean doesDialectSupportDropTableIfExist() { + private boolean doesDialectSupportDropTableIfExist() { final Dialect dialect = metadata.getDatabase().getDialect(); return dialect.supportsIfExistsAfterTableName() || dialect.supportsIfExistsBeforeTableName(); - } + } protected ServiceRegistry serviceRegistry; - protected MetadataImplementor metadata; + protected MetadataImplementor metadata; @Before public void setUp() { serviceRegistry = ServiceRegistryBuilder.buildServiceRegistry( Environment.getProperties() ); - metadata = (MetadataImplementor) new MetadataSources( serviceRegistry ) - .addResource( "org/hibernate/orm/test/schemaupdate/mapping.hbm.xml" ) - .buildMetadata(); + metadata = (MetadataImplementor) new MetadataSources( serviceRegistry ) + .addResource( "org/hibernate/orm/test/schemaupdate/mapping.hbm.xml" ) + .buildMetadata(); metadata.orderColumns( false ); - metadata.validate(); + metadata.validate(); new SchemaExport().drop( EnumSet.of( TargetType.DATABASE, TargetType.STDOUT ), metadata ); } @@ -64,37 +64,37 @@ public class SchemaExportTest extends BaseUnitTestCase { serviceRegistry = null; } - @Test - public void testCreateAndDropOnlyType() { + @Test + public void testCreateAndDropOnlyType() { final SchemaExport schemaExport = new SchemaExport(); - // create w/o dropping first; (OK because tables don't exist yet - schemaExport.execute( EnumSet.of( TargetType.DATABASE ), SchemaExport.Action.CREATE, metadata ); - assertEquals( 0, schemaExport.getExceptions().size() ); - - // create w/o dropping again; should cause an exception because the tables exist already + // create w/o dropping first; (OK because tables don't exist yet schemaExport.execute( EnumSet.of( TargetType.DATABASE ), SchemaExport.Action.CREATE, metadata ); - assertEquals( 1, schemaExport.getExceptions().size() ); + assertEquals( 0, schemaExport.getExceptions().size() ); - // drop tables only + // create w/o dropping again; should cause an exception because the tables exist already + schemaExport.execute( EnumSet.of( TargetType.DATABASE ), SchemaExport.Action.CREATE, metadata ); + assertEquals( 1, schemaExport.getExceptions().size() ); + + // drop tables only schemaExport.execute( EnumSet.of( TargetType.DATABASE ), SchemaExport.Action.DROP, metadata ); - assertEquals( 0, schemaExport.getExceptions().size() ); - } + assertEquals( 0, schemaExport.getExceptions().size() ); + } - @Test - public void testBothType() { + @Test + public void testBothType() { final SchemaExport schemaExport = new SchemaExport(); - // drop before create (nothing to drop yeT) - schemaExport.execute( EnumSet.of( TargetType.DATABASE ), SchemaExport.Action.DROP, metadata ); - if ( doesDialectSupportDropTableIfExist() ) { - assertEquals( 0, schemaExport.getExceptions().size() ); - } - else { - assertEquals( 1, schemaExport.getExceptions().size() ); - } + // drop before create (nothing to drop yeT) + schemaExport.execute( EnumSet.of( TargetType.DATABASE ), SchemaExport.Action.DROP, metadata ); + if ( doesDialectSupportDropTableIfExist() ) { + assertEquals( 0, schemaExport.getExceptions().size() ); + } + else { + assertEquals( 1, schemaExport.getExceptions().size() ); + } - // drop before create again (this time drops the tables before re-creating) + // drop before create again (this time drops the tables before re-creating) schemaExport.execute( EnumSet.of( TargetType.DATABASE ), SchemaExport.Action.BOTH, metadata ); int exceptionCount = schemaExport.getExceptions().size(); if ( doesDialectSupportDropTableIfExist() ) { @@ -103,47 +103,47 @@ public class SchemaExportTest extends BaseUnitTestCase { // drop tables schemaExport.execute( EnumSet.of( TargetType.DATABASE ), SchemaExport.Action.DROP, metadata ); - assertEquals( 0, schemaExport.getExceptions().size() ); - } + assertEquals( 0, schemaExport.getExceptions().size() ); + } - @Test - public void testGenerateDdlToFile() { + @Test + public void testGenerateDdlToFile() { final SchemaExport schemaExport = new SchemaExport(); - File outFile = new File("schema.ddl"); - schemaExport.setOutputFile( outFile.getPath() ); + File outFile = new File("schema.ddl"); + schemaExport.setOutputFile( outFile.getPath() ); - // do not script to console or export to database - schemaExport.execute( EnumSet.of( TargetType.SCRIPT ), SchemaExport.Action.DROP, metadata ); - if ( doesDialectSupportDropTableIfExist() && schemaExport.getExceptions().size() > 0 ) { - assertEquals( 2, schemaExport.getExceptions().size() ); - } - assertTrue( outFile.exists() ); + // do not script to console or export to database + schemaExport.execute( EnumSet.of( TargetType.SCRIPT ), SchemaExport.Action.DROP, metadata ); + if ( doesDialectSupportDropTableIfExist() && schemaExport.getExceptions().size() > 0 ) { + assertEquals( 2, schemaExport.getExceptions().size() ); + } + assertTrue( outFile.exists() ); - //check file is not empty - assertTrue( outFile.length() > 0 ); - outFile.delete(); - } + //check file is not empty + assertTrue( outFile.length() > 0 ); + outFile.delete(); + } - @Test - public void testCreateAndDrop() { + @Test + public void testCreateAndDrop() { final SchemaExport schemaExport = new SchemaExport(); - // should drop before creating, but tables don't exist yet - schemaExport.create( EnumSet.of( TargetType.DATABASE ), metadata ); + // should drop before creating, but tables don't exist yet + schemaExport.create( EnumSet.of( TargetType.DATABASE ), metadata ); if ( doesDialectSupportDropTableIfExist() ) { assertEquals( 0, schemaExport.getExceptions().size() ); } else { assertEquals( 1, schemaExport.getExceptions().size() ); } - // call create again; it should drop tables before re-creating + // call create again; it should drop tables before re-creating schemaExport.create( EnumSet.of( TargetType.DATABASE ), metadata ); - assertEquals( 0, schemaExport.getExceptions().size() ); - // drop the tables + assertEquals( 0, schemaExport.getExceptions().size() ); + // drop the tables schemaExport.drop( EnumSet.of( TargetType.DATABASE ), metadata ); - assertEquals( 0, schemaExport.getExceptions().size() ); - } + assertEquals( 0, schemaExport.getExceptions().size() ); + } @Test @JiraKey(value = "HHH-10678") diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/SchemaUpdateSQLServerTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/SchemaUpdateSQLServerTest.java index e3cc959d7f..1ea5b9964f 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/SchemaUpdateSQLServerTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/SchemaUpdateSQLServerTest.java @@ -240,8 +240,8 @@ public class SchemaUpdateSQLServerTest extends BaseUnitTestCase { String match; @ElementCollection - @CollectionTable(catalog = "hibernate_orm_test_collation", schema = "dbo") - private Map timeline = new TreeMap<>(); + @CollectionTable(catalog = "hibernate_orm_test_collation", schema = "dbo") + private Map timeline = new TreeMap<>(); } @Entity(name = "InheritanceRootEntity") diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/SchemaUpdateTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/SchemaUpdateTest.java index e2c973fcd3..1a454e613f 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/SchemaUpdateTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/SchemaUpdateTest.java @@ -233,8 +233,8 @@ public class SchemaUpdateTest { String match; @ElementCollection - @CollectionTable - private Map timeline = new TreeMap<>(); + @CollectionTable + private Map timeline = new TreeMap<>(); } @Entity(name = "InheritanceRootEntity") diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/foreignkeys/ForeignKeyGenerationTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/foreignkeys/ForeignKeyGenerationTest.java index f9230416af..eff6d0c590 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/foreignkeys/ForeignKeyGenerationTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/foreignkeys/ForeignKeyGenerationTest.java @@ -107,9 +107,9 @@ public class ForeignKeyGenerationTest extends BaseUnitTestCase { /* The generated SQL for the foreign keys should be: - alter table PERSON_PHONE add constraint PERSON_ID_FK foreign key (PERSON_ID) references PERSON - alter table PERSON_PHONE add constraint PHONE_ID_FK foreign key (PHONE_ID) references PHONE - */ + alter table PERSON_PHONE add constraint PERSON_ID_FK foreign key (PERSON_ID) references PERSON + alter table PERSON_PHONE add constraint PHONE_ID_FK foreign key (PHONE_ID) references PHONE + */ checkAlterTableStatement( new AlterTableStatement( ssr, "PERSON_PHONE", @@ -131,11 +131,11 @@ public class ForeignKeyGenerationTest extends BaseUnitTestCase { public void manyToManyTest() throws Exception { createSchema( new Class[] {Project.class, Employee.class} ); - /* + /* The generated SQL for the foreign keys should be: - alter table EMPLOYEE_PROJECT add constraint FK_EMPLOYEE foreign key (EMPLOYEE_ID) references EMPLOYEE - alter table EMPLOYEE_PROJECT add constraint FK_PROJECT foreign key (PROJECT_ID) references PROJECT - */ + alter table EMPLOYEE_PROJECT add constraint FK_EMPLOYEE foreign key (EMPLOYEE_ID) references EMPLOYEE + alter table EMPLOYEE_PROJECT add constraint FK_PROJECT foreign key (PROJECT_ID) references PROJECT + */ checkAlterTableStatement( new AlterTableStatement( ssr, "EMPLOYEE_PROJECT", diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/secondarytable/Record.java b/hibernate-core/src/test/java/org/hibernate/orm/test/secondarytable/Record.java index 5f677b5fd0..72564b608f 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/secondarytable/Record.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/secondarytable/Record.java @@ -24,9 +24,9 @@ import jakarta.persistence.Table; @SecondaryRow(table = "Optional", optional = true) @SequenceGenerator(name="RecordSeq", sequenceName = "RecordId", allocationSize = 1) public class Record { - @Id @GeneratedValue(generator = "RecordSeq") long id; - String name; - @Column(table = "NonOptional") String text; - @Column(table = "NonOptional") boolean enabled; - @Column(table = "Optional", name="`comment`") String comment; + @Id @GeneratedValue(generator = "RecordSeq") long id; + String name; + @Column(table = "NonOptional") String text; + @Column(table = "NonOptional") boolean enabled; + @Column(table = "Optional", name="`comment`") String comment; } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/secondarytable/SpecialRecord.java b/hibernate-core/src/test/java/org/hibernate/orm/test/secondarytable/SpecialRecord.java index cdbecacc19..d6475efb8b 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/secondarytable/SpecialRecord.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/secondarytable/SpecialRecord.java @@ -18,6 +18,6 @@ import jakarta.persistence.SecondaryTable; @SecondaryTable(name = "`View`") @SecondaryRow(table = "`View`", owned = false) public class SpecialRecord extends Record { - @Column(table = "`View`", name="`timestamp`") - Instant timestamp; + @Column(table = "`View`", name="`timestamp`") + Instant timestamp; } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/serialization/CacheKeySerializationTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/serialization/CacheKeySerializationTest.java index 9cfaee5267..f468bf98be 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/serialization/CacheKeySerializationTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/serialization/CacheKeySerializationTest.java @@ -42,93 +42,93 @@ import static org.junit.jupiter.api.Assertions.assertTrue; */ @BaseUnitTest public class CacheKeySerializationTest { - private SessionFactoryImplementor getSessionFactory(String cacheKeysFactory) { - Configuration configuration = new Configuration() - .setProperty(Environment.USE_SECOND_LEVEL_CACHE, true) - .setProperty(Environment.CACHE_REGION_FACTORY, CachingRegionFactory.class) - .setProperty(Environment.DEFAULT_CACHE_CONCURRENCY_STRATEGY, CacheConcurrencyStrategy.TRANSACTIONAL) - .setProperty(Environment.JPA_SHARED_CACHE_MODE, SharedCacheMode.ALL) - .setProperty(Environment.HBM2DDL_AUTO, Action.ACTION_CREATE_THEN_DROP); - ServiceRegistryUtil.applySettings( configuration.getStandardServiceRegistryBuilder() ); - if (cacheKeysFactory != null) { - configuration.setProperty(Environment.CACHE_KEYS_FACTORY, cacheKeysFactory); - } - configuration.addAnnotatedClass( WithSimpleId.class ); - configuration.addAnnotatedClass( WithEmbeddedId.class ); - return (SessionFactoryImplementor) configuration.buildSessionFactory(); - } - - @Test - @JiraKey(value = "HHH-11202") - public void testSimpleCacheKeySimpleId() throws Exception { - testId( SimpleCacheKeysFactory.INSTANCE, WithSimpleId.class.getName(), 1L ); - } - - @Test - @JiraKey(value = "HHH-11202") - public void testSimpleCacheKeyEmbeddedId() throws Exception { - testId( SimpleCacheKeysFactory.INSTANCE, WithEmbeddedId.class.getName(), new PK( 1L ) ); - } - - @Test - @JiraKey(value = "HHH-11202") - public void testDefaultCacheKeySimpleId() throws Exception { - testId( DefaultCacheKeysFactory.INSTANCE, WithSimpleId.class.getName(), 1L ); - } - - @Test - @JiraKey(value = "HHH-11202") - public void testDefaultCacheKeyEmbeddedId() throws Exception { - testId( DefaultCacheKeysFactory.INSTANCE, WithEmbeddedId.class.getName(), new PK( 1L ) ); - } - - private void testId(CacheKeysFactory cacheKeysFactory, String entityName, Object id) throws Exception { - final SessionFactoryImplementor sessionFactory = getSessionFactory(cacheKeysFactory.getClass().getName()); - final EntityPersister persister = sessionFactory.getRuntimeMetamodels().getMappingMetamodel().getEntityDescriptor(entityName); - final Object key = cacheKeysFactory.createEntityKey( - id, - persister, - sessionFactory, - null - ); - - final ByteArrayOutputStream baos = new ByteArrayOutputStream(); - final ObjectOutputStream oos = new ObjectOutputStream(baos); - oos.writeObject( key ); - - final ObjectInputStream ois = new ObjectInputStream( new ByteArrayInputStream( baos.toByteArray() ) ); - final Object keyClone = ois.readObject(); - - try { - assertEquals( key, keyClone ); - assertEquals( keyClone, key ); - - assertEquals( key.hashCode(), keyClone.hashCode() ); - - final Object idClone; - if ( cacheKeysFactory == SimpleCacheKeysFactory.INSTANCE ) { - idClone = cacheKeysFactory.getEntityId( keyClone ); - } - else { - // DefaultCacheKeysFactory#getEntityId will return a disassembled version - try (Session session = sessionFactory.openSession()) { - idClone = persister.getIdentifierType().assemble( - (Serializable) cacheKeysFactory.getEntityId( keyClone ), - (SharedSessionContractImplementor) session, - null - ); - } - } - - assertEquals( id.hashCode(), idClone.hashCode() ); - assertEquals( id, idClone ); - assertEquals( idClone, id ); - assertTrue( persister.getIdentifierType().isEqual( id, idClone, sessionFactory ) ); - assertTrue( persister.getIdentifierType().isEqual( idClone, id, sessionFactory ) ); - sessionFactory.close(); - } - finally { - sessionFactory.close(); - } - } +private SessionFactoryImplementor getSessionFactory(String cacheKeysFactory) { + Configuration configuration = new Configuration() + .setProperty(Environment.USE_SECOND_LEVEL_CACHE, true) + .setProperty(Environment.CACHE_REGION_FACTORY, CachingRegionFactory.class) + .setProperty(Environment.DEFAULT_CACHE_CONCURRENCY_STRATEGY, CacheConcurrencyStrategy.TRANSACTIONAL) + .setProperty(Environment.JPA_SHARED_CACHE_MODE, SharedCacheMode.ALL) + .setProperty(Environment.HBM2DDL_AUTO, Action.ACTION_CREATE_THEN_DROP); + ServiceRegistryUtil.applySettings( configuration.getStandardServiceRegistryBuilder() ); + if (cacheKeysFactory != null) { + configuration.setProperty(Environment.CACHE_KEYS_FACTORY, cacheKeysFactory); + } + configuration.addAnnotatedClass( WithSimpleId.class ); + configuration.addAnnotatedClass( WithEmbeddedId.class ); + return (SessionFactoryImplementor) configuration.buildSessionFactory(); +} + +@Test +@JiraKey(value = "HHH-11202") +public void testSimpleCacheKeySimpleId() throws Exception { + testId( SimpleCacheKeysFactory.INSTANCE, WithSimpleId.class.getName(), 1L ); +} + +@Test +@JiraKey(value = "HHH-11202") +public void testSimpleCacheKeyEmbeddedId() throws Exception { + testId( SimpleCacheKeysFactory.INSTANCE, WithEmbeddedId.class.getName(), new PK( 1L ) ); +} + +@Test +@JiraKey(value = "HHH-11202") +public void testDefaultCacheKeySimpleId() throws Exception { + testId( DefaultCacheKeysFactory.INSTANCE, WithSimpleId.class.getName(), 1L ); +} + +@Test +@JiraKey(value = "HHH-11202") +public void testDefaultCacheKeyEmbeddedId() throws Exception { + testId( DefaultCacheKeysFactory.INSTANCE, WithEmbeddedId.class.getName(), new PK( 1L ) ); +} + +private void testId(CacheKeysFactory cacheKeysFactory, String entityName, Object id) throws Exception { + final SessionFactoryImplementor sessionFactory = getSessionFactory(cacheKeysFactory.getClass().getName()); + final EntityPersister persister = sessionFactory.getRuntimeMetamodels().getMappingMetamodel().getEntityDescriptor(entityName); + final Object key = cacheKeysFactory.createEntityKey( + id, + persister, + sessionFactory, + null + ); + + final ByteArrayOutputStream baos = new ByteArrayOutputStream(); + final ObjectOutputStream oos = new ObjectOutputStream(baos); + oos.writeObject( key ); + + final ObjectInputStream ois = new ObjectInputStream( new ByteArrayInputStream( baos.toByteArray() ) ); + final Object keyClone = ois.readObject(); + + try { + assertEquals( key, keyClone ); + assertEquals( keyClone, key ); + + assertEquals( key.hashCode(), keyClone.hashCode() ); + + final Object idClone; + if ( cacheKeysFactory == SimpleCacheKeysFactory.INSTANCE ) { + idClone = cacheKeysFactory.getEntityId( keyClone ); + } + else { + // DefaultCacheKeysFactory#getEntityId will return a disassembled version + try (Session session = sessionFactory.openSession()) { + idClone = persister.getIdentifierType().assemble( + (Serializable) cacheKeysFactory.getEntityId( keyClone ), + (SharedSessionContractImplementor) session, + null + ); + } + } + + assertEquals( id.hashCode(), idClone.hashCode() ); + assertEquals( id, idClone ); + assertEquals( idClone, id ); + assertTrue( persister.getIdentifierType().isEqual( id, idClone, sessionFactory ) ); + assertTrue( persister.getIdentifierType().isEqual( idClone, id, sessionFactory ) ); + sessionFactory.close(); + } + finally { + sessionFactory.close(); + } +} } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/serialization/TypedValueSerializationTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/serialization/TypedValueSerializationTest.java index bc6d9d0ac7..c79e95fde8 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/serialization/TypedValueSerializationTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/serialization/TypedValueSerializationTest.java @@ -32,15 +32,15 @@ public class TypedValueSerializationTest { final TypedValue typedValue = new TypedValue(mockType, value); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); - final ObjectOutputStream oos = new ObjectOutputStream(baos); - oos.writeObject(typedValue); + final ObjectOutputStream oos = new ObjectOutputStream(baos); + oos.writeObject(typedValue); - final ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray())); - final TypedValue typedValueClone = (TypedValue) ois.readObject(); + final ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray())); + final TypedValue typedValueClone = (TypedValue) ois.readObject(); - assertEquals(typedValue.hashCode(), typedValueClone.hashCode()); - assertEquals(typedValue.toString(), typedValueClone.toString()); - assertEquals(typedValue.getValue(), typedValueClone.getValue()); + assertEquals(typedValue.hashCode(), typedValueClone.hashCode()); + assertEquals(typedValue.toString(), typedValueClone.toString()); + assertEquals(typedValue.getValue(), typedValueClone.getValue()); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/serialization/entity/WithSimpleId.java b/hibernate-core/src/test/java/org/hibernate/orm/test/serialization/entity/WithSimpleId.java index 24233ea5f5..e6bcc04e65 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/serialization/entity/WithSimpleId.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/serialization/entity/WithSimpleId.java @@ -19,6 +19,6 @@ import jakarta.persistence.Id; @Entity @Cacheable public class WithSimpleId { - @Id - private Long id; +@Id +private Long id; } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/service/ClassLoaderServiceImplTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/service/ClassLoaderServiceImplTest.java index ed5d296495..72080a481d 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/service/ClassLoaderServiceImplTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/service/ClassLoaderServiceImplTest.java @@ -34,41 +34,41 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Emmanuel Bernard */ public class ClassLoaderServiceImplTest { - /** - * Test for bug: HHH-7084 - */ - @Test - public void testSystemClassLoaderNotOverriding() throws IOException, ClassNotFoundException { - Class testClass = Entity.class; + /** + * Test for bug: HHH-7084 + */ + @Test + public void testSystemClassLoaderNotOverriding() throws IOException, ClassNotFoundException { + Class testClass = Entity.class; - // Check that class is accessible by SystemClassLoader. - ClassLoader.getSystemClassLoader().loadClass(testClass.getName()); + // Check that class is accessible by SystemClassLoader. + ClassLoader.getSystemClassLoader().loadClass(testClass.getName()); - // Create ClassLoader with overridden class. - TestClassLoader anotherLoader = new TestClassLoader(); - anotherLoader.overrideClass(testClass); - Class anotherClass = anotherLoader.loadClass(testClass.getName()); - Assert.assertNotSame( testClass, anotherClass ); + // Create ClassLoader with overridden class. + TestClassLoader anotherLoader = new TestClassLoader(); + anotherLoader.overrideClass(testClass); + Class anotherClass = anotherLoader.loadClass(testClass.getName()); + Assert.assertNotSame( testClass, anotherClass ); - // Check ClassLoaderServiceImpl().classForName() returns correct class (not from current ClassLoader). - ClassLoaderServiceImpl loaderService = new ClassLoaderServiceImpl(anotherLoader); - Class objectClass = loaderService.classForName(testClass.getName()); - Assert.assertSame("Should not return class loaded from the parent classloader of ClassLoaderServiceImpl", + // Check ClassLoaderServiceImpl().classForName() returns correct class (not from current ClassLoader). + ClassLoaderServiceImpl loaderService = new ClassLoaderServiceImpl(anotherLoader); + Class objectClass = loaderService.classForName(testClass.getName()); + Assert.assertSame("Should not return class loaded from the parent classloader of ClassLoaderServiceImpl", objectClass, anotherClass); - } + } - /** - * HHH-8363 discovered multiple leaks within CLS. Most notably, it wasn't getting GC'd due to holding - * references to ServiceLoaders. Ensure that the addition of Stoppable functionality cleans up properly. - * - * TODO: Is there a way to test that the ServiceLoader was actually reset? - */ - @Test - @JiraKey(value = "HHH-8363") - public void testStoppableClassLoaderService() { - final BootstrapServiceRegistryBuilder bootstrapBuilder = new BootstrapServiceRegistryBuilder(); - bootstrapBuilder.applyClassLoader( new TestClassLoader() ); - final ServiceRegistry serviceRegistry = ServiceRegistryUtil.serviceRegistryBuilder( bootstrapBuilder.build() ).build(); + /** + * HHH-8363 discovered multiple leaks within CLS. Most notably, it wasn't getting GC'd due to holding + * references to ServiceLoaders. Ensure that the addition of Stoppable functionality cleans up properly. + * + * TODO: Is there a way to test that the ServiceLoader was actually reset? + */ + @Test + @JiraKey(value = "HHH-8363") + public void testStoppableClassLoaderService() { + final BootstrapServiceRegistryBuilder bootstrapBuilder = new BootstrapServiceRegistryBuilder(); + bootstrapBuilder.applyClassLoader( new TestClassLoader() ); + final ServiceRegistry serviceRegistry = ServiceRegistryUtil.serviceRegistryBuilder( bootstrapBuilder.build() ).build(); final TypeContributor contributor1 = getTypeContributorServices( serviceRegistry ); assertThat( contributor1 ).isNotNull(); @@ -78,17 +78,17 @@ public class ClassLoaderServiceImplTest { assertThat( contributor1 ).isSameAs( contributor2 ); - StandardServiceRegistryBuilder.destroy( serviceRegistry ); + StandardServiceRegistryBuilder.destroy( serviceRegistry ); - try { + try { getTypeContributorServices( serviceRegistry ); - Assert.fail("Should have thrown an HibernateException -- the ClassLoaderService instance was closed."); - } - catch (HibernateException e) { + Assert.fail("Should have thrown an HibernateException -- the ClassLoaderService instance was closed."); + } + catch (HibernateException e) { Assert.assertEquals( "The ClassLoaderService cannot be reused (this instance was stopped already)", e.getMessage() ); - } - } + } + } private TypeContributor getTypeContributorServices(ServiceRegistry serviceRegistry) { final ClassLoaderService classLoaderService = serviceRegistry.getService( ClassLoaderService.class ); @@ -99,62 +99,62 @@ public class ClassLoaderServiceImplTest { private static class TestClassLoader extends ClassLoader { - /** - * testStoppableClassLoaderService() needs a custom JDK service implementation. Rather than using a real one - * on the test classpath, force it in here. - */ - @Override - protected Enumeration findResources(String name) throws IOException { - if (name.equals( "META-INF/services/org.hibernate.boot.model.TypeContributor" )) { - final URL serviceUrl = ConfigHelper.findAsResource( + /** + * testStoppableClassLoaderService() needs a custom JDK service implementation. Rather than using a real one + * on the test classpath, force it in here. + */ + @Override + protected Enumeration findResources(String name) throws IOException { + if (name.equals( "META-INF/services/org.hibernate.boot.model.TypeContributor" )) { + final URL serviceUrl = ConfigHelper.findAsResource( "org/hibernate/orm/test/service/org.hibernate.boot.model.TypeContributor" ); - return new Enumeration() { - boolean hasMore = true; + return new Enumeration() { + boolean hasMore = true; - @Override - public boolean hasMoreElements() { - return hasMore; - } + @Override + public boolean hasMoreElements() { + return hasMore; + } - @Override - public URL nextElement() { - hasMore = false; - return serviceUrl; - } - }; - } - else { - return java.util.Collections.enumeration( java.util.Collections.emptyList() ); - } - } + @Override + public URL nextElement() { + hasMore = false; + return serviceUrl; + } + }; + } + else { + return java.util.Collections.enumeration( java.util.Collections.emptyList() ); + } + } - /** - * Reloading class from binary file. - * - * @param originalClass Original class. - * @throws IOException . - */ - public void overrideClass(final Class originalClass) throws IOException { - String originalPath = "/" + originalClass.getName().replaceAll("\\.", "/") + ".class"; - InputStream inputStream = originalClass.getResourceAsStream(originalPath); - Assert.assertNotNull(inputStream); - try { - byte[] data = toByteArray( inputStream ); - defineClass(originalClass.getName(), data, 0, data.length); - } finally { - inputStream.close(); - } - } + /** + * Reloading class from binary file. + * + * @param originalClass Original class. + * @throws IOException . + */ + public void overrideClass(final Class originalClass) throws IOException { + String originalPath = "/" + originalClass.getName().replaceAll("\\.", "/") + ".class"; + InputStream inputStream = originalClass.getResourceAsStream(originalPath); + Assert.assertNotNull(inputStream); + try { + byte[] data = toByteArray( inputStream ); + defineClass(originalClass.getName(), data, 0, data.length); + } finally { + inputStream.close(); + } + } private byte[] toByteArray(InputStream inputStream) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); int read; byte[] slice = new byte[2000]; while ( (read = inputStream.read(slice, 0, slice.length) ) != -1) { - out.write( slice, 0, read ); + out.write( slice, 0, read ); } out.flush(); return out.toByteArray(); } - } + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/service/internal/JndiServiceImplTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/service/internal/JndiServiceImplTest.java index 65a717d53c..7bead7729b 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/service/internal/JndiServiceImplTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/service/internal/JndiServiceImplTest.java @@ -39,8 +39,8 @@ public class JndiServiceImplTest { //The "java" scheme is allowed to be used; it will also fail as we didn't setup a full JNDI context //in this test, but we can verify it's been attempted by checking the error message. final JndiException javaLookupException = assertThrows( JndiException.class, - () -> jndiService.locate( - "java:comp/env/jdbc/MyDatasource" ) + () -> jndiService.locate( + "java:comp/env/jdbc/MyDatasource" ) ); assertEquals( "Error parsing JNDI name [java:comp/env/jdbc/MyDatasource]", javaLookupException.getMessage() ); } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/set/SetOperationJpaCriteriaTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/set/SetOperationJpaCriteriaTest.java index 43d8ac1cc7..701ac56099 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/set/SetOperationJpaCriteriaTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/set/SetOperationJpaCriteriaTest.java @@ -36,158 +36,158 @@ import static org.hamcrest.MatcherAssert.assertThat; @ServiceRegistry @SessionFactory public class SetOperationJpaCriteriaTest { - @BeforeEach - public void createTestData(SessionFactoryScope scope) { - scope.inTransaction( - session -> { - session.persist( new EntityOfLists( 1, "first" ) ); - session.persist( new EntityOfLists( 2, "second" ) ); - session.persist( new EntityOfLists( 3, "third" ) ); - } - ); - } + @BeforeEach + public void createTestData(SessionFactoryScope scope) { + scope.inTransaction( + session -> { + session.persist( new EntityOfLists( 1, "first" ) ); + session.persist( new EntityOfLists( 2, "second" ) ); + session.persist( new EntityOfLists( 3, "third" ) ); + } + ); + } - @AfterEach - public void dropTestData(SessionFactoryScope scope) { - scope.inTransaction( - session -> { - session.createQuery( "delete from EntityOfLists" ).executeUpdate(); - session.createQuery( "delete from SimpleEntity" ).executeUpdate(); - } - ); - } + @AfterEach + public void dropTestData(SessionFactoryScope scope) { + scope.inTransaction( + session -> { + session.createQuery( "delete from EntityOfLists" ).executeUpdate(); + session.createQuery( "delete from SimpleEntity" ).executeUpdate(); + } + ); + } - @Test - @RequiresDialectFeature(feature = DialectFeatureChecks.SupportsUnion.class) - public void testUnionAll(SessionFactoryScope scope) { - scope.inSession( - session -> { - HibernateCriteriaBuilder cb = session.getCriteriaBuilder(); + @Test + @RequiresDialectFeature(feature = DialectFeatureChecks.SupportsUnion.class) + public void testUnionAll(SessionFactoryScope scope) { + scope.inSession( + session -> { + HibernateCriteriaBuilder cb = session.getCriteriaBuilder(); - JpaCriteriaQuery query1 = cb.createQuery( EntityOfLists.class ); - JpaRoot root1 = query1.from( EntityOfLists.class ); - query1.where( cb.equal( root1.get( "id" ), 1 ) ); + JpaCriteriaQuery query1 = cb.createQuery( EntityOfLists.class ); + JpaRoot root1 = query1.from( EntityOfLists.class ); + query1.where( cb.equal( root1.get( "id" ), 1 ) ); - JpaCriteriaQuery query2 = cb.createQuery( EntityOfLists.class ); - JpaRoot root2 = query2.from( EntityOfLists.class ); - query2.where( cb.equal( root2.get( "id" ), 2 ) ); + JpaCriteriaQuery query2 = cb.createQuery( EntityOfLists.class ); + JpaRoot root2 = query2.from( EntityOfLists.class ); + query2.where( cb.equal( root2.get( "id" ), 2 ) ); - List list = session.createQuery( - cb.unionAll( query1, query2 ) - ).list(); - assertThat( list.size(), is( 2 ) ); - } - ); - } + List list = session.createQuery( + cb.unionAll( query1, query2 ) + ).list(); + assertThat( list.size(), is( 2 ) ); + } + ); + } - @Test - @RequiresDialectFeature(feature = DialectFeatureChecks.SupportsUnion.class) - public void testUnionAllLimit(SessionFactoryScope scope) { - scope.inSession( - session -> { - HibernateCriteriaBuilder cb = session.getCriteriaBuilder(); + @Test + @RequiresDialectFeature(feature = DialectFeatureChecks.SupportsUnion.class) + public void testUnionAllLimit(SessionFactoryScope scope) { + scope.inSession( + session -> { + HibernateCriteriaBuilder cb = session.getCriteriaBuilder(); - JpaCriteriaQuery query1 = cb.createQuery( EntityOfLists.class ); - JpaRoot root1 = query1.from( EntityOfLists.class ); - query1.where( cb.equal( root1.get( "id" ), 1 ) ); + JpaCriteriaQuery query1 = cb.createQuery( EntityOfLists.class ); + JpaRoot root1 = query1.from( EntityOfLists.class ); + query1.where( cb.equal( root1.get( "id" ), 1 ) ); - JpaCriteriaQuery query2 = cb.createQuery( EntityOfLists.class ); - JpaRoot root2 = query2.from( EntityOfLists.class ); - query2.where( cb.equal( root2.get( "id" ), 2 ) ); + JpaCriteriaQuery query2 = cb.createQuery( EntityOfLists.class ); + JpaRoot root2 = query2.from( EntityOfLists.class ); + query2.where( cb.equal( root2.get( "id" ), 2 ) ); - List list = session.createQuery( - cb.unionAll( query1, query2 ) - .orderBy( cb.asc( cb.literal( 1 ) ) ) - .fetch( 1 ) - ).list(); - assertThat( list.size(), is( 1 ) ); - } - ); - } + List list = session.createQuery( + cb.unionAll( query1, query2 ) + .orderBy( cb.asc( cb.literal( 1 ) ) ) + .fetch( 1 ) + ).list(); + assertThat( list.size(), is( 1 ) ); + } + ); + } - @Test - @RequiresDialectFeature(feature = DialectFeatureChecks.SupportsUnion.class) - @RequiresDialectFeature(feature = DialectFeatureChecks.SupportsOrderByInSubquery.class) - public void testUnionAllLimitSubquery(SessionFactoryScope scope) { - scope.inSession( - session -> { - HibernateCriteriaBuilder cb = session.getCriteriaBuilder(); + @Test + @RequiresDialectFeature(feature = DialectFeatureChecks.SupportsUnion.class) + @RequiresDialectFeature(feature = DialectFeatureChecks.SupportsOrderByInSubquery.class) + public void testUnionAllLimitSubquery(SessionFactoryScope scope) { + scope.inSession( + session -> { + HibernateCriteriaBuilder cb = session.getCriteriaBuilder(); - JpaCriteriaQuery query1 = cb.createQuery( EntityOfLists.class ); - JpaRoot root1 = query1.from( EntityOfLists.class ); - query1.where( cb.equal( root1.get( "id" ), 1 ) ); + JpaCriteriaQuery query1 = cb.createQuery( EntityOfLists.class ); + JpaRoot root1 = query1.from( EntityOfLists.class ); + query1.where( cb.equal( root1.get( "id" ), 1 ) ); - JpaCriteriaQuery query2 = cb.createQuery( EntityOfLists.class ); - JpaRoot root2 = query2.from( EntityOfLists.class ); - query2.where( cb.equal( root2.get( "id" ), 2 ) ); + JpaCriteriaQuery query2 = cb.createQuery( EntityOfLists.class ); + JpaRoot root2 = query2.from( EntityOfLists.class ); + query2.where( cb.equal( root2.get( "id" ), 2 ) ); - List list = session.createQuery( - cb.unionAll( - query1, - query2.orderBy( cb.asc( cb.literal( 1 ) ) ) - .fetch( 1 ) - ) - ).list(); - assertThat( list.size(), is( 2 ) ); - } - ); - } + List list = session.createQuery( + cb.unionAll( + query1, + query2.orderBy( cb.asc( cb.literal( 1 ) ) ) + .fetch( 1 ) + ) + ).list(); + assertThat( list.size(), is( 2 ) ); + } + ); + } - @Test - @RequiresDialectFeature(feature = DialectFeatureChecks.SupportsUnion.class) - @RequiresDialectFeature(feature = DialectFeatureChecks.SupportsOrderByInSubquery.class) - public void testUnionAllLimitNested(SessionFactoryScope scope) { - scope.inSession( - session -> { - HibernateCriteriaBuilder cb = session.getCriteriaBuilder(); + @Test + @RequiresDialectFeature(feature = DialectFeatureChecks.SupportsUnion.class) + @RequiresDialectFeature(feature = DialectFeatureChecks.SupportsOrderByInSubquery.class) + public void testUnionAllLimitNested(SessionFactoryScope scope) { + scope.inSession( + session -> { + HibernateCriteriaBuilder cb = session.getCriteriaBuilder(); - JpaCriteriaQuery query1 = cb.createQuery( EntityOfLists.class ); - JpaRoot root1 = query1.from( EntityOfLists.class ); - query1.where( cb.equal( root1.get( "id" ), 1 ) ); + JpaCriteriaQuery query1 = cb.createQuery( EntityOfLists.class ); + JpaRoot root1 = query1.from( EntityOfLists.class ); + query1.where( cb.equal( root1.get( "id" ), 1 ) ); - JpaCriteriaQuery query2 = cb.createQuery( EntityOfLists.class ); - JpaRoot root2 = query2.from( EntityOfLists.class ); - query2.where( cb.equal( root2.get( "id" ), 2 ) ); + JpaCriteriaQuery query2 = cb.createQuery( EntityOfLists.class ); + JpaRoot root2 = query2.from( EntityOfLists.class ); + query2.where( cb.equal( root2.get( "id" ), 2 ) ); - List list = session.createQuery( - cb.unionAll( - query1, - query2.orderBy( cb.asc( cb.literal( 1 ) ) ) - .fetch( 1 ) - ).orderBy( cb.asc( cb.literal( 1 ) ) ) - .fetch( 1 ) - ).list(); - assertThat( list.size(), is( 1 ) ); - } - ); - } + List list = session.createQuery( + cb.unionAll( + query1, + query2.orderBy( cb.asc( cb.literal( 1 ) ) ) + .fetch( 1 ) + ).orderBy( cb.asc( cb.literal( 1 ) ) ) + .fetch( 1 ) + ).list(); + assertThat( list.size(), is( 1 ) ); + } + ); + } - @Test - @RequiresDialectFeature(feature = DialectFeatureChecks.SupportsUnion.class) - @RequiresDialectFeature(feature = DialectFeatureChecks.SupportsOrderByInSubquery.class) - @Jira( "https://hibernate.atlassian.net/browse/HHH-16754" ) - public void testUnionAllSubqueryOrderByPath(SessionFactoryScope scope) { - scope.inSession( - session -> { - HibernateCriteriaBuilder cb = session.getCriteriaBuilder(); + @Test + @RequiresDialectFeature(feature = DialectFeatureChecks.SupportsUnion.class) + @RequiresDialectFeature(feature = DialectFeatureChecks.SupportsOrderByInSubquery.class) + @Jira( "https://hibernate.atlassian.net/browse/HHH-16754" ) + public void testUnionAllSubqueryOrderByPath(SessionFactoryScope scope) { + scope.inSession( + session -> { + HibernateCriteriaBuilder cb = session.getCriteriaBuilder(); - JpaCriteriaQuery query1 = cb.createQuery( EntityOfLists.class ); - JpaRoot root1 = query1.from( EntityOfLists.class ); - query1.where( cb.equal( root1.get( "id" ), 1 ) ); + JpaCriteriaQuery query1 = cb.createQuery( EntityOfLists.class ); + JpaRoot root1 = query1.from( EntityOfLists.class ); + query1.where( cb.equal( root1.get( "id" ), 1 ) ); - JpaCriteriaQuery query2 = cb.createQuery( EntityOfLists.class ); - JpaRoot root2 = query2.from( EntityOfLists.class ); - query2.where( cb.equal( root2.get( "id" ), 2 ) ); + JpaCriteriaQuery query2 = cb.createQuery( EntityOfLists.class ); + JpaRoot root2 = query2.from( EntityOfLists.class ); + query2.where( cb.equal( root2.get( "id" ), 2 ) ); - List list = session.createQuery( - cb.unionAll( - query1, - query2.orderBy( cb.asc( root2.get("name") ) ) - .fetch( 1 ) - ) - ).list(); - assertThat( list.size(), is( 2 ) ); - } - ); - } + List list = session.createQuery( + cb.unionAll( + query1, + query2.orderBy( cb.asc( root2.get("name") ) ) + .fetch( 1 ) + ) + ).list(); + assertThat( list.size(), is( 2 ) ); + } + ); + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/sharedSession/SessionWithSharedConnectionTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/sharedSession/SessionWithSharedConnectionTest.java index 7963c668ac..2d3dece22b 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/sharedSession/SessionWithSharedConnectionTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/sharedSession/SessionWithSharedConnectionTest.java @@ -58,9 +58,9 @@ public class SessionWithSharedConnectionTest { // secondSession.createCriteria( IrrelevantEntity.class ).list(); //the list should have registered and then released a JDBC resource - assertFalse( + assertFalse( ((SessionImplementor) secondSession) - .getJdbcCoordinator().getLogicalConnection().getResourceRegistry() + .getJdbcCoordinator().getLogicalConnection().getResourceRegistry() .hasRegisteredResources() ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/sql/Captain.java b/hibernate-core/src/test/java/org/hibernate/orm/test/sql/Captain.java index 893ae1e0a4..7cb5ba6108 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/sql/Captain.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/sql/Captain.java @@ -16,20 +16,20 @@ import jakarta.persistence.Entity; @Entity public class Captain { - @EmbeddedId - private Identity id; + @EmbeddedId + private Identity id; - //Getters and setters are omitted for brevity + //Getters and setters are omitted for brevity //end::sql-composite-key-entity-associations_named-query-example[] - public Identity getId() { - return id; - } + public Identity getId() { + return id; + } - public void setId(Identity id) { - this.id = id; - } + public void setId(Identity id) { + this.id = id; + } //tag::sql-composite-key-entity-associations_named-query-example[] } //end::sql-composite-key-entity-associations_named-query-example[] diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/sql/CollectionLoaderTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/sql/CollectionLoaderTest.java index d4c8ec7e62..fd4609c774 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/sql/CollectionLoaderTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/sql/CollectionLoaderTest.java @@ -69,10 +69,10 @@ public class CollectionLoaderTest extends BaseEntityManagerFunctionalTestCase { session.doWork(connection -> { try(Statement statement = connection.createStatement();) { statement.executeUpdate(String.format( "ALTER TABLE person %s valid %s", - getDialect().getAddColumnString(), + getDialect().getAddColumnString(), ddlTypeRegistry.getTypeName( Types.BOOLEAN, getDialect()))); statement.executeUpdate(String.format( "ALTER TABLE Person_phones %s valid %s", - getDialect().getAddColumnString(), + getDialect().getAddColumnString(), ddlTypeRegistry.getTypeName( Types.BOOLEAN, getDialect()))); } }); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/sql/CustomSQLSecondaryTableTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/sql/CustomSQLSecondaryTableTest.java index 23c03a0422..712012bf17 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/sql/CustomSQLSecondaryTableTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/sql/CustomSQLSecondaryTableTest.java @@ -39,122 +39,122 @@ import static org.junit.Assert.assertNull; @RequiresDialect(PostgreSQLDialect.class) public class CustomSQLSecondaryTableTest extends BaseEntityManagerFunctionalTestCase { - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Person.class - }; - } + @Override + protected Class[] getAnnotatedClasses() { + return new Class[] { + Person.class + }; + } - @Before - public void init() { - doInJPA(this::entityManagerFactory, entityManager -> { - Session session = entityManager.unwrap(Session.class); - session.doWork(connection -> { - try(Statement statement = connection.createStatement();) { - statement.executeUpdate("ALTER TABLE person ADD COLUMN valid boolean"); - statement.executeUpdate("ALTER TABLE person_details ADD COLUMN valid boolean"); - } - }); - }); - } + @Before + public void init() { + doInJPA(this::entityManagerFactory, entityManager -> { + Session session = entityManager.unwrap(Session.class); + session.doWork(connection -> { + try(Statement statement = connection.createStatement();) { + statement.executeUpdate("ALTER TABLE person ADD COLUMN valid boolean"); + statement.executeUpdate("ALTER TABLE person_details ADD COLUMN valid boolean"); + } + }); + }); + } - @Test - public void test_sql_custom_crud() { + @Test + public void test_sql_custom_crud() { - Person _person = doInJPA(this::entityManagerFactory, entityManager -> { - Person person = new Person(); - person.setName("John Doe"); - entityManager.persist(person); - person.setImage(new byte[] {1, 2, 3}); - return person; - }); + Person _person = doInJPA(this::entityManagerFactory, entityManager -> { + Person person = new Person(); + person.setName("John Doe"); + entityManager.persist(person); + person.setImage(new byte[] {1, 2, 3}); + return person; + }); - doInJPA(this::entityManagerFactory, entityManager -> { - Long postId = _person.getId(); - Person person = entityManager.find(Person.class, postId); - assertArrayEquals(new byte[] {1, 2, 3}, person.getImage()); - entityManager.remove(person); - }); + doInJPA(this::entityManagerFactory, entityManager -> { + Long postId = _person.getId(); + Person person = entityManager.find(Person.class, postId); + assertArrayEquals(new byte[] {1, 2, 3}, person.getImage()); + entityManager.remove(person); + }); - doInJPA(this::entityManagerFactory, entityManager -> { - Long postId = _person.getId(); - Person person = entityManager.find(Person.class, postId); - assertNull(person); - }); - } + doInJPA(this::entityManagerFactory, entityManager -> { + Long postId = _person.getId(); + Person person = entityManager.find(Person.class, postId); + assertNull(person); + }); + } - //tag::sql-custom-crud-secondary-table-example[] - @Entity(name = "Person") - @Table(name = "person") - @SecondaryTable(name = "person_details", - pkJoinColumns = @PrimaryKeyJoinColumn(name = "person_id")) - @SQLInsert( - sql = "INSERT INTO person (name, id, valid) VALUES (?, ?, true) " - ) - @SQLDelete( - sql = "UPDATE person SET valid = false WHERE id = ? " - ) - @SQLInsert( - table = "person_details", - sql = "INSERT INTO person_details (image, person_id, valid) VALUES (?, ?, true) ", - check = ResultCheckStyle.COUNT - ) - @SQLDelete( - table = "person_details", - sql = "UPDATE person_details SET valid = false WHERE person_id = ? " - ) + //tag::sql-custom-crud-secondary-table-example[] + @Entity(name = "Person") + @Table(name = "person") + @SecondaryTable(name = "person_details", + pkJoinColumns = @PrimaryKeyJoinColumn(name = "person_id")) + @SQLInsert( + sql = "INSERT INTO person (name, id, valid) VALUES (?, ?, true) " +) + @SQLDelete( + sql = "UPDATE person SET valid = false WHERE id = ? " + ) + @SQLInsert( + table = "person_details", + sql = "INSERT INTO person_details (image, person_id, valid) VALUES (?, ?, true) ", + check = ResultCheckStyle.COUNT + ) + @SQLDelete( + table = "person_details", + sql = "UPDATE person_details SET valid = false WHERE person_id = ? " + ) - @SQLSelect( - sql = "SELECT " + - " p.id, " + - " p.name, " + - " pd.image " + - "FROM person p " + - "LEFT OUTER JOIN person_details pd ON p.id = pd.person_id " + - "WHERE p.id = ? AND p.valid = true AND pd.valid = true" - ) - public static class Person { + @SQLSelect( + sql = "SELECT " + + " p.id, " + + " p.name, " + + " pd.image " + + "FROM person p " + + "LEFT OUTER JOIN person_details pd ON p.id = pd.person_id " + + "WHERE p.id = ? AND p.valid = true AND pd.valid = true" + ) + public static class Person { - @Id - @GeneratedValue - private Long id; + @Id + @GeneratedValue + private Long id; - private String name; + private String name; - @Column(name = "image", table = "person_details") - private byte[] image; + @Column(name = "image", table = "person_details") + private byte[] image; - //Getters and setters are omitted for brevity + //Getters and setters are omitted for brevity - //end::sql-custom-crud-secondary-table-example[] + //end::sql-custom-crud-secondary-table-example[] - public Long getId() { - return id; - } + public Long getId() { + return id; + } - public void setId(Long id) { - this.id = id; - } + public void setId(Long id) { + this.id = id; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - public byte[] getImage() { - return image; - } + public byte[] getImage() { + return image; + } - public void setImage(byte[] image) { - this.image = image; - } - //tag::sql-custom-crud-secondary-table-example[] - } - //end::sql-custom-crud-secondary-table-example[] + public void setImage(byte[] image) { + this.image = image; + } + //tag::sql-custom-crud-secondary-table-example[] + } + //end::sql-custom-crud-secondary-table-example[] } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/sql/Dimensions.java b/hibernate-core/src/test/java/org/hibernate/orm/test/sql/Dimensions.java index 3b795c6948..7d7b381635 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/sql/Dimensions.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/sql/Dimensions.java @@ -15,29 +15,29 @@ import jakarta.persistence.Embeddable; @Embeddable public class Dimensions { - private int length; + private int length; - private int width; + private int width; - //Getters and setters are omitted for brevity + //Getters and setters are omitted for brevity //end::sql-composite-key-entity-associations_named-query-example[] - public int getLength() { - return length; - } + public int getLength() { + return length; + } - public void setLength(int length) { - this.length = length; - } + public void setLength(int length) { + this.length = length; + } - public int getWidth() { - return width; - } + public int getWidth() { + return width; + } - public void setWidth(int width) { - this.width = width; - } + public void setWidth(int width) { + this.width = width; + } //tag::sql-composite-key-entity-associations_named-query-example[] } //end::sql-composite-key-entity-associations_named-query-example[] diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/sql/Identity.java b/hibernate-core/src/test/java/org/hibernate/orm/test/sql/Identity.java index 2f9b7e5254..000bad52bf 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/sql/Identity.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/sql/Identity.java @@ -16,48 +16,48 @@ import jakarta.persistence.Embeddable; @Embeddable public class Identity implements Serializable { - private String firstname; + private String firstname; - private String lastname; + private String lastname; - //Getters and setters are omitted for brevity + //Getters and setters are omitted for brevity //end::sql-composite-key-entity-associations_named-query-example[] - public String getFirstname() { - return firstname; - } + public String getFirstname() { + return firstname; + } - public void setFirstname(String firstname) { - this.firstname = firstname; - } + public void setFirstname(String firstname) { + this.firstname = firstname; + } - public String getLastname() { - return lastname; - } + public String getLastname() { + return lastname; + } - public void setLastname(String lastname) { - this.lastname = lastname; - } + public void setLastname(String lastname) { + this.lastname = lastname; + } //tag::sql-composite-key-entity-associations_named-query-example[] - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; - final Identity identity = (Identity) o; + final Identity identity = (Identity) o; - if (!firstname.equals(identity.firstname)) return false; - if (!lastname.equals(identity.lastname)) return false; + if (!firstname.equals(identity.firstname)) return false; + if (!lastname.equals(identity.lastname)) return false; - return true; - } + return true; + } - public int hashCode() { - int result; - result = firstname.hashCode(); - result = 29 * result + lastname.hashCode(); - return result; - } + public int hashCode() { + int result; + result = firstname.hashCode(); + result = 29 * result + lastname.hashCode(); + return result; + } } //end::sql-composite-key-entity-associations_named-query-example[] diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/sql/MySQLStoredProcedureTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/sql/MySQLStoredProcedureTest.java index 4dbe0580db..b9719e0f73 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/sql/MySQLStoredProcedureTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/sql/MySQLStoredProcedureTest.java @@ -312,7 +312,7 @@ public class MySQLStoredProcedureTest { //end::sql-jpa-call-sp-inout-with-result-list-mysql-example[] // now let's see how the JDBC ResultSet is extracted // this test should fail as of Hibernate 6.4.1, each item in the result set is an array: [Phone, Long] - assertInstanceOf(Phone.class, supposedToBePhone.get(0)); + assertInstanceOf(Phone.class, supposedToBePhone.get(0)); } ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/sql/OracleStoredProcedureTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/sql/OracleStoredProcedureTest.java index 75dbedff92..685c95eb05 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/sql/OracleStoredProcedureTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/sql/OracleStoredProcedureTest.java @@ -46,193 +46,193 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; */ @RequiresDialect(value = OracleDialect.class) @Jpa( - annotatedClasses = { - Person.class, - Partner.class, - Phone.class, - Call.class, - Payment.class, - Account.class - } + annotatedClasses = { + Person.class, + Partner.class, + Phone.class, + Call.class, + Payment.class, + Account.class + } ) public class OracleStoredProcedureTest { - @BeforeAll - public void init(EntityManagerFactoryScope scope) { - scope.inTransaction( entityManager -> { - Session session = entityManager.unwrap(Session.class); - session.doWork(connection -> { - try (Statement statement = connection.createStatement()) { - statement.executeUpdate( - "CREATE OR REPLACE PROCEDURE sp_count_phones ( " + - " personId IN NUMBER, " + - " phoneCount OUT NUMBER) " + - "AS " + - "BEGIN " + - " SELECT COUNT(*) INTO phoneCount " + - " FROM phone " + - " WHERE person_id = personId; " + - "END;" - ); - //tag::sql-sp-ref-cursor-oracle-example[] - statement.executeUpdate( - "CREATE OR REPLACE PROCEDURE sp_person_phones (" + - " personId IN NUMBER, " + - " personPhones OUT SYS_REFCURSOR) " + - "AS " + - "BEGIN " + - " OPEN personPhones FOR " + - " SELECT *" + - " FROM phone " + - " WHERE person_id = personId; " + - "END;" - ); - //end::sql-sp-ref-cursor-oracle-example[] - statement.executeUpdate( - "CREATE OR REPLACE FUNCTION fn_count_phones (" + - " personId IN NUMBER) " + - " RETURN NUMBER " + - "IS " + - " phoneCount NUMBER; " + - "BEGIN " + - " SELECT COUNT(*) INTO phoneCount " + - " FROM phone " + - " WHERE person_id = personId; " + - " RETURN(phoneCount); " + - "END;" - ); - } + @BeforeAll + public void init(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { + Session session = entityManager.unwrap(Session.class); + session.doWork(connection -> { + try (Statement statement = connection.createStatement()) { + statement.executeUpdate( + "CREATE OR REPLACE PROCEDURE sp_count_phones ( " + + " personId IN NUMBER, " + + " phoneCount OUT NUMBER) " + + "AS " + + "BEGIN " + + " SELECT COUNT(*) INTO phoneCount " + + " FROM phone " + + " WHERE person_id = personId; " + + "END;" + ); + //tag::sql-sp-ref-cursor-oracle-example[] + statement.executeUpdate( + "CREATE OR REPLACE PROCEDURE sp_person_phones (" + + " personId IN NUMBER, " + + " personPhones OUT SYS_REFCURSOR) " + + "AS " + + "BEGIN " + + " OPEN personPhones FOR " + + " SELECT *" + + " FROM phone " + + " WHERE person_id = personId; " + + "END;" + ); + //end::sql-sp-ref-cursor-oracle-example[] + statement.executeUpdate( + "CREATE OR REPLACE FUNCTION fn_count_phones (" + + " personId IN NUMBER) " + + " RETURN NUMBER " + + "IS " + + " phoneCount NUMBER; " + + "BEGIN " + + " SELECT COUNT(*) INTO phoneCount " + + " FROM phone " + + " WHERE person_id = personId; " + + " RETURN(phoneCount); " + + "END;" + ); + } }); - }); - scope.inTransaction( entityManager -> { - Person person1 = new Person("John Doe"); - person1.setNickName("JD"); - person1.setAddress("Earth"); - person1.setCreatedOn(LocalDateTime.of(2000, 1, 1, 0, 0, 0)) ; - person1.getAddresses().put(AddressType.HOME, "Home address"); - person1.getAddresses().put(AddressType.OFFICE, "Office address"); + }); + scope.inTransaction( entityManager -> { + Person person1 = new Person("John Doe"); + person1.setNickName("JD"); + person1.setAddress("Earth"); + person1.setCreatedOn(LocalDateTime.of(2000, 1, 1, 0, 0, 0)) ; + person1.getAddresses().put(AddressType.HOME, "Home address"); + person1.getAddresses().put(AddressType.OFFICE, "Office address"); - entityManager.persist(person1); + entityManager.persist(person1); - Phone phone1 = new Phone("123-456-7890"); - phone1.setId(1L); - phone1.setType(PhoneType.MOBILE); + Phone phone1 = new Phone("123-456-7890"); + phone1.setId(1L); + phone1.setType(PhoneType.MOBILE); - person1.addPhone(phone1); + person1.addPhone(phone1); - Phone phone2 = new Phone("098_765-4321"); - phone2.setId(2L); - phone2.setType(PhoneType.LAND_LINE); + Phone phone2 = new Phone("098_765-4321"); + phone2.setId(2L); + phone2.setType(PhoneType.LAND_LINE); - person1.addPhone(phone2); - }); - } + person1.addPhone(phone2); + }); + } - @AfterAll - public void destroy(EntityManagerFactoryScope scope) { - scope.inTransaction( entityManager -> { - Session session = entityManager.unwrap(Session.class); - session.doWork(connection -> { - try(Statement statement = connection.createStatement()) { - statement.executeUpdate("DROP PROCEDURE sp_count_phones"); - } - catch (SQLException ignore) { - } - }); - }); - scope.inTransaction( entityManager -> { - Session session = entityManager.unwrap(Session.class); - session.doWork(connection -> { - try(Statement statement = connection.createStatement()) { - statement.executeUpdate("DROP PROCEDURE sp_person_phones"); - } - catch (SQLException ignore) { - } - }); - }); - scope.inTransaction( entityManager -> { - Session session = entityManager.unwrap(Session.class); - session.doWork(connection -> { - try(Statement statement = connection.createStatement()) { - statement.executeUpdate("DROP FUNCTION fn_count_phones"); - } - catch (SQLException ignore) { - } - }); - }); - } + @AfterAll + public void destroy(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { + Session session = entityManager.unwrap(Session.class); + session.doWork(connection -> { + try(Statement statement = connection.createStatement()) { + statement.executeUpdate("DROP PROCEDURE sp_count_phones"); + } + catch (SQLException ignore) { + } + }); + }); + scope.inTransaction( entityManager -> { + Session session = entityManager.unwrap(Session.class); + session.doWork(connection -> { + try(Statement statement = connection.createStatement()) { + statement.executeUpdate("DROP PROCEDURE sp_person_phones"); + } + catch (SQLException ignore) { + } + }); + }); + scope.inTransaction( entityManager -> { + Session session = entityManager.unwrap(Session.class); + session.doWork(connection -> { + try(Statement statement = connection.createStatement()) { + statement.executeUpdate("DROP FUNCTION fn_count_phones"); + } + catch (SQLException ignore) { + } + }); + }); + } - @Test - public void testStoredProcedureOutParameter(EntityManagerFactoryScope scope) { - scope.inTransaction( entityManager -> { - StoredProcedureQuery query = entityManager.createStoredProcedureQuery("sp_count_phones"); - query.registerStoredProcedureParameter(1, Long.class, ParameterMode.IN); - query.registerStoredProcedureParameter(2, Long.class, ParameterMode.OUT); + @Test + public void testStoredProcedureOutParameter(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { + StoredProcedureQuery query = entityManager.createStoredProcedureQuery("sp_count_phones"); + query.registerStoredProcedureParameter(1, Long.class, ParameterMode.IN); + query.registerStoredProcedureParameter(2, Long.class, ParameterMode.OUT); - query.setParameter(1, 1L); + query.setParameter(1, 1L); - query.execute(); - Long phoneCount = (Long) query.getOutputParameterValue(2); - assertEquals(2l, phoneCount); - }); - } + query.execute(); + Long phoneCount = (Long) query.getOutputParameterValue(2); + assertEquals(2l, phoneCount); + }); + } - @Test - public void testStoredProcedureRefCursor(EntityManagerFactoryScope scope) { - scope.inTransaction( entityManager -> { - //tag::sql-jpa-call-sp-ref-cursor-oracle-example[] - StoredProcedureQuery query = entityManager.createStoredProcedureQuery("sp_person_phones"); - query.registerStoredProcedureParameter(1, Long.class, ParameterMode.IN); - query.registerStoredProcedureParameter(2, Class.class, ParameterMode.REF_CURSOR); - query.setParameter(1, 1L); + @Test + public void testStoredProcedureRefCursor(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { + //tag::sql-jpa-call-sp-ref-cursor-oracle-example[] + StoredProcedureQuery query = entityManager.createStoredProcedureQuery("sp_person_phones"); + query.registerStoredProcedureParameter(1, Long.class, ParameterMode.IN); + query.registerStoredProcedureParameter(2, Class.class, ParameterMode.REF_CURSOR); + query.setParameter(1, 1L); - query.execute(); - List postComments = query.getResultList(); - //end::sql-jpa-call-sp-ref-cursor-oracle-example[] - assertNotNull(postComments); - }); - } + query.execute(); + List postComments = query.getResultList(); + //end::sql-jpa-call-sp-ref-cursor-oracle-example[] + assertNotNull(postComments); + }); + } - @Test - public void testStoredProcedureRefCursorUsingNamedQuery(EntityManagerFactoryScope scope) { - scope.inTransaction( entityManager -> { - //tag::sql-jpa-call-sp-ref-cursor-oracle-named-query-example[] - List postComments = entityManager - .createNamedStoredProcedureQuery("sp_person_phones") - .setParameter("personId", 1L) - .getResultList(); - //end::sql-jpa-call-sp-ref-cursor-oracle-named-query-example[] + @Test + public void testStoredProcedureRefCursorUsingNamedQuery(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { + //tag::sql-jpa-call-sp-ref-cursor-oracle-named-query-example[] + List postComments = entityManager + .createNamedStoredProcedureQuery("sp_person_phones") + .setParameter("personId", 1L) + .getResultList(); + //end::sql-jpa-call-sp-ref-cursor-oracle-named-query-example[] - assertNotNull(postComments); - }); - } + assertNotNull(postComments); + }); + } - @Test - public void testHibernateProcedureCallRefCursor(EntityManagerFactoryScope scope) { - scope.inTransaction( entityManager -> { - //tag::sql-hibernate-call-sp-ref-cursor-oracle-example[] - Session session = entityManager.unwrap(Session.class); + @Test + public void testHibernateProcedureCallRefCursor(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { + //tag::sql-hibernate-call-sp-ref-cursor-oracle-example[] + Session session = entityManager.unwrap(Session.class); - ProcedureCall call = session.createStoredProcedureCall("sp_person_phones"); - ProcedureParameter parameter = call.registerParameter(1, Long.class, ParameterMode.IN); - call.setParameter(parameter, 1L); - call.registerParameter(2, Class.class, ParameterMode.REF_CURSOR); + ProcedureCall call = session.createStoredProcedureCall("sp_person_phones"); + ProcedureParameter parameter = call.registerParameter(1, Long.class, ParameterMode.IN); + call.setParameter(parameter, 1L); + call.registerParameter(2, Class.class, ParameterMode.REF_CURSOR); - Output output = call.getOutputs().getCurrent(); - List postComments = ((ResultSetOutput) output).getResultList(); - assertEquals(2, postComments.size()); - //end::sql-hibernate-call-sp-ref-cursor-oracle-example[] - }); - } + Output output = call.getOutputs().getCurrent(); + List postComments = ((ResultSetOutput) output).getResultList(); + assertEquals(2, postComments.size()); + //end::sql-hibernate-call-sp-ref-cursor-oracle-example[] + }); + } - @Test - public void testStoredProcedureReturnValue(EntityManagerFactoryScope scope) { - scope.inTransaction( entityManager -> { - BigDecimal phoneCount = (BigDecimal) entityManager - .createNativeQuery( "SELECT fn_count_phones(:personId) FROM DUAL" ) - .setParameter( "personId", 1 ) - .getSingleResult(); - assertEquals( BigDecimal.valueOf( 2L ), phoneCount ); - } ); - } + @Test + public void testStoredProcedureReturnValue(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { + BigDecimal phoneCount = (BigDecimal) entityManager + .createNativeQuery( "SELECT fn_count_phones(:personId) FROM DUAL" ) + .setParameter( "personId", 1 ) + .getSingleResult(); + assertEquals( BigDecimal.valueOf( 2L ), phoneCount ); + } ); + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/sql/PersonSummaryDTO.java b/hibernate-core/src/test/java/org/hibernate/orm/test/sql/PersonSummaryDTO.java index d5e51168c2..1c0e4d8ce7 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/sql/PersonSummaryDTO.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/sql/PersonSummaryDTO.java @@ -12,26 +12,26 @@ package org.hibernate.orm.test.sql; //tag::sql-hibernate-dto-query-example[] public class PersonSummaryDTO { - private Number id; + private Number id; - private String name; + private String name; - //Getters and setters are omitted for brevity + //Getters and setters are omitted for brevity - public Number getId() { - return id; - } + public Number getId() { + return id; + } - public void setId(Number id) { - this.id = id; - } + public void setId(Number id) { + this.id = id; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } } //end::sql-hibernate-dto-query-example[] diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/sql/SQLSelectTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/sql/SQLSelectTest.java index a1245b8510..f69e618bcd 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/sql/SQLSelectTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/sql/SQLSelectTest.java @@ -67,10 +67,10 @@ public class SQLSelectTest extends BaseEntityManagerFunctionalTestCase { session.doWork(connection -> { try(Statement statement = connection.createStatement();) { statement.executeUpdate(String.format( "ALTER TABLE person %s valid %s", - getDialect().getAddColumnString(), + getDialect().getAddColumnString(), ddlTypeRegistry.getTypeName( Types.BOOLEAN, getDialect()))); statement.executeUpdate(String.format( "ALTER TABLE Person_phones %s valid %s", - getDialect().getAddColumnString(), + getDialect().getAddColumnString(), ddlTypeRegistry.getTypeName( Types.BOOLEAN, getDialect()))); } }); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/sql/SQLTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/sql/SQLTest.java index 8a8e69957d..0da29bf42b 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/sql/SQLTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/sql/SQLTest.java @@ -56,7 +56,7 @@ public class SQLTest extends BaseEntityManagerFunctionalTestCase { return new Class[] { Person.class, Partner.class, - Phone.class, + Phone.class, Call.class, Account.class, CreditCardPayment.class, @@ -182,7 +182,7 @@ public class SQLTest extends BaseEntityManagerFunctionalTestCase { @Test public void test_sql_hibernate_query_scalar_example() { - doInJPA(this::entityManagerFactory, entityManager -> { + doInJPA(this::entityManagerFactory, entityManager -> { Session session = entityManager.unwrap(Session.class); //tag::sql-hibernate-all-columns-scalar-query-example[] List persons = session.createNativeQuery( @@ -214,7 +214,7 @@ public class SQLTest extends BaseEntityManagerFunctionalTestCase { @Test public void test_sql_hibernate_query_scalar_explicit_result_set_example() { - doInJPA(this::entityManagerFactory, entityManager -> { + doInJPA(this::entityManagerFactory, entityManager -> { Session session = entityManager.unwrap(Session.class); //tag::sql-hibernate-scalar-query-explicit-result-set-example[] List persons = session.createNativeQuery( @@ -255,7 +255,7 @@ public class SQLTest extends BaseEntityManagerFunctionalTestCase { @Test public void test_sql_jpa_entity_query_example() { - doInJPA(this::entityManagerFactory, entityManager -> { + doInJPA(this::entityManagerFactory, entityManager -> { //tag::sql-jpa-entity-query-example[] List persons = entityManager.createNativeQuery( "SELECT * FROM Person", Person.class) @@ -267,7 +267,7 @@ public class SQLTest extends BaseEntityManagerFunctionalTestCase { @Test public void test_sql_hibernate_entity_query_example() { - doInJPA(this::entityManagerFactory, entityManager -> { + doInJPA(this::entityManagerFactory, entityManager -> { Session session = entityManager.unwrap(Session.class); //tag::sql-hibernate-entity-query-example[] List persons = session.createNativeQuery( @@ -280,7 +280,7 @@ public class SQLTest extends BaseEntityManagerFunctionalTestCase { @Test public void test_sql_jpa_entity_query_explicit_result_set_example() { - doInJPA(this::entityManagerFactory, entityManager -> { + doInJPA(this::entityManagerFactory, entityManager -> { //tag::sql-jpa-entity-query-explicit-result-set-example[] List persons = entityManager.createNativeQuery( "SELECT id, name, nick_name, address, created_on, version " + @@ -293,7 +293,7 @@ public class SQLTest extends BaseEntityManagerFunctionalTestCase { @Test public void test_sql_hibernate_entity_query_explicit_result_set_example() { - doInJPA(this::entityManagerFactory, entityManager -> { + doInJPA(this::entityManagerFactory, entityManager -> { Session session = entityManager.unwrap(Session.class); //tag::sql-hibernate-entity-query-explicit-result-set-example[] List persons = session.createNativeQuery( @@ -307,7 +307,7 @@ public class SQLTest extends BaseEntityManagerFunctionalTestCase { @Test public void test_sql_jpa_entity_associations_query_many_to_one_example() { - doInJPA(this::entityManagerFactory, entityManager -> { + doInJPA(this::entityManagerFactory, entityManager -> { //tag::sql-jpa-entity-associations-query-many-to-one-example[] List phones = entityManager.createNativeQuery( "SELECT id, phone_number, phone_type, person_id " + @@ -320,7 +320,7 @@ public class SQLTest extends BaseEntityManagerFunctionalTestCase { @Test public void test_sql_hibernate_entity_associations_query_many_to_one_example() { - doInJPA(this::entityManagerFactory, entityManager -> { + doInJPA(this::entityManagerFactory, entityManager -> { Session session = entityManager.unwrap(Session.class); //tag::sql-hibernate-entity-associations-query-many-to-one-example[] List phones = session.createNativeQuery( diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/sql/SpaceShip.java b/hibernate-core/src/test/java/org/hibernate/orm/test/sql/SpaceShip.java index 8b79267e75..5b1a1723e2 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/sql/SpaceShip.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/sql/SpaceShip.java @@ -25,100 +25,100 @@ import jakarta.persistence.SqlResultSetMapping; //tag::sql-composite-key-entity-associations_named-query-example[] @Entity @NamedNativeQueries({ - @NamedNativeQuery(name = "find_all_spaceships", - query = - "SELECT " + - " name as \"name\", " + - " model, " + - " speed, " + - " lname as lastn, " + - " fname as firstn, " + - " length, " + - " width, " + - " length * width as surface, " + - " length * width * 10 as volume " + - "FROM SpaceShip", - resultSetMapping = "spaceship" - ) + @NamedNativeQuery(name = "find_all_spaceships", + query = + "SELECT " + + " name as \"name\", " + + " model, " + + " speed, " + + " lname as lastn, " + + " fname as firstn, " + + " length, " + + " width, " + + " length * width as surface, " + + " length * width * 10 as volume " + + "FROM SpaceShip", + resultSetMapping = "spaceship" +) }) @SqlResultSetMapping( - name = "spaceship", - entities = @EntityResult( - entityClass = SpaceShip.class, - fields = { - @FieldResult(name = "name", column = "name"), - @FieldResult(name = "model", column = "model"), - @FieldResult(name = "speed", column = "speed"), - @FieldResult(name = "captain.id.lastname", column = "lastn"), - @FieldResult(name = "captain.id.firstname", column = "firstn"), - @FieldResult(name = "dimensions.length", column = "length"), - @FieldResult(name = "dimensions.width", column = "width"), - } - ), - columns = { - @ColumnResult(name = "surface"), - @ColumnResult(name = "volume") - } + name = "spaceship", + entities = @EntityResult( + entityClass = SpaceShip.class, + fields = { + @FieldResult(name = "name", column = "name"), + @FieldResult(name = "model", column = "model"), + @FieldResult(name = "speed", column = "speed"), + @FieldResult(name = "captain.id.lastname", column = "lastn"), + @FieldResult(name = "captain.id.firstname", column = "firstn"), + @FieldResult(name = "dimensions.length", column = "length"), + @FieldResult(name = "dimensions.width", column = "width"), + } +), + columns = { + @ColumnResult(name = "surface"), + @ColumnResult(name = "volume") + } ) public class SpaceShip { - @Id - private String name; + @Id + private String name; - private String model; + private String model; - private double speed; + private double speed; - @ManyToOne(fetch = FetchType.LAZY) - @JoinColumn(name = "fname", referencedColumnName = "firstname") - @JoinColumn(name = "lname", referencedColumnName = "lastname") - private Captain captain; + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "fname", referencedColumnName = "firstname") + @JoinColumn(name = "lname", referencedColumnName = "lastname") + private Captain captain; - private Dimensions dimensions; + private Dimensions dimensions; - //Getters and setters are omitted for brevity + //Getters and setters are omitted for brevity //end::sql-composite-key-entity-associations_named-query-example[] - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - public String getModel() { - return model; - } + public String getModel() { + return model; + } - public void setModel(String model) { - this.model = model; - } + public void setModel(String model) { + this.model = model; + } - public double getSpeed() { - return speed; - } + public double getSpeed() { + return speed; + } - public void setSpeed(double speed) { - this.speed = speed; - } + public void setSpeed(double speed) { + this.speed = speed; + } - public Captain getCaptain() { - return captain; - } + public Captain getCaptain() { + return captain; + } - public void setCaptain(Captain captain) { - this.captain = captain; - } + public void setCaptain(Captain captain) { + this.captain = captain; + } - public Dimensions getDimensions() { - return dimensions; - } + public Dimensions getDimensions() { + return dimensions; + } - public void setDimensions(Dimensions dimensions) { - this.dimensions = dimensions; - } + public void setDimensions(Dimensions dimensions) { + this.dimensions = dimensions; + } //tag::sql-composite-key-entity-associations_named-query-example[] } //end::sql-composite-key-entity-associations_named-query-example[] diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/sql/StatementCommentTests.java b/hibernate-core/src/test/java/org/hibernate/orm/test/sql/StatementCommentTests.java index fae846692a..81e2eb0ced 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/sql/StatementCommentTests.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/sql/StatementCommentTests.java @@ -86,11 +86,11 @@ public class StatementCommentTests { @Entity( name = "VersionedEntity" ) @Table( name = "entity_table" ) public static class VersionedEntity { - @Id - private Integer id; + @Id + private Integer id; @Version private Integer version; - @Basic + @Basic private String name; protected VersionedEntity() { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/sql/ast/ParameterMarkerStrategyTests.java b/hibernate-core/src/test/java/org/hibernate/orm/test/sql/ast/ParameterMarkerStrategyTests.java index ea401b81e3..a4429e57d6 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/sql/ast/ParameterMarkerStrategyTests.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/sql/ast/ParameterMarkerStrategyTests.java @@ -205,9 +205,9 @@ public class ParameterMarkerStrategyTests { ) @Filter( name = "region" ) public static class EntityWithFilters { - @Id - private Integer id; - @Basic + @Id + private Integer id; + @Basic private String name; @Basic private String region; @@ -246,9 +246,9 @@ public class ParameterMarkerStrategyTests { @Entity( name = "EntityWithVersion" ) @Table( name = "versioned_entity" ) public static class EntityWithVersion { - @Id - private Integer id; - @Basic + @Id + private Integer id; + @Basic private String name; @Version private int version; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/sql/autodiscovery/AutoDiscoveryTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/sql/autodiscovery/AutoDiscoveryTest.java index 15f7f7112e..0d91fc4e8d 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/sql/autodiscovery/AutoDiscoveryTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/sql/autodiscovery/AutoDiscoveryTest.java @@ -132,8 +132,8 @@ public class AutoDiscoveryTest extends BaseCoreFunctionalTestCase { Assert.assertFalse( "bad dialect.getColumnAliasExtractor impl", column1Alias.equals( column2Alias ) ); } finally { - sessionImplementor.getJdbcCoordinator().getLogicalConnection().getResourceRegistry().release( rs, ps ); - sessionImplementor.getJdbcCoordinator().getLogicalConnection().getResourceRegistry().release( ps ); + sessionImplementor.getJdbcCoordinator().getLogicalConnection().getResourceRegistry().release( rs, ps ); + sessionImplementor.getJdbcCoordinator().getLogicalConnection().getResourceRegistry().release( ps ); } } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/sql/hand/MonetaryAmount.java b/hibernate-core/src/test/java/org/hibernate/orm/test/sql/hand/MonetaryAmount.java index 6c206d5c1b..85fa22e97c 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/sql/hand/MonetaryAmount.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/sql/hand/MonetaryAmount.java @@ -56,7 +56,7 @@ public class MonetaryAmount implements Serializable { public String toString() { return "Value: '" + getValue() + "', " + - "Currency: '" + getCurrency() + "'"; + "Currency: '" + getCurrency() + "'"; } public int compareTo(Object o) { @@ -71,11 +71,11 @@ public class MonetaryAmount implements Serializable { public static MonetaryAmount fromString(String amount, String currencyCode) { return new MonetaryAmount(new BigDecimal(amount), - Currency.getInstance(currencyCode)); + Currency.getInstance(currencyCode)); } public static MonetaryAmount convert(MonetaryAmount amount, - Currency toConcurrency) { + Currency toConcurrency) { // TODO: This requires some conversion magic and is therefore broken return new MonetaryAmount(amount.getValue(), toConcurrency); } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/sql/partition/PartitionKeyTests.java b/hibernate-core/src/test/java/org/hibernate/orm/test/sql/partition/PartitionKeyTests.java index b7bc7f438f..0b3749fb26 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/sql/partition/PartitionKeyTests.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/sql/partition/PartitionKeyTests.java @@ -70,12 +70,12 @@ public class PartitionKeyTests { @Entity( name = "PartitionedEntity" ) @Table( name = "entity_table" ) public static class PartitionedEntity { - @Id - private Integer id; + @Id + private Integer id; @PartitionKey @Column(name = "tenant_id", updatable = false) private Integer tenantId; - @Basic + @Basic private String name; protected PartitionedEntity() { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/stateless/GetAllTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/stateless/GetAllTest.java index ffe04195ca..51f2740af7 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/stateless/GetAllTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/stateless/GetAllTest.java @@ -21,29 +21,29 @@ import static org.junit.jupiter.api.Assertions.assertNull; @SessionFactory @DomainModel(annotatedClasses = GetAllTest.Record.class) public class GetAllTest { - @Test void test(SessionFactoryScope scope) { - scope.inStatelessTransaction(s-> { - s.insert(new Record(123L,"hello earth")); - s.insert(new Record(456L,"hello mars")); - }); - scope.inStatelessTransaction(s-> { - List all = s.getAll(Record.class, List.of(456L, 123L, 2L)); - assertEquals("hello mars",all.get(0).message); - assertEquals("hello earth",all.get(1).message); - assertNull(all.get(2)); - }); - } - @Entity - static class Record { - @Id Long id; - String message; + @Test void test(SessionFactoryScope scope) { + scope.inStatelessTransaction(s-> { + s.insert(new Record(123L,"hello earth")); + s.insert(new Record(456L,"hello mars")); + }); + scope.inStatelessTransaction(s-> { + List all = s.getAll(Record.class, List.of(456L, 123L, 2L)); + assertEquals("hello mars",all.get(0).message); + assertEquals("hello earth",all.get(1).message); + assertNull(all.get(2)); + }); + } + @Entity + static class Record { + @Id Long id; + String message; - Record(Long id, String message) { - this.id = id; - this.message = message; - } + Record(Long id, String message) { + this.id = id; + this.message = message; + } - Record() { - } - } + Record() { + } + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/stateless/UpsertTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/stateless/UpsertTest.java index 7854218069..2d2625336d 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/stateless/UpsertTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/stateless/UpsertTest.java @@ -18,34 +18,34 @@ import static org.junit.Assert.assertEquals; @SessionFactory @DomainModel(annotatedClasses = UpsertTest.Record.class) public class UpsertTest { - @Test void test(SessionFactoryScope scope) { - scope.inStatelessTransaction(s-> { - s.upsert(new Record(123L,"hello earth")); - s.upsert(new Record(456L,"hello mars")); - }); - scope.inStatelessTransaction(s-> { - assertEquals("hello earth",s.get(Record.class,123L).message); - assertEquals("hello mars",s.get(Record.class,456L).message); - }); - scope.inStatelessTransaction(s-> { - s.upsert(new Record(123L,"goodbye earth")); - }); - scope.inStatelessTransaction(s-> { - assertEquals("goodbye earth",s.get(Record.class,123L).message); - assertEquals("hello mars",s.get(Record.class,456L).message); - }); - } - @Entity - static class Record { - @Id Long id; - String message; + @Test void test(SessionFactoryScope scope) { + scope.inStatelessTransaction(s-> { + s.upsert(new Record(123L,"hello earth")); + s.upsert(new Record(456L,"hello mars")); + }); + scope.inStatelessTransaction(s-> { + assertEquals("hello earth",s.get(Record.class,123L).message); + assertEquals("hello mars",s.get(Record.class,456L).message); + }); + scope.inStatelessTransaction(s-> { + s.upsert(new Record(123L,"goodbye earth")); + }); + scope.inStatelessTransaction(s-> { + assertEquals("goodbye earth",s.get(Record.class,123L).message); + assertEquals("hello mars",s.get(Record.class,456L).message); + }); + } + @Entity + static class Record { + @Id Long id; + String message; - Record(Long id, String message) { - this.id = id; - this.message = message; - } + Record(Long id, String message) { + this.id = id; + this.message = message; + } - Record() { - } - } + Record() { + } + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/stateless/UpsertVersionedTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/stateless/UpsertVersionedTest.java index 8d7da92fba..d58fb7cdf2 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/stateless/UpsertVersionedTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/stateless/UpsertVersionedTest.java @@ -19,43 +19,43 @@ import static org.junit.Assert.assertEquals; @SessionFactory @DomainModel(annotatedClasses = UpsertVersionedTest.Record.class) public class UpsertVersionedTest { - @Test void test(SessionFactoryScope scope) { - scope.inStatelessTransaction(s-> { - s.upsert(new Record(123L,null,"hello earth")); - s.upsert(new Record(456L,2L,"hello mars")); - }); - scope.inStatelessTransaction(s-> { - assertEquals("hello earth",s.get(Record.class,123L).message); - assertEquals("hello mars",s.get(Record.class,456L).message); - }); - scope.inStatelessTransaction(s-> { - s.upsert(new Record(123L,0L,"goodbye earth")); - }); - scope.inStatelessTransaction(s-> { - assertEquals("goodbye earth",s.get(Record.class,123L).message); - assertEquals("hello mars",s.get(Record.class,456L).message); - }); - scope.inStatelessTransaction(s-> { - s.upsert(new Record(456L,3L,"goodbye mars")); - }); - scope.inStatelessTransaction(s-> { - assertEquals("goodbye earth",s.get(Record.class,123L).message); - assertEquals("goodbye mars",s.get(Record.class,456L).message); - }); - } - @Entity(name = "Record") - static class Record { - @Id Long id; - @Version Long version; - String message; + @Test void test(SessionFactoryScope scope) { + scope.inStatelessTransaction(s-> { + s.upsert(new Record(123L,null,"hello earth")); + s.upsert(new Record(456L,2L,"hello mars")); + }); + scope.inStatelessTransaction(s-> { + assertEquals("hello earth",s.get(Record.class,123L).message); + assertEquals("hello mars",s.get(Record.class,456L).message); + }); + scope.inStatelessTransaction(s-> { + s.upsert(new Record(123L,0L,"goodbye earth")); + }); + scope.inStatelessTransaction(s-> { + assertEquals("goodbye earth",s.get(Record.class,123L).message); + assertEquals("hello mars",s.get(Record.class,456L).message); + }); + scope.inStatelessTransaction(s-> { + s.upsert(new Record(456L,3L,"goodbye mars")); + }); + scope.inStatelessTransaction(s-> { + assertEquals("goodbye earth",s.get(Record.class,123L).message); + assertEquals("goodbye mars",s.get(Record.class,456L).message); + }); + } + @Entity(name = "Record") + static class Record { + @Id Long id; + @Version Long version; + String message; - Record(Long id, Long version, String message) { - this.id = id; - this.version = version; - this.message = message; - } + Record(Long id, Long version, String message) { + this.id = id; + this.version = version; + this.message = message; + } - Record() { - } - } + Record() { + } + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/stateless/insert/Message.java b/hibernate-core/src/test/java/org/hibernate/orm/test/stateless/insert/Message.java index 8361a54fc8..692a304f59 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/stateless/insert/Message.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/stateless/insert/Message.java @@ -11,31 +11,31 @@ package org.hibernate.orm.test.stateless.insert; */ public class Message { - private String id; - private String subject; - private String content; + private String id; + private String subject; + private String content; - public String getId() { - return id; - } + public String getId() { + return id; + } - public void setId(String id) { - this.id = id; - } + public void setId(String id) { + this.id = id; + } - public String getSubject() { - return subject; - } + public String getSubject() { + return subject; + } - public void setSubject(String subject) { - this.subject = subject; - } + public void setSubject(String subject) { + this.subject = subject; + } - public String getContent() { - return content; - } + public String getContent() { + return content; + } - public void setContent(String content) { - this.content = content; - } + public void setContent(String content) { + this.content = content; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/stateless/insert/MessageRecipient.java b/hibernate-core/src/test/java/org/hibernate/orm/test/stateless/insert/MessageRecipient.java index ae3db75b8b..9aa1235221 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/stateless/insert/MessageRecipient.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/stateless/insert/MessageRecipient.java @@ -11,31 +11,31 @@ package org.hibernate.orm.test.stateless.insert; */ public class MessageRecipient { - private String id; - private String email; - private Message message; + private String id; + private String email; + private Message message; - public String getId() { - return id; - } + public String getId() { + return id; + } - public void setId(String id) { - this.id = id; - } + public void setId(String id) { + this.id = id; + } - public String getEmail() { - return email; - } + public String getEmail() { + return email; + } - public void setEmail(String email) { - this.email = email; - } + public void setEmail(String email) { + this.email = email; + } - public Message getMessage() { - return message; - } + public Message getMessage() { + return message; + } - public void setMessage(Message message) { - this.message = message; - } + public void setMessage(Message message) { + this.message = message; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/subclassProxyInterface/Doctor.java b/hibernate-core/src/test/java/org/hibernate/orm/test/subclassProxyInterface/Doctor.java index 1219c32a34..b964ef98ef 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/subclassProxyInterface/Doctor.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/subclassProxyInterface/Doctor.java @@ -18,7 +18,7 @@ public class Doctor extends Person implements IDoctor { super( name ); } - public String operate() { - return "Dr. " + getName() + " is in"; - } + public String operate() { + return "Dr. " + getName() + " is in"; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/subclassProxyInterface/IDoctor.java b/hibernate-core/src/test/java/org/hibernate/orm/test/subclassProxyInterface/IDoctor.java index 7ebfffd103..ce7342cd56 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/subclassProxyInterface/IDoctor.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/subclassProxyInterface/IDoctor.java @@ -11,5 +11,5 @@ package org.hibernate.orm.test.subclassProxyInterface; * @author Steve Ebersole */ public interface IDoctor { - String operate(); + String operate(); } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/subclassProxyInterface/Person.java b/hibernate-core/src/test/java/org/hibernate/orm/test/subclassProxyInterface/Person.java index e8dfbb3974..1275e75cb4 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/subclassProxyInterface/Person.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/subclassProxyInterface/Person.java @@ -11,8 +11,8 @@ package org.hibernate.orm.test.subclassProxyInterface; * @author Steve Ebersole */ public class Person { - private Long id; - private String name; + private Long id; + private String name; public Person() { } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/subclassProxyInterface/SubclassProxyInterfaceTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/subclassProxyInterface/SubclassProxyInterfaceTest.java index 15d975d8eb..e9a62c5ef6 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/subclassProxyInterface/SubclassProxyInterfaceTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/subclassProxyInterface/SubclassProxyInterfaceTest.java @@ -21,7 +21,7 @@ import org.junit.jupiter.api.Test; public class SubclassProxyInterfaceTest { @Test public void testSubclassProxyInterfaces() { - final Configuration cfg = new Configuration() + final Configuration cfg = new Configuration() .setProperty( Environment.DIALECT, H2Dialect.class ) .addClass( Person.class ); try (ServiceRegistry serviceRegistry = ServiceRegistryBuilder.buildServiceRegistry( cfg.getProperties() ) ) { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/subclassfilter/DiscrimSubclassFilterTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/subclassfilter/DiscrimSubclassFilterTest.java index 623604f7ee..9ca8436829 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/subclassfilter/DiscrimSubclassFilterTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/subclassfilter/DiscrimSubclassFilterTest.java @@ -52,7 +52,7 @@ public class DiscrimSubclassFilterTest { s.clear(); results = new ArrayList( new HashSet( s.createQuery( "from Person as p left join fetch p.minions" ) - .list() ) ); + .list() ) ); assertEquals( 4, results.size(), "Incorrect qry result count" ); itr = results.iterator(); while ( itr.hasNext() ) { @@ -67,7 +67,7 @@ public class DiscrimSubclassFilterTest { s.clear(); results = new ArrayList( new HashSet( s.createQuery( "from Employee as p left join fetch p.minions" ) - .list() ) ); + .list() ) ); assertEquals( 2, results.size(), "Incorrect qry result count" ); itr = results.iterator(); while ( itr.hasNext() ) { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/subclassfilter/Employee.java b/hibernate-core/src/test/java/org/hibernate/orm/test/subclassfilter/Employee.java index 3147002454..413ca5c6b5 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/subclassfilter/Employee.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/subclassfilter/Employee.java @@ -16,7 +16,7 @@ import java.util.Set; */ public class Employee extends Person { @Column(name="`title`") - private String title; + private String title; private String department; private Employee manager; private Set minions = new HashSet(); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/subclassfilter/UnionSubclassFilterTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/subclassfilter/UnionSubclassFilterTest.java index 186f80fa8f..6c8b98927c 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/subclassfilter/UnionSubclassFilterTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/subclassfilter/UnionSubclassFilterTest.java @@ -52,7 +52,7 @@ public class UnionSubclassFilterTest { s.clear(); results = new ArrayList( new HashSet( s.createQuery( "from Person as p left join fetch p.minions" ) - .list() ) ); + .list() ) ); assertEquals( 4, results.size(), "Incorrect qry result count" ); itr = results.iterator(); while ( itr.hasNext() ) { @@ -67,7 +67,7 @@ public class UnionSubclassFilterTest { s.clear(); results = new ArrayList( new HashSet( s.createQuery( "from Employee as p left join fetch p.minions" ) - .list() ) ); + .list() ) ); assertEquals( 2, results.size(), "Incorrect qry result count" ); itr = results.iterator(); while ( itr.hasNext() ) { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/subquery/EntityA.java b/hibernate-core/src/test/java/org/hibernate/orm/test/subquery/EntityA.java index a6211ffca5..ca322bcbb3 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/subquery/EntityA.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/subquery/EntityA.java @@ -10,32 +10,32 @@ import jakarta.persistence.*; @Entity public class EntityA { - @Id - @Column(name = "id", nullable = false) - private int id; - private String name; + @Id + @Column(name = "id", nullable = false) + private int id; + private String name; - public EntityA() { - } + public EntityA() { + } - public EntityA(int id, String name) { - this.id = id; - this.name = name; - } + public EntityA(int id, String name) { + this.id = id; + this.name = name; + } - public int getId() { - return id; - } + public int getId() { + return id; + } - public void setId(int id) { - this.id = id; - } + public void setId(int id) { + this.id = id; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/temporal/TimePropertyTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/temporal/TimePropertyTest.java index 7b74a5df33..e584ea020c 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/temporal/TimePropertyTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/temporal/TimePropertyTest.java @@ -69,7 +69,7 @@ public class TimePropertyTest { final String queryString; - if ( SQLServerDialect.class.isAssignableFrom( scope.getSessionFactory().getJdbcServices().getDialect().getClass() ) ) { + if ( SQLServerDialect.class.isAssignableFrom( scope.getSessionFactory().getJdbcServices().getDialect().getClass() ) ) { queryString = "from TimePropertyTest$Entity where tAsDate = cast ( ?1 as time )"; } else { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/tenantid/Account.java b/hibernate-core/src/test/java/org/hibernate/orm/test/tenantid/Account.java index 787bed9931..36d7cda161 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/tenantid/Account.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/tenantid/Account.java @@ -16,15 +16,15 @@ import jakarta.persistence.ManyToOne; @Entity public class Account { - @Id @GeneratedValue Long id; + @Id @GeneratedValue Long id; - @TenantId String tenantId; + @TenantId String tenantId; - @ManyToOne(optional = false) Client client; + @ManyToOne(optional = false) Client client; - public Account(Client client) { - this.client = client; - } + public Account(Client client) { + this.client = client; + } - Account() {} + Account() {} } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/tenantid/Client.java b/hibernate-core/src/test/java/org/hibernate/orm/test/tenantid/Client.java index a25d337168..61bca222d0 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/tenantid/Client.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/tenantid/Client.java @@ -17,21 +17,21 @@ import java.util.Set; @Entity public class Client { - @Id - @GeneratedValue - Long id; + @Id + @GeneratedValue + Long id; - String name; + String name; - @TenantId - String tenantId; + @TenantId + String tenantId; - @OneToMany(mappedBy = "client") - Set accounts = new HashSet<>(); + @OneToMany(mappedBy = "client") + Set accounts = new HashSet<>(); - public Client(String name) { - this.name = name; - } + public Client(String name) { + this.name = name; + } - Client() {} + Client() {} } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/tenantid/Record.java b/hibernate-core/src/test/java/org/hibernate/orm/test/tenantid/Record.java index 731ba222be..50c913aa87 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/tenantid/Record.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/tenantid/Record.java @@ -12,7 +12,7 @@ import jakarta.persistence.Id; @Entity public class Record { - @Id @GeneratedValue - public Long id; - public State state = new State(); + @Id @GeneratedValue + public Long id; + public State state = new State(); } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/tenantid/State.java b/hibernate-core/src/test/java/org/hibernate/orm/test/tenantid/State.java index abebf6ba8c..807d9e5b38 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/tenantid/State.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/tenantid/State.java @@ -14,7 +14,7 @@ import java.time.Instant; @Embeddable public class State { - public boolean deleted; - public @TenantId String tenantId; - public @UpdateTimestamp Instant updated; + public boolean deleted; + public @TenantId String tenantId; + public @UpdateTimestamp Instant updated; } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/tenantid/TenantIdTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/tenantid/TenantIdTest.java index d7db5d26b4..971201671e 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/tenantid/TenantIdTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/tenantid/TenantIdTest.java @@ -56,301 +56,301 @@ import java.util.List; @SessionFactory @DomainModel(annotatedClasses = { Account.class, Client.class, Record.class }) @ServiceRegistry( - settings = { - @Setting(name = JAKARTA_HBM2DDL_DATABASE_ACTION, value = "create-drop") - }, - settingProviders = @SettingProvider(settingName = CurrentTimestampGeneration.CLOCK_SETTING_NAME, provider = MutableClockSettingProvider.class) + settings = { + @Setting(name = JAKARTA_HBM2DDL_DATABASE_ACTION, value = "create-drop") + }, + settingProviders = @SettingProvider(settingName = CurrentTimestampGeneration.CLOCK_SETTING_NAME, provider = MutableClockSettingProvider.class) ) public class TenantIdTest implements SessionFactoryProducer { - String currentTenant; - MutableClock clock; + String currentTenant; + MutableClock clock; - @BeforeEach - public void setup(SessionFactoryScope scope) { - clock = CurrentTimestampGeneration.getClock( scope.getSessionFactory() ); - clock.reset(); - } + @BeforeEach + public void setup(SessionFactoryScope scope) { + clock = CurrentTimestampGeneration.getClock( scope.getSessionFactory() ); + clock.reset(); + } - @AfterEach - public void cleanup(SessionFactoryScope scope) { - // Use the root tenant to clean up all partitions - currentTenant = "root"; - scope.inTransaction( - session -> { - session.createMutationQuery( "delete from Account" ).executeUpdate(); - session.createMutationQuery( "delete from Client" ).executeUpdate(); - session.createMutationQuery( "delete from Record" ).executeUpdate(); - } - ); - } + @AfterEach + public void cleanup(SessionFactoryScope scope) { + // Use the root tenant to clean up all partitions + currentTenant = "root"; + scope.inTransaction( + session -> { + session.createMutationQuery( "delete from Account" ).executeUpdate(); + session.createMutationQuery( "delete from Client" ).executeUpdate(); + session.createMutationQuery( "delete from Record" ).executeUpdate(); + } + ); + } - @Override - public SessionFactoryImplementor produceSessionFactory(MetadataImplementor model) { - final SessionFactoryBuilder sessionFactoryBuilder = model.getSessionFactoryBuilder(); - sessionFactoryBuilder.applyCurrentTenantIdentifierResolver( new CurrentTenantIdentifierResolver() { - @Override - public String resolveCurrentTenantIdentifier() { - return currentTenant; - } - @Override - public boolean validateExistingCurrentSessions() { - return false; - } + @Override + public SessionFactoryImplementor produceSessionFactory(MetadataImplementor model) { + final SessionFactoryBuilder sessionFactoryBuilder = model.getSessionFactoryBuilder(); + sessionFactoryBuilder.applyCurrentTenantIdentifierResolver( new CurrentTenantIdentifierResolver() { + @Override + public String resolveCurrentTenantIdentifier() { + return currentTenant; + } + @Override + public boolean validateExistingCurrentSessions() { + return false; + } - @Override - public boolean isRoot(String tenantId) { - return "root".equals( tenantId ); - } - } ); - return (SessionFactoryImplementor) sessionFactoryBuilder.build(); - } + @Override + public boolean isRoot(String tenantId) { + return "root".equals( tenantId ); + } + } ); + return (SessionFactoryImplementor) sessionFactoryBuilder.build(); + } - @Test - public void test(SessionFactoryScope scope) { - currentTenant = "mine"; - Client client = new Client("Gavin"); - Account acc = new Account(client); - scope.inTransaction( session -> { - session.persist(client); - session.persist(acc); - } ); - scope.inTransaction( session -> { - assertNotNull( session.find(Account.class, acc.id) ); - assertEquals( 1, session.createQuery("from Account", Account.class).getResultList().size() ); - } ); - assertEquals("mine", acc.tenantId); + @Test + public void test(SessionFactoryScope scope) { + currentTenant = "mine"; + Client client = new Client("Gavin"); + Account acc = new Account(client); + scope.inTransaction( session -> { + session.persist(client); + session.persist(acc); + } ); + scope.inTransaction( session -> { + assertNotNull( session.find(Account.class, acc.id) ); + assertEquals( 1, session.createQuery("from Account", Account.class).getResultList().size() ); + } ); + assertEquals("mine", acc.tenantId); - currentTenant = "yours"; - scope.inTransaction( session -> { - //HHH-16830 Sessions applies tenantId filter on find() - assertNull( session.find(Account.class, acc.id) ); - assertEquals( 0, session.createQuery("from Account", Account.class).getResultList().size() ); - session.disableFilter(TenantIdBinder.FILTER_NAME); - assertNotNull( session.find(Account.class, acc.id) ); - assertEquals( 1, session.createQuery("from Account", Account.class).getResultList().size() ); - } ); - } + currentTenant = "yours"; + scope.inTransaction( session -> { + //HHH-16830 Sessions applies tenantId filter on find() + assertNull( session.find(Account.class, acc.id) ); + assertEquals( 0, session.createQuery("from Account", Account.class).getResultList().size() ); + session.disableFilter(TenantIdBinder.FILTER_NAME); + assertNotNull( session.find(Account.class, acc.id) ); + assertEquals( 1, session.createQuery("from Account", Account.class).getResultList().size() ); + } ); + } - @Test - public void testRoot(SessionFactoryScope scope) { - currentTenant = "root"; - scope.inTransaction( session -> { - assertEquals( 0, session.createQuery( "from Account", Account.class ).getResultList().size() ); - } ); + @Test + public void testRoot(SessionFactoryScope scope) { + currentTenant = "root"; + scope.inTransaction( session -> { + assertEquals( 0, session.createQuery( "from Account", Account.class ).getResultList().size() ); + } ); - currentTenant = "mine"; - Client client = new Client( "Gavin" ); - Account acc = new Account( client ); - scope.inTransaction( session -> { - session.persist( client ); - session.persist( acc ); - } ); - assertEquals( "mine", acc.tenantId ); - scope.inTransaction( session -> { - assertNotNull( session.find( Account.class, acc.id ) ); - assertEquals( 1, session.createQuery( "from Account", Account.class ).getResultList().size() ); - } ); + currentTenant = "mine"; + Client client = new Client( "Gavin" ); + Account acc = new Account( client ); + scope.inTransaction( session -> { + session.persist( client ); + session.persist( acc ); + } ); + assertEquals( "mine", acc.tenantId ); + scope.inTransaction( session -> { + assertNotNull( session.find( Account.class, acc.id ) ); + assertEquals( 1, session.createQuery( "from Account", Account.class ).getResultList().size() ); + } ); - currentTenant = "root"; - // Root tenants should find entities from other tenants - scope.inTransaction( session -> { - assertNotNull( session.find( Account.class, acc.id ) ); - assertEquals( 1, session.createQuery( "from Account", Account.class ).getResultList().size() ); - } ); + currentTenant = "root"; + // Root tenants should find entities from other tenants + scope.inTransaction( session -> { + assertNotNull( session.find( Account.class, acc.id ) ); + assertEquals( 1, session.createQuery( "from Account", Account.class ).getResultList().size() ); + } ); - // Root tenants should find entities from their own tenant - Client rootClient = new Client( "Sacha" ); - Account rootAcc = new Account( rootClient ); - scope.inTransaction( session -> { - session.persist( rootClient ); - session.persist( rootAcc ); - } ); - assertEquals( "root", rootAcc.tenantId ); - scope.inTransaction( session -> { - assertNotNull( session.find( Account.class, rootAcc.id ) ); - assertEquals( 2, session.createQuery( "from Account", Account.class ).getResultList().size() ); - } ); - } + // Root tenants should find entities from their own tenant + Client rootClient = new Client( "Sacha" ); + Account rootAcc = new Account( rootClient ); + scope.inTransaction( session -> { + session.persist( rootClient ); + session.persist( rootAcc ); + } ); + assertEquals( "root", rootAcc.tenantId ); + scope.inTransaction( session -> { + assertNotNull( session.find( Account.class, rootAcc.id ) ); + assertEquals( 2, session.createQuery( "from Account", Account.class ).getResultList().size() ); + } ); + } - @Test - public void testErrorOnInsert(SessionFactoryScope scope) { - currentTenant = "mine"; - Client client = new Client("Gavin"); - Account acc = new Account(client); - acc.tenantId = "yours"; - try { - scope.inTransaction( session -> { - session.persist(client); - session.persist(acc); - } ); - fail("should have thrown"); - } - catch (Throwable e) { - assertTrue( e instanceof PropertyValueException ); - } - } + @Test + public void testErrorOnInsert(SessionFactoryScope scope) { + currentTenant = "mine"; + Client client = new Client("Gavin"); + Account acc = new Account(client); + acc.tenantId = "yours"; + try { + scope.inTransaction( session -> { + session.persist(client); + session.persist(acc); + } ); + fail("should have thrown"); + } + catch (Throwable e) { + assertTrue( e instanceof PropertyValueException ); + } + } - @Test - public void testErrorOnUpdate(SessionFactoryScope scope) { - currentTenant = "mine"; - Client client = new Client("Gavin"); - Account acc = new Account(client); - scope.inTransaction( session -> { - session.persist(client); - session.persist(acc); - acc.tenantId = "yours"; - client.tenantId = "yours"; - client.name = "Steve"; - } ); - //TODO: it would be better if this were an error - scope.inTransaction( session -> { - Account account = session.find(Account.class, acc.id); - assertNotNull(account); - assertEquals( "mine", acc.tenantId ); - assertEquals( "Steve", acc.client.name ); - assertEquals( "mine", acc.client.tenantId ); - } ); - } + @Test + public void testErrorOnUpdate(SessionFactoryScope scope) { + currentTenant = "mine"; + Client client = new Client("Gavin"); + Account acc = new Account(client); + scope.inTransaction( session -> { + session.persist(client); + session.persist(acc); + acc.tenantId = "yours"; + client.tenantId = "yours"; + client.name = "Steve"; + } ); + //TODO: it would be better if this were an error + scope.inTransaction( session -> { + Account account = session.find(Account.class, acc.id); + assertNotNull(account); + assertEquals( "mine", acc.tenantId ); + assertEquals( "Steve", acc.client.name ); + assertEquals( "mine", acc.client.tenantId ); + } ); + } - @Test - @SkipForDialect(dialectClass = SybaseASEDialect.class, - reason = "low timestamp precision on Sybase") - public void testEmbeddedTenantId(SessionFactoryScope scope) { - currentTenant = "mine"; - Record record = new Record(); - scope.inTransaction( s -> s.persist( record ) ); - assertEquals( "mine", record.state.tenantId ); - assertNotNull( record.state.updated ); + @Test + @SkipForDialect(dialectClass = SybaseASEDialect.class, + reason = "low timestamp precision on Sybase") + public void testEmbeddedTenantId(SessionFactoryScope scope) { + currentTenant = "mine"; + Record record = new Record(); + scope.inTransaction( s -> s.persist( record ) ); + assertEquals( "mine", record.state.tenantId ); + assertNotNull( record.state.updated ); - clock.tick(); + clock.tick(); - scope.inTransaction( s -> { - Record r = s.find( Record.class, record.id ); - assertEquals( "mine", r.state.tenantId ); - assertEquals( record.state.updated, r.state.updated ); - assertEquals( false, r.state.deleted ); - r.state.deleted = true; - } ); - scope.inTransaction( s -> { - Record r = s.find( Record.class, record.id ); - assertEquals( "mine", r.state.tenantId ); - assertNotEquals( record.state.updated, r.state.updated ); - assertEquals( true, r.state.deleted ); - } ); - } + scope.inTransaction( s -> { + Record r = s.find( Record.class, record.id ); + assertEquals( "mine", r.state.tenantId ); + assertEquals( record.state.updated, r.state.updated ); + assertEquals( false, r.state.deleted ); + r.state.deleted = true; + } ); + scope.inTransaction( s -> { + Record r = s.find( Record.class, record.id ); + assertEquals( "mine", r.state.tenantId ); + assertNotEquals( record.state.updated, r.state.updated ); + assertEquals( true, r.state.deleted ); + } ); + } - @Test - public void testEntityManagerHint(SessionFactoryScope scope) { - currentTenant = "mine"; - Record record = new Record(); - scope.inTransaction( s -> s.persist( record ) ); - assertEquals( "mine", record.state.tenantId ); - assertNotNull( record.state.updated ); + @Test + public void testEntityManagerHint(SessionFactoryScope scope) { + currentTenant = "mine"; + Record record = new Record(); + scope.inTransaction( s -> s.persist( record ) ); + assertEquals( "mine", record.state.tenantId ); + assertNotNull( record.state.updated ); - currentTenant = "yours"; - Record record2 = new Record(); - scope.inTransaction( s -> s.persist( record2 ) ); - assertEquals( "yours", record2.state.tenantId ); - assertNotNull( record2.state.updated ); + currentTenant = "yours"; + Record record2 = new Record(); + scope.inTransaction( s -> s.persist( record2 ) ); + assertEquals( "yours", record2.state.tenantId ); + assertNotNull( record2.state.updated ); - currentTenant = null; - final EntityManagerFactory emf = scope.getSessionFactory(); - try (EntityManager em = emf.createEntityManager( toMap( HINT_TENANT_ID, "mine" ) ) ) { - Record r = em.find( Record.class, record.id ); - assertEquals( "mine", r.state.tenantId ); + currentTenant = null; + final EntityManagerFactory emf = scope.getSessionFactory(); + try (EntityManager em = emf.createEntityManager( toMap( HINT_TENANT_ID, "mine" ) ) ) { + Record r = em.find( Record.class, record.id ); + assertEquals( "mine", r.state.tenantId ); - // HHH-16830 Session applies tenant-id on #find - Record yours = em.find( Record.class, record2.id ); - assertNull(yours); + // HHH-16830 Session applies tenant-id on #find + Record yours = em.find( Record.class, record2.id ); + assertNull(yours); - em.createQuery( "from Record where id = :id", Record.class ) - .setParameter( "id", record.id ) - .getSingleResult(); - assertEquals( "mine", r.state.tenantId ); + em.createQuery( "from Record where id = :id", Record.class ) + .setParameter( "id", record.id ) + .getSingleResult(); + assertEquals( "mine", r.state.tenantId ); - // However, Session does seem to apply tenant-id on queries - try { - em.createQuery( "from Record where id = :id", Record.class ) - .setParameter( "id", record2.id ) - .getSingleResult(); - fail( "Expecting an exception" ); - } - catch (Exception expected) { - } - } - catch (RuntimeException e) { - currentTenant = "yours"; - scope.inTransaction( (s) -> s.createMutationQuery( "delete Record" ) ); + // However, Session does seem to apply tenant-id on queries + try { + em.createQuery( "from Record where id = :id", Record.class ) + .setParameter( "id", record2.id ) + .getSingleResult(); + fail( "Expecting an exception" ); + } + catch (Exception expected) { + } + } + catch (RuntimeException e) { + currentTenant = "yours"; + scope.inTransaction( (s) -> s.createMutationQuery( "delete Record" ) ); - throw e; - } - finally { - // for cleanup - currentTenant = "mine"; - } - } + throw e; + } + finally { + // for cleanup + currentTenant = "mine"; + } + } - @Test - public void tenantFilterWithStatelessSession(SessionFactoryScope scope) { - currentTenant = "mine"; - Record myRecord1 = new Record(); - Record myRecord2 = new Record(); + @Test + public void tenantFilterWithStatelessSession(SessionFactoryScope scope) { + currentTenant = "mine"; + Record myRecord1 = new Record(); + Record myRecord2 = new Record(); - scope.inTransaction( session -> { - session.persist(myRecord1); - session.persist(myRecord2); - } ); - scope.inStatelessTransaction( session -> { - assertThat( listAllRecordsForTenant( session ) ).hasSize( 2 ); - } ); + scope.inTransaction( session -> { + session.persist(myRecord1); + session.persist(myRecord2); + } ); + scope.inStatelessTransaction( session -> { + assertThat( listAllRecordsForTenant( session ) ).hasSize( 2 ); + } ); - currentTenant = "yours"; - scope.inStatelessTransaction( session -> { - assertThat( listAllRecordsForTenant( session ) ).isEmpty(); - } ); - } + currentTenant = "yours"; + scope.inStatelessTransaction( session -> { + assertThat( listAllRecordsForTenant( session ) ).isEmpty(); + } ); + } - @Test - @JiraKey( value = "HHH-17972") - public void testChangeTenantId(SessionFactoryScope scope) { - currentTenant = "mine"; - scope.inSession( - session -> { - Query sessionQuery = session.createQuery( "from Client", Client.class ); + @Test + @JiraKey( value = "HHH-17972") + public void testChangeTenantId(SessionFactoryScope scope) { + currentTenant = "mine"; + scope.inSession( + session -> { + Query sessionQuery = session.createQuery( "from Client", Client.class ); - Transaction t = session.beginTransaction(); - session.persist( new Client("Gavin") ); - t.commit(); - assertEquals(1, sessionQuery.getResultList().size() ); - assertEquals( "mine", sessionQuery.getResultList().get( 0 ).tenantId ); + Transaction t = session.beginTransaction(); + session.persist( new Client("Gavin") ); + t.commit(); + assertEquals(1, sessionQuery.getResultList().size() ); + assertEquals( "mine", sessionQuery.getResultList().get( 0 ).tenantId ); - Session newSession = session.sessionWithOptions().tenantIdentifier( "yours" ).connection().openSession(); - Query newSessionQuery = newSession.createQuery( "from Client", Client.class ); - t = newSession.beginTransaction(); - newSession.persist( new Client("Jan") ); - t.commit(); + Session newSession = session.sessionWithOptions().tenantIdentifier( "yours" ).connection().openSession(); + Query newSessionQuery = newSession.createQuery( "from Client", Client.class ); + t = newSession.beginTransaction(); + newSession.persist( new Client("Jan") ); + t.commit(); - assertEquals(1, newSessionQuery.getResultList().size() ); - assertEquals( "yours", newSessionQuery.getResultList().get( 0 ).tenantId ); + assertEquals(1, newSessionQuery.getResultList().size() ); + assertEquals( "yours", newSessionQuery.getResultList().get( 0 ).tenantId ); - session.disableFilter( TenantIdBinder.FILTER_NAME ); - assertEquals(2, sessionQuery.getResultList().size() ); + session.disableFilter( TenantIdBinder.FILTER_NAME ); + assertEquals(2, sessionQuery.getResultList().size() ); - newSession.disableFilter( TenantIdBinder.FILTER_NAME ); - assertEquals(2, newSessionQuery.getResultList().size() ); + newSession.disableFilter( TenantIdBinder.FILTER_NAME ); + assertEquals(2, newSessionQuery.getResultList().size() ); - newSession.close(); - } - ); - } + newSession.close(); + } + ); + } - private static List listAllRecordsForTenant(StatelessSession session) { - HibernateCriteriaBuilder criteriaBuilder = session.getCriteriaBuilder(); - JpaCriteriaQuery criteriaQuery = criteriaBuilder.createQuery( Record.class ); - JpaRoot from = criteriaQuery.from( Record.class ); - return session.createQuery( criteriaQuery ).getResultList(); - } + private static List listAllRecordsForTenant(StatelessSession session) { + HibernateCriteriaBuilder criteriaBuilder = session.getCriteriaBuilder(); + JpaCriteriaQuery criteriaQuery = criteriaBuilder.createQuery( Record.class ); + JpaRoot from = criteriaQuery.from( Record.class ); + return session.createQuery( criteriaQuery ).getResultList(); + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/tenantidpk/Account.java b/hibernate-core/src/test/java/org/hibernate/orm/test/tenantidpk/Account.java index 605f7be9b2..9c5f35c5c4 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/tenantidpk/Account.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/tenantidpk/Account.java @@ -18,16 +18,16 @@ import java.util.UUID; @Entity @IdClass(TenantizedId.class) public class Account { - @Id @GeneratedValue Long id; + @Id @GeneratedValue Long id; - @Id @TenantId UUID tenantId; + @Id @TenantId UUID tenantId; - @ManyToOne(optional = false) - Client client; + @ManyToOne(optional = false) + Client client; - public Account(Client client) { - this.client = client; - } + public Account(Client client) { + this.client = client; + } - Account() {} + Account() {} } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/tenantidpk/Client.java b/hibernate-core/src/test/java/org/hibernate/orm/test/tenantidpk/Client.java index 9d56c8e261..5b5b4e07a1 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/tenantidpk/Client.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/tenantidpk/Client.java @@ -18,21 +18,21 @@ import java.util.UUID; @Entity public class Client { - @Id - @GeneratedValue - Long id; + @Id + @GeneratedValue + Long id; - String name; + String name; - @Id @TenantId - UUID tenantId; + @Id @TenantId + UUID tenantId; - @OneToMany(mappedBy = "client") - Set accounts = new HashSet<>(); + @OneToMany(mappedBy = "client") + Set accounts = new HashSet<>(); - public Client(String name) { - this.name = name; - } + public Client(String name) { + this.name = name; + } - Client() {} + Client() {} } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/tenantidpk/TenantPkTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/tenantidpk/TenantPkTest.java index 998eaf1e8b..60f86959c4 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/tenantidpk/TenantPkTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/tenantidpk/TenantPkTest.java @@ -30,83 +30,83 @@ import static org.junit.jupiter.api.Assertions.assertNull; @SessionFactory @DomainModel(annotatedClasses = { Account.class, Client.class }) @ServiceRegistry( - settings = { - @Setting(name = JAKARTA_HBM2DDL_DATABASE_ACTION, value = "create-drop") - } + settings = { + @Setting(name = JAKARTA_HBM2DDL_DATABASE_ACTION, value = "create-drop") + } ) public class TenantPkTest implements SessionFactoryProducer { - private static final UUID mine = UUID.randomUUID(); - private static final UUID yours = UUID.randomUUID(); + private static final UUID mine = UUID.randomUUID(); + private static final UUID yours = UUID.randomUUID(); - UUID currentTenant; + UUID currentTenant; - @AfterEach - public void cleanup(SessionFactoryScope scope) { - scope.inTransaction( session -> { - session.createQuery("delete from Account").executeUpdate(); - session.createQuery("delete from Client").executeUpdate(); - }); - } + @AfterEach + public void cleanup(SessionFactoryScope scope) { + scope.inTransaction( session -> { + session.createQuery("delete from Account").executeUpdate(); + session.createQuery("delete from Client").executeUpdate(); + }); + } - @Override - public SessionFactoryImplementor produceSessionFactory(MetadataImplementor model) { - final SessionFactoryBuilder sessionFactoryBuilder = model.getSessionFactoryBuilder(); - sessionFactoryBuilder.applyCurrentTenantIdentifierResolver( new CurrentTenantIdentifierResolver() { - @Override - public UUID resolveCurrentTenantIdentifier() { - return currentTenant; - } - @Override - public boolean validateExistingCurrentSessions() { - return false; - } - } ); - return (SessionFactoryImplementor) sessionFactoryBuilder.build(); - } + @Override + public SessionFactoryImplementor produceSessionFactory(MetadataImplementor model) { + final SessionFactoryBuilder sessionFactoryBuilder = model.getSessionFactoryBuilder(); + sessionFactoryBuilder.applyCurrentTenantIdentifierResolver( new CurrentTenantIdentifierResolver() { + @Override + public UUID resolveCurrentTenantIdentifier() { + return currentTenant; + } + @Override + public boolean validateExistingCurrentSessions() { + return false; + } + } ); + return (SessionFactoryImplementor) sessionFactoryBuilder.build(); + } - @Test - public void test(SessionFactoryScope scope) { - currentTenant = mine; - Client client = new Client("Gavin"); - Account acc = new Account(client); - scope.inTransaction( session -> { - session.persist(client); - session.persist(acc); - } ); - scope.inTransaction( session -> { - assertNotNull( session.createSelectionQuery("where id=?1", Account.class) - .setParameter(1, acc.id) - .getSingleResultOrNull() ); - assertEquals( 1, session.createQuery("from Account").getResultList().size() ); - } ); - assertEquals(mine, acc.tenantId); + @Test + public void test(SessionFactoryScope scope) { + currentTenant = mine; + Client client = new Client("Gavin"); + Account acc = new Account(client); + scope.inTransaction( session -> { + session.persist(client); + session.persist(acc); + } ); + scope.inTransaction( session -> { + assertNotNull( session.createSelectionQuery("where id=?1", Account.class) + .setParameter(1, acc.id) + .getSingleResultOrNull() ); + assertEquals( 1, session.createQuery("from Account").getResultList().size() ); + } ); + assertEquals(mine, acc.tenantId); - currentTenant = yours; - scope.inTransaction( session -> { - assertNull( session.createSelectionQuery("where id=?1", Account.class) - .setParameter(1, acc.id) - .getSingleResultOrNull() ); - assertEquals( 0, session.createQuery("from Account").getResultList().size() ); - session.disableFilter(TenantIdBinder.FILTER_NAME); - assertNotNull( session.createSelectionQuery("where id=?1", Account.class) - .setParameter(1, acc.id) - .getSingleResultOrNull() ); - assertEquals( 1, session.createQuery("from Account").getResultList().size() ); - } ); - } + currentTenant = yours; + scope.inTransaction( session -> { + assertNull( session.createSelectionQuery("where id=?1", Account.class) + .setParameter(1, acc.id) + .getSingleResultOrNull() ); + assertEquals( 0, session.createQuery("from Account").getResultList().size() ); + session.disableFilter(TenantIdBinder.FILTER_NAME); + assertNotNull( session.createSelectionQuery("where id=?1", Account.class) + .setParameter(1, acc.id) + .getSingleResultOrNull() ); + assertEquals( 1, session.createQuery("from Account").getResultList().size() ); + } ); + } - @Test - public void testErrorOnInsert(SessionFactoryScope scope) { - currentTenant = mine; - Client client = new Client("Gavin"); - Account acc = new Account(client); - acc.tenantId = yours; - scope.inTransaction( session -> { - session.persist(client); - session.persist(acc); - } ); - assertEquals( mine, acc.tenantId ); - assertEquals( mine, client.tenantId ); - } + @Test + public void testErrorOnInsert(SessionFactoryScope scope) { + currentTenant = mine; + Client client = new Client("Gavin"); + Account acc = new Account(client); + acc.tenantId = yours; + scope.inTransaction( session -> { + session.persist(client); + session.persist(acc); + } ); + assertEquals( mine, acc.tenantId ); + assertEquals( mine, client.tenantId ); + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/tenantlongid/Account.java b/hibernate-core/src/test/java/org/hibernate/orm/test/tenantlongid/Account.java index 09d86cc3de..8be26a7b99 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/tenantlongid/Account.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/tenantlongid/Account.java @@ -15,16 +15,16 @@ import org.hibernate.annotations.TenantId; @Entity public class Account { - @Id @GeneratedValue Long id; + @Id @GeneratedValue Long id; - @TenantId Long tenantId; + @TenantId Long tenantId; - @ManyToOne(optional = false) - Client client; + @ManyToOne(optional = false) + Client client; - public Account(Client client) { - this.client = client; - } + public Account(Client client) { + this.client = client; + } - Account() {} + Account() {} } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/tenantlongid/Client.java b/hibernate-core/src/test/java/org/hibernate/orm/test/tenantlongid/Client.java index da18cadeed..30021df5d8 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/tenantlongid/Client.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/tenantlongid/Client.java @@ -17,21 +17,21 @@ import java.util.Set; @Entity public class Client { - @Id - @GeneratedValue - Long id; + @Id + @GeneratedValue + Long id; - String name; + String name; - @TenantId - Long tenantId; + @TenantId + Long tenantId; - @OneToMany(mappedBy = "client") - Set accounts = new HashSet<>(); + @OneToMany(mappedBy = "client") + Set accounts = new HashSet<>(); - public Client(String name) { - this.name = name; - } + public Client(String name) { + this.name = name; + } - Client() {} + Client() {} } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/tenantlongid/TenantLongIdTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/tenantlongid/TenantLongIdTest.java index 0d98864d0d..8a2d717694 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/tenantlongid/TenantLongIdTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/tenantlongid/TenantLongIdTest.java @@ -27,104 +27,104 @@ import static org.junit.jupiter.api.Assertions.*; @SessionFactory @DomainModel(annotatedClasses = { Account.class, Client.class }) @ServiceRegistry( - settings = { - @Setting(name = JAKARTA_HBM2DDL_DATABASE_ACTION, value = "create-drop") - } + settings = { + @Setting(name = JAKARTA_HBM2DDL_DATABASE_ACTION, value = "create-drop") + } ) public class TenantLongIdTest implements SessionFactoryProducer { - private static final Long mine = 1L; - private static final Long yours = 2L; + private static final Long mine = 1L; + private static final Long yours = 2L; - Long currentTenant; + Long currentTenant; - @AfterEach - public void cleanup(SessionFactoryScope scope) { - scope.inTransaction( session -> { - session.createQuery("delete from Account").executeUpdate(); - session.createQuery("delete from Client").executeUpdate(); - }); - } + @AfterEach + public void cleanup(SessionFactoryScope scope) { + scope.inTransaction( session -> { + session.createQuery("delete from Account").executeUpdate(); + session.createQuery("delete from Client").executeUpdate(); + }); + } - @Override - public SessionFactoryImplementor produceSessionFactory(MetadataImplementor model) { - final SessionFactoryBuilder sessionFactoryBuilder = model.getSessionFactoryBuilder(); - sessionFactoryBuilder.applyCurrentTenantIdentifierResolver( new CurrentTenantIdentifierResolver() { - @Override - public Long resolveCurrentTenantIdentifier() { - return currentTenant; - } - @Override - public boolean validateExistingCurrentSessions() { - return false; - } - } ); - return (SessionFactoryImplementor) sessionFactoryBuilder.build(); - } + @Override + public SessionFactoryImplementor produceSessionFactory(MetadataImplementor model) { + final SessionFactoryBuilder sessionFactoryBuilder = model.getSessionFactoryBuilder(); + sessionFactoryBuilder.applyCurrentTenantIdentifierResolver( new CurrentTenantIdentifierResolver() { + @Override + public Long resolveCurrentTenantIdentifier() { + return currentTenant; + } + @Override + public boolean validateExistingCurrentSessions() { + return false; + } + } ); + return (SessionFactoryImplementor) sessionFactoryBuilder.build(); + } - @Test - public void test(SessionFactoryScope scope) { - currentTenant = mine; - Client client = new Client("Gavin"); - Account acc = new Account(client); - scope.inTransaction( session -> { - session.persist(client); - session.persist(acc); - } ); - scope.inTransaction( session -> { - assertNotNull( session.find(Account.class, acc.id) ); - assertEquals( 1, session.createQuery("from Account").getResultList().size() ); - } ); - assertEquals(mine, acc.tenantId); + @Test + public void test(SessionFactoryScope scope) { + currentTenant = mine; + Client client = new Client("Gavin"); + Account acc = new Account(client); + scope.inTransaction( session -> { + session.persist(client); + session.persist(acc); + } ); + scope.inTransaction( session -> { + assertNotNull( session.find(Account.class, acc.id) ); + assertEquals( 1, session.createQuery("from Account").getResultList().size() ); + } ); + assertEquals(mine, acc.tenantId); - currentTenant = yours; - scope.inTransaction( session -> { - //HHH-16830 Sessions applies tenantId filter on find() - assertNull( session.find(Account.class, acc.id) ); - assertEquals( 0, session.createQuery("from Account").getResultList().size() ); - session.disableFilter(TenantIdBinder.FILTER_NAME); - assertNotNull( session.find(Account.class, acc.id) ); - assertEquals( 1, session.createQuery("from Account").getResultList().size() ); - } ); - } + currentTenant = yours; + scope.inTransaction( session -> { + //HHH-16830 Sessions applies tenantId filter on find() + assertNull( session.find(Account.class, acc.id) ); + assertEquals( 0, session.createQuery("from Account").getResultList().size() ); + session.disableFilter(TenantIdBinder.FILTER_NAME); + assertNotNull( session.find(Account.class, acc.id) ); + assertEquals( 1, session.createQuery("from Account").getResultList().size() ); + } ); + } - @Test - public void testErrorOnInsert(SessionFactoryScope scope) { - currentTenant = mine; - Client client = new Client("Gavin"); - Account acc = new Account(client); - acc.tenantId = yours; - try { - scope.inTransaction( session -> { - session.persist(client); - session.persist(acc); - } ); - fail("should have thrown"); - } - catch (Throwable e) { - assertTrue( e instanceof PropertyValueException ); - } - } + @Test + public void testErrorOnInsert(SessionFactoryScope scope) { + currentTenant = mine; + Client client = new Client("Gavin"); + Account acc = new Account(client); + acc.tenantId = yours; + try { + scope.inTransaction( session -> { + session.persist(client); + session.persist(acc); + } ); + fail("should have thrown"); + } + catch (Throwable e) { + assertTrue( e instanceof PropertyValueException ); + } + } - @Test - public void testErrorOnUpdate(SessionFactoryScope scope) { - currentTenant = mine; - Client client = new Client("Gavin"); - Account acc = new Account(client); - scope.inTransaction( session -> { - session.persist(client); - session.persist(acc); - acc.tenantId = yours; - client.tenantId = yours; - client.name = "Steve"; - } ); - //TODO: it would be better if this were an error - scope.inTransaction( session -> { - Account account = session.find(Account.class, acc.id); - assertNotNull(account); - assertEquals( mine, acc.tenantId ); - assertEquals( "Steve", acc.client.name ); - assertEquals( mine, acc.client.tenantId ); - } ); - } + @Test + public void testErrorOnUpdate(SessionFactoryScope scope) { + currentTenant = mine; + Client client = new Client("Gavin"); + Account acc = new Account(client); + scope.inTransaction( session -> { + session.persist(client); + session.persist(acc); + acc.tenantId = yours; + client.tenantId = yours; + client.name = "Steve"; + } ); + //TODO: it would be better if this were an error + scope.inTransaction( session -> { + Account account = session.find(Account.class, acc.id); + assertNotNull(account); + assertEquals( mine, acc.tenantId ); + assertEquals( "Steve", acc.client.name ); + assertEquals( mine, acc.client.tenantId ); + } ); + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/tenantuuid/Account.java b/hibernate-core/src/test/java/org/hibernate/orm/test/tenantuuid/Account.java index 18a8803d77..0cc2fda670 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/tenantuuid/Account.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/tenantuuid/Account.java @@ -17,16 +17,16 @@ import java.util.UUID; @Entity public class Account { - @Id @GeneratedValue Long id; + @Id @GeneratedValue Long id; - @TenantId UUID tenantId; + @TenantId UUID tenantId; - @ManyToOne(optional = false) - Client client; + @ManyToOne(optional = false) + Client client; - public Account(Client client) { - this.client = client; - } + public Account(Client client) { + this.client = client; + } - Account() {} + Account() {} } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/tenantuuid/Client.java b/hibernate-core/src/test/java/org/hibernate/orm/test/tenantuuid/Client.java index 7eeab1f352..94e840f4c8 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/tenantuuid/Client.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/tenantuuid/Client.java @@ -18,21 +18,21 @@ import java.util.UUID; @Entity public class Client { - @Id - @GeneratedValue - Long id; + @Id + @GeneratedValue + Long id; - String name; + String name; - @TenantId - UUID tenantId; + @TenantId + UUID tenantId; - @OneToMany(mappedBy = "client") - Set accounts = new HashSet<>(); + @OneToMany(mappedBy = "client") + Set accounts = new HashSet<>(); - public Client(String name) { - this.name = name; - } + public Client(String name) { + this.name = name; + } - Client() {} + Client() {} } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/tenantuuid/TenantUuidTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/tenantuuid/TenantUuidTest.java index 377235ee00..17abc35f3e 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/tenantuuid/TenantUuidTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/tenantuuid/TenantUuidTest.java @@ -35,104 +35,104 @@ import static org.junit.jupiter.api.Assertions.fail; @SessionFactory @DomainModel(annotatedClasses = { Account.class, Client.class }) @ServiceRegistry( - settings = { - @Setting(name = JAKARTA_HBM2DDL_DATABASE_ACTION, value = "create-drop") - } + settings = { + @Setting(name = JAKARTA_HBM2DDL_DATABASE_ACTION, value = "create-drop") + } ) public class TenantUuidTest implements SessionFactoryProducer { - private static final UUID mine = SafeRandomUUIDGenerator.safeRandomUUID(); - private static final UUID yours = SafeRandomUUIDGenerator.safeRandomUUID(); + private static final UUID mine = SafeRandomUUIDGenerator.safeRandomUUID(); + private static final UUID yours = SafeRandomUUIDGenerator.safeRandomUUID(); - UUID currentTenant; + UUID currentTenant; - @AfterEach - public void cleanup(SessionFactoryScope scope) { - scope.inTransaction( session -> { - session.createQuery("delete from Account").executeUpdate(); - session.createQuery("delete from Client").executeUpdate(); - }); - } + @AfterEach + public void cleanup(SessionFactoryScope scope) { + scope.inTransaction( session -> { + session.createQuery("delete from Account").executeUpdate(); + session.createQuery("delete from Client").executeUpdate(); + }); + } - @Override - public SessionFactoryImplementor produceSessionFactory(MetadataImplementor model) { - final SessionFactoryBuilder sessionFactoryBuilder = model.getSessionFactoryBuilder(); - sessionFactoryBuilder.applyCurrentTenantIdentifierResolver( new CurrentTenantIdentifierResolver() { - @Override - public UUID resolveCurrentTenantIdentifier() { - return currentTenant; - } - @Override - public boolean validateExistingCurrentSessions() { - return false; - } - } ); - return (SessionFactoryImplementor) sessionFactoryBuilder.build(); - } + @Override + public SessionFactoryImplementor produceSessionFactory(MetadataImplementor model) { + final SessionFactoryBuilder sessionFactoryBuilder = model.getSessionFactoryBuilder(); + sessionFactoryBuilder.applyCurrentTenantIdentifierResolver( new CurrentTenantIdentifierResolver() { + @Override + public UUID resolveCurrentTenantIdentifier() { + return currentTenant; + } + @Override + public boolean validateExistingCurrentSessions() { + return false; + } + } ); + return (SessionFactoryImplementor) sessionFactoryBuilder.build(); + } - @Test - public void test(SessionFactoryScope scope) { - currentTenant = mine; - Client client = new Client("Gavin"); - Account acc = new Account(client); - scope.inTransaction( session -> { - session.persist(client); - session.persist(acc); - } ); - scope.inTransaction( session -> { - assertNotNull( session.find(Account.class, acc.id) ); - assertEquals( 1, session.createQuery("from Account").getResultList().size() ); - } ); - assertEquals(mine, acc.tenantId); + @Test + public void test(SessionFactoryScope scope) { + currentTenant = mine; + Client client = new Client("Gavin"); + Account acc = new Account(client); + scope.inTransaction( session -> { + session.persist(client); + session.persist(acc); + } ); + scope.inTransaction( session -> { + assertNotNull( session.find(Account.class, acc.id) ); + assertEquals( 1, session.createQuery("from Account").getResultList().size() ); + } ); + assertEquals(mine, acc.tenantId); - currentTenant = yours; - scope.inTransaction( session -> { - //HHH-16830 Sessions applies tenantId filter on find() - assertNull( session.find(Account.class, acc.id) ); - assertEquals( 0, session.createQuery("from Account").getResultList().size() ); - session.disableFilter(TenantIdBinder.FILTER_NAME); - assertNotNull( session.find(Account.class, acc.id) ); - assertEquals( 1, session.createQuery("from Account").getResultList().size() ); - } ); - } + currentTenant = yours; + scope.inTransaction( session -> { + //HHH-16830 Sessions applies tenantId filter on find() + assertNull( session.find(Account.class, acc.id) ); + assertEquals( 0, session.createQuery("from Account").getResultList().size() ); + session.disableFilter(TenantIdBinder.FILTER_NAME); + assertNotNull( session.find(Account.class, acc.id) ); + assertEquals( 1, session.createQuery("from Account").getResultList().size() ); + } ); + } - @Test - public void testErrorOnInsert(SessionFactoryScope scope) { - currentTenant = mine; - Client client = new Client("Gavin"); - Account acc = new Account(client); - acc.tenantId = yours; - try { - scope.inTransaction( session -> { - session.persist(client); - session.persist(acc); - } ); - fail("should have thrown"); - } - catch (Throwable e) { - assertTrue( e instanceof PropertyValueException ); - } - } + @Test + public void testErrorOnInsert(SessionFactoryScope scope) { + currentTenant = mine; + Client client = new Client("Gavin"); + Account acc = new Account(client); + acc.tenantId = yours; + try { + scope.inTransaction( session -> { + session.persist(client); + session.persist(acc); + } ); + fail("should have thrown"); + } + catch (Throwable e) { + assertTrue( e instanceof PropertyValueException ); + } + } - @Test - public void testErrorOnUpdate(SessionFactoryScope scope) { - currentTenant = mine; - Client client = new Client("Gavin"); - Account acc = new Account(client); - scope.inTransaction( session -> { - session.persist(client); - session.persist(acc); - acc.tenantId = yours; - client.tenantId = yours; - client.name = "Steve"; - } ); - //TODO: it would be better if this were an error - scope.inTransaction( session -> { - Account account = session.find(Account.class, acc.id); - assertNotNull(account); - assertEquals( mine, acc.tenantId ); - assertEquals( "Steve", acc.client.name ); - assertEquals( mine, acc.client.tenantId ); - } ); - } + @Test + public void testErrorOnUpdate(SessionFactoryScope scope) { + currentTenant = mine; + Client client = new Client("Gavin"); + Account acc = new Account(client); + scope.inTransaction( session -> { + session.persist(client); + session.persist(acc); + acc.tenantId = yours; + client.tenantId = yours; + client.name = "Steve"; + } ); + //TODO: it would be better if this were an error + scope.inTransaction( session -> { + Account account = session.find(Account.class, acc.id); + assertNotNull(account); + assertEquals( mine, acc.tenantId ); + assertEquals( "Steve", acc.client.name ); + assertEquals( mine, acc.client.tenantId ); + } ); + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/timestamp/JdbcTimestampCustomSessionLevelTimeZoneTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/timestamp/JdbcTimestampCustomSessionLevelTimeZoneTest.java index c7f165f007..741c08ea70 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/timestamp/JdbcTimestampCustomSessionLevelTimeZoneTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/timestamp/JdbcTimestampCustomSessionLevelTimeZoneTest.java @@ -103,7 +103,7 @@ public class JdbcTimestampCustomSessionLevelTimeZoneTest .getOffset( 0 ) - TIME_ZONE.getOffset( 0 ); assertEquals( Math.abs( Long.valueOf( offsetDiff ) - .longValue() ), + .longValue() ), Math.abs( timestamp.getTime() ) ); } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/timestamp/JdbcTimestampCustomTimeZoneTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/timestamp/JdbcTimestampCustomTimeZoneTest.java index bc1e667e9f..f6178adf4e 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/timestamp/JdbcTimestampCustomTimeZoneTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/timestamp/JdbcTimestampCustomTimeZoneTest.java @@ -105,7 +105,7 @@ public class JdbcTimestampCustomTimeZoneTest .getOffset( 0 ) - TIME_ZONE.getOffset( 0 ); assertEquals( Math.abs( Long.valueOf( offsetDiff ) - .longValue() ), + .longValue() ), Math.abs( timestamp.getTime() ) ); } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/tool/schema/MySQLColumnValidationTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/tool/schema/MySQLColumnValidationTest.java index 54e0786652..057b7439ff 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/tool/schema/MySQLColumnValidationTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/tool/schema/MySQLColumnValidationTest.java @@ -88,23 +88,23 @@ public class MySQLColumnValidationTest { } statement.execute( "CREATE TABLE `TEST_DATA1` ( " + - " `ID` int unsigned NOT NULL, " + - " `INTEGRAL1` tinyint unsigned DEFAULT '0', " + - " `INTEGRAL2` tinyint unsigned DEFAULT '0', " + - " PRIMARY KEY (`ID`)" + - ") ENGINE=InnoDB" ); + " `ID` int unsigned NOT NULL, " + + " `INTEGRAL1` tinyint unsigned DEFAULT '0', " + + " `INTEGRAL2` tinyint unsigned DEFAULT '0', " + + " PRIMARY KEY (`ID`)" + + ") ENGINE=InnoDB" ); statement.execute( "CREATE TABLE `TEST_DATA2` ( " + - " `ID` int unsigned NOT NULL, " + - " `INTEGRAL1` tinyint unsigned DEFAULT '0', " + - " PRIMARY KEY (`ID`)" + - ") ENGINE=InnoDB" ); + " `ID` int unsigned NOT NULL, " + + " `INTEGRAL1` tinyint unsigned DEFAULT '0', " + + " PRIMARY KEY (`ID`)" + + ") ENGINE=InnoDB" ); statement.execute( "CREATE TABLE `TEST_DATA3` ( " + - " `ID` int unsigned NOT NULL, " + - " `INTEGRAL1` tinyint unsigned DEFAULT '0', " + - " PRIMARY KEY (`ID`)" + - ") ENGINE=InnoDB" ); + " `ID` int unsigned NOT NULL, " + + " `INTEGRAL1` tinyint unsigned DEFAULT '0', " + + " PRIMARY KEY (`ID`)" + + ") ENGINE=InnoDB" ); } catch (SQLException e) { @@ -171,9 +171,9 @@ public class MySQLColumnValidationTest { try { schemaValidator.doValidation( scope.getMetadataImplementor(), executionOptions, - contributed -> { + contributed -> { return "test_data1".equalsIgnoreCase( contributed.getExportIdentifier() ); - } ); + } ); } catch (SchemaManagementException e) { fail( e.getMessage() ); @@ -181,9 +181,9 @@ public class MySQLColumnValidationTest { try { schemaValidator.doValidation( scope.getMetadataImplementor(), executionOptions, - contributed -> { - return "test_data2".equalsIgnoreCase( contributed.getExportIdentifier() ); - } ); + contributed -> { + return "test_data2".equalsIgnoreCase( contributed.getExportIdentifier() ); + } ); fail( "SchemaManagementException expected" ); } catch (SchemaManagementException e) { @@ -195,9 +195,9 @@ public class MySQLColumnValidationTest { try { schemaValidator.doValidation( scope.getMetadataImplementor(), executionOptions, - contributed -> { - return "test_data3".equalsIgnoreCase( contributed.getExportIdentifier() ); - } ); + contributed -> { + return "test_data3".equalsIgnoreCase( contributed.getExportIdentifier() ); + } ); fail( "SchemaManagementException expected" ); } catch (SchemaManagementException e) { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/transactions/TransactionsTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/transactions/TransactionsTest.java index ffeed068f7..32ef78f3d5 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/transactions/TransactionsTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/transactions/TransactionsTest.java @@ -49,7 +49,7 @@ public class TransactionsTest extends BaseEntityManagerFunctionalTestCase { .build(); //end::transactions-api-jdbc-example[] - */ + */ //tag::transactions-api-jdbc-example[] Metadata metadata = new MetadataSources(serviceRegistry) diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/type/BooleanArrayTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/type/BooleanArrayTest.java index 60d274f572..2b155bd840 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/type/BooleanArrayTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/type/BooleanArrayTest.java @@ -90,7 +90,7 @@ public class BooleanArrayTest { @Test @SkipForDialect( dialectClass = OracleDialect.class, reason = "External driver fix required") public void testQueryById(SessionFactoryScope scope) { - scope.inSession( em -> { + scope.inSession( em -> { TypedQuery tq = em.createNamedQuery( "TableWithBooleanArrays.JPQL.getById", TableWithBooleanArrays.class ); tq.setParameter( "id", 2L ); TableWithBooleanArrays tableRecord = tq.getSingleResult(); @@ -100,8 +100,8 @@ public class BooleanArrayTest { @Test @SkipForDialect( dialectClass = OracleDialect.class, reason = "External driver fix required") - public void testQuery(SessionFactoryScope scope) { - scope.inSession( em -> { + public void testQuery(SessionFactoryScope scope) { + scope.inSession( em -> { TypedQuery tq = em.createNamedQuery( "TableWithBooleanArrays.JPQL.getByData", TableWithBooleanArrays.class ); tq.setParameter( "data", new Boolean[]{} ); TableWithBooleanArrays tableRecord = tq.getSingleResult(); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/type/LobUnfetchedPropertyTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/type/LobUnfetchedPropertyTest.java index f5d3b09b44..4ab8bd6833 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/type/LobUnfetchedPropertyTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/type/LobUnfetchedPropertyTest.java @@ -125,15 +125,15 @@ public class LobUnfetchedPropertyTest { NClob nClob = file.getClob(); assertTrue( Hibernate.isPropertyInitialized( file, "clob" ) ); try { - final char[] chars = new char[(int) file.getClob().length()]; - nClob.getCharacterStream().read( chars ); + final char[] chars = new char[(int) file.getClob().length()]; + nClob.getCharacterStream().read( chars ); assertArrayEquals( "TEST CASE".toCharArray(), chars ); } catch (SQLException ex ) { - fail( "could not determine Lob length" ); + fail( "could not determine Lob length" ); } catch (IOException ex) { - fail( "could not read Lob" ); + fail( "could not read Lob" ); } }); } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/type/contributor/ArrayJavaType.java b/hibernate-core/src/test/java/org/hibernate/orm/test/type/contributor/ArrayJavaType.java index b4ba92d16d..b8665076c0 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/type/contributor/ArrayJavaType.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/type/contributor/ArrayJavaType.java @@ -19,77 +19,77 @@ import org.hibernate.type.descriptor.jdbc.JdbcTypeIndicators; */ public class ArrayJavaType extends AbstractClassJavaType { - private static final String DELIMITER = ","; + private static final String DELIMITER = ","; - public static final ArrayJavaType INSTANCE = new ArrayJavaType(); + public static final ArrayJavaType INSTANCE = new ArrayJavaType(); - public ArrayJavaType() { - super( Array.class ); - } + public ArrayJavaType() { + super( Array.class ); + } - @Override - public JdbcType getRecommendedJdbcType(JdbcTypeIndicators indicators) { - return indicators.getJdbcType( Types.VARCHAR ); - } + @Override + public JdbcType getRecommendedJdbcType(JdbcTypeIndicators indicators) { + return indicators.getJdbcType( Types.VARCHAR ); + } - @Override - public String toString(Array value) { - StringBuilder builder = new StringBuilder(); - for ( String token : value ) { - if ( builder.length() > 0 ) { - builder.append( DELIMITER ); - } - builder.append( token ); - } - return builder.toString(); - } + @Override + public String toString(Array value) { + StringBuilder builder = new StringBuilder(); + for ( String token : value ) { + if ( builder.length() > 0 ) { + builder.append( DELIMITER ); + } + builder.append( token ); + } + return builder.toString(); + } - public static String extractString(Array value) { - StringBuilder builder = new StringBuilder(); - for ( String token : value ) { - if ( builder.length() > 0 ) { - builder.append( DELIMITER ); - } - builder.append( token ); - } - return builder.toString(); - } + public static String extractString(Array value) { + StringBuilder builder = new StringBuilder(); + for ( String token : value ) { + if ( builder.length() > 0 ) { + builder.append( DELIMITER ); + } + builder.append( token ); + } + return builder.toString(); + } - @Override - public Array fromString(CharSequence string) { - if ( string == null || string.length() == 0 ) { - return null; - } - String[] tokens = string.toString().split( DELIMITER ); - Array array = new Array(); - array.addAll( Arrays.asList(tokens) ); - return array; - } + @Override + public Array fromString(CharSequence string) { + if ( string == null || string.length() == 0 ) { + return null; + } + String[] tokens = string.toString().split( DELIMITER ); + Array array = new Array(); + array.addAll( Arrays.asList(tokens) ); + return array; + } - @SuppressWarnings("unchecked") - public X unwrap(Array value, Class type, WrapperOptions options) { - if ( value == null ) { - return null; - } - if ( Array.class.isAssignableFrom( type ) ) { - return (X) value; - } - if ( String.class.isAssignableFrom( type ) ) { - return (X) toString( value); - } - throw unknownUnwrap( type ); - } + @SuppressWarnings("unchecked") + public X unwrap(Array value, Class type, WrapperOptions options) { + if ( value == null ) { + return null; + } + if ( Array.class.isAssignableFrom( type ) ) { + return (X) value; + } + if ( String.class.isAssignableFrom( type ) ) { + return (X) toString( value); + } + throw unknownUnwrap( type ); + } - public Array wrap(X value, WrapperOptions options) { - if ( value == null ) { - return null; - } - if ( value instanceof String ) { - return fromString( (String) value ); - } - if ( value instanceof Array ) { - return (Array) value; - } - throw unknownWrap( value.getClass() ); - } + public Array wrap(X value, WrapperOptions options) { + if ( value == null ) { + return null; + } + if ( value instanceof String ) { + return fromString( (String) value ); + } + if ( value instanceof Array ) { + return (Array) value; + } + throw unknownWrap( value.getClass() ); + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/type/contributor/ArrayType.java b/hibernate-core/src/test/java/org/hibernate/orm/test/type/contributor/ArrayType.java index beba6ef95a..b0bd5616c5 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/type/contributor/ArrayType.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/type/contributor/ArrayType.java @@ -29,107 +29,107 @@ import org.hibernate.usertype.UserType; * @author Vlad Mihalcea */ public class ArrayType implements UserType, BindableType, BasicValueConverter { - public static final ArrayType INSTANCE = new ArrayType(); + public static final ArrayType INSTANCE = new ArrayType(); - private final BasicJavaType javaType = ArrayJavaType.INSTANCE; - private final JdbcType jdbcType = VarcharJdbcType.INSTANCE; + private final BasicJavaType javaType = ArrayJavaType.INSTANCE; + private final JdbcType jdbcType = VarcharJdbcType.INSTANCE; - @Override - public Class getBindableJavaType() { - // really a UserType should not implement BindableType - return Array.class; - } + @Override + public Class getBindableJavaType() { + // really a UserType should not implement BindableType + return Array.class; + } - @Override - public SqmExpressible resolveExpressible(BindingContext bindingContext) { - // really a UserType should not implement BindableType - throw new UnsupportedOperationException(); - } + @Override + public SqmExpressible resolveExpressible(BindingContext bindingContext) { + // really a UserType should not implement BindableType + throw new UnsupportedOperationException(); + } - @Override - public int getSqlType() { - return jdbcType.getJdbcTypeCode(); - } + @Override + public int getSqlType() { + return jdbcType.getJdbcTypeCode(); + } - @Override - public JdbcType getJdbcType(TypeConfiguration typeConfiguration) { - return jdbcType; - } + @Override + public JdbcType getJdbcType(TypeConfiguration typeConfiguration) { + return jdbcType; + } - @Override - public Class returnedClass() { - return Array.class; - } + @Override + public Class returnedClass() { + return Array.class; + } - @Override - public boolean equals(Array x, Array y) throws HibernateException { - return javaType.areEqual( x, y ); - } + @Override + public boolean equals(Array x, Array y) throws HibernateException { + return javaType.areEqual( x, y ); + } - @Override - public int hashCode(Array x) throws HibernateException { - return javaType.extractHashCode( x ); - } + @Override + public int hashCode(Array x) throws HibernateException { + return javaType.extractHashCode( x ); + } - @Override - public Array nullSafeGet(ResultSet rs, int position, SharedSessionContractImplementor session) - throws SQLException { - return jdbcType.getExtractor( javaType ).extract( rs, position, session ); - } + @Override + public Array nullSafeGet(ResultSet rs, int position, SharedSessionContractImplementor session) + throws SQLException { + return jdbcType.getExtractor( javaType ).extract( rs, position, session ); + } - @Override - public void nullSafeSet(PreparedStatement st, Array value, int index, SharedSessionContractImplementor session) - throws SQLException { - jdbcType.getBinder( javaType ).bind( st, value, index, session ); - } + @Override + public void nullSafeSet(PreparedStatement st, Array value, int index, SharedSessionContractImplementor session) + throws SQLException { + jdbcType.getBinder( javaType ).bind( st, value, index, session ); + } - @Override - public BasicValueConverter getValueConverter() { - return (BasicValueConverter) this; - } + @Override + public BasicValueConverter getValueConverter() { + return (BasicValueConverter) this; + } - @Override - public Array toDomainValue(String relationalForm) { - return assemble( relationalForm, null ); - } + @Override + public Array toDomainValue(String relationalForm) { + return assemble( relationalForm, null ); + } - @Override - public String toRelationalValue(Array domainForm) { - return (String) disassemble( domainForm ); - } + @Override + public String toRelationalValue(Array domainForm) { + return (String) disassemble( domainForm ); + } - @Override - public JavaType getDomainJavaType() { - return javaType; - } + @Override + public JavaType getDomainJavaType() { + return javaType; + } - @Override - public JavaType getRelationalJavaType() { - return StringJavaType.INSTANCE; - } + @Override + public JavaType getRelationalJavaType() { + return StringJavaType.INSTANCE; + } - @Override - public Array deepCopy(Array value) throws HibernateException { - return ArrayMutabilityPlan.INSTANCE.deepCopy( value ); - } + @Override + public Array deepCopy(Array value) throws HibernateException { + return ArrayMutabilityPlan.INSTANCE.deepCopy( value ); + } - @Override - public boolean isMutable() { - return true; - } + @Override + public boolean isMutable() { + return true; + } - @Override - public Serializable disassemble(Array value) throws HibernateException { - return ArrayMutabilityPlan.INSTANCE.disassemble( value, null ); - } + @Override + public Serializable disassemble(Array value) throws HibernateException { + return ArrayMutabilityPlan.INSTANCE.disassemble( value, null ); + } - @Override - public Array assemble(Serializable cached, Object owner) throws HibernateException { - return ArrayMutabilityPlan.INSTANCE.assemble( cached, null ); - } + @Override + public Array assemble(Serializable cached, Object owner) throws HibernateException { + return ArrayMutabilityPlan.INSTANCE.assemble( cached, null ); + } - @Override - public Array replace(Array original, Array target, Object owner) throws HibernateException { - return null; - } + @Override + public Array replace(Array original, Array target, Object owner) throws HibernateException { + return null; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/type/contributor/usertype/StringWrapper.java b/hibernate-core/src/test/java/org/hibernate/orm/test/type/contributor/usertype/StringWrapper.java index dbfbba7097..6b61da726a 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/type/contributor/usertype/StringWrapper.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/type/contributor/usertype/StringWrapper.java @@ -13,32 +13,32 @@ import java.io.Serializable; */ public class StringWrapper implements Serializable { - private final String value; + private final String value; - public StringWrapper(String value) { - this.value = value; - } + public StringWrapper(String value) { + this.value = value; + } - public String getValue() { - return value; - } + public String getValue() { + return value; + } - @Override - public boolean equals(Object o) { - if ( this == o ) { - return true; - } - if ( o == null || getClass() != o.getClass() ) { - return false; - } + @Override + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( o == null || getClass() != o.getClass() ) { + return false; + } - StringWrapper that = (StringWrapper) o; + StringWrapper that = (StringWrapper) o; - return value.equals( that.value ); - } + return value.equals( that.value ); + } - @Override - public int hashCode() { - return value.hashCode(); - } + @Override + public int hashCode() { + return value.hashCode(); + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/type/contributor/usertype/StringWrapperUserType.java b/hibernate-core/src/test/java/org/hibernate/orm/test/type/contributor/usertype/StringWrapperUserType.java index 4a6c7b2192..f2881843d1 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/type/contributor/usertype/StringWrapperUserType.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/type/contributor/usertype/StringWrapperUserType.java @@ -26,89 +26,89 @@ public class StringWrapperUserType implements UserType { public static final StringWrapperUserType INSTANCE = new StringWrapperUserType(); - private static final Logger log = Logger.getLogger( StringWrapperUserType.class ); + private static final Logger log = Logger.getLogger( StringWrapperUserType.class ); - @Override - public int getSqlType() { - return Types.VARCHAR; - } + @Override + public int getSqlType() { + return Types.VARCHAR; + } - @Override - public Class returnedClass() { - return StringWrapper.class; - } + @Override + public Class returnedClass() { + return StringWrapper.class; + } - @Override - public boolean equals(StringWrapper x, StringWrapper y) + @Override + public boolean equals(StringWrapper x, StringWrapper y) throws HibernateException { - return Objects.equals( x, y ); - } + return Objects.equals( x, y ); + } - @Override - public int hashCode(StringWrapper x) + @Override + public int hashCode(StringWrapper x) throws HibernateException { - return Objects.hashCode( x ); - } + return Objects.hashCode( x ); + } - @Override - public StringWrapper nullSafeGet(ResultSet rs, int position, SharedSessionContractImplementor session) - throws SQLException { - String columnValue = (String) rs.getObject( position ); - log.debugv( "Result set column {0} value is {1}", position, columnValue ); - return columnValue == null ? null : fromString( columnValue ); - } + @Override + public StringWrapper nullSafeGet(ResultSet rs, int position, SharedSessionContractImplementor session) + throws SQLException { + String columnValue = (String) rs.getObject( position ); + log.debugv( "Result set column {0} value is {1}", position, columnValue ); + return columnValue == null ? null : fromString( columnValue ); + } - @Override - public void nullSafeSet( - PreparedStatement st, StringWrapper value, int index, SharedSessionContractImplementor session) - throws SQLException { - if ( value == null ) { - log.debugv("Binding null to parameter {0} ",index); - st.setNull( index, Types.VARCHAR ); - } - else { - String stringValue = toString( value ); - log.debugv("Binding {0} to parameter {1} ", stringValue, index); - st.setString( index, stringValue ); - } - } - public String toString(StringWrapper value) { - return value.getValue(); - } + @Override + public void nullSafeSet( + PreparedStatement st, StringWrapper value, int index, SharedSessionContractImplementor session) + throws SQLException { + if ( value == null ) { + log.debugv("Binding null to parameter {0} ",index); + st.setNull( index, Types.VARCHAR ); + } + else { + String stringValue = toString( value ); + log.debugv("Binding {0} to parameter {1} ", stringValue, index); + st.setString( index, stringValue ); + } + } + public String toString(StringWrapper value) { + return value.getValue(); + } - public StringWrapper fromString(String string) { - if ( string == null || string.isEmpty() ) { - return null; - } - return new StringWrapper( string ); - } + public StringWrapper fromString(String string) { + if ( string == null || string.isEmpty() ) { + return null; + } + return new StringWrapper( string ); + } - @Override - public StringWrapper deepCopy(StringWrapper value) + @Override + public StringWrapper deepCopy(StringWrapper value) throws HibernateException { - return value; - } + return value; + } - @Override - public boolean isMutable() { - return false; - } + @Override + public boolean isMutable() { + return false; + } - @Override - public Serializable disassemble(StringWrapper value) + @Override + public Serializable disassemble(StringWrapper value) throws HibernateException { - return value == null ? null : value.getValue().getBytes(); - } + return value == null ? null : value.getValue().getBytes(); + } - @Override - public StringWrapper assemble(Serializable cached, Object owner) + @Override + public StringWrapper assemble(Serializable cached, Object owner) throws HibernateException { - return new StringWrapper( new String( (byte[]) cached ) ); - } + return new StringWrapper( new String( (byte[]) cached ) ); + } - @Override - public StringWrapper replace(StringWrapper original, StringWrapper target, Object owner) + @Override + public StringWrapper replace(StringWrapper original, StringWrapper target, Object owner) throws HibernateException { - return deepCopy( original ); - } + return deepCopy( original ); + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/type/descriptor/jdbc/ArrayJdbcTypeTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/type/descriptor/jdbc/ArrayJdbcTypeTest.java index c4a7df2163..73835f9c88 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/type/descriptor/jdbc/ArrayJdbcTypeTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/type/descriptor/jdbc/ArrayJdbcTypeTest.java @@ -19,15 +19,15 @@ import java.util.Map; import static org.hamcrest.MatcherAssert.assertThat; public class ArrayJdbcTypeTest { - @Test - @JiraKey(value = "HHH-17662") - public void testEquality() { - Map typeMap = new HashMap<>(); - JdbcType bigInt = new BigIntJdbcType(); - typeMap.put(new ArrayJdbcType(bigInt), "bees"); - typeMap.put(new ArrayJdbcType(bigInt), "bees"); - typeMap.put(new ArrayJdbcType(bigInt), "bees"); - typeMap.put(new ArrayJdbcType(new IntegerJdbcType()), "waffles"); - assertThat("A map of arrays only contains non duplicate entries", typeMap.size() == 2); - } + @Test + @JiraKey(value = "HHH-17662") + public void testEquality() { + Map typeMap = new HashMap<>(); + JdbcType bigInt = new BigIntJdbcType(); + typeMap.put(new ArrayJdbcType(bigInt), "bees"); + typeMap.put(new ArrayJdbcType(bigInt), "bees"); + typeMap.put(new ArrayJdbcType(bigInt), "bees"); + typeMap.put(new ArrayJdbcType(new IntegerJdbcType()), "waffles"); + assertThat("A map of arrays only contains non duplicate entries", typeMap.size() == 2); + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/typedescriptor/Issue.java b/hibernate-core/src/test/java/org/hibernate/orm/test/typedescriptor/Issue.java index f6f9431ef3..3997c161af 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/typedescriptor/Issue.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/typedescriptor/Issue.java @@ -11,40 +11,40 @@ import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; import jakarta.persistence.Id; - /** - * @author Strong Liu - */ +/** +* @author Strong Liu +*/ @Entity - public class Issue { - @Id - @GeneratedValue - private Long id; - private String description; - @Column(columnDefinition = "char(8)") - private String issueNumber; +public class Issue { + @Id + @GeneratedValue + private Long id; + private String description; + @Column(columnDefinition = "char(8)") + private String issueNumber; - public String getDescription() { - return description; - } + public String getDescription() { + return description; + } - public void setDescription(String description) { - this.description = description; - } + public void setDescription(String description) { + this.description = description; + } - public Long getId() { - return id; - } + public Long getId() { + return id; + } - public void setId(Long id) { - this.id = id; - } + public void setId(Long id) { + this.id = id; + } - public String getIssueNumber() { - return issueNumber; - } + public String getIssueNumber() { + return issueNumber; + } - public void setIssueNumber(String issueNumber) { - this.issueNumber = issueNumber; - } - } + public void setIssueNumber(String issueNumber) { + this.issueNumber = issueNumber; + } +} diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/unidir/BackrefTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/unidir/BackrefTest.java index 888250b70f..6c1f97f192 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/unidir/BackrefTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/unidir/BackrefTest.java @@ -110,7 +110,7 @@ public class BackrefTest extends BaseCoreFunctionalTestCase { s.beginTransaction(); Parent me = new Parent( "Steve", 192837465 ); me.getChildren().add( new Child( "Joe" ) ); - s.persist( me ); + s.persist( me ); s.getTransaction().commit(); s.close(); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/unidir/Child1.java b/hibernate-core/src/test/java/org/hibernate/orm/test/unidir/Child1.java index b1f4ae41a1..37226d9926 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/unidir/Child1.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/unidir/Child1.java @@ -13,23 +13,23 @@ import java.util.List; @Entity @Table(name = "CHILD1") public class Child1 { - @Id - @Column(name = "ID") - private Long id; + @Id + @Column(name = "ID") + private Long id; - @OneToMany(fetch = FetchType.LAZY) - @JoinColumn(name = "CHILD1_ID", nullable = false) - private List parents = new ArrayList(); + @OneToMany(fetch = FetchType.LAZY) + @JoinColumn(name = "CHILD1_ID", nullable = false) + private List parents = new ArrayList(); - public Long getId() { - return this.id; - } + public Long getId() { + return this.id; + } - public List getParents() { - return this.parents; - } + public List getParents() { + return this.parents; + } - public void setParents(List parents) { - this.parents = parents; - } + public void setParents(List parents) { + this.parents = parents; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/unidir/Child2.java b/hibernate-core/src/test/java/org/hibernate/orm/test/unidir/Child2.java index 0d2dacbe07..d20c960646 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/unidir/Child2.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/unidir/Child2.java @@ -13,23 +13,23 @@ import java.util.List; @Entity @Table(name = "CHILD2") public class Child2 { - @Id - @Column(name = "ID") - private Long id; + @Id + @Column(name = "ID") + private Long id; - @OneToMany(fetch = FetchType.LAZY) - @JoinColumn(name = "CHILD2_ID", nullable = false) - private List parents = new ArrayList(); + @OneToMany(fetch = FetchType.LAZY) + @JoinColumn(name = "CHILD2_ID", nullable = false) + private List parents = new ArrayList(); - public Long getId() { - return this.id; - } + public Long getId() { + return this.id; + } - public List getParents() { - return this.parents; - } + public List getParents() { + return this.parents; + } - public void setParents(List parents) { - this.parents = parents; - } + public void setParents(List parents) { + this.parents = parents; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/unidir/Parent1.java b/hibernate-core/src/test/java/org/hibernate/orm/test/unidir/Parent1.java index a7c2db27c5..c4b567906e 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/unidir/Parent1.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/unidir/Parent1.java @@ -14,11 +14,11 @@ import jakarta.persistence.Table; @Entity @Table(name = "PARENT1") public class Parent1 { - @Id - @Column(name = "ID") - Long id; + @Id + @Column(name = "ID") + Long id; - public Long getId() { - return this.id; - } + public Long getId() { + return this.id; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/unionsubclass/UnionSubclassTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/unionsubclass/UnionSubclassTest.java index 8ecc693f71..eab4e0c60f 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/unionsubclass/UnionSubclassTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/unionsubclass/UnionSubclassTest.java @@ -525,28 +525,28 @@ public class UnionSubclassTest extends BaseSessionFactoryFunctionalTest { inTransaction( s2 -> { // Force connection acquisition s2.getJdbcCoordinator().getLogicalConnection().getPhysicalConnection(); - // Check same assertions for s2 as was done for s1. + // Check same assertions for s2 as was done for s1. assertTrue( s2.getJdbcCoordinator().getLogicalConnection().isPhysicallyConnected() ); - assertEquals( - PhysicalConnectionHandlingMode.DELAYED_ACQUISITION_AND_RELEASE_AFTER_TRANSACTION, - s2.getJdbcCoordinator().getLogicalConnection().getConnectionHandlingMode() - ); + assertEquals( + PhysicalConnectionHandlingMode.DELAYED_ACQUISITION_AND_RELEASE_AFTER_TRANSACTION, + s2.getJdbcCoordinator().getLogicalConnection().getConnectionHandlingMode() + ); - // Get the Connection s2 will use. - Connection connection2 = s2.getJdbcCoordinator().getLogicalConnection().getPhysicalConnection(); + // Get the Connection s2 will use. + Connection connection2 = s2.getJdbcCoordinator().getLogicalConnection().getPhysicalConnection(); - // Assert that connection2 is not the same as connection1 - assertNotSame( connection1, connection2 ); + // Assert that connection2 is not the same as connection1 + assertNotSame( connection1, connection2 ); - // Execute a bulk operation on s2 (using connection2) - assertEquals( - 1, - s2.createQuery( "delete from Being where species = 'Martian'" ).executeUpdate() - ); + // Execute a bulk operation on s2 (using connection2) + assertEquals( + 1, + s2.createQuery( "delete from Being where species = 'Martian'" ).executeUpdate() + ); - // Assert the Connection has not changed - assertSame( connection2, s2.getJdbcCoordinator().getLogicalConnection().getPhysicalConnection() ); - } + // Assert the Connection has not changed + assertSame( connection2, s2.getJdbcCoordinator().getLogicalConnection().getPhysicalConnection() ); + } ); // Assert that the Connection used by s1 has hot changed. diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/unionsubclass/alias/CarBuyer.java b/hibernate-core/src/test/java/org/hibernate/orm/test/unionsubclass/alias/CarBuyer.java index ed212fc6c3..2c26ce9e7c 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/unionsubclass/alias/CarBuyer.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/unionsubclass/alias/CarBuyer.java @@ -12,32 +12,32 @@ package org.hibernate.orm.test.unionsubclass.alias; * @author Strong Liu */ public class CarBuyer extends Customer { - private String sellerName; - private String pid; - private Seller seller; + private String sellerName; + private String pid; + private Seller seller; - public String getSellerName() { - return sellerName; - } + public String getSellerName() { + return sellerName; + } - public void setSellerName( String sellerName ) { - this.sellerName = sellerName; - } + public void setSellerName( String sellerName ) { + this.sellerName = sellerName; + } - public String getPid() { - return pid; - } + public String getPid() { + return pid; + } - public void setPid( String pid ) { - this.pid = pid; - } + public void setPid( String pid ) { + this.pid = pid; + } - public Seller getSeller() { - return seller; - } + public Seller getSeller() { + return seller; + } - public void setSeller( Seller seller ) { - this.seller = seller; - } + public void setSeller( Seller seller ) { + this.seller = seller; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/unionsubclass/alias/Customer.java b/hibernate-core/src/test/java/org/hibernate/orm/test/unionsubclass/alias/Customer.java index 24f0b04636..81e69419af 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/unionsubclass/alias/Customer.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/unionsubclass/alias/Customer.java @@ -12,28 +12,28 @@ import java.io.Serializable; * @author Strong Liu */ public abstract class Customer implements Serializable { - private PersonID id; + private PersonID id; - public PersonID getId() { - return id; - } + public PersonID getId() { + return id; + } - public void setId( PersonID id ) { - this.id = id; - } + public void setId( PersonID id ) { + this.id = id; + } - public boolean equals( Object obj ) { - if ( obj == null ) - return false; - if ( obj == this ) - return true; - if ( !( obj instanceof Customer ) ) - return false; - return ( (Customer) obj ).getId().equals( getId() ); - } + public boolean equals( Object obj ) { + if ( obj == null ) + return false; + if ( obj == this ) + return true; + if ( !( obj instanceof Customer ) ) + return false; + return ( (Customer) obj ).getId().equals( getId() ); + } - public int hashCode() { - return id.hashCode(); - } + public int hashCode() { + return id.hashCode(); + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/unionsubclass/alias/PersonID.java b/hibernate-core/src/test/java/org/hibernate/orm/test/unionsubclass/alias/PersonID.java index 109424e173..d90e3bcaec 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/unionsubclass/alias/PersonID.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/unionsubclass/alias/PersonID.java @@ -12,65 +12,65 @@ import java.io.Serializable; * @author Strong Liu */ public class PersonID implements Serializable { - private Long num; - private String name; + private Long num; + private String name; - public Long getNum() { - return num; - } + public Long getNum() { + return num; + } - public void setNum( Long num ) { - this.num = num; - } + public void setNum( Long num ) { + this.num = num; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName( String name ) { - this.name = name; - } + public void setName( String name ) { + this.name = name; + } - public boolean equals( Object obj ) { - if ( this == obj ) - return true; - if ( obj == null ) - return false; - if ( getClass() != obj.getClass() ) - return false; - final PersonID other = (PersonID) obj; - if ( name == null ) { - if ( other.name != null ) - return false; + public boolean equals( Object obj ) { + if ( this == obj ) + return true; + if ( obj == null ) + return false; + if ( getClass() != obj.getClass() ) + return false; + final PersonID other = (PersonID) obj; + if ( name == null ) { + if ( other.name != null ) + return false; - } else if ( !name.equals( other.name ) ) { - return false; - } - if ( num == null ) { - if ( other.num != null ) - return false; + } else if ( !name.equals( other.name ) ) { + return false; + } + if ( num == null ) { + if ( other.num != null ) + return false; - } else if ( !num.equals( other.num ) ) { - return false; - } - return true; - } + } else if ( !num.equals( other.num ) ) { + return false; + } + return true; + } - public int hashCode() { - final int PRIME = 31; - int result = 1; - if ( name != null ) { - result += name.hashCode(); - } - result *= PRIME; - if ( num != null ) { - result += num.hashCode(); - } - return result; - } + public int hashCode() { + final int PRIME = 31; + int result = 1; + if ( name != null ) { + result += name.hashCode(); + } + result *= PRIME; + if ( num != null ) { + result += num.hashCode(); + } + return result; + } - public String toString() { - return name + " | " + num; - } + public String toString() { + return name + " | " + num; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/unionsubclass/alias/SellCarTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/unionsubclass/alias/SellCarTest.java index da122bbdb2..254c5ade6b 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/unionsubclass/alias/SellCarTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/unionsubclass/alias/SellCarTest.java @@ -23,52 +23,52 @@ import static org.junit.Assert.assertNotNull; @JiraKey( value = "HHH-4825" ) public class SellCarTest extends BaseCoreFunctionalTestCase { - @Override - protected String getBaseForMappings() { - return "org/hibernate/orm/test/"; - } + @Override + protected String getBaseForMappings() { + return "org/hibernate/orm/test/"; + } - @Override - public String[] getMappings() { - return new String[] { "unionsubclass/alias/mapping.hbm.xml" }; - } + @Override + public String[] getMappings() { + return new String[] { "unionsubclass/alias/mapping.hbm.xml" }; + } @Test - public void testSellCar() { - prepareData(); - Session session = openSession(); - Transaction tx = session.beginTransaction(); - Query query = session.createQuery( "from Seller" ); - Seller seller = (Seller) query.uniqueResult(); - assertNotNull( seller ); - assertEquals( 1, seller.getBuyers().size() ); - tx.commit(); - session.close(); - } + public void testSellCar() { + prepareData(); + Session session = openSession(); + Transaction tx = session.beginTransaction(); + Query query = session.createQuery( "from Seller" ); + Seller seller = (Seller) query.uniqueResult(); + assertNotNull( seller ); + assertEquals( 1, seller.getBuyers().size() ); + tx.commit(); + session.close(); + } - private void prepareData() { - Session session = openSession(); - Transaction tx = session.beginTransaction(); - session.persist( createData() ); - tx.commit(); - session.close(); - } + private void prepareData() { + Session session = openSession(); + Transaction tx = session.beginTransaction(); + session.persist( createData() ); + tx.commit(); + session.close(); + } private Object createData() { - Seller stliu = new Seller(); - stliu.setId( createID( "stliu" ) ); - CarBuyer zd = new CarBuyer(); - zd.setId( createID( "zd" ) ); - zd.setSeller( stliu ); - zd.setSellerName( stliu.getId().getName() ); - stliu.getBuyers().add( zd ); - return stliu; - } + Seller stliu = new Seller(); + stliu.setId( createID( "stliu" ) ); + CarBuyer zd = new CarBuyer(); + zd.setId( createID( "zd" ) ); + zd.setSeller( stliu ); + zd.setSellerName( stliu.getId().getName() ); + stliu.getBuyers().add( zd ); + return stliu; + } private PersonID createID( String name ) { - PersonID id = new PersonID(); - id.setName( name ); - id.setNum(100L); - return id; - } + PersonID id = new PersonID(); + id.setName( name ); + id.setNum(100L); + return id; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/unionsubclass/alias/Seller.java b/hibernate-core/src/test/java/org/hibernate/orm/test/unionsubclass/alias/Seller.java index ed5d99a053..92a68847cd 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/unionsubclass/alias/Seller.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/unionsubclass/alias/Seller.java @@ -14,38 +14,38 @@ import java.util.Set; * @author Strong Liu */ public class Seller implements Serializable { - private PersonID id; - private Set buyers = new HashSet(); + private PersonID id; + private Set buyers = new HashSet(); - public PersonID getId() { - return id; - } + public PersonID getId() { + return id; + } - public void setId( PersonID id ) { - this.id = id; - } + public void setId( PersonID id ) { + this.id = id; + } - public Set getBuyers() { - return buyers; - } + public Set getBuyers() { + return buyers; + } - public void setBuyers( Set buyers ) { - this.buyers = buyers; - } + public void setBuyers( Set buyers ) { + this.buyers = buyers; + } - public boolean equals( Object obj ) { - if ( obj == null ) - return false; - if ( obj == this ) - return true; - if ( !( obj instanceof Seller ) ) - return false; + public boolean equals( Object obj ) { + if ( obj == null ) + return false; + if ( obj == this ) + return true; + if ( !( obj instanceof Seller ) ) + return false; - return ( (Seller) obj ).getId().equals( getId() ); - } + return ( (Seller) obj ).getId().equals( getId() ); + } - public int hashCode() { - return id.hashCode(); - } + public int hashCode() { + return id.hashCode(); + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/uniquekey/NaturalIdCachingTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/uniquekey/NaturalIdCachingTest.java index fc49c9c75e..4e3e52a9af 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/uniquekey/NaturalIdCachingTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/uniquekey/NaturalIdCachingTest.java @@ -25,24 +25,24 @@ import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; public class NaturalIdCachingTest extends BaseCoreFunctionalTestCase { - @Override - protected Class[] getAnnotatedClasses() { - return new Class[]{ - PropertyHolder.class, - Property.class - }; - } + @Override + protected Class[] getAnnotatedClasses() { + return new Class[]{ + PropertyHolder.class, + Property.class + }; + } - @Override - protected void configure(Configuration configuration) { - super.configure(configuration); - configuration.setProperty(AvailableSettings.SHOW_SQL, true); - configuration.setProperty(AvailableSettings.GENERATE_STATISTICS, true); - } + @Override + protected void configure(Configuration configuration) { + super.configure(configuration); + configuration.setProperty(AvailableSettings.SHOW_SQL, true); + configuration.setProperty(AvailableSettings.GENERATE_STATISTICS, true); + } - @Test - public void test() throws Exception { + @Test + public void test() throws Exception { doInHibernate( this::sessionFactory, session -> { Property property = new Property( 1, 1, 1 ); session.persist( property ); @@ -50,7 +50,7 @@ public class NaturalIdCachingTest extends BaseCoreFunctionalTestCase { session.persist( new PropertyHolder( 2, property ) ); } ); - assertThat(sessionFactory().getStatistics().getEntityInsertCount(), is(3L)); + assertThat(sessionFactory().getStatistics().getEntityInsertCount(), is(3L)); sessionFactory().getStatistics().clear(); doInHibernate( this::sessionFactory, session -> { @@ -60,9 +60,9 @@ public class NaturalIdCachingTest extends BaseCoreFunctionalTestCase { assertThat( sessionFactory().getStatistics().getEntityLoadCount(), is(3L) ); assertThat( sessionFactory().getStatistics().getPrepareStatementCount(), is(3L) ); - } + } - @Entity(name = "PropertyHolder") + @Entity(name = "PropertyHolder") public static class PropertyHolder implements Serializable { @Id diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/version/sybase/SybaseTimestampComparisonAnnotationsTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/version/sybase/SybaseTimestampComparisonAnnotationsTest.java index 992359a039..4ef912e70b 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/version/sybase/SybaseTimestampComparisonAnnotationsTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/version/sybase/SybaseTimestampComparisonAnnotationsTest.java @@ -36,7 +36,7 @@ public class SybaseTimestampComparisonAnnotationsTest extends BaseCoreFunctional @Test @JiraKey( value = "HHH-10413" ) public void testComparableTimestamps() { - final BasicType versionType = sessionFactory() + final BasicType versionType = sessionFactory() .getMappingMetamodel() .getEntityDescriptor(Thing.class.getName()).getVersionType(); assertTrue( versionType.getJavaTypeDescriptor() instanceof PrimitiveByteArrayJavaType ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/version/sybase/SybaseTimestampVersioningTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/version/sybase/SybaseTimestampVersioningTest.java index ae70766785..5a3022fe5a 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/version/sybase/SybaseTimestampVersioningTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/version/sybase/SybaseTimestampVersioningTest.java @@ -261,7 +261,7 @@ public class SybaseTimestampVersioningTest extends BaseCoreFunctionalTestCase { @Test @JiraKey( value = "HHH-10413" ) public void testComparableTimestamps() { - final BasicType versionType = sessionFactory() + final BasicType versionType = sessionFactory() .getMappingMetamodel() .getEntityDescriptor(User.class.getName()) .getVersionType(); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/write/CustomSqlTests.java b/hibernate-core/src/test/java/org/hibernate/orm/test/write/CustomSqlTests.java index c830954195..1d155fc64f 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/write/CustomSqlTests.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/write/CustomSqlTests.java @@ -55,9 +55,9 @@ public class CustomSqlTests { @SQLDelete( sql = "delete from custom_entity where id = ?" ) @SQLUpdate( sql = "update custom_entity set name = ? where id = ? " ) public static class CustomEntity { - @Id - private Integer id; - @Basic + @Id + private Integer id; + @Basic private String name; private CustomEntity() { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/write/CustomSqlWithExpectationTests.java b/hibernate-core/src/test/java/org/hibernate/orm/test/write/CustomSqlWithExpectationTests.java index 7a793b3902..5508573467 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/write/CustomSqlWithExpectationTests.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/write/CustomSqlWithExpectationTests.java @@ -78,9 +78,9 @@ public class CustomSqlWithExpectationTests { @SQLDelete( sql = "delete from custom_entity where id = ?", verify = Custom.class ) @SQLUpdate( sql = "update custom_entity set name = ? where id = ? ", verify = Custom.class ) public static class CustomEntity { - @Id - private Integer id; - @Basic + @Id + private Integer id; + @Basic private String name; CustomEntity() { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/write/OptionalTableUpdateTests.java b/hibernate-core/src/test/java/org/hibernate/orm/test/write/OptionalTableUpdateTests.java index cdd4bf9c49..9a77bb2cef 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/write/OptionalTableUpdateTests.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/write/OptionalTableUpdateTests.java @@ -99,9 +99,9 @@ public class OptionalTableUpdateTests { @Table( name = "entities" ) @SecondaryTable( name = "supplements" ) public static class TheEntity { - @Id - private Integer id; - @Basic + @Id + private Integer id; + @Basic private String name; @Basic @Column( table = "supplements" ) diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/write/StaticDeleteTests.java b/hibernate-core/src/test/java/org/hibernate/orm/test/write/StaticDeleteTests.java index 6e3e8e6c71..8ba768a441 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/write/StaticDeleteTests.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/write/StaticDeleteTests.java @@ -54,9 +54,9 @@ public class StaticDeleteTests { @Entity( name = "SimpleEntity" ) @Table( name = "SimpleEntity" ) public static class SimpleEntity { - @Id - private Integer id; - @Basic + @Id + private Integer id; + @Basic private String name; private SimpleEntity() { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/write/staticinsert/SingleTableStaticInsertTests.java b/hibernate-core/src/test/java/org/hibernate/orm/test/write/staticinsert/SingleTableStaticInsertTests.java index d49b81fad1..0d607bf555 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/write/staticinsert/SingleTableStaticInsertTests.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/write/staticinsert/SingleTableStaticInsertTests.java @@ -85,9 +85,9 @@ public class SingleTableStaticInsertTests { @Entity( name = "SimpleEntity" ) @Table( name = "SimpleEntity" ) public static class SimpleEntity { - @Id - private Integer id; - @Basic + @Id + private Integer id; + @Basic private String name; private SimpleEntity() { diff --git a/hibernate-core/src/test/java/org/hibernate/tool/schema/internal/AbstractSchemaMigratorTest.java b/hibernate-core/src/test/java/org/hibernate/tool/schema/internal/AbstractSchemaMigratorTest.java index 00211859d1..4699e1ee8c 100644 --- a/hibernate-core/src/test/java/org/hibernate/tool/schema/internal/AbstractSchemaMigratorTest.java +++ b/hibernate-core/src/test/java/org/hibernate/tool/schema/internal/AbstractSchemaMigratorTest.java @@ -42,40 +42,40 @@ import static org.mockito.Mockito.mock; */ public class AbstractSchemaMigratorTest { - @Test - @JiraKey(value = "HHH-13779") - public void testForeignKeyPreExistenceDetectionIgnoresCaseForTableAndColumnName() { - final AbstractSchemaMigrator schemaMigrator = new AbstractSchemaMigrator(null, null) { - @Override - protected NameSpaceTablesInformation performTablesMigration(Metadata metadata, + @Test + @JiraKey(value = "HHH-13779") + public void testForeignKeyPreExistenceDetectionIgnoresCaseForTableAndColumnName() { + final AbstractSchemaMigrator schemaMigrator = new AbstractSchemaMigrator(null, null) { + @Override + protected NameSpaceTablesInformation performTablesMigration(Metadata metadata, DatabaseInformation existingDatabase, ExecutionOptions options,ContributableMatcher contributableInclusionFilter, Dialect dialect, Formatter formatter, Set exportIdentifiers, boolean tryToCreateCatalogs, boolean tryToCreateSchemas, Set exportedCatalogs, Namespace namespace, SqlStringGenerationContext sqlStringGenerationContext, GenerationTarget[] targets) { return null; } - }; + }; - final TableInformation existingTableInformation = mock(TableInformation.class); - final ArrayList columnReferenceMappings = new ArrayList<>(); + final TableInformation existingTableInformation = mock(TableInformation.class); + final ArrayList columnReferenceMappings = new ArrayList<>(); - final TableInformation destinationTableInformation = mock(TableInformation.class); - doReturn(new QualifiedTableName(toIdentifier("catalog"), toIdentifier("schema"), - toIdentifier("referenced_table"))) // Table name is lower case - .when(destinationTableInformation).getName(); - columnReferenceMappings.add(new ForeignKeyInformationImpl.ColumnReferenceMappingImpl( - new ColumnInformationImpl(null, toIdentifier("referencing_column"), // column name is lower case - 0, "typeName", 255, 0, TruthValue.TRUE), - new ColumnInformationImpl(destinationTableInformation, null, 1, "typeName", 0, 0, TruthValue.TRUE))); - doReturn(singletonList(new ForeignKeyInformationImpl(toIdentifier("FKp8mpamfw2inhj88hwhty1eipm"), columnReferenceMappings))) - .when(existingTableInformation).getForeignKeys(); + final TableInformation destinationTableInformation = mock(TableInformation.class); + doReturn(new QualifiedTableName(toIdentifier("catalog"), toIdentifier("schema"), + toIdentifier("referenced_table"))) // Table name is lower case + .when(destinationTableInformation).getName(); + columnReferenceMappings.add(new ForeignKeyInformationImpl.ColumnReferenceMappingImpl( + new ColumnInformationImpl(null, toIdentifier("referencing_column"), // column name is lower case + 0, "typeName", 255, 0, TruthValue.TRUE), + new ColumnInformationImpl(destinationTableInformation, null, 1, "typeName", 0, 0, TruthValue.TRUE))); + doReturn(singletonList(new ForeignKeyInformationImpl(toIdentifier("FKp8mpamfw2inhj88hwhty1eipm"), columnReferenceMappings))) + .when(existingTableInformation).getForeignKeys(); - final boolean existInDatabase = schemaMigrator.equivalentForeignKeyExistsInDatabase( - existingTableInformation, - "REFERENCING_COLUMN", "REFERENCED_TABLE"); // Table and column names are UPPER-case here, to prove the test + final boolean existInDatabase = schemaMigrator.equivalentForeignKeyExistsInDatabase( + existingTableInformation, + "REFERENCING_COLUMN", "REFERENCED_TABLE"); // Table and column names are UPPER-case here, to prove the test - assertThat("Expected ForeignKey pre-existence check to be case-insensitive", - existInDatabase, - is(true)); - } + assertThat("Expected ForeignKey pre-existence check to be case-insensitive", + existInDatabase, + is(true)); + } } diff --git a/hibernate-envers/src/demo/java/org/hibernate/envers/demo/Address.java b/hibernate-envers/src/demo/java/org/hibernate/envers/demo/Address.java index 42dc2cfcae..2b18a0992f 100644 --- a/hibernate-envers/src/demo/java/org/hibernate/envers/demo/Address.java +++ b/hibernate-envers/src/demo/java/org/hibernate/envers/demo/Address.java @@ -18,83 +18,83 @@ import org.hibernate.envers.Audited; */ @Entity public class Address { - @Id - @GeneratedValue - private int id; + @Id + @GeneratedValue + private int id; - @Audited - private String streetName; + @Audited + private String streetName; - @Audited - private Integer houseNumber; + @Audited + private Integer houseNumber; - @Audited - private Integer flatNumber; + @Audited + private Integer flatNumber; - @Audited - @OneToMany(mappedBy = "address") - private Set persons; + @Audited + @OneToMany(mappedBy = "address") + private Set persons; - public int getId() { - return id; - } + public int getId() { + return id; + } - public void setId(int id) { - this.id = id; - } + public void setId(int id) { + this.id = id; + } - public String getStreetName() { - return streetName; - } + public String getStreetName() { + return streetName; + } - public void setStreetName(String streetName) { - this.streetName = streetName; - } + public void setStreetName(String streetName) { + this.streetName = streetName; + } - public Integer getHouseNumber() { - return houseNumber; - } + public Integer getHouseNumber() { + return houseNumber; + } - public void setHouseNumber(Integer houseNumber) { - this.houseNumber = houseNumber; - } + public void setHouseNumber(Integer houseNumber) { + this.houseNumber = houseNumber; + } - public Integer getFlatNumber() { - return flatNumber; - } + public Integer getFlatNumber() { + return flatNumber; + } - public void setFlatNumber(Integer flatNumber) { - this.flatNumber = flatNumber; - } + public void setFlatNumber(Integer flatNumber) { + this.flatNumber = flatNumber; + } - public Set getPersons() { - return persons; - } + public Set getPersons() { + return persons; + } - public void setPersons(Set persons) { - this.persons = persons; - } + public void setPersons(Set persons) { + this.persons = persons; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof Address)) return false; + public boolean equals(Object o) { + if (this == o) return true; + if (!(o instanceof Address)) return false; - Address address = (Address) o; + Address address = (Address) o; - if (id != address.id) return false; - if (flatNumber != null ? !flatNumber.equals(address.flatNumber) : address.flatNumber != null) return false; - if (houseNumber != null ? !houseNumber.equals(address.houseNumber) : address.houseNumber != null) return false; - if (streetName != null ? !streetName.equals(address.streetName) : address.streetName != null) return false; + if (id != address.id) return false; + if (flatNumber != null ? !flatNumber.equals(address.flatNumber) : address.flatNumber != null) return false; + if (houseNumber != null ? !houseNumber.equals(address.houseNumber) : address.houseNumber != null) return false; + if (streetName != null ? !streetName.equals(address.streetName) : address.streetName != null) return false; - return true; - } + return true; + } - public int hashCode() { - int result; - result = id; - result = 31 * result + (streetName != null ? streetName.hashCode() : 0); - result = 31 * result + (houseNumber != null ? houseNumber.hashCode() : 0); - result = 31 * result + (flatNumber != null ? flatNumber.hashCode() : 0); - return result; - } + public int hashCode() { + int result; + result = id; + result = 31 * result + (streetName != null ? streetName.hashCode() : 0); + result = 31 * result + (houseNumber != null ? houseNumber.hashCode() : 0); + result = 31 * result + (flatNumber != null ? flatNumber.hashCode() : 0); + return result; + } } diff --git a/hibernate-envers/src/demo/java/org/hibernate/envers/demo/Person.java b/hibernate-envers/src/demo/java/org/hibernate/envers/demo/Person.java index 7673f68d27..28d0a05f06 100644 --- a/hibernate-envers/src/demo/java/org/hibernate/envers/demo/Person.java +++ b/hibernate-envers/src/demo/java/org/hibernate/envers/demo/Person.java @@ -17,70 +17,70 @@ import org.hibernate.envers.Audited; */ @Entity public class Person { - @Id - @GeneratedValue - private int id; + @Id + @GeneratedValue + private int id; - @Audited - private String name; + @Audited + private String name; - @Audited - private String surname; + @Audited + private String surname; - @Audited - @ManyToOne - private Address address; + @Audited + @ManyToOne + private Address address; - public int getId() { - return id; - } + public int getId() { + return id; + } - public void setId(int id) { - this.id = id; - } + public void setId(int id) { + this.id = id; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - public String getSurname() { - return surname; - } + public String getSurname() { + return surname; + } - public void setSurname(String surname) { - this.surname = surname; - } + public void setSurname(String surname) { + this.surname = surname; + } - public Address getAddress() { - return address; - } + public Address getAddress() { + return address; + } - public void setAddress(Address address) { - this.address = address; - } + public void setAddress(Address address) { + this.address = address; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof Person)) return false; + public boolean equals(Object o) { + if (this == o) return true; + if (!(o instanceof Person)) return false; - Person person = (Person) o; + Person person = (Person) o; - if (id != person.id) return false; - if (name != null ? !name.equals(person.name) : person.name != null) return false; - if (surname != null ? !surname.equals(person.surname) : person.surname != null) return false; + if (id != person.id) return false; + if (name != null ? !name.equals(person.name) : person.name != null) return false; + if (surname != null ? !surname.equals(person.surname) : person.surname != null) return false; - return true; - } + return true; + } - public int hashCode() { - int result; - result = id; - result = 31 * result + (name != null ? name.hashCode() : 0); - result = 31 * result + (surname != null ? surname.hashCode() : 0); - return result; - } + public int hashCode() { + int result; + result = id; + result = 31 * result + (name != null ? name.hashCode() : 0); + result = 31 * result + (surname != null ? surname.hashCode() : 0); + return result; + } } diff --git a/hibernate-envers/src/demo/java/org/hibernate/envers/demo/TestConsole.java b/hibernate-envers/src/demo/java/org/hibernate/envers/demo/TestConsole.java index f4f52fe6d7..d5819b8a50 100644 --- a/hibernate-envers/src/demo/java/org/hibernate/envers/demo/TestConsole.java +++ b/hibernate-envers/src/demo/java/org/hibernate/envers/demo/TestConsole.java @@ -26,432 +26,432 @@ import org.hibernate.envers.query.AuditEntity; * @author Adam Warski (adam at warski dot org) */ public class TestConsole { - private EntityManager entityManager; - - public TestConsole(EntityManager entityManager) { - this.entityManager = entityManager; - } - - private String convertString(String s, String def) { - if ("NULL".equals(s)) { return null; } - if ("".equals(s)) { return def; } - return s; - } - - private int convertStringToInteger(String s, int def) { - if ("".equals(s)) { return def; } - try { - return Integer.parseInt(s); - } catch (NumberFormatException e) { - System.err.println("Invalid number, returning 0."); - return 0; - } - } - - private void printPerson(StringBuilder sb, Person p) { - sb.append("id = ").append(p.getId()).append(", name = ").append(p.getName()) - .append(", surname = ").append(p.getSurname()); - - Address a = p.getAddress(); - if (a != null) { - sb.append(", address = <").append(a.getId()).append("> ").append(a.getStreetName()).append(" ") - .append(a.getHouseNumber()).append("/").append(a.getFlatNumber()); - } - } - - @SuppressWarnings("unchecked") - private void printPersons(StringBuilder sb) { - List persons = entityManager.createQuery( - "select p from Person p order by p.id").getResultList(); - - sb.append("Persons:\n"); - for (Person p : persons) { - printPerson(sb, p); - sb.append("\n"); - } - } - - private void printPersonHistory(StringBuilder sb, int personId) { - AuditReader reader = AuditReaderFactory.get(entityManager); - - List personHistory = reader.createQuery() - .forRevisionsOfEntity(Person.class, false, true) - .add(AuditEntity.id().eq(personId)) - .getResultList(); - - if (personHistory.size() == 0) { - sb.append("A person with id ").append(personId).append(" does not exist.\n"); - } else { - for (Object historyObj : personHistory) { - Object[] history = (Object[]) historyObj; - DefaultRevisionEntity revision = (DefaultRevisionEntity) history[1]; - sb.append("revision = ").append(revision.getId()).append(", "); - printPerson(sb, (Person) history[0]); - sb.append(" (").append(revision.getRevisionDate()).append(")\n"); - } - } - } - - private void printPersonAtRevision(StringBuilder sb, int personId, int revision) { - AuditReader reader = AuditReaderFactory.get(entityManager); - - Person p = reader.find(Person.class, personId, revision); - if (p == null) { - sb.append("This person does not exist at that revision."); - } else { - printPerson(sb, p); - } - } - - private void readAndSetAddress(Scanner scanner, Person p) { - Address old = p.getAddress(); - - String input = scanner.nextLine(); - if ("NULL".equals(input)) { - p.setAddress(null); - if (old != null) { - old.getPersons().remove(p); - } - } else if ("".equals(input)) { - } else { - try { - Integer id = Integer.valueOf(input); - - Address a = entityManager.find(Address.class, id); - - if (a == null) { - System.err.println("Unknown address id, setting to NULL."); - p.setAddress(null); - if (old != null) { - old.getPersons().remove(p); - } - } else { - p.setAddress(a); - - a.getPersons().add(p); - - if (old != null) { - old.getPersons().remove(p); - } - } - } catch (NumberFormatException e) { - System.err.println("Invalid address id, setting to NULL."); - p.setAddress(null); - if (old != null) { - old.getPersons().remove(p); - } - } - } - } - - private Person readNewPerson(PrintStream out, Scanner scanner) { - Person p = new Person(); - - out.print("Person name (NULL for null): "); - p.setName(convertString(scanner.nextLine(), "")); - - out.print("Person surname (NULL for null): "); - p.setSurname(convertString(scanner.nextLine(), "")); - - out.print("Person address id (NULL for null): "); - readAndSetAddress(scanner, p); - - return p; - } - - private void readModifyPerson(PrintStream out, Scanner scanner, int personId) { - Person current = entityManager.find(Person.class, personId); - - if (current == null) { - out.println("Person with id " + personId + " does not exist."); - return; - } - - out.print("Person name (NULL for null, enter for no change, current - " + current.getName() + "): "); - current.setName(convertString(scanner.nextLine(), current.getName())); - - out.print("Person surname (NULL for null, enter for no change, current - " + current.getSurname() + "): "); - current.setSurname(convertString(scanner.nextLine(), current.getSurname())); - - out.print("Person address id (NULL for null, enter for no change, current - " + - (current.getAddress() == null ? "NULL" : current.getAddress().getId()) + "): "); - readAndSetAddress(scanner, current); - } - - private void printAddress(StringBuilder sb, Address a) { - sb.append("id = ").append(a.getId()).append(", streetName = ").append(a.getStreetName()) - .append(", houseNumber = ").append(a.getHouseNumber()) - .append(", flatNumber = ").append(a.getFlatNumber()) - .append(", persons = ("); - - Iterator iter = a.getPersons().iterator(); - while (iter.hasNext()) { - Person p = iter.next(); - sb.append("<").append(p.getId()).append("> ").append(p.getName()).append(" ").append(p.getSurname()); - if (iter.hasNext()) { - sb.append(", "); - } - } - - sb.append(")"); - } - - @SuppressWarnings("unchecked") - private void printAddresses(StringBuilder sb) { - List
addresses = entityManager.createQuery( - "select a from Address a order by a.id").getResultList(); - - sb.append("Addresses:\n"); - for (Address a : addresses) { - printAddress(sb, a); - sb.append("\n"); - } - } - - private void printAddressHistory(StringBuilder sb, int addressId) { - AuditReader reader = AuditReaderFactory.get(entityManager); - - List addressHistory = reader.createQuery() - .forRevisionsOfEntity(Address.class, false, true) - .add(AuditEntity.id().eq(addressId)) - .getResultList(); - - if (addressHistory.size() == 0) { - sb.append("A address with id ").append(addressId).append(" does not exist.\n"); - } else { - for (Object historyObj : addressHistory) { - Object[] history = (Object[]) historyObj; - DefaultRevisionEntity revision = (DefaultRevisionEntity) history[1]; - sb.append("revision = ").append(revision.getId()).append(", "); - printAddress(sb, (Address) history[0]); - sb.append(" (").append(revision.getRevisionDate()).append(")\n"); - } - } - } - - private void printAddressAtRevision(StringBuilder sb, int addressId, int revision) { - AuditReader reader = AuditReaderFactory.get(entityManager); - - Address a = reader.find(Address.class, addressId, revision); - if (a == null) { - sb.append("This address does not exist at that revision."); - } else { - printAddress(sb, a); - } - } - - private Address readNewAddress(PrintStream out, Scanner scanner) { - Address a = new Address(); - - out.print("Street name (NULL for null): "); - a.setStreetName(convertString(scanner.nextLine(), "")); - - out.print("House number: "); - a.setHouseNumber(convertStringToInteger(scanner.nextLine(), 0)); - - out.print("Flat number: "); - a.setFlatNumber(convertStringToInteger(scanner.nextLine(), 0)); - - a.setPersons(new HashSet()); - - return a; - } - - private void readModifyAddress(PrintStream out, Scanner scanner, int addressId) { - Address current = entityManager.find(Address.class, addressId); - - if (current == null) { - out.println("Address with id " + addressId + " does not exist."); - return; - } - - out.print("Street name (NULL for null, enter for no change, current - " + current.getStreetName() + "): "); - current.setStreetName(convertString(scanner.nextLine(), current.getStreetName())); - - out.print("House number (enter for no change, current - " + current.getHouseNumber() + "): "); - current.setHouseNumber(convertStringToInteger(scanner.nextLine(), current.getHouseNumber())); - - out.print("Flat number (enter for no change, current - " + current.getFlatNumber() + "): "); - current.setFlatNumber(convertStringToInteger(scanner.nextLine(), current.getFlatNumber())); - } - - private void start() { - Scanner scanner = new Scanner(System.in); - PrintStream out = System.out; - - while (true) { - out.println("-----------------------------------------------"); - out.println("1 - list persons 5 - list addresses"); - out.println("2 - list person history 6 - list addresses history"); - out.println("3 - new person 7 - new address"); - out.println("4 - modify person 8 - modify address"); - out.println("9 - get person at revision 10 - get address at revision"); - out.println(" 0 - end"); - - try { - int choice = scanner.nextInt(); - - scanner.nextLine(); - - entityManager.getTransaction().begin(); - - StringBuilder sb; - int personId; - int addressId; - int revision; - switch (choice) { - case 1: - sb = new StringBuilder(); - printPersons(sb); - out.println(sb.toString()); - break; - case 2: - out.print("Person id: "); - personId = scanner.nextInt(); scanner.nextLine(); - sb = new StringBuilder(); - printPersonHistory(sb, personId); - out.println(sb.toString()); - break; - case 3: - Person p = readNewPerson(out, scanner); - entityManager.persist(p); - break; - case 4: - out.print("Person id: "); - personId = scanner.nextInt(); scanner.nextLine(); - readModifyPerson(out, scanner, personId); - break; - case 5: - sb = new StringBuilder(); - printAddresses(sb); - out.println(sb.toString()); - break; - case 6: - out.print("Address id: "); - addressId = scanner.nextInt(); scanner.nextLine(); - sb = new StringBuilder(); - printAddressHistory(sb, addressId); - out.println(sb.toString()); - break; - case 7: - Address a = readNewAddress(out, scanner); - entityManager.persist(a); - break; - case 8: - out.print("Address id: "); - addressId = scanner.nextInt(); scanner.nextLine(); - readModifyAddress(out, scanner, addressId); - break; - case 9: - out.print("Person id: "); - personId = scanner.nextInt(); scanner.nextLine(); - out.print("Revision number: "); - revision = scanner.nextInt(); scanner.nextLine(); - if (revision <= 0) { - System.out.println("Revision must be greater then 0!"); - continue; - } - sb = new StringBuilder(); - printPersonAtRevision(sb, personId, revision); - out.println(sb.toString()); - break; - case 10: - out.print("Address id: "); - addressId = scanner.nextInt(); scanner.nextLine(); - out.print("Revision number: "); - revision = scanner.nextInt(); scanner.nextLine(); - if (revision <= 0) { - System.out.println("Revision must be greater then 0!"); - continue; - } - sb = new StringBuilder(); - printAddressAtRevision(sb, addressId, revision); - out.println(sb.toString()); - break; - - case 0: - return; - } - } catch (InputMismatchException e) { - // continuing - } finally { - entityManager.getTransaction().commit(); - } - } - } - - private boolean hasData() { - return (((Long) entityManager.createQuery("select count(a) from Address a").getSingleResult()) + - ((Long) entityManager.createQuery("select count(p) from Person p").getSingleResult())) > 0; - } - - private void populateTestData() { - entityManager.getTransaction().begin(); - - if (!hasData()) { - Person p1 = new Person(); - Person p2 = new Person(); - Person p3 = new Person(); - - Address a1 = new Address(); - Address a2 = new Address(); - - p1.setName("James"); - p1.setSurname("Bond"); - p1.setAddress(a1); - - p2.setName("John"); - p2.setSurname("McClane"); - p2.setAddress(a2); - - p3.setName("Holly"); - p3.setSurname("Gennaro"); - p3.setAddress(a2); - - a1.setStreetName("MI6"); - a1.setHouseNumber(18); - a1.setFlatNumber(25); - a1.setPersons(new HashSet()); - a1.getPersons().add(p1); - - a2.setStreetName("Nakatomi Plaza"); - a2.setHouseNumber(10); - a2.setFlatNumber(34); - a2.setPersons(new HashSet()); - a2.getPersons().add(p2); - a2.getPersons().add(p3); - - entityManager.persist(a1); - entityManager.persist(a2); - - entityManager.persist(p1); - entityManager.persist(p2); - entityManager.persist(p3); - - System.out.println("The DB was populated with example data."); - } - - entityManager.getTransaction().commit(); - } - - public static void main(String[] args) { - Map configurationOverrides = new HashMap(); - EntityManagerFactory emf = Persistence.createEntityManagerFactory("ConsolePU", configurationOverrides); - EntityManager entityManager = emf.createEntityManager(); - - TestConsole console = new TestConsole(entityManager); - - System.out.println(""); - System.out.println("Welcome to EntityVersions demo!"); + private EntityManager entityManager; + + public TestConsole(EntityManager entityManager) { + this.entityManager = entityManager; + } + + private String convertString(String s, String def) { + if ("NULL".equals(s)) { return null; } + if ("".equals(s)) { return def; } + return s; + } + + private int convertStringToInteger(String s, int def) { + if ("".equals(s)) { return def; } + try { + return Integer.parseInt(s); + } catch (NumberFormatException e) { + System.err.println("Invalid number, returning 0."); + return 0; + } + } + + private void printPerson(StringBuilder sb, Person p) { + sb.append("id = ").append(p.getId()).append(", name = ").append(p.getName()) + .append(", surname = ").append(p.getSurname()); + + Address a = p.getAddress(); + if (a != null) { + sb.append(", address = <").append(a.getId()).append("> ").append(a.getStreetName()).append(" ") + .append(a.getHouseNumber()).append("/").append(a.getFlatNumber()); + } + } + + @SuppressWarnings("unchecked") + private void printPersons(StringBuilder sb) { + List persons = entityManager.createQuery( + "select p from Person p order by p.id").getResultList(); + + sb.append("Persons:\n"); + for (Person p : persons) { + printPerson(sb, p); + sb.append("\n"); + } + } + + private void printPersonHistory(StringBuilder sb, int personId) { + AuditReader reader = AuditReaderFactory.get(entityManager); + + List personHistory = reader.createQuery() + .forRevisionsOfEntity(Person.class, false, true) + .add(AuditEntity.id().eq(personId)) + .getResultList(); + + if (personHistory.size() == 0) { + sb.append("A person with id ").append(personId).append(" does not exist.\n"); + } else { + for (Object historyObj : personHistory) { + Object[] history = (Object[]) historyObj; + DefaultRevisionEntity revision = (DefaultRevisionEntity) history[1]; + sb.append("revision = ").append(revision.getId()).append(", "); + printPerson(sb, (Person) history[0]); + sb.append(" (").append(revision.getRevisionDate()).append(")\n"); + } + } + } + + private void printPersonAtRevision(StringBuilder sb, int personId, int revision) { + AuditReader reader = AuditReaderFactory.get(entityManager); + + Person p = reader.find(Person.class, personId, revision); + if (p == null) { + sb.append("This person does not exist at that revision."); + } else { + printPerson(sb, p); + } + } + + private void readAndSetAddress(Scanner scanner, Person p) { + Address old = p.getAddress(); + + String input = scanner.nextLine(); + if ("NULL".equals(input)) { + p.setAddress(null); + if (old != null) { + old.getPersons().remove(p); + } + } else if ("".equals(input)) { + } else { + try { + Integer id = Integer.valueOf(input); + + Address a = entityManager.find(Address.class, id); + + if (a == null) { + System.err.println("Unknown address id, setting to NULL."); + p.setAddress(null); + if (old != null) { + old.getPersons().remove(p); + } + } else { + p.setAddress(a); + + a.getPersons().add(p); + + if (old != null) { + old.getPersons().remove(p); + } + } + } catch (NumberFormatException e) { + System.err.println("Invalid address id, setting to NULL."); + p.setAddress(null); + if (old != null) { + old.getPersons().remove(p); + } + } + } + } + + private Person readNewPerson(PrintStream out, Scanner scanner) { + Person p = new Person(); + + out.print("Person name (NULL for null): "); + p.setName(convertString(scanner.nextLine(), "")); + + out.print("Person surname (NULL for null): "); + p.setSurname(convertString(scanner.nextLine(), "")); + + out.print("Person address id (NULL for null): "); + readAndSetAddress(scanner, p); + + return p; + } + + private void readModifyPerson(PrintStream out, Scanner scanner, int personId) { + Person current = entityManager.find(Person.class, personId); + + if (current == null) { + out.println("Person with id " + personId + " does not exist."); + return; + } + + out.print("Person name (NULL for null, enter for no change, current - " + current.getName() + "): "); + current.setName(convertString(scanner.nextLine(), current.getName())); + + out.print("Person surname (NULL for null, enter for no change, current - " + current.getSurname() + "): "); + current.setSurname(convertString(scanner.nextLine(), current.getSurname())); + + out.print("Person address id (NULL for null, enter for no change, current - " + + (current.getAddress() == null ? "NULL" : current.getAddress().getId()) + "): "); + readAndSetAddress(scanner, current); + } + + private void printAddress(StringBuilder sb, Address a) { + sb.append("id = ").append(a.getId()).append(", streetName = ").append(a.getStreetName()) + .append(", houseNumber = ").append(a.getHouseNumber()) + .append(", flatNumber = ").append(a.getFlatNumber()) + .append(", persons = ("); + + Iterator iter = a.getPersons().iterator(); + while (iter.hasNext()) { + Person p = iter.next(); + sb.append("<").append(p.getId()).append("> ").append(p.getName()).append(" ").append(p.getSurname()); + if (iter.hasNext()) { + sb.append(", "); + } + } + + sb.append(")"); + } + + @SuppressWarnings("unchecked") + private void printAddresses(StringBuilder sb) { + List
addresses = entityManager.createQuery( + "select a from Address a order by a.id").getResultList(); + + sb.append("Addresses:\n"); + for (Address a : addresses) { + printAddress(sb, a); + sb.append("\n"); + } + } + + private void printAddressHistory(StringBuilder sb, int addressId) { + AuditReader reader = AuditReaderFactory.get(entityManager); + + List addressHistory = reader.createQuery() + .forRevisionsOfEntity(Address.class, false, true) + .add(AuditEntity.id().eq(addressId)) + .getResultList(); + + if (addressHistory.size() == 0) { + sb.append("A address with id ").append(addressId).append(" does not exist.\n"); + } else { + for (Object historyObj : addressHistory) { + Object[] history = (Object[]) historyObj; + DefaultRevisionEntity revision = (DefaultRevisionEntity) history[1]; + sb.append("revision = ").append(revision.getId()).append(", "); + printAddress(sb, (Address) history[0]); + sb.append(" (").append(revision.getRevisionDate()).append(")\n"); + } + } + } + + private void printAddressAtRevision(StringBuilder sb, int addressId, int revision) { + AuditReader reader = AuditReaderFactory.get(entityManager); + + Address a = reader.find(Address.class, addressId, revision); + if (a == null) { + sb.append("This address does not exist at that revision."); + } else { + printAddress(sb, a); + } + } + + private Address readNewAddress(PrintStream out, Scanner scanner) { + Address a = new Address(); + + out.print("Street name (NULL for null): "); + a.setStreetName(convertString(scanner.nextLine(), "")); + + out.print("House number: "); + a.setHouseNumber(convertStringToInteger(scanner.nextLine(), 0)); + + out.print("Flat number: "); + a.setFlatNumber(convertStringToInteger(scanner.nextLine(), 0)); + + a.setPersons(new HashSet()); + + return a; + } + + private void readModifyAddress(PrintStream out, Scanner scanner, int addressId) { + Address current = entityManager.find(Address.class, addressId); + + if (current == null) { + out.println("Address with id " + addressId + " does not exist."); + return; + } + + out.print("Street name (NULL for null, enter for no change, current - " + current.getStreetName() + "): "); + current.setStreetName(convertString(scanner.nextLine(), current.getStreetName())); + + out.print("House number (enter for no change, current - " + current.getHouseNumber() + "): "); + current.setHouseNumber(convertStringToInteger(scanner.nextLine(), current.getHouseNumber())); + + out.print("Flat number (enter for no change, current - " + current.getFlatNumber() + "): "); + current.setFlatNumber(convertStringToInteger(scanner.nextLine(), current.getFlatNumber())); + } + + private void start() { + Scanner scanner = new Scanner(System.in); + PrintStream out = System.out; + + while (true) { + out.println("-----------------------------------------------"); + out.println("1 - list persons 5 - list addresses"); + out.println("2 - list person history 6 - list addresses history"); + out.println("3 - new person 7 - new address"); + out.println("4 - modify person 8 - modify address"); + out.println("9 - get person at revision 10 - get address at revision"); + out.println(" 0 - end"); + + try { + int choice = scanner.nextInt(); + + scanner.nextLine(); + + entityManager.getTransaction().begin(); + + StringBuilder sb; + int personId; + int addressId; + int revision; + switch (choice) { + case 1: + sb = new StringBuilder(); + printPersons(sb); + out.println(sb.toString()); + break; + case 2: + out.print("Person id: "); + personId = scanner.nextInt(); scanner.nextLine(); + sb = new StringBuilder(); + printPersonHistory(sb, personId); + out.println(sb.toString()); + break; + case 3: + Person p = readNewPerson(out, scanner); + entityManager.persist(p); + break; + case 4: + out.print("Person id: "); + personId = scanner.nextInt(); scanner.nextLine(); + readModifyPerson(out, scanner, personId); + break; + case 5: + sb = new StringBuilder(); + printAddresses(sb); + out.println(sb.toString()); + break; + case 6: + out.print("Address id: "); + addressId = scanner.nextInt(); scanner.nextLine(); + sb = new StringBuilder(); + printAddressHistory(sb, addressId); + out.println(sb.toString()); + break; + case 7: + Address a = readNewAddress(out, scanner); + entityManager.persist(a); + break; + case 8: + out.print("Address id: "); + addressId = scanner.nextInt(); scanner.nextLine(); + readModifyAddress(out, scanner, addressId); + break; + case 9: + out.print("Person id: "); + personId = scanner.nextInt(); scanner.nextLine(); + out.print("Revision number: "); + revision = scanner.nextInt(); scanner.nextLine(); + if (revision <= 0) { + System.out.println("Revision must be greater then 0!"); + continue; + } + sb = new StringBuilder(); + printPersonAtRevision(sb, personId, revision); + out.println(sb.toString()); + break; + case 10: + out.print("Address id: "); + addressId = scanner.nextInt(); scanner.nextLine(); + out.print("Revision number: "); + revision = scanner.nextInt(); scanner.nextLine(); + if (revision <= 0) { + System.out.println("Revision must be greater then 0!"); + continue; + } + sb = new StringBuilder(); + printAddressAtRevision(sb, addressId, revision); + out.println(sb.toString()); + break; + + case 0: + return; + } + } catch (InputMismatchException e) { + // continuing + } finally { + entityManager.getTransaction().commit(); + } + } + } + + private boolean hasData() { + return (((Long) entityManager.createQuery("select count(a) from Address a").getSingleResult()) + + ((Long) entityManager.createQuery("select count(p) from Person p").getSingleResult())) > 0; + } + + private void populateTestData() { + entityManager.getTransaction().begin(); + + if (!hasData()) { + Person p1 = new Person(); + Person p2 = new Person(); + Person p3 = new Person(); + + Address a1 = new Address(); + Address a2 = new Address(); + + p1.setName("James"); + p1.setSurname("Bond"); + p1.setAddress(a1); + + p2.setName("John"); + p2.setSurname("McClane"); + p2.setAddress(a2); + + p3.setName("Holly"); + p3.setSurname("Gennaro"); + p3.setAddress(a2); + + a1.setStreetName("MI6"); + a1.setHouseNumber(18); + a1.setFlatNumber(25); + a1.setPersons(new HashSet()); + a1.getPersons().add(p1); + + a2.setStreetName("Nakatomi Plaza"); + a2.setHouseNumber(10); + a2.setFlatNumber(34); + a2.setPersons(new HashSet()); + a2.getPersons().add(p2); + a2.getPersons().add(p3); + + entityManager.persist(a1); + entityManager.persist(a2); + + entityManager.persist(p1); + entityManager.persist(p2); + entityManager.persist(p3); + + System.out.println("The DB was populated with example data."); + } + + entityManager.getTransaction().commit(); + } + + public static void main(String[] args) { + Map configurationOverrides = new HashMap(); + EntityManagerFactory emf = Persistence.createEntityManagerFactory("ConsolePU", configurationOverrides); + EntityManager entityManager = emf.createEntityManager(); + + TestConsole console = new TestConsole(entityManager); + + System.out.println(""); + System.out.println("Welcome to EntityVersions demo!"); // If you would like to use HSQLDB, uncomment relevant entries in // hibernate-envers/src/demo/resources/META-INF/persistence.xml descriptor and add required JAR libraries. // String userDbFile = System.getProperty("java.io.tmpdir") + File.separator + "_versions_demo.db"; // System.out.println("HSQLDB database file location: " + userDbFile); - console.populateTestData(); - console.start(); + console.populateTestData(); + console.start(); - entityManager.close(); - emf.close(); - } + entityManager.close(); + emf.close(); + } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/metadata/reader/PropertyAuditingData.java b/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/metadata/reader/PropertyAuditingData.java index 49c80d084d..c3415e5f15 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/metadata/reader/PropertyAuditingData.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/metadata/reader/PropertyAuditingData.java @@ -90,7 +90,7 @@ public class PropertyAuditingData { * @param accessType the access type * @param relationTargetNotFoundAction the relation target not found action * @param forceInsertable whether the property is forced insertable - * @param synthetic whether the property is a synthetic, non-logic column-based property + * @param synthetic whether the property is a synthetic, non-logic column-based property * @param value the mapping model's value */ public PropertyAuditingData( diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/internal/synchronization/work/FakeBidirectionalRelationWorkUnit.java b/hibernate-envers/src/main/java/org/hibernate/envers/internal/synchronization/work/FakeBidirectionalRelationWorkUnit.java index c99f960489..2d7ee889e1 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/internal/synchronization/work/FakeBidirectionalRelationWorkUnit.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/internal/synchronization/work/FakeBidirectionalRelationWorkUnit.java @@ -216,13 +216,13 @@ public class FakeBidirectionalRelationWorkUnit extends AbstractAuditWorkUnit imp return first; } - /* + /* * The merging rules are the following (revision types of the first and second changes): - * - DEL, DEL - return any (the work units are the same) - * - DEL, ADD - return ADD (points to new owner) - * - ADD, DEL - return ADD (points to new owner) - * - ADD, ADD - return second (points to newer owner) - */ + * - DEL, DEL - return any (the work units are the same) + * - DEL, ADD - return ADD (points to new owner) + * - ADD, DEL - return ADD (points to new owner) + * - ADD, ADD - return second (points to newer owner) + */ if ( first.getRevisionType() == RevisionType.DEL || second.getRevisionType() == RevisionType.ADD ) { return second; } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/internal/tools/query/Parameters.java b/hibernate-envers/src/main/java/org/hibernate/envers/internal/tools/query/Parameters.java index fda1efd49d..f7cbcfa361 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/internal/tools/query/Parameters.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/internal/tools/query/Parameters.java @@ -296,7 +296,7 @@ public class Parameters { * @param op The operator. * @param right Right property name. * @param addAliasRight Whether to add the alias to the right property. - */ + */ public void addWhereOrNullRestriction(String left, boolean addAliasLeft, String op, String right, boolean addAliasRight) { if ( "=".equals( op ) ) { addWhere( left, addAliasLeft, " is not distinct from ", right, addAliasRight ); diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/query/criteria/AuditProperty.java b/hibernate-envers/src/main/java/org/hibernate/envers/query/criteria/AuditProperty.java index 1386f5a57f..f7f71c99a9 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/query/criteria/AuditProperty.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/query/criteria/AuditProperty.java @@ -91,9 +91,9 @@ public class AuditProperty implements AuditProjection { return new SimpleAuditExpression( alias, propertyNameGetter, matchMode.toMatchString( value ), " like " ); } - /** - * Apply an "ilike" constraint - */ + /** + * Apply an "ilike" constraint + */ public AuditCriterion ilike(T value) { return new IlikeAuditExpression( alias, propertyNameGetter, value.toString() ); } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/query/internal/impl/EntitiesAtRevisionQuery.java b/hibernate-envers/src/main/java/org/hibernate/envers/query/internal/impl/EntitiesAtRevisionQuery.java index ae2d2c8db3..5034fff074 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/query/internal/impl/EntitiesAtRevisionQuery.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/query/internal/impl/EntitiesAtRevisionQuery.java @@ -57,22 +57,22 @@ public class EntitiesAtRevisionQuery extends AbstractAuditQuery { public List list() { /* - * The query that we need to create: - * SELECT new list(e) FROM versionsReferencedEntity e - * WHERE - * (all specified conditions, transformed, on the "e" entity) AND - * (selecting e entities at revision :revision) - * --> for DefaultAuditStrategy: - * e.revision = (SELECT max(e2.revision) FROM versionsReferencedEntity e2 - * WHERE e2.revision <= :revision AND e2.id = e.id) - * - * --> for ValidityAuditStrategy: - * e.revision <= :revision and (e.endRevision > :revision or e.endRevision is null) - * - * AND - * (only non-deleted entities) - * e.revision_type != DEL - */ + * The query that we need to create: + * SELECT new list(e) FROM versionsReferencedEntity e + * WHERE + * (all specified conditions, transformed, on the "e" entity) AND + * (selecting e entities at revision :revision) + * --> for DefaultAuditStrategy: + * e.revision = (SELECT max(e2.revision) FROM versionsReferencedEntity e2 + * WHERE e2.revision <= :revision AND e2.id = e.id) + * + * --> for ValidityAuditStrategy: + * e.revision <= :revision and (e.endRevision > :revision or e.endRevision is null) + * + * AND + * (only non-deleted entities) + * e.revision_type != DEL + */ Configuration configuration = enversService.getConfig(); String revisionPropertyPath = configuration.getRevisionNumberPath(); String originalIdPropertyName = configuration.getOriginalIdPropertyName(); diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/query/internal/impl/EntitiesModifiedAtRevisionQuery.java b/hibernate-envers/src/main/java/org/hibernate/envers/query/internal/impl/EntitiesModifiedAtRevisionQuery.java index b8cc656955..c983b1dd65 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/query/internal/impl/EntitiesModifiedAtRevisionQuery.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/query/internal/impl/EntitiesModifiedAtRevisionQuery.java @@ -56,12 +56,12 @@ public class EntitiesModifiedAtRevisionQuery extends AbstractAuditQuery { @Override public List list() { /* - * The query that we need to create: - * SELECT new list(e) FROM versionsReferencedEntity e - * WHERE - * (all specified conditions, transformed, on the "e" entity) AND - * e.revision = :revision - */ + * The query that we need to create: + * SELECT new list(e) FROM versionsReferencedEntity e + * WHERE + * (all specified conditions, transformed, on the "e" entity) AND + * e.revision = :revision + */ String revisionPropertyPath = enversService.getConfig().getRevisionNumberPath(); qb.getRootParameters().addWhereWithParam( revisionPropertyPath, "=", revision ); diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/query/internal/impl/RevisionsOfEntityQuery.java b/hibernate-envers/src/main/java/org/hibernate/envers/query/internal/impl/RevisionsOfEntityQuery.java index 9edb2d5a3e..38c919d4f4 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/query/internal/impl/RevisionsOfEntityQuery.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/query/internal/impl/RevisionsOfEntityQuery.java @@ -130,14 +130,14 @@ public class RevisionsOfEntityQuery extends AbstractAuditQuery { public List list() throws AuditException { Configuration configuration = enversService.getConfig(); - /* + /* The query that should be executed in the versions table: - SELECT e (unless another projection is specified) FROM ent_ver e, rev_entity r WHERE - e.revision_type != DEL (if selectDeletedEntities == false) AND - e.revision = r.revision AND - (all specified conditions, transformed, on the "e" entity) - ORDER BY e.revision ASC (unless another order or projection is specified) - */ + SELECT e (unless another projection is specified) FROM ent_ver e, rev_entity r WHERE + e.revision_type != DEL (if selectDeletedEntities == false) AND + e.revision = r.revision AND + (all specified conditions, transformed, on the "e" entity) + ORDER BY e.revision ASC (unless another order or projection is specified) + */ if ( !selectDeletedEntities ) { // e.revision_type != DEL AND qb.getRootParameters().addWhereWithParam( configuration.getRevisionTypePropertyName(), "<>", RevisionType.DEL ); diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/customtype/DurationTest.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/customtype/DurationTest.java index 54fac86de5..23b4e50851 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/customtype/DurationTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/customtype/DurationTest.java @@ -33,12 +33,12 @@ public class DurationTest extends BaseEnversJPAFunctionalTestCase{ private Duration duration; - DurationTestEntity(){ + DurationTestEntity(){ - } + } DurationTestEntity(Duration aDuration) { - this.duration = aDuration; + this.duration = aDuration; } public Integer getId() { diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytoone/lazy/Address.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytoone/lazy/Address.java index 61019d3964..575a43bf2b 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytoone/lazy/Address.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytoone/lazy/Address.java @@ -23,33 +23,33 @@ import jakarta.persistence.Table; @Entity @Table(name = "address") public class Address extends BaseDomainEntity { - private static final long serialVersionUID = 7380477602657080463L; + private static final long serialVersionUID = 7380477602657080463L; - @Column(name = "name") - private String name; + @Column(name = "name") + private String name; - @OneToMany(fetch = FetchType.LAZY, mappedBy = "id", cascade = CascadeType.ALL) - Collection versions = new LinkedList<>(); + @OneToMany(fetch = FetchType.LAZY, mappedBy = "id", cascade = CascadeType.ALL) + Collection versions = new LinkedList<>(); - Address() { - } + Address() { + } - Address(Instant when, String who, String name) { - super( when, who ); - this.name = name; - } + Address(Instant when, String who, String name) { + super( when, who ); + this.name = name; + } - public AddressVersion addInitialVersion(String description) { - AddressVersion version = new AddressVersion( getCreatedAt(), getCreatedBy(), this, 0, description ); - versions.add( version ); - return version; - } + public AddressVersion addInitialVersion(String description) { + AddressVersion version = new AddressVersion( getCreatedAt(), getCreatedBy(), this, 0, description ); + versions.add( version ); + return version; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public Collection getVersions() { - return versions; - } + public Collection getVersions() { + return versions; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytoone/lazy/AddressVersion.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytoone/lazy/AddressVersion.java index 946173119d..bed9b0c3cc 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytoone/lazy/AddressVersion.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytoone/lazy/AddressVersion.java @@ -23,39 +23,39 @@ import jakarta.persistence.Table; @Entity @Table(name = "address_version") public class AddressVersion extends BaseDomainEntityVersion { - private static final long serialVersionUID = 1100389518057335117L; + private static final long serialVersionUID = 1100389518057335117L; - @Id - @ManyToOne(optional = false, fetch = FetchType.LAZY) - @JoinColumn(name = "id", referencedColumnName = "id", updatable = false, nullable = false) - private Address id; + @Id + @ManyToOne(optional = false, fetch = FetchType.LAZY) + @JoinColumn(name = "id", referencedColumnName = "id", updatable = false, nullable = false) + private Address id; - @Column(name = "description", updatable = false) - private String description; + @Column(name = "description", updatable = false) + private String description; - AddressVersion() { - } + AddressVersion() { + } - AddressVersion(Instant when, String who, Address id, long version, String description) { - setCreatedAt( when ); - setCreatedBy( who ); - setVersion( version ); - this.id = Objects.requireNonNull(id ); - this.description = description; - } + AddressVersion(Instant when, String who, Address id, long version, String description) { + setCreatedAt( when ); + setCreatedBy( who ); + setVersion( version ); + this.id = Objects.requireNonNull(id ); + this.description = description; + } - @Override - public Address getId() { - return id; - } + @Override + public Address getId() { + return id; + } - public String getDescription() { - return description; - } + public String getDescription() { + return description; + } - public AddressVersion update(Instant when, String who, String description) { - AddressVersion version = new AddressVersion( when, who, id, getVersion() + 1, description ); - id.versions.add( version ); - return version; - } + public AddressVersion update(Instant when, String who, String description) { + AddressVersion version = new AddressVersion( when, who, id, getVersion() + 1, description ); + id.versions.add( version ); + return version; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytoone/lazy/BaseDomainEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytoone/lazy/BaseDomainEntity.java index 0a793e4fa3..552af9f787 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytoone/lazy/BaseDomainEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytoone/lazy/BaseDomainEntity.java @@ -19,38 +19,38 @@ import jakarta.persistence.MappedSuperclass; */ @MappedSuperclass public abstract class BaseDomainEntity extends BaseDomainEntityMetadata { - private static final long serialVersionUID = 1023010094948580516L; + private static final long serialVersionUID = 1023010094948580516L; - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - protected long id = 0; + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + protected long id = 0; - BaseDomainEntity() { + BaseDomainEntity() { - } + } - BaseDomainEntity(Instant timestamp, String who) { - super( timestamp, who ); - } + BaseDomainEntity(Instant timestamp, String who) { + super( timestamp, who ); + } - public long getId() { - return id; - } + public long getId() { + return id; + } - @Override - public boolean equals(Object o) { - if ( this == o ) { - return true; - } - if ( o == null || getClass() != o.getClass() ) { - return false; - } - BaseDomainEntity that = (BaseDomainEntity) o; - return id == that.id; - } + @Override + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( o == null || getClass() != o.getClass() ) { + return false; + } + BaseDomainEntity that = (BaseDomainEntity) o; + return id == that.id; + } - @Override - public int hashCode() { - return Objects.hash( id ); - } + @Override + public int hashCode() { + return Objects.hash( id ); + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytoone/lazy/BaseDomainEntityMetadata.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytoone/lazy/BaseDomainEntityMetadata.java index 0f495283b9..80bdd3a394 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytoone/lazy/BaseDomainEntityMetadata.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytoone/lazy/BaseDomainEntityMetadata.java @@ -19,37 +19,37 @@ import org.hibernate.annotations.CreationTimestamp; */ @MappedSuperclass public abstract class BaseDomainEntityMetadata extends Base implements Serializable { - private static final long serialVersionUID = 2765056578095518489L; + private static final long serialVersionUID = 2765056578095518489L; - @Column(name = "created_by", nullable = false, updatable = false) - private String createdBy; + @Column(name = "created_by", nullable = false, updatable = false) + private String createdBy; - @CreationTimestamp - @Column(name = "created_at", nullable = false, updatable = false) - private Instant createdAt; + @CreationTimestamp + @Column(name = "created_at", nullable = false, updatable = false) + private Instant createdAt; - BaseDomainEntityMetadata() { + BaseDomainEntityMetadata() { - } + } - BaseDomainEntityMetadata(Instant timestamp, String who) { - this.createdBy = who; - this.createdAt = timestamp; - } + BaseDomainEntityMetadata(Instant timestamp, String who) { + this.createdBy = who; + this.createdAt = timestamp; + } - public String getCreatedBy() { - return createdBy; - } + public String getCreatedBy() { + return createdBy; + } - public void setCreatedBy(String createdBy) { - this.createdBy = createdBy; - } + public void setCreatedBy(String createdBy) { + this.createdBy = createdBy; + } - public Instant getCreatedAt() { - return createdAt; - } + public Instant getCreatedAt() { + return createdAt; + } - public void setCreatedAt(Instant createdAt) { - this.createdAt = createdAt; - } + public void setCreatedAt(Instant createdAt) { + this.createdAt = createdAt; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytoone/lazy/BaseDomainEntityVersion.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytoone/lazy/BaseDomainEntityVersion.java index 6fb683a361..c1b116ae10 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytoone/lazy/BaseDomainEntityVersion.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytoone/lazy/BaseDomainEntityVersion.java @@ -17,36 +17,36 @@ import jakarta.persistence.MappedSuperclass; */ @MappedSuperclass public abstract class BaseDomainEntityVersion extends BaseDomainEntityMetadata { - private static final long serialVersionUID = 1564895954324242368L; + private static final long serialVersionUID = 1564895954324242368L; - @Id - @Column(name = "version", nullable = false, updatable = false) - private long version; + @Id + @Column(name = "version", nullable = false, updatable = false) + private long version; - public long getVersion() { - return version; - } + public long getVersion() { + return version; + } - public void setVersion(long version) { - this.version = version; - } + public void setVersion(long version) { + this.version = version; + } - public abstract Object getId(); + public abstract Object getId(); - @Override - public boolean equals(Object o) { - if ( this == o ) { - return true; - } - if ( o == null || getClass() != o.getClass() ) { - return false; - } - BaseDomainEntityVersion that = (BaseDomainEntityVersion) o; - return Objects.equals( getId(), that.getId() ) && version == that.version; - } + @Override + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( o == null || getClass() != o.getClass() ) { + return false; + } + BaseDomainEntityVersion that = (BaseDomainEntityVersion) o; + return Objects.equals( getId(), that.getId() ) && version == that.version; + } - @Override - public int hashCode() { - return Objects.hash( getId(), version ); - } + @Override + public int hashCode() { + return Objects.hash( getId(), version ); + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytoone/lazy/ChildUser.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytoone/lazy/ChildUser.java index eb0854cb2b..4416c14a25 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytoone/lazy/ChildUser.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytoone/lazy/ChildUser.java @@ -20,14 +20,14 @@ import java.util.List; @Entity public class ChildUser extends User { - @OneToMany(fetch = FetchType.LAZY, mappedBy = "user", cascade = CascadeType.REMOVE) - @NotAudited - private List shipmentList; + @OneToMany(fetch = FetchType.LAZY, mappedBy = "user", cascade = CascadeType.REMOVE) + @NotAudited + private List shipmentList; - ChildUser() { - } + ChildUser() { + } - public long getId() { - return id; - } + public long getId() { + return id; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytoone/lazy/ManyToOneLazyDeleteTest.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytoone/lazy/ManyToOneLazyDeleteTest.java index 05fdd0a866..6582ecd1da 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytoone/lazy/ManyToOneLazyDeleteTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytoone/lazy/ManyToOneLazyDeleteTest.java @@ -30,59 +30,59 @@ import static org.hibernate.testing.transaction.TransactionUtil.doInHibernate; @JiraKey(value = "HHH-13945") @RequiresDialectFeature(DialectChecks.SupportsIdentityColumns.class) public class ManyToOneLazyDeleteTest extends BaseEnversFunctionalTestCase { - private Long shipmentId; - private User user; + private Long shipmentId; + private User user; - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { Shipment.class, Address.class, AddressVersion.class, User.class, ChildUser.class }; - } + @Override + protected Class[] getAnnotatedClasses() { + return new Class[] { Shipment.class, Address.class, AddressVersion.class, User.class, ChildUser.class }; + } - @Test - @Priority(10) - public void initData() { + @Test + @Priority(10) + public void initData() { - this.shipmentId = doInHibernate( this::sessionFactory, session -> { - final Shipment shipment = new Shipment( Instant.now(), "system", Instant.now().plus( Duration.ofDays( 3 ) ), "abcd123", null, null ); - session.persist( shipment ); - session.flush(); + this.shipmentId = doInHibernate( this::sessionFactory, session -> { + final Shipment shipment = new Shipment( Instant.now(), "system", Instant.now().plus( Duration.ofDays( 3 ) ), "abcd123", null, null ); + session.persist( shipment ); + session.flush(); - final Address origin = new Address( Instant.now(), "system", "Valencia#1" ); - final Address destination = new Address( Instant.now(), "system", "Madrid#3" ); - final AddressVersion originVersion0 = origin.addInitialVersion( "Poligono Manises" ); - final AddressVersion destinationVersion0 = destination.addInitialVersion( "Poligono Alcobendas" ); - user = new ChildUser(); - session.persist( origin ); - session.persist( destination ); - session.persist( user ); + final Address origin = new Address( Instant.now(), "system", "Valencia#1" ); + final Address destination = new Address( Instant.now(), "system", "Madrid#3" ); + final AddressVersion originVersion0 = origin.addInitialVersion( "Poligono Manises" ); + final AddressVersion destinationVersion0 = destination.addInitialVersion( "Poligono Alcobendas" ); + user = new ChildUser(); + session.persist( origin ); + session.persist( destination ); + session.persist( user ); - session.flush(); - shipment.setUser( user ); - shipment.setOrigin( originVersion0 ); - shipment.setDestination( destinationVersion0 ); + session.flush(); + shipment.setUser( user ); + shipment.setOrigin( originVersion0 ); + shipment.setDestination( destinationVersion0 ); - session.merge( shipment ); - session.flush(); + session.merge( shipment ); + session.flush(); - return shipment.getId(); - } ); + return shipment.getId(); + } ); - doInHibernate( this::sessionFactory, session -> { - final Shipment shipment = session.get( Shipment.class, shipmentId ); - session.remove(shipment); - // Cast the User instance to the ChildUser, and delete the child one, so the cache for - // the User instance will not be there, and entityNotFound exception will be thrown while envers processing it - ChildUser childUser = session.get(ChildUser.class, user.getId()); - session.remove(childUser); + doInHibernate( this::sessionFactory, session -> { + final Shipment shipment = session.get( Shipment.class, shipmentId ); + session.remove(shipment); + // Cast the User instance to the ChildUser, and delete the child one, so the cache for + // the User instance will not be there, and entityNotFound exception will be thrown while envers processing it + ChildUser childUser = session.get(ChildUser.class, user.getId()); + session.remove(childUser); - session.flush(); - } ); - } + session.flush(); + } ); + } - @Override - protected void addSettings(Map settings) { - super.addSettings( settings ); + @Override + protected void addSettings(Map settings) { + super.addSettings( settings ); - settings.put(EnversSettings.STORE_DATA_AT_DELETE, "true"); - } + settings.put(EnversSettings.STORE_DATA_AT_DELETE, "true"); + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytoone/lazy/ManyToOneLazyFetchTest.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytoone/lazy/ManyToOneLazyFetchTest.java index 9001fb3549..b140ca624d 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytoone/lazy/ManyToOneLazyFetchTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytoone/lazy/ManyToOneLazyFetchTest.java @@ -31,51 +31,51 @@ import static org.junit.Assert.assertEquals; @JiraKey(value = "HHH-13760") @RequiresDialectFeature(DialectChecks.SupportsIdentityColumns.class) public class ManyToOneLazyFetchTest extends BaseEnversFunctionalTestCase { - private Long shipmentId; + private Long shipmentId; - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { Shipment.class, Address.class, AddressVersion.class, User.class, ChildUser.class }; - } + @Override + protected Class[] getAnnotatedClasses() { + return new Class[] { Shipment.class, Address.class, AddressVersion.class, User.class, ChildUser.class }; + } - @Test - @Priority(10) - public void initData() { - this.shipmentId = doInHibernate( this::sessionFactory, session -> { - final Shipment shipment = new Shipment( Instant.now(), "system", Instant.now().plus( Duration.ofDays( 3 ) ), "abcd123", null, null ); - session.persist( shipment ); - session.flush(); + @Test + @Priority(10) + public void initData() { + this.shipmentId = doInHibernate( this::sessionFactory, session -> { + final Shipment shipment = new Shipment( Instant.now(), "system", Instant.now().plus( Duration.ofDays( 3 ) ), "abcd123", null, null ); + session.persist( shipment ); + session.flush(); - final Address origin = new Address( Instant.now(), "system", "Valencia#1" ); - final Address destination = new Address( Instant.now(), "system", "Madrid#3" ); - final AddressVersion originVersion0 = origin.addInitialVersion( "Poligono Manises" ); - final AddressVersion destinationVersion0 = destination.addInitialVersion( "Poligono Alcobendas" ); - session.persist( origin ); - session.persist( destination ); - session.flush(); + final Address origin = new Address( Instant.now(), "system", "Valencia#1" ); + final Address destination = new Address( Instant.now(), "system", "Madrid#3" ); + final AddressVersion originVersion0 = origin.addInitialVersion( "Poligono Manises" ); + final AddressVersion destinationVersion0 = destination.addInitialVersion( "Poligono Alcobendas" ); + session.persist( origin ); + session.persist( destination ); + session.flush(); - shipment.setOrigin( originVersion0 ); - shipment.setDestination( destinationVersion0 ); - session.merge( shipment ); - session.flush(); + shipment.setOrigin( originVersion0 ); + shipment.setDestination( destinationVersion0 ); + session.merge( shipment ); + session.flush(); - return shipment.getId(); - } ); + return shipment.getId(); + } ); - doInHibernate( this::sessionFactory, session -> { - final Shipment shipment = session.get( Shipment.class, shipmentId ); + doInHibernate( this::sessionFactory, session -> { + final Shipment shipment = session.get( Shipment.class, shipmentId ); - Hibernate.initialize( shipment.getOrigin() ); - Hibernate.initialize( shipment.getDestination() ); - shipment.setClosed( true ); + Hibernate.initialize( shipment.getOrigin() ); + Hibernate.initialize( shipment.getDestination() ); + shipment.setClosed( true ); - session.merge( shipment ); - session.flush(); - } ); - } + session.merge( shipment ); + session.flush(); + } ); + } - @Test - public void testRevisionHistory() { - assertEquals( Arrays.asList( 1, 2 ), getAuditReader().getRevisions( Shipment.class, shipmentId ) ); - } + @Test + public void testRevisionHistory() { + assertEquals( Arrays.asList( 1, 2 ), getAuditReader().getRevisions( Shipment.class, shipmentId ) ); + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytoone/lazy/Shipment.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytoone/lazy/Shipment.java index 78e272ab79..8b4edaf8ab 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytoone/lazy/Shipment.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytoone/lazy/Shipment.java @@ -31,86 +31,86 @@ import org.hibernate.envers.RelationTargetAuditMode; @Audited @AuditTable(value = "shipment_audit") public class Shipment extends BaseDomainEntity { - private static final long serialVersionUID = 5061763935663020703L; + private static final long serialVersionUID = 5061763935663020703L; - @Column(name = "due_date", nullable = false, updatable = false) - private Instant dueDate; + @Column(name = "due_date", nullable = false, updatable = false) + private Instant dueDate; - @Column(name = "identifier", nullable = false, updatable = false) - private String identifier; + @Column(name = "identifier", nullable = false, updatable = false) + private String identifier; - @Version - @Column(name = "mvc_version", nullable = false) - private Long mvcVersion; + @Version + @Column(name = "mvc_version", nullable = false) + private Long mvcVersion; - @Column(name = "closed") - private Boolean closed; + @Column(name = "closed") + private Boolean closed; - @ManyToOne(optional = true, fetch = FetchType.LAZY, targetEntity = AddressVersion.class) - @JoinColumns(value = { - @JoinColumn(name = "origin_address_id", referencedColumnName = "id", nullable = true), - @JoinColumn(name = "origin_address_version", referencedColumnName = "version", nullable = true) - }) - @Audited(targetAuditMode = RelationTargetAuditMode.NOT_AUDITED) - private AddressVersion origin; + @ManyToOne(optional = true, fetch = FetchType.LAZY, targetEntity = AddressVersion.class) + @JoinColumns(value = { + @JoinColumn(name = "origin_address_id", referencedColumnName = "id", nullable = true), + @JoinColumn(name = "origin_address_version", referencedColumnName = "version", nullable = true) + }) + @Audited(targetAuditMode = RelationTargetAuditMode.NOT_AUDITED) + private AddressVersion origin; - @ManyToOne(optional = true, fetch = FetchType.LAZY, targetEntity = AddressVersion.class) - @JoinColumns(value = { - @JoinColumn(name = "destination_address_id", referencedColumnName = "id", nullable = true), - @JoinColumn(name = "destination_address_version", referencedColumnName = "version", nullable = true) - }) - @Audited(targetAuditMode = RelationTargetAuditMode.NOT_AUDITED) - private AddressVersion destination; + @ManyToOne(optional = true, fetch = FetchType.LAZY, targetEntity = AddressVersion.class) + @JoinColumns(value = { + @JoinColumn(name = "destination_address_id", referencedColumnName = "id", nullable = true), + @JoinColumn(name = "destination_address_version", referencedColumnName = "version", nullable = true) + }) + @Audited(targetAuditMode = RelationTargetAuditMode.NOT_AUDITED) + private AddressVersion destination; - @ManyToOne(optional = true, fetch = FetchType.LAZY) - @JoinColumn(name = "user_id", referencedColumnName = "id", nullable = true) - @Audited(targetAuditMode = RelationTargetAuditMode.NOT_AUDITED) - private User user; + @ManyToOne(optional = true, fetch = FetchType.LAZY) + @JoinColumn(name = "user_id", referencedColumnName = "id", nullable = true) + @Audited(targetAuditMode = RelationTargetAuditMode.NOT_AUDITED) + private User user; - Shipment() { - } + Shipment() { + } - Shipment(Instant when, String who, Instant dueDate, String identifier, AddressVersion origin, AddressVersion dest) { - super( when, who ); - this.dueDate = dueDate; - this.identifier = Objects.requireNonNull( identifier ); - this.origin = origin; - this.destination = dest; - } + Shipment(Instant when, String who, Instant dueDate, String identifier, AddressVersion origin, AddressVersion dest) { + super( when, who ); + this.dueDate = dueDate; + this.identifier = Objects.requireNonNull( identifier ); + this.origin = origin; + this.destination = dest; + } - public Instant getDueDate() { - return dueDate; - } + public Instant getDueDate() { + return dueDate; + } - public String getIdentifier() { - return identifier; - } + public String getIdentifier() { + return identifier; + } - public Boolean getClosed() { - return closed; - } + public Boolean getClosed() { + return closed; + } - public void setClosed(Boolean closed) { - this.closed = closed; - } + public void setClosed(Boolean closed) { + this.closed = closed; + } - public AddressVersion getOrigin() { - return origin; - } + public AddressVersion getOrigin() { + return origin; + } - public void setOrigin(AddressVersion origin) { - this.origin = origin; - } + public void setOrigin(AddressVersion origin) { + this.origin = origin; + } - public AddressVersion getDestination() { - return destination; - } + public AddressVersion getDestination() { + return destination; + } - public void setDestination(AddressVersion destination) { - this.destination = destination; - } + public void setDestination(AddressVersion destination) { + this.destination = destination; + } - public void setUser(User user) { - this.user = user; - } + public void setUser(User user) { + this.user = user; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytoone/lazy/User.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytoone/lazy/User.java index 0f4ee5f80c..03b504a0f1 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytoone/lazy/User.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytoone/lazy/User.java @@ -25,18 +25,18 @@ import java.util.List; @Table(name = "user_tbl") public class User { - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - protected long id = 0; + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + protected long id = 0; - @OneToMany(fetch = FetchType.LAZY, mappedBy = "user", cascade = CascadeType.REMOVE) - @NotAudited - private List shipmentList; + @OneToMany(fetch = FetchType.LAZY, mappedBy = "user", cascade = CascadeType.REMOVE) + @NotAudited + private List shipmentList; - User() { - } + User() { + } - public long getId() { - return id; - } + public long getId() { + return id; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/naming/VersionsJoinTableRangeComponentNamingTest.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/naming/VersionsJoinTableRangeComponentNamingTest.java index ef506e9f5b..60c4ef09cf 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/naming/VersionsJoinTableRangeComponentNamingTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/naming/VersionsJoinTableRangeComponentNamingTest.java @@ -30,7 +30,7 @@ import org.junit.Test; * @author Erik-Berndt Scheper */ public class VersionsJoinTableRangeComponentNamingTest extends - BaseEnversJPAFunctionalTestCase { + BaseEnversJPAFunctionalTestCase { private Integer vjrcte_id; private Integer vjtrte_id; private Integer vjtrtae_id1; diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/tm/SessionFactoryInterceptorTransactionTest.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/tm/SessionFactoryInterceptorTransactionTest.java index 1782a43481..f208de10d1 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/tm/SessionFactoryInterceptorTransactionTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/tm/SessionFactoryInterceptorTransactionTest.java @@ -30,48 +30,48 @@ import org.hibernate.testing.jta.TestingJtaPlatformImpl; */ public class SessionFactoryInterceptorTransactionTest extends BaseEnversJPAFunctionalTestCase { - private TestInterceptor interceptor; - private TransactionManager tm; + private TestInterceptor interceptor; + private TransactionManager tm; - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { StrTestEntity.class }; - } + @Override + protected Class[] getAnnotatedClasses() { + return new Class[] { StrTestEntity.class }; + } - @Override - protected void addConfigOptions(Map options) { - super.addConfigOptions( options ); + @Override + protected void addConfigOptions(Map options) { + super.addConfigOptions( options ); - TestInterceptor.reset(); + TestInterceptor.reset(); - this.interceptor = new TestInterceptor(); - options.put( AvailableSettings.INTERCEPTOR, interceptor ); - options.put( AvailableSettings.ALLOW_JTA_TRANSACTION_ACCESS, true ); + this.interceptor = new TestInterceptor(); + options.put( AvailableSettings.INTERCEPTOR, interceptor ); + options.put( AvailableSettings.ALLOW_JTA_TRANSACTION_ACCESS, true ); - TestingJtaBootstrap.prepare( options ); - tm = TestingJtaPlatformImpl.INSTANCE.getTransactionManager(); - } + TestingJtaBootstrap.prepare( options ); + tm = TestingJtaPlatformImpl.INSTANCE.getTransactionManager(); + } - @Test - @Priority(10) - public void initData() throws Exception { - // Revision 1 - EntityManager em = getEntityManager(); - // Explicitly use manual flush to trigger separate temporary session write via Envers - em.unwrap( SessionImpl.class ).setHibernateFlushMode( FlushMode.MANUAL ); - tm.begin(); - StrTestEntity entity = new StrTestEntity( "Test" ); - em.persist( entity ); - em.flush(); - tm.commit(); - } + @Test + @Priority(10) + public void initData() throws Exception { + // Revision 1 + EntityManager em = getEntityManager(); + // Explicitly use manual flush to trigger separate temporary session write via Envers + em.unwrap( SessionImpl.class ).setHibernateFlushMode( FlushMode.MANUAL ); + tm.begin(); + StrTestEntity entity = new StrTestEntity( "Test" ); + em.persist( entity ); + em.flush(); + tm.commit(); + } - @Test - public void testInterceptorInvocations() throws Exception { - // Expect the interceptor to have been created once and invoked twice, once for the original session - // and follow-up for the Envers temporary session. - final Map invocationMap = TestInterceptor.getBeforeCompletionCallbacks(); - assertEquals( 1, invocationMap.size() ); - assertEquals( invocationMap.values().stream().filter( v -> v == 2 ).count(), 1 ); - } + @Test + public void testInterceptorInvocations() throws Exception { + // Expect the interceptor to have been created once and invoked twice, once for the original session + // and follow-up for the Envers temporary session. + final Map invocationMap = TestInterceptor.getBeforeCompletionCallbacks(); + assertEquals( 1, invocationMap.size() ); + assertEquals( invocationMap.values().stream().filter( v -> v == 2 ).count(), 1 ); + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/tm/SessionInterceptorTransactionTest.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/tm/SessionInterceptorTransactionTest.java index 9b072e0484..b58526f4db 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/tm/SessionInterceptorTransactionTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/tm/SessionInterceptorTransactionTest.java @@ -30,45 +30,45 @@ import org.hibernate.testing.jta.TestingJtaPlatformImpl; */ public class SessionInterceptorTransactionTest extends BaseEnversJPAFunctionalTestCase { - private TransactionManager tm; + private TransactionManager tm; - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { StrTestEntity.class }; - } + @Override + protected Class[] getAnnotatedClasses() { + return new Class[] { StrTestEntity.class }; + } - @Override - protected void addConfigOptions(Map options) { - super.addConfigOptions( options ); + @Override + protected void addConfigOptions(Map options) { + super.addConfigOptions( options ); - TestInterceptor.reset(); + TestInterceptor.reset(); - options.put( AvailableSettings.SESSION_SCOPED_INTERCEPTOR, TestInterceptor.class.getName() ); - options.put( AvailableSettings.ALLOW_JTA_TRANSACTION_ACCESS, "true" ); + options.put( AvailableSettings.SESSION_SCOPED_INTERCEPTOR, TestInterceptor.class.getName() ); + options.put( AvailableSettings.ALLOW_JTA_TRANSACTION_ACCESS, "true" ); - TestingJtaBootstrap.prepare( options ); - tm = TestingJtaPlatformImpl.INSTANCE.getTransactionManager(); - } + TestingJtaBootstrap.prepare( options ); + tm = TestingJtaPlatformImpl.INSTANCE.getTransactionManager(); + } - @Test - @Priority(10) - public void initData() throws Exception { - // Revision 1 - EntityManager em = getEntityManager(); - // Explicitly use manual flush to trigger separate temporary session write via Envers - em.unwrap( SessionImpl.class ).setHibernateFlushMode( FlushMode.MANUAL ); - tm.begin(); - StrTestEntity entity = new StrTestEntity( "Test" ); - em.persist( entity ); - em.flush(); - tm.commit(); - } + @Test + @Priority(10) + public void initData() throws Exception { + // Revision 1 + EntityManager em = getEntityManager(); + // Explicitly use manual flush to trigger separate temporary session write via Envers + em.unwrap( SessionImpl.class ).setHibernateFlushMode( FlushMode.MANUAL ); + tm.begin(); + StrTestEntity entity = new StrTestEntity( "Test" ); + em.persist( entity ); + em.flush(); + tm.commit(); + } - @Test - public void testInterceptorInvocations() throws Exception { - // The interceptor should only be created once and should only be invoked once. - final Map invocationMap = TestInterceptor.getBeforeCompletionCallbacks(); - assertEquals( 1, invocationMap.size() ); - assertEquals( invocationMap.values().stream().filter( v -> v == 1 ).count(), 1 ); - } + @Test + public void testInterceptorInvocations() throws Exception { + // The interceptor should only be created once and should only be invoked once. + final Map invocationMap = TestInterceptor.getBeforeCompletionCallbacks(); + assertEquals( 1, invocationMap.size() ); + assertEquals( invocationMap.values().stream().filter( v -> v == 1 ).count(), 1 ); + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/tm/TestInterceptor.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/tm/TestInterceptor.java index 1d7a68278d..cb90124b2c 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/tm/TestInterceptor.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/tm/TestInterceptor.java @@ -19,24 +19,24 @@ import org.jboss.logging.Logger; */ public class TestInterceptor implements Interceptor { - private static final Logger LOGGER = Logger.getLogger( TestInterceptor.class ); - private static Map interceptorInvocations = new HashMap<>(); + private static final Logger LOGGER = Logger.getLogger( TestInterceptor.class ); + private static Map interceptorInvocations = new HashMap<>(); - public TestInterceptor() { - interceptorInvocations.put( this, 0 ); - } + public TestInterceptor() { + interceptorInvocations.put( this, 0 ); + } - @Override - public void beforeTransactionCompletion(Transaction tx) { - interceptorInvocations.put( this, interceptorInvocations.get( this ) + 1 ); - LOGGER.info( "Interceptor beforeTransactionCompletion invoked" ); - } + @Override + public void beforeTransactionCompletion(Transaction tx) { + interceptorInvocations.put( this, interceptorInvocations.get( this ) + 1 ); + LOGGER.info( "Interceptor beforeTransactionCompletion invoked" ); + } - public static Map getBeforeCompletionCallbacks() { - return interceptorInvocations; - } + public static Map getBeforeCompletionCallbacks() { + return interceptorInvocations; + } - public static void reset() { - interceptorInvocations.clear(); - } + public static void reset() { + interceptorInvocations.clear(); + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/DefaultAuditTest.java b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/DefaultAuditTest.java index ba1c03df19..71ecc8fb7a 100644 --- a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/DefaultAuditTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/DefaultAuditTest.java @@ -63,7 +63,7 @@ public class DefaultAuditTest { //tag::envers-audited-revisions-example[] List revisions = scope.fromTransaction( entityManager -> { - return AuditReaderFactory.get(entityManager).getRevisions( + return AuditReaderFactory.get(entityManager).getRevisions( Customer.class, 1L ); diff --git a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/EntityTypeChangeAuditTest.java b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/EntityTypeChangeAuditTest.java index 654c311d75..316602a2f5 100644 --- a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/EntityTypeChangeAuditTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/EntityTypeChangeAuditTest.java @@ -43,217 +43,217 @@ import static org.junit.Assert.assertEquals; */ public class EntityTypeChangeAuditTest extends EntityManagerFactoryBasedFunctionalTest { - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Customer.class, - CustomTrackingRevisionEntity.class - }; - } + @Override + protected Class[] getAnnotatedClasses() { + return new Class[] { + Customer.class, + CustomTrackingRevisionEntity.class + }; + } - @Test - public void test() { - final EntityManagerFactory testEmf = produceEntityManagerFactory(); + @Test + public void test() { + final EntityManagerFactory testEmf = produceEntityManagerFactory(); - doInJPA( () -> testEmf, entityManager -> { - Customer customer = new Customer(); - customer.setId(1L); - customer.setFirstName("John"); - customer.setLastName("Doe"); + doInJPA( () -> testEmf, entityManager -> { + Customer customer = new Customer(); + customer.setId(1L); + customer.setFirstName("John"); + customer.setLastName("Doe"); - entityManager.persist(customer); - }); + entityManager.persist(customer); + }); - doInJPA( () -> testEmf, entityManager -> { - //tag::envers-tracking-modified-entities-queries-example1[] - assertEquals( - "org.hibernate.orm.test.envers.EntityTypeChangeAuditTest$Customer", - AuditReaderFactory - .get(entityManager) - .getCrossTypeRevisionChangesReader() - .findEntityTypes(1) - .iterator().next() - .getFirst() - ); - //end::envers-tracking-modified-entities-queries-example1[] - }); + doInJPA( () -> testEmf, entityManager -> { + //tag::envers-tracking-modified-entities-queries-example1[] + assertEquals( + "org.hibernate.orm.test.envers.EntityTypeChangeAuditTest$Customer", + AuditReaderFactory + .get(entityManager) + .getCrossTypeRevisionChangesReader() + .findEntityTypes(1) + .iterator().next() + .getFirst() + ); + //end::envers-tracking-modified-entities-queries-example1[] + }); - EntityManagerFactory entityManagerFactory = null; - try { - Map settings = buildSettings(); - settings.put( - AvailableSettings.LOADED_CLASSES, - Arrays.asList( - ApplicationCustomer.class, - CustomTrackingRevisionEntity.class - ) - ); - settings.put( - AvailableSettings.HBM2DDL_AUTO, - "update" - ); - entityManagerFactory = Bootstrap.getEntityManagerFactoryBuilder( - new TestingPersistenceUnitDescriptorImpl(getClass().getSimpleName()), - settings - ).build().unwrap(SessionFactoryImplementor.class); + EntityManagerFactory entityManagerFactory = null; + try { + Map settings = buildSettings(); + settings.put( + AvailableSettings.LOADED_CLASSES, + Arrays.asList( + ApplicationCustomer.class, + CustomTrackingRevisionEntity.class + ) + ); + settings.put( + AvailableSettings.HBM2DDL_AUTO, + "update" + ); + entityManagerFactory = Bootstrap.getEntityManagerFactoryBuilder( + new TestingPersistenceUnitDescriptorImpl(getClass().getSimpleName()), + settings + ).build().unwrap(SessionFactoryImplementor.class); - final EntityManagerFactory emf = entityManagerFactory; + final EntityManagerFactory emf = entityManagerFactory; - doInJPA(() -> emf, entityManager -> { - ApplicationCustomer customer = entityManager.find(ApplicationCustomer.class, 1L); - customer.setLastName("Doe Jr."); - }); + doInJPA(() -> emf, entityManager -> { + ApplicationCustomer customer = entityManager.find(ApplicationCustomer.class, 1L); + customer.setLastName("Doe Jr."); + }); - doInJPA(() -> emf, entityManager -> { - //tag::envers-tracking-modified-entities-queries-example2[] - assertEquals( - "org.hibernate.orm.test.envers.EntityTypeChangeAuditTest$ApplicationCustomer", - AuditReaderFactory - .get(entityManager) - .getCrossTypeRevisionChangesReader() - .findEntityTypes(2) - .iterator().next() - .getFirst() - ); - //end::envers-tracking-modified-entities-queries-example2[] - }); - } - finally { - if (entityManagerFactory != null) { - entityManagerFactory.close(); - } - testEmf.close(); - } - } + doInJPA(() -> emf, entityManager -> { + //tag::envers-tracking-modified-entities-queries-example2[] + assertEquals( + "org.hibernate.orm.test.envers.EntityTypeChangeAuditTest$ApplicationCustomer", + AuditReaderFactory + .get(entityManager) + .getCrossTypeRevisionChangesReader() + .findEntityTypes(2) + .iterator().next() + .getFirst() + ); + //end::envers-tracking-modified-entities-queries-example2[] + }); + } + finally { + if (entityManagerFactory != null) { + entityManagerFactory.close(); + } + testEmf.close(); + } + } - //tag::envers-tracking-modified-entities-revchanges-before-rename-example[] - @Audited - @Entity(name = "Customer") - public static class Customer { + //tag::envers-tracking-modified-entities-revchanges-before-rename-example[] + @Audited + @Entity(name = "Customer") + public static class Customer { - @Id - private Long id; + @Id + private Long id; - private String firstName; + private String firstName; - private String lastName; + private String lastName; - @Temporal(TemporalType.TIMESTAMP) - @Column(name = "created_on") - @CreationTimestamp - private Date createdOn; + @Temporal(TemporalType.TIMESTAMP) + @Column(name = "created_on") + @CreationTimestamp + private Date createdOn; - //Getters and setters are omitted for brevity - //end::envers-tracking-modified-entities-revchanges-before-rename-example[] + //Getters and setters are omitted for brevity + //end::envers-tracking-modified-entities-revchanges-before-rename-example[] - public Long getId() { - return id; - } + public Long getId() { + return id; + } - public void setId(Long id) { - this.id = id; - } + public void setId(Long id) { + this.id = id; + } - public String getFirstName() { - return firstName; - } + public String getFirstName() { + return firstName; + } - public void setFirstName(String firstName) { - this.firstName = firstName; - } + public void setFirstName(String firstName) { + this.firstName = firstName; + } - public String getLastName() { - return lastName; - } + public String getLastName() { + return lastName; + } - public void setLastName(String lastName) { - this.lastName = lastName; - } + public void setLastName(String lastName) { + this.lastName = lastName; + } - public Date getCreatedOn() { - return createdOn; - } + public Date getCreatedOn() { + return createdOn; + } - public void setCreatedOn(Date createdOn) { - this.createdOn = createdOn; - } - //tag::envers-tracking-modified-entities-revchanges-before-rename-example[] - } - //end::envers-tracking-modified-entities-revchanges-before-rename-example[] + public void setCreatedOn(Date createdOn) { + this.createdOn = createdOn; + } + //tag::envers-tracking-modified-entities-revchanges-before-rename-example[] + } + //end::envers-tracking-modified-entities-revchanges-before-rename-example[] - //tag::envers-tracking-modified-entities-revchanges-after-rename-example[] - @Audited - @Entity(name = "Customer") - public static class ApplicationCustomer { + //tag::envers-tracking-modified-entities-revchanges-after-rename-example[] + @Audited + @Entity(name = "Customer") + public static class ApplicationCustomer { - @Id - private Long id; + @Id + private Long id; - private String firstName; + private String firstName; - private String lastName; + private String lastName; - @Temporal(TemporalType.TIMESTAMP) - @Column(name = "created_on") - @CreationTimestamp - private Date createdOn; + @Temporal(TemporalType.TIMESTAMP) + @Column(name = "created_on") + @CreationTimestamp + private Date createdOn; - //Getters and setters are omitted for brevity - //end::envers-tracking-modified-entities-revchanges-after-rename-example[] + //Getters and setters are omitted for brevity + //end::envers-tracking-modified-entities-revchanges-after-rename-example[] - public Long getId() { - return id; - } + public Long getId() { + return id; + } - public void setId(Long id) { - this.id = id; - } + public void setId(Long id) { + this.id = id; + } - public String getFirstName() { - return firstName; - } + public String getFirstName() { + return firstName; + } - public void setFirstName(String firstName) { - this.firstName = firstName; - } + public void setFirstName(String firstName) { + this.firstName = firstName; + } - public String getLastName() { - return lastName; - } + public String getLastName() { + return lastName; + } - public void setLastName(String lastName) { - this.lastName = lastName; - } + public void setLastName(String lastName) { + this.lastName = lastName; + } - public Date getCreatedOn() { - return createdOn; - } + public Date getCreatedOn() { + return createdOn; + } - public void setCreatedOn(Date createdOn) { - this.createdOn = createdOn; - } - //tag::envers-tracking-modified-entities-revchanges-after-rename-example[] - } - //end::envers-tracking-modified-entities-revchanges-after-rename-example[] + public void setCreatedOn(Date createdOn) { + this.createdOn = createdOn; + } + //tag::envers-tracking-modified-entities-revchanges-after-rename-example[] + } + //end::envers-tracking-modified-entities-revchanges-after-rename-example[] - //tag::envers-tracking-modified-entities-revchanges-example[] - @Entity(name = "CustomTrackingRevisionEntity") - @Table(name = "TRACKING_REV_INFO") - @RevisionEntity - public static class CustomTrackingRevisionEntity extends DefaultRevisionEntity { + //tag::envers-tracking-modified-entities-revchanges-example[] + @Entity(name = "CustomTrackingRevisionEntity") + @Table(name = "TRACKING_REV_INFO") + @RevisionEntity + public static class CustomTrackingRevisionEntity extends DefaultRevisionEntity { - @ElementCollection - @JoinTable( - name = "REVCHANGES", - joinColumns = @JoinColumn(name = "REV") - ) - @Column(name = "ENTITYNAME") - @ModifiedEntityNames - private Set modifiedEntityNames = new HashSet<>(); + @ElementCollection + @JoinTable( + name = "REVCHANGES", + joinColumns = @JoinColumn(name = "REV") + ) + @Column(name = "ENTITYNAME") + @ModifiedEntityNames + private Set modifiedEntityNames = new HashSet<>(); - public Set getModifiedEntityNames() { - return modifiedEntityNames; - } - } - //end::envers-tracking-modified-entities-revchanges-example[] + public Set getModifiedEntityNames() { + return modifiedEntityNames; + } + } + //end::envers-tracking-modified-entities-revchanges-example[] } diff --git a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/EntityTypeChangeAuditTrackingRevisionListenerTest.java b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/EntityTypeChangeAuditTrackingRevisionListenerTest.java index 5e42271793..c8d9a5c2c9 100644 --- a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/EntityTypeChangeAuditTrackingRevisionListenerTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/EntityTypeChangeAuditTrackingRevisionListenerTest.java @@ -238,10 +238,10 @@ public class EntityTypeChangeAuditTrackingRevisionListenerTest extends EntityMan @Override public void entityChanged(Class entityClass, - String entityName, - Object entityId, - RevisionType revisionType, - Object revisionEntity) { + String entityName, + Object entityId, + RevisionType revisionType, + Object revisionEntity) { String type = entityClass.getName(); ((CustomTrackingRevisionEntity) revisionEntity).addModifiedEntityType(type); } diff --git a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/QueryAuditTest.java b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/QueryAuditTest.java index 8ad370f618..408a5e7905 100644 --- a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/QueryAuditTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/QueryAuditTest.java @@ -77,7 +77,7 @@ public class QueryAuditTest { }); List revisions = scope.fromTransaction( entityManager -> { - return AuditReaderFactory.get(entityManager).getRevisions( + return AuditReaderFactory.get(entityManager).getRevisions( Customer.class, 1L ); diff --git a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/ValidityStrategyAuditTest.java b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/ValidityStrategyAuditTest.java index cac8c26fe4..38b19c5f01 100644 --- a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/ValidityStrategyAuditTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/ValidityStrategyAuditTest.java @@ -72,7 +72,7 @@ public class ValidityStrategyAuditTest { }); List revisions = scope.fromTransaction( entityManager -> { - return AuditReaderFactory.get(entityManager).getRevisions( + return AuditReaderFactory.get(entityManager).getRevisions( Customer.class, 1L ); diff --git a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/entities/IntTestPrivSeqEntity.java b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/entities/IntTestPrivSeqEntity.java index 2474fd8268..03b94c7df5 100644 --- a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/entities/IntTestPrivSeqEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/entities/IntTestPrivSeqEntity.java @@ -25,7 +25,7 @@ public class IntTestPrivSeqEntity { @Id @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "IntTestPrivSeq") @SequenceGenerator(name = "IntTestPrivSeq", sequenceName = "INTTESTPRIV_SEQ", - allocationSize = 1, initialValue = 1) + allocationSize = 1, initialValue = 1) private Integer id; @Audited diff --git a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/entities/StrTestPrivSeqEntity.java b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/entities/StrTestPrivSeqEntity.java index f410b80801..98696b27ed 100644 --- a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/entities/StrTestPrivSeqEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/entities/StrTestPrivSeqEntity.java @@ -26,7 +26,7 @@ public class StrTestPrivSeqEntity { @Id @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "StrTestPrivSeq") @SequenceGenerator(name = "StrTestPrivSeq", sequenceName = "STRTESTPRIV_SEQ", - allocationSize = 1, initialValue = 1) + allocationSize = 1, initialValue = 1) private Integer id; @Audited diff --git a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/entities/components/Component3.java b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/entities/components/Component3.java index 3c526c4538..ca9c87784d 100644 --- a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/entities/components/Component3.java +++ b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/entities/components/Component3.java @@ -37,7 +37,7 @@ public class Component3 { @AttributeOverride(name = "key", column = @Column(name = "notAudComp_key")), @AttributeOverride(name = "value", column = @Column(name = "notAudComp_value")), @AttributeOverride(name = "description", - column = @Column(name = "notAudComp_description")) + column = @Column(name = "notAudComp_description")) }) private Component4 nonAuditedComponent; diff --git a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/entities/manytomany/unidirectional/JoinTableEntity.java b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/entities/manytomany/unidirectional/JoinTableEntity.java index ce18f0396d..932b8c2568 100644 --- a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/entities/manytomany/unidirectional/JoinTableEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/entities/manytomany/unidirectional/JoinTableEntity.java @@ -33,8 +33,8 @@ public class JoinTableEntity implements Serializable { @ManyToMany @JoinTable(name = "test_join_table", - joinColumns = @JoinColumn(name = "assoc_id1"), - inverseJoinColumns = @JoinColumn(name = "assoc_id2") + joinColumns = @JoinColumn(name = "assoc_id1"), + inverseJoinColumns = @JoinColumn(name = "assoc_id2") ) private Set references = new HashSet(); diff --git a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/entities/reventity/CustomDataRevEntity.java b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/entities/reventity/CustomDataRevEntity.java index d2101dc1b1..6ed82b08f6 100644 --- a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/entities/reventity/CustomDataRevEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/entities/reventity/CustomDataRevEntity.java @@ -21,13 +21,13 @@ import org.hibernate.envers.RevisionTimestamp; */ @Entity @GenericGenerator(name = "EnversTestingRevisionGenerator", - strategy = "org.hibernate.id.enhanced.TableGenerator", - parameters = { - @Parameter(name = "table_name", value = "REVISION_GENERATOR"), - @Parameter(name = "initial_value", value = "1"), - @Parameter(name = "increment_size", value = "1"), - @Parameter(name = "prefer_entity_table_as_segment_value", value = "true") - } + strategy = "org.hibernate.id.enhanced.TableGenerator", + parameters = { + @Parameter(name = "table_name", value = "REVISION_GENERATOR"), + @Parameter(name = "initial_value", value = "1"), + @Parameter(name = "increment_size", value = "1"), + @Parameter(name = "prefer_entity_table_as_segment_value", value = "true") + } ) @RevisionEntity public class CustomDataRevEntity { diff --git a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/entities/reventity/CustomDateRevEntity.java b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/entities/reventity/CustomDateRevEntity.java index 3b55735e49..341e0a57dc 100644 --- a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/entities/reventity/CustomDateRevEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/entities/reventity/CustomDateRevEntity.java @@ -22,13 +22,13 @@ import org.hibernate.envers.RevisionTimestamp; */ @Entity @GenericGenerator(name = "EnversTestingRevisionGenerator", - strategy = "org.hibernate.id.enhanced.TableGenerator", - parameters = { - @Parameter(name = "table_name", value = "REVISION_GENERATOR"), - @Parameter(name = "initial_value", value = "1"), - @Parameter(name = "increment_size", value = "1"), - @Parameter(name = "prefer_entity_table_as_segment_value", value = "true") - } + strategy = "org.hibernate.id.enhanced.TableGenerator", + parameters = { + @Parameter(name = "table_name", value = "REVISION_GENERATOR"), + @Parameter(name = "initial_value", value = "1"), + @Parameter(name = "increment_size", value = "1"), + @Parameter(name = "prefer_entity_table_as_segment_value", value = "true") + } ) @RevisionEntity public class CustomDateRevEntity { diff --git a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/entities/reventity/CustomInstantRevEntity.java b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/entities/reventity/CustomInstantRevEntity.java index 2a7708aaca..1e78761d4c 100644 --- a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/entities/reventity/CustomInstantRevEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/entities/reventity/CustomInstantRevEntity.java @@ -22,65 +22,65 @@ import org.hibernate.envers.RevisionTimestamp; */ @Entity @GenericGenerator(name = "EnversTestingRevisionGenerator", - strategy = "org.hibernate.id.enhanced.TableGenerator", - parameters = { - @Parameter(name = "table_name", value = "REVISION_GENERATOR"), - @Parameter(name = "initial_value", value = "1"), - @Parameter(name = "increment_size", value = "1"), - @Parameter(name = "prefer_entity_table_as_segment_value", value = "true") - } + strategy = "org.hibernate.id.enhanced.TableGenerator", + parameters = { + @Parameter(name = "table_name", value = "REVISION_GENERATOR"), + @Parameter(name = "initial_value", value = "1"), + @Parameter(name = "increment_size", value = "1"), + @Parameter(name = "prefer_entity_table_as_segment_value", value = "true") + } ) @RevisionEntity public class CustomInstantRevEntity { - @Id - @GeneratedValue(generator = "EnversTestingRevisionGenerator") - @RevisionNumber - private int customId; + @Id + @GeneratedValue(generator = "EnversTestingRevisionGenerator") + @RevisionNumber + private int customId; - @RevisionTimestamp - private Instant instantTimestamp; + @RevisionTimestamp + private Instant instantTimestamp; - public int getCustomId() { - return customId; - } + public int getCustomId() { + return customId; + } - public void setCustomId(int customId) { - this.customId = customId; - } + public void setCustomId(int customId) { + this.customId = customId; + } - public Instant getInstantTimestamp() { - return instantTimestamp; - } + public Instant getInstantTimestamp() { + return instantTimestamp; + } - public void setInstantTimestamp(Instant instantTimestamp) { - this.instantTimestamp = instantTimestamp; - } + public void setInstantTimestamp(Instant instantTimestamp) { + this.instantTimestamp = instantTimestamp; + } - @Override - public boolean equals(Object o) { - if ( this == o ) { - return true; - } - if ( o == null || getClass() != o.getClass() ) { - return false; - } + @Override + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( o == null || getClass() != o.getClass() ) { + return false; + } - CustomInstantRevEntity that = (CustomInstantRevEntity) o; + CustomInstantRevEntity that = (CustomInstantRevEntity) o; - if ( customId != that.customId ) { - return false; - } - if ( instantTimestamp != null ? !instantTimestamp.equals( that.instantTimestamp ) : that.instantTimestamp != null ) { - return false; - } + if ( customId != that.customId ) { + return false; + } + if ( instantTimestamp != null ? !instantTimestamp.equals( that.instantTimestamp ) : that.instantTimestamp != null ) { + return false; + } - return true; - } + return true; + } - @Override - public int hashCode() { - int result = customId; - result = 31 * result + (instantTimestamp != null ? instantTimestamp.hashCode() : 0); - return result; - } + @Override + public int hashCode() { + int result = customId; + result = 31 * result + (instantTimestamp != null ? instantTimestamp.hashCode() : 0); + return result; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/entities/reventity/CustomLocalDateTimeRevEntity.java b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/entities/reventity/CustomLocalDateTimeRevEntity.java index f975099b31..e7b30b7b16 100644 --- a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/entities/reventity/CustomLocalDateTimeRevEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/entities/reventity/CustomLocalDateTimeRevEntity.java @@ -24,56 +24,56 @@ import org.hibernate.envers.RevisionTimestamp; */ @Entity @GenericGenerator(name = "EnversTestingRevisionGenerator", - strategy = "org.hibernate.id.enhanced.TableGenerator", - parameters = { - @Parameter(name = "table_name", value = "REVISION_GENERATOR"), - @Parameter(name = "initial_value", value = "1"), - @Parameter(name = "increment_size", value = "1"), - @Parameter(name = "prefer_entity_table_as_segment_value", value = "true") - } + strategy = "org.hibernate.id.enhanced.TableGenerator", + parameters = { + @Parameter(name = "table_name", value = "REVISION_GENERATOR"), + @Parameter(name = "initial_value", value = "1"), + @Parameter(name = "increment_size", value = "1"), + @Parameter(name = "prefer_entity_table_as_segment_value", value = "true") + } ) @RevisionEntity public class CustomLocalDateTimeRevEntity { - @Id - @GeneratedValue(generator = "EnversTestingRevisionGenerator") - @RevisionNumber - private int id; + @Id + @GeneratedValue(generator = "EnversTestingRevisionGenerator") + @RevisionNumber + private int id; - @RevisionTimestamp - private LocalDateTime localDateTimestamp; + @RevisionTimestamp + private LocalDateTime localDateTimestamp; - public int getId() { - return id; - } + public int getId() { + return id; + } - public void setId(int id) { - this.id = id; - } + public void setId(int id) { + this.id = id; + } - public LocalDateTime getLocalDateTimestamp() { - return localDateTimestamp; - } + public LocalDateTime getLocalDateTimestamp() { + return localDateTimestamp; + } - public void setLocalDateTimestamp(LocalDateTime localDateTimestamp) { - this.localDateTimestamp = localDateTimestamp; - } + public void setLocalDateTimestamp(LocalDateTime localDateTimestamp) { + this.localDateTimestamp = localDateTimestamp; + } - @Override - public int hashCode() { - int result = id; - result = 31 * result + ( localDateTimestamp != null ? localDateTimestamp.hashCode() : 0 ); - return result; - } + @Override + public int hashCode() { + int result = id; + result = 31 * result + ( localDateTimestamp != null ? localDateTimestamp.hashCode() : 0 ); + return result; + } - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - CustomLocalDateTimeRevEntity that = (CustomLocalDateTimeRevEntity) o; - return id == that.id && Objects.equals(localDateTimestamp, that.localDateTimestamp); - } + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + CustomLocalDateTimeRevEntity that = (CustomLocalDateTimeRevEntity) o; + return id == that.id && Objects.equals(localDateTimestamp, that.localDateTimestamp); + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/entities/reventity/CustomPropertyAccessRevEntity.java b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/entities/reventity/CustomPropertyAccessRevEntity.java index 1617506dc3..7043a42d62 100644 --- a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/entities/reventity/CustomPropertyAccessRevEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/entities/reventity/CustomPropertyAccessRevEntity.java @@ -21,13 +21,13 @@ import org.hibernate.envers.RevisionTimestamp; */ @Entity @GenericGenerator(name = "EnversTestingRevisionGenerator", - strategy = "org.hibernate.id.enhanced.TableGenerator", - parameters = { - @Parameter(name = "table_name", value = "REVISION_GENERATOR"), - @Parameter(name = "initial_value", value = "1"), - @Parameter(name = "increment_size", value = "1"), - @Parameter(name = "prefer_entity_table_as_segment_value", value = "true") - } + strategy = "org.hibernate.id.enhanced.TableGenerator", + parameters = { + @Parameter(name = "table_name", value = "REVISION_GENERATOR"), + @Parameter(name = "initial_value", value = "1"), + @Parameter(name = "increment_size", value = "1"), + @Parameter(name = "prefer_entity_table_as_segment_value", value = "true") + } ) @RevisionEntity public class CustomPropertyAccessRevEntity { diff --git a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/entities/reventity/CustomRevEntity.java b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/entities/reventity/CustomRevEntity.java index 583509d799..6d5818da42 100644 --- a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/entities/reventity/CustomRevEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/entities/reventity/CustomRevEntity.java @@ -21,13 +21,13 @@ import org.hibernate.envers.RevisionTimestamp; */ @Entity @GenericGenerator(name = "EnversTestingRevisionGenerator", - strategy = "org.hibernate.id.enhanced.TableGenerator", - parameters = { - @Parameter(name = "table_name", value = "REVISION_GENERATOR"), - @Parameter(name = "initial_value", value = "1"), - @Parameter(name = "increment_size", value = "1"), - @Parameter(name = "prefer_entity_table_as_segment_value", value = "true") - } + strategy = "org.hibernate.id.enhanced.TableGenerator", + parameters = { + @Parameter(name = "table_name", value = "REVISION_GENERATOR"), + @Parameter(name = "initial_value", value = "1"), + @Parameter(name = "increment_size", value = "1"), + @Parameter(name = "prefer_entity_table_as_segment_value", value = "true") + } ) @RevisionEntity public class CustomRevEntity { diff --git a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/entities/reventity/CustomRevEntityColumnMapping.java b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/entities/reventity/CustomRevEntityColumnMapping.java index afae231606..2bc17b5004 100644 --- a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/entities/reventity/CustomRevEntityColumnMapping.java +++ b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/entities/reventity/CustomRevEntityColumnMapping.java @@ -22,13 +22,13 @@ import org.hibernate.envers.RevisionTimestamp; */ @Entity @GenericGenerator(name = "EnversTestingRevisionGenerator", - strategy = "org.hibernate.id.enhanced.TableGenerator", - parameters = { - @Parameter(name = "table_name", value = "REVISION_GENERATOR"), - @Parameter(name = "initial_value", value = "1"), - @Parameter(name = "increment_size", value = "1"), - @Parameter(name = "prefer_entity_table_as_segment_value", value = "true") - } + strategy = "org.hibernate.id.enhanced.TableGenerator", + parameters = { + @Parameter(name = "table_name", value = "REVISION_GENERATOR"), + @Parameter(name = "initial_value", value = "1"), + @Parameter(name = "increment_size", value = "1"), + @Parameter(name = "prefer_entity_table_as_segment_value", value = "true") + } ) @RevisionEntity public class CustomRevEntityColumnMapping { diff --git a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/entities/reventity/trackmodifiedentities/AnnotatedTrackingRevisionEntity.java b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/entities/reventity/trackmodifiedentities/AnnotatedTrackingRevisionEntity.java index 9a55bfb225..72c4e92a49 100644 --- a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/entities/reventity/trackmodifiedentities/AnnotatedTrackingRevisionEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/entities/reventity/trackmodifiedentities/AnnotatedTrackingRevisionEntity.java @@ -31,13 +31,13 @@ import org.hibernate.envers.RevisionTimestamp; @Entity @Table(name = "AnnotatedTrackRevInfo") @GenericGenerator(name = "EnversTestingRevisionGenerator", - strategy = "org.hibernate.id.enhanced.TableGenerator", - parameters = { - @Parameter(name = "table_name", value = "REVISION_GENERATOR"), - @Parameter(name = "initial_value", value = "1"), - @Parameter(name = "increment_size", value = "1"), - @Parameter(name = "prefer_entity_table_as_segment_value", value = "true") - } + strategy = "org.hibernate.id.enhanced.TableGenerator", + parameters = { + @Parameter(name = "table_name", value = "REVISION_GENERATOR"), + @Parameter(name = "initial_value", value = "1"), + @Parameter(name = "increment_size", value = "1"), + @Parameter(name = "prefer_entity_table_as_segment_value", value = "true") + } ) @RevisionEntity public class AnnotatedTrackingRevisionEntity { diff --git a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/entities/reventity/trackmodifiedentities/CustomTrackingRevisionEntity.java b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/entities/reventity/trackmodifiedentities/CustomTrackingRevisionEntity.java index e1741b2024..cc7f585c30 100644 --- a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/entities/reventity/trackmodifiedentities/CustomTrackingRevisionEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/entities/reventity/trackmodifiedentities/CustomTrackingRevisionEntity.java @@ -29,13 +29,13 @@ import org.hibernate.envers.RevisionTimestamp; @Entity @Table(name = "CustomTrackRevInfo") @GenericGenerator(name = "EnversTestingRevisionGenerator", - strategy = "org.hibernate.id.enhanced.TableGenerator", - parameters = { - @Parameter(name = "table_name", value = "REVISION_GENERATOR"), - @Parameter(name = "initial_value", value = "1"), - @Parameter(name = "increment_size", value = "1"), - @Parameter(name = "prefer_entity_table_as_segment_value", value = "true") - } + strategy = "org.hibernate.id.enhanced.TableGenerator", + parameters = { + @Parameter(name = "table_name", value = "REVISION_GENERATOR"), + @Parameter(name = "initial_value", value = "1"), + @Parameter(name = "increment_size", value = "1"), + @Parameter(name = "prefer_entity_table_as_segment_value", value = "true") + } ) @RevisionEntity(CustomTrackingRevisionListener.class) public class CustomTrackingRevisionEntity { diff --git a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/basic/RelationTargetNotFoundConfigTest.java b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/basic/RelationTargetNotFoundConfigTest.java index 5b3f31b2f8..a25209b985 100644 --- a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/basic/RelationTargetNotFoundConfigTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/basic/RelationTargetNotFoundConfigTest.java @@ -34,203 +34,203 @@ import static org.junit.Assert.assertNull; */ @JiraKey(value = "HHH-8051") public class RelationTargetNotFoundConfigTest extends BaseEnversJPAFunctionalTestCase { - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { Foo.class, Bar.class, FooBar.class }; - } + @Override + protected Class[] getAnnotatedClasses() { + return new Class[] { Foo.class, Bar.class, FooBar.class }; + } - @Override - protected void addConfigOptions(Map options) { - super.addConfigOptions( options ); - options.put( EnversSettings.GLOBAL_RELATION_NOT_FOUND_LEGACY_FLAG, Boolean.FALSE ); - } + @Override + protected void addConfigOptions(Map options) { + super.addConfigOptions( options ); + options.put( EnversSettings.GLOBAL_RELATION_NOT_FOUND_LEGACY_FLAG, Boolean.FALSE ); + } - @Test - public void testRelationTargetNotFoundAction() { - // Revision 1, initialize the data for test case - doInJPA( this::entityManagerFactory, entityManager -> { - final Bar bar = new Bar( 1 ); - entityManager.persist( bar ); + @Test + public void testRelationTargetNotFoundAction() { + // Revision 1, initialize the data for test case + doInJPA( this::entityManagerFactory, entityManager -> { + final Bar bar = new Bar( 1 ); + entityManager.persist( bar ); - final FooBar fooBar1 = new FooBar( 1, "fooBar" ); - entityManager.persist( fooBar1 ); + final FooBar fooBar1 = new FooBar( 1, "fooBar" ); + entityManager.persist( fooBar1 ); - final FooBar fooBar2 = new FooBar( 2, "fooBar2" ); - entityManager.persist( fooBar2 ); + final FooBar fooBar2 = new FooBar( 2, "fooBar2" ); + entityManager.persist( fooBar2 ); - final Foo foo = new Foo( 1, bar, fooBar1, fooBar2 ); - entityManager.persist( foo ); - } ); + final Foo foo = new Foo( 1, bar, fooBar1, fooBar2 ); + entityManager.persist( foo ); + } ); - // This test verifies that everything is fine before doing various record manipulation changes. - doInJPA( this::entityManagerFactory, entityManager -> { - final AuditReader auditReader = AuditReaderFactory.get(entityManager ); - final Foo rev1 = auditReader.find( Foo.class, 1, 1 ); - assertNotNull( rev1 ); - assertNotNull( rev1.getBar() ); - assertNotNull( rev1.getFooBar() ); - assertNotNull( rev1.getFooBar2() ); - } ); + // This test verifies that everything is fine before doing various record manipulation changes. + doInJPA( this::entityManagerFactory, entityManager -> { + final AuditReader auditReader = AuditReaderFactory.get(entityManager ); + final Foo rev1 = auditReader.find( Foo.class, 1, 1 ); + assertNotNull( rev1 ); + assertNotNull( rev1.getBar() ); + assertNotNull( rev1.getFooBar() ); + assertNotNull( rev1.getFooBar2() ); + } ); - // Simulate the removal of main data table data by removing FooBar1 (an audited entity) - doInJPA( this::entityManagerFactory, entityManager -> { - // obviously we assume either there isn't a FK between tables or the users do something like this - entityManager.createNativeQuery( "UPDATE Foo Set fooBar_id = NULL WHERE id = 1" ).executeUpdate(); - entityManager.createNativeQuery( "DELETE FROM FooBar WHERE id = 1" ).executeUpdate(); - } ); + // Simulate the removal of main data table data by removing FooBar1 (an audited entity) + doInJPA( this::entityManagerFactory, entityManager -> { + // obviously we assume either there isn't a FK between tables or the users do something like this + entityManager.createNativeQuery( "UPDATE Foo Set fooBar_id = NULL WHERE id = 1" ).executeUpdate(); + entityManager.createNativeQuery( "DELETE FROM FooBar WHERE id = 1" ).executeUpdate(); + } ); - // This shouldn't fail because the audited entity data is cached in the audit table and exists. - doInJPA( this::entityManagerFactory, entityManager -> { - final AuditReader auditReader = AuditReaderFactory.get( entityManager ); - final Foo rev1 = auditReader.find( Foo.class, 1, 1 ); - assertNotNull( rev1 ); - assertNotNull( rev1.getFooBar() ); - } ); + // This shouldn't fail because the audited entity data is cached in the audit table and exists. + doInJPA( this::entityManagerFactory, entityManager -> { + final AuditReader auditReader = AuditReaderFactory.get( entityManager ); + final Foo rev1 = auditReader.find( Foo.class, 1, 1 ); + assertNotNull( rev1 ); + assertNotNull( rev1.getFooBar() ); + } ); - // Simulate the removal of envers data via purge process by removing FooBar2 (an audited entity) - doInJPA( this::entityManagerFactory, entityManager -> { - entityManager.createNativeQuery( "DELETE FROM FooBar_AUD WHERE id = 2" ).executeUpdate(); - } ); + // Simulate the removal of envers data via purge process by removing FooBar2 (an audited entity) + doInJPA( this::entityManagerFactory, entityManager -> { + entityManager.createNativeQuery( "DELETE FROM FooBar_AUD WHERE id = 2" ).executeUpdate(); + } ); - // Test querying history record where the reference audit row no longer exists. - doInJPA( this::entityManagerFactory, entityManager -> { - final AuditReader auditReader = AuditReaderFactory.get( entityManager ); - final Foo rev1 = auditReader.find( Foo.class, 1, 1 ); - assertNotNull( rev1 ); - // With RelationTargetNotFoundAction.ERROR, this would throw an EntityNotFoundException. - assertNull( rev1.getFooBar2() ); - } ); + // Test querying history record where the reference audit row no longer exists. + doInJPA( this::entityManagerFactory, entityManager -> { + final AuditReader auditReader = AuditReaderFactory.get( entityManager ); + final Foo rev1 = auditReader.find( Foo.class, 1, 1 ); + assertNotNull( rev1 ); + // With RelationTargetNotFoundAction.ERROR, this would throw an EntityNotFoundException. + assertNull( rev1.getFooBar2() ); + } ); - // this simulates the removal of a non-audited entity from the main table - doInJPA( this::entityManagerFactory, entityManager -> { - // obviously we assume either there isn't a FK between tables or the users do something like this - entityManager.createNativeQuery( "UPDATE Foo SET bar_id = NULL WHERE id = 1" ).executeUpdate(); - entityManager.createNativeQuery( "DELETE FROM Bar WHERE id = 1" ).executeUpdate(); - } ); + // this simulates the removal of a non-audited entity from the main table + doInJPA( this::entityManagerFactory, entityManager -> { + // obviously we assume either there isn't a FK between tables or the users do something like this + entityManager.createNativeQuery( "UPDATE Foo SET bar_id = NULL WHERE id = 1" ).executeUpdate(); + entityManager.createNativeQuery( "DELETE FROM Bar WHERE id = 1" ).executeUpdate(); + } ); - // Test querying history record where the reference non-audited row no longer exists. - doInJPA( this::entityManagerFactory, entityManager -> { - final AuditReader auditReader = AuditReaderFactory.get( entityManager ); - final Foo rev1 = auditReader.find( Foo.class, 1, 1 ); - assertNotNull( rev1 ); - // With RelationTargetNotFoundAction.ERROR, this would throw an EntityNotFoundException - assertNull( rev1.getBar() ); - } ); - } + // Test querying history record where the reference non-audited row no longer exists. + doInJPA( this::entityManagerFactory, entityManager -> { + final AuditReader auditReader = AuditReaderFactory.get( entityManager ); + final Foo rev1 = auditReader.find( Foo.class, 1, 1 ); + assertNotNull( rev1 ); + // With RelationTargetNotFoundAction.ERROR, this would throw an EntityNotFoundException + assertNull( rev1.getBar() ); + } ); + } - @Audited - @Entity(name = "Foo") - public static class Foo { - @Id - private Integer id; + @Audited + @Entity(name = "Foo") + public static class Foo { + @Id + private Integer id; - @ManyToOne - @Audited(targetAuditMode = RelationTargetAuditMode.NOT_AUDITED) - private Bar bar; + @ManyToOne + @Audited(targetAuditMode = RelationTargetAuditMode.NOT_AUDITED) + private Bar bar; - @ManyToOne - private FooBar fooBar; + @ManyToOne + private FooBar fooBar; - @ManyToOne - private FooBar fooBar2; + @ManyToOne + private FooBar fooBar2; - Foo() { - // Required by JPA - } + Foo() { + // Required by JPA + } - Foo(Integer id, Bar bar, FooBar fooBar, FooBar fooBar2) { - this.id = id; - this.bar = bar; - this.fooBar = fooBar; - this.fooBar2 = fooBar2; - } + Foo(Integer id, Bar bar, FooBar fooBar, FooBar fooBar2) { + this.id = id; + this.bar = bar; + this.fooBar = fooBar; + this.fooBar2 = fooBar2; + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public Bar getBar() { - return bar; - } + public Bar getBar() { + return bar; + } - public void setBar(Bar bar) { - this.bar = bar; - } + public void setBar(Bar bar) { + this.bar = bar; + } - public FooBar getFooBar() { - return fooBar; - } + public FooBar getFooBar() { + return fooBar; + } - public void setFooBar(FooBar fooBar) { - this.fooBar = fooBar; - } + public void setFooBar(FooBar fooBar) { + this.fooBar = fooBar; + } - public FooBar getFooBar2() { - return fooBar2; - } + public FooBar getFooBar2() { + return fooBar2; + } - public void setFooBar2(FooBar fooBar2) { - this.fooBar2 = fooBar2; - } - } + public void setFooBar2(FooBar fooBar2) { + this.fooBar2 = fooBar2; + } + } - @Entity(name = "Bar") - public static class Bar { - @Id - private Integer id; + @Entity(name = "Bar") + public static class Bar { + @Id + private Integer id; - Bar() { - // Required by JPA - } + Bar() { + // Required by JPA + } - Bar(Integer id) { - this.id = id; - } + Bar(Integer id) { + this.id = id; + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } - } + public void setId(Integer id) { + this.id = id; + } + } - @Audited - @Entity(name = "FooBar") - public static class FooBar { - @Id - private Integer id; - private String name; + @Audited + @Entity(name = "FooBar") + public static class FooBar { + @Id + private Integer id; + private String name; - FooBar() { - // Required by JPA - } + FooBar() { + // Required by JPA + } - FooBar(Integer id, String name) { - this.id = id; - this.name = name; - } + FooBar(Integer id, String name) { + this.id = id; + this.name = name; + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } - } + public void setName(String name) { + this.name = name; + } + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/basic/RelationTargetNotFoundLegacyTest.java b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/basic/RelationTargetNotFoundLegacyTest.java index 144810fffd..3de3bcc941 100644 --- a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/basic/RelationTargetNotFoundLegacyTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/basic/RelationTargetNotFoundLegacyTest.java @@ -34,208 +34,208 @@ import static org.junit.Assert.fail; */ @JiraKey(value = "HHH-8051") public class RelationTargetNotFoundLegacyTest extends BaseEnversJPAFunctionalTestCase { - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { Foo.class, Bar.class, FooBar.class }; - } + @Override + protected Class[] getAnnotatedClasses() { + return new Class[] { Foo.class, Bar.class, FooBar.class }; + } - @Test - public void testRelationTargetNotFoundAction() { - // Revision 1, initialize the data for test case - doInJPA( this::entityManagerFactory, entityManager -> { - final Bar bar = new Bar( 1 ); - entityManager.persist( bar ); + @Test + public void testRelationTargetNotFoundAction() { + // Revision 1, initialize the data for test case + doInJPA( this::entityManagerFactory, entityManager -> { + final Bar bar = new Bar( 1 ); + entityManager.persist( bar ); - final FooBar fooBar1 = new FooBar( 1, "fooBar" ); - entityManager.persist( fooBar1 ); + final FooBar fooBar1 = new FooBar( 1, "fooBar" ); + entityManager.persist( fooBar1 ); - final FooBar fooBar2 = new FooBar( 2, "fooBar2" ); - entityManager.persist( fooBar2 ); + final FooBar fooBar2 = new FooBar( 2, "fooBar2" ); + entityManager.persist( fooBar2 ); - final Foo foo = new Foo( 1, bar, fooBar1, fooBar2 ); - entityManager.persist( foo ); - } ); + final Foo foo = new Foo( 1, bar, fooBar1, fooBar2 ); + entityManager.persist( foo ); + } ); - // This test verifies that everything is fine before doing various record manipulation changes. - doInJPA( this::entityManagerFactory, entityManager -> { - final AuditReader auditReader = AuditReaderFactory.get(entityManager ); - final Foo rev1 = auditReader.find( Foo.class, 1, 1 ); - assertNotNull( rev1 ); - assertNotNull( rev1.getBar() ); - assertNotNull( rev1.getFooBar() ); - assertNotNull( rev1.getFooBar2() ); - } ); + // This test verifies that everything is fine before doing various record manipulation changes. + doInJPA( this::entityManagerFactory, entityManager -> { + final AuditReader auditReader = AuditReaderFactory.get(entityManager ); + final Foo rev1 = auditReader.find( Foo.class, 1, 1 ); + assertNotNull( rev1 ); + assertNotNull( rev1.getBar() ); + assertNotNull( rev1.getFooBar() ); + assertNotNull( rev1.getFooBar2() ); + } ); - // Simulate the removal of main data table data by removing FooBar1 (an audited entity) - doInJPA( this::entityManagerFactory, entityManager -> { - // obviously we assume either there isn't a FK between tables or the users do something like this - entityManager.createNativeQuery( "UPDATE Foo Set fooBar_id = NULL WHERE id = 1" ).executeUpdate(); - entityManager.createNativeQuery( "DELETE FROM FooBar WHERE id = 1" ).executeUpdate(); - } ); + // Simulate the removal of main data table data by removing FooBar1 (an audited entity) + doInJPA( this::entityManagerFactory, entityManager -> { + // obviously we assume either there isn't a FK between tables or the users do something like this + entityManager.createNativeQuery( "UPDATE Foo Set fooBar_id = NULL WHERE id = 1" ).executeUpdate(); + entityManager.createNativeQuery( "DELETE FROM FooBar WHERE id = 1" ).executeUpdate(); + } ); - // This shouldn't fail because the audited entity data is cached in the audit table and exists. - doInJPA( this::entityManagerFactory, entityManager -> { - final AuditReader auditReader = AuditReaderFactory.get( entityManager ); - final Foo rev1 = auditReader.find( Foo.class, 1, 1 ); - assertNotNull( rev1 ); - assertNotNull( rev1.getFooBar() ); - } ); + // This shouldn't fail because the audited entity data is cached in the audit table and exists. + doInJPA( this::entityManagerFactory, entityManager -> { + final AuditReader auditReader = AuditReaderFactory.get( entityManager ); + final Foo rev1 = auditReader.find( Foo.class, 1, 1 ); + assertNotNull( rev1 ); + assertNotNull( rev1.getFooBar() ); + } ); - // Simulate the removal of envers data via purge process by removing FooBar2 (an audited entity) - doInJPA( this::entityManagerFactory, entityManager -> { - entityManager.createNativeQuery( "DELETE FROM FooBar_AUD WHERE id = 2" ).executeUpdate(); - } ); + // Simulate the removal of envers data via purge process by removing FooBar2 (an audited entity) + doInJPA( this::entityManagerFactory, entityManager -> { + entityManager.createNativeQuery( "DELETE FROM FooBar_AUD WHERE id = 2" ).executeUpdate(); + } ); - // Test querying history record where the reference audit row no longer exists. - doInJPA( this::entityManagerFactory, entityManager -> { - final AuditReader auditReader = AuditReaderFactory.get( entityManager ); - final Foo rev1 = auditReader.find( Foo.class, 1, 1 ); - assertNotNull( rev1 ); - try { - // With RelationTargetNotFoundAction.ERROR, this would throw an EntityNotFoundException. - assertNull( rev1.getFooBar2() ); - fail( "This expected an EntityNotFoundException to be thrown" ); - } - catch ( Exception e ) { - assertTyping(EntityNotFoundException.class, e ); - } - } ); + // Test querying history record where the reference audit row no longer exists. + doInJPA( this::entityManagerFactory, entityManager -> { + final AuditReader auditReader = AuditReaderFactory.get( entityManager ); + final Foo rev1 = auditReader.find( Foo.class, 1, 1 ); + assertNotNull( rev1 ); + try { + // With RelationTargetNotFoundAction.ERROR, this would throw an EntityNotFoundException. + assertNull( rev1.getFooBar2() ); + fail( "This expected an EntityNotFoundException to be thrown" ); + } + catch ( Exception e ) { + assertTyping(EntityNotFoundException.class, e ); + } + } ); - // this simulates the removal of a non-audited entity from the main table - doInJPA( this::entityManagerFactory, entityManager -> { - // obviously we assume either there isn't a FK between tables or the users do something like this - entityManager.createNativeQuery( "UPDATE Foo SET bar_id = NULL WHERE id = 1" ).executeUpdate(); - entityManager.createNativeQuery( "DELETE FROM Bar WHERE id = 1" ).executeUpdate(); - } ); + // this simulates the removal of a non-audited entity from the main table + doInJPA( this::entityManagerFactory, entityManager -> { + // obviously we assume either there isn't a FK between tables or the users do something like this + entityManager.createNativeQuery( "UPDATE Foo SET bar_id = NULL WHERE id = 1" ).executeUpdate(); + entityManager.createNativeQuery( "DELETE FROM Bar WHERE id = 1" ).executeUpdate(); + } ); - // Test querying history record where the reference non-audited row no longer exists. - doInJPA( this::entityManagerFactory, entityManager -> { - final AuditReader auditReader = AuditReaderFactory.get( entityManager ); - final Foo rev1 = auditReader.find( Foo.class, 1, 1 ); - assertNotNull( rev1 ); - try { - // With RelationTargetNotFoundAction.ERROR, this would throw an EntityNotFoundException - assertNull( rev1.getBar() ); - fail( "This expected an EntityNotFoundException to be thrown" ); - } - catch ( Exception e ) { - assertTyping( EntityNotFoundException.class, e ); - } - } ); - } + // Test querying history record where the reference non-audited row no longer exists. + doInJPA( this::entityManagerFactory, entityManager -> { + final AuditReader auditReader = AuditReaderFactory.get( entityManager ); + final Foo rev1 = auditReader.find( Foo.class, 1, 1 ); + assertNotNull( rev1 ); + try { + // With RelationTargetNotFoundAction.ERROR, this would throw an EntityNotFoundException + assertNull( rev1.getBar() ); + fail( "This expected an EntityNotFoundException to be thrown" ); + } + catch ( Exception e ) { + assertTyping( EntityNotFoundException.class, e ); + } + } ); + } - @Audited - @Entity(name = "Foo") - public static class Foo { - @Id - private Integer id; + @Audited + @Entity(name = "Foo") + public static class Foo { + @Id + private Integer id; - @ManyToOne - @Audited(targetAuditMode = RelationTargetAuditMode.NOT_AUDITED) - private Bar bar; + @ManyToOne + @Audited(targetAuditMode = RelationTargetAuditMode.NOT_AUDITED) + private Bar bar; - @ManyToOne - private FooBar fooBar; + @ManyToOne + private FooBar fooBar; - @ManyToOne - private FooBar fooBar2; + @ManyToOne + private FooBar fooBar2; - Foo() { - // Required by JPA - } + Foo() { + // Required by JPA + } - Foo(Integer id, Bar bar, FooBar fooBar, FooBar fooBar2) { - this.id = id; - this.bar = bar; - this.fooBar = fooBar; - this.fooBar2 = fooBar2; - } + Foo(Integer id, Bar bar, FooBar fooBar, FooBar fooBar2) { + this.id = id; + this.bar = bar; + this.fooBar = fooBar; + this.fooBar2 = fooBar2; + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public Bar getBar() { - return bar; - } + public Bar getBar() { + return bar; + } - public void setBar(Bar bar) { - this.bar = bar; - } + public void setBar(Bar bar) { + this.bar = bar; + } - public FooBar getFooBar() { - return fooBar; - } + public FooBar getFooBar() { + return fooBar; + } - public void setFooBar(FooBar fooBar) { - this.fooBar = fooBar; - } + public void setFooBar(FooBar fooBar) { + this.fooBar = fooBar; + } - public FooBar getFooBar2() { - return fooBar2; - } + public FooBar getFooBar2() { + return fooBar2; + } - public void setFooBar2(FooBar fooBar2) { - this.fooBar2 = fooBar2; - } - } + public void setFooBar2(FooBar fooBar2) { + this.fooBar2 = fooBar2; + } + } - @Entity(name = "Bar") - public static class Bar { - @Id - private Integer id; + @Entity(name = "Bar") + public static class Bar { + @Id + private Integer id; - Bar() { - // Required by JPA - } + Bar() { + // Required by JPA + } - Bar(Integer id) { - this.id = id; - } + Bar(Integer id) { + this.id = id; + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } - } + public void setId(Integer id) { + this.id = id; + } + } - @Audited - @Entity(name = "FooBar") - public static class FooBar { - @Id - private Integer id; - private String name; + @Audited + @Entity(name = "FooBar") + public static class FooBar { + @Id + private Integer id; + private String name; - FooBar() { - // Required by JPA - } + FooBar() { + // Required by JPA + } - FooBar(Integer id, String name) { - this.id = id; - this.name = name; - } + FooBar(Integer id, String name) { + this.id = id; + this.name = name; + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } - } + public void setName(String name) { + this.name = name; + } + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/basic/RelationTargetNotFoundTest.java b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/basic/RelationTargetNotFoundTest.java index f9ec97f008..a12c6d09c8 100644 --- a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/basic/RelationTargetNotFoundTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/basic/RelationTargetNotFoundTest.java @@ -32,196 +32,196 @@ import static org.junit.Assert.assertNull; */ @JiraKey(value = "HHH-8051") public class RelationTargetNotFoundTest extends BaseEnversJPAFunctionalTestCase { - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { Foo.class, Bar.class, FooBar.class }; - } + @Override + protected Class[] getAnnotatedClasses() { + return new Class[] { Foo.class, Bar.class, FooBar.class }; + } - @Test - public void testRelationTargetNotFoundAction() { - // Revision 1, initialize the data for test case - doInJPA( this::entityManagerFactory, entityManager -> { - final Bar bar = new Bar( 1 ); - entityManager.persist( bar ); + @Test + public void testRelationTargetNotFoundAction() { + // Revision 1, initialize the data for test case + doInJPA( this::entityManagerFactory, entityManager -> { + final Bar bar = new Bar( 1 ); + entityManager.persist( bar ); - final FooBar fooBar1 = new FooBar( 1, "fooBar" ); - entityManager.persist( fooBar1 ); + final FooBar fooBar1 = new FooBar( 1, "fooBar" ); + entityManager.persist( fooBar1 ); - final FooBar fooBar2 = new FooBar( 2, "fooBar2" ); - entityManager.persist( fooBar2 ); + final FooBar fooBar2 = new FooBar( 2, "fooBar2" ); + entityManager.persist( fooBar2 ); - final Foo foo = new Foo( 1, bar, fooBar1, fooBar2 ); - entityManager.persist( foo ); - } ); + final Foo foo = new Foo( 1, bar, fooBar1, fooBar2 ); + entityManager.persist( foo ); + } ); - // This test verifies that everything is fine before doing various record manipulation changes. - doInJPA( this::entityManagerFactory, entityManager -> { - final AuditReader auditReader = AuditReaderFactory.get(entityManager ); - final Foo rev1 = auditReader.find( Foo.class, 1, 1 ); - assertNotNull( rev1 ); - assertNotNull( rev1.getBar() ); - assertNotNull( rev1.getFooBar() ); - assertNotNull( rev1.getFooBar2() ); - } ); + // This test verifies that everything is fine before doing various record manipulation changes. + doInJPA( this::entityManagerFactory, entityManager -> { + final AuditReader auditReader = AuditReaderFactory.get(entityManager ); + final Foo rev1 = auditReader.find( Foo.class, 1, 1 ); + assertNotNull( rev1 ); + assertNotNull( rev1.getBar() ); + assertNotNull( rev1.getFooBar() ); + assertNotNull( rev1.getFooBar2() ); + } ); - // Simulate the removal of main data table data by removing FooBar1 (an audited entity) - doInJPA( this::entityManagerFactory, entityManager -> { - // obviously we assume either there isn't a FK between tables or the users do something like this - entityManager.createNativeQuery( "UPDATE Foo Set fooBar_id = NULL WHERE id = 1" ).executeUpdate(); - entityManager.createNativeQuery( "DELETE FROM FooBar WHERE id = 1" ).executeUpdate(); - } ); + // Simulate the removal of main data table data by removing FooBar1 (an audited entity) + doInJPA( this::entityManagerFactory, entityManager -> { + // obviously we assume either there isn't a FK between tables or the users do something like this + entityManager.createNativeQuery( "UPDATE Foo Set fooBar_id = NULL WHERE id = 1" ).executeUpdate(); + entityManager.createNativeQuery( "DELETE FROM FooBar WHERE id = 1" ).executeUpdate(); + } ); - // This shouldn't fail because the audited entity data is cached in the audit table and exists. - doInJPA( this::entityManagerFactory, entityManager -> { - final AuditReader auditReader = AuditReaderFactory.get( entityManager ); - final Foo rev1 = auditReader.find( Foo.class, 1, 1 ); - assertNotNull( rev1 ); - assertNotNull( rev1.getFooBar() ); - } ); + // This shouldn't fail because the audited entity data is cached in the audit table and exists. + doInJPA( this::entityManagerFactory, entityManager -> { + final AuditReader auditReader = AuditReaderFactory.get( entityManager ); + final Foo rev1 = auditReader.find( Foo.class, 1, 1 ); + assertNotNull( rev1 ); + assertNotNull( rev1.getFooBar() ); + } ); - // Simulate the removal of envers data via purge process by removing FooBar2 (an audited entity) - doInJPA( this::entityManagerFactory, entityManager -> { - entityManager.createNativeQuery( "DELETE FROM FooBar_AUD WHERE id = 2" ).executeUpdate(); - } ); + // Simulate the removal of envers data via purge process by removing FooBar2 (an audited entity) + doInJPA( this::entityManagerFactory, entityManager -> { + entityManager.createNativeQuery( "DELETE FROM FooBar_AUD WHERE id = 2" ).executeUpdate(); + } ); - // Test querying history record where the reference audit row no longer exists. - doInJPA( this::entityManagerFactory, entityManager -> { - final AuditReader auditReader = AuditReaderFactory.get( entityManager ); - final Foo rev1 = auditReader.find( Foo.class, 1, 1 ); - assertNotNull( rev1 ); - // With RelationTargetNotFoundAction.ERROR, this would throw an EntityNotFoundException. - assertNull( rev1.getFooBar2() ); - } ); + // Test querying history record where the reference audit row no longer exists. + doInJPA( this::entityManagerFactory, entityManager -> { + final AuditReader auditReader = AuditReaderFactory.get( entityManager ); + final Foo rev1 = auditReader.find( Foo.class, 1, 1 ); + assertNotNull( rev1 ); + // With RelationTargetNotFoundAction.ERROR, this would throw an EntityNotFoundException. + assertNull( rev1.getFooBar2() ); + } ); - // this simulates the removal of a non-audited entity from the main table - doInJPA( this::entityManagerFactory, entityManager -> { - // obviously we assume either there isn't a FK between tables or the users do something like this - entityManager.createNativeQuery( "UPDATE Foo SET bar_id = NULL WHERE id = 1" ).executeUpdate(); - entityManager.createNativeQuery( "DELETE FROM Bar WHERE id = 1" ).executeUpdate(); - } ); + // this simulates the removal of a non-audited entity from the main table + doInJPA( this::entityManagerFactory, entityManager -> { + // obviously we assume either there isn't a FK between tables or the users do something like this + entityManager.createNativeQuery( "UPDATE Foo SET bar_id = NULL WHERE id = 1" ).executeUpdate(); + entityManager.createNativeQuery( "DELETE FROM Bar WHERE id = 1" ).executeUpdate(); + } ); - // Test querying history record where the reference non-audited row no longer exists. - doInJPA( this::entityManagerFactory, entityManager -> { - final AuditReader auditReader = AuditReaderFactory.get( entityManager ); - final Foo rev1 = auditReader.find( Foo.class, 1, 1 ); - assertNotNull( rev1 ); - // With RelationTargetNotFoundAction.ERROR, this would throw an EntityNotFoundException - assertNull( rev1.getBar() ); - } ); - } + // Test querying history record where the reference non-audited row no longer exists. + doInJPA( this::entityManagerFactory, entityManager -> { + final AuditReader auditReader = AuditReaderFactory.get( entityManager ); + final Foo rev1 = auditReader.find( Foo.class, 1, 1 ); + assertNotNull( rev1 ); + // With RelationTargetNotFoundAction.ERROR, this would throw an EntityNotFoundException + assertNull( rev1.getBar() ); + } ); + } - @Audited(targetNotFoundAction = RelationTargetNotFoundAction.IGNORE) - @Entity(name = "Foo") - public static class Foo { - @Id - private Integer id; + @Audited(targetNotFoundAction = RelationTargetNotFoundAction.IGNORE) + @Entity(name = "Foo") + public static class Foo { + @Id + private Integer id; - @ManyToOne - @Audited(targetAuditMode = RelationTargetAuditMode.NOT_AUDITED) - private Bar bar; + @ManyToOne + @Audited(targetAuditMode = RelationTargetAuditMode.NOT_AUDITED) + private Bar bar; - @ManyToOne - private FooBar fooBar; + @ManyToOne + private FooBar fooBar; - @ManyToOne - private FooBar fooBar2; + @ManyToOne + private FooBar fooBar2; - Foo() { - // Required by JPA - } + Foo() { + // Required by JPA + } - Foo(Integer id, Bar bar, FooBar fooBar, FooBar fooBar2) { - this.id = id; - this.bar = bar; - this.fooBar = fooBar; - this.fooBar2 = fooBar2; - } + Foo(Integer id, Bar bar, FooBar fooBar, FooBar fooBar2) { + this.id = id; + this.bar = bar; + this.fooBar = fooBar; + this.fooBar2 = fooBar2; + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public Bar getBar() { - return bar; - } + public Bar getBar() { + return bar; + } - public void setBar(Bar bar) { - this.bar = bar; - } + public void setBar(Bar bar) { + this.bar = bar; + } - public FooBar getFooBar() { - return fooBar; - } + public FooBar getFooBar() { + return fooBar; + } - public void setFooBar(FooBar fooBar) { - this.fooBar = fooBar; - } + public void setFooBar(FooBar fooBar) { + this.fooBar = fooBar; + } - public FooBar getFooBar2() { - return fooBar2; - } + public FooBar getFooBar2() { + return fooBar2; + } - public void setFooBar2(FooBar fooBar2) { - this.fooBar2 = fooBar2; - } - } + public void setFooBar2(FooBar fooBar2) { + this.fooBar2 = fooBar2; + } + } - @Entity(name = "Bar") - public static class Bar { - @Id - private Integer id; + @Entity(name = "Bar") + public static class Bar { + @Id + private Integer id; - Bar() { - // Required by JPA - } + Bar() { + // Required by JPA + } - Bar(Integer id) { - this.id = id; - } + Bar(Integer id) { + this.id = id; + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } - } + public void setId(Integer id) { + this.id = id; + } + } - @Audited - @Entity(name = "FooBar") - public static class FooBar { - @Id - private Integer id; - private String name; + @Audited + @Entity(name = "FooBar") + public static class FooBar { + @Id + private Integer id; + private String name; - FooBar() { - // Required by JPA - } + FooBar() { + // Required by JPA + } - FooBar(Integer id, String name) { - this.id = id; - this.name = name; - } + FooBar(Integer id, String name) { + this.id = id; + this.name = name; + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } - } + public void setName(String name) { + this.name = name; + } + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/components/mappedsuperclass/AbstractAuditedEmbeddable.java b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/components/mappedsuperclass/AbstractAuditedEmbeddable.java index c21f7c8fef..fc1b60a746 100644 --- a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/components/mappedsuperclass/AbstractAuditedEmbeddable.java +++ b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/components/mappedsuperclass/AbstractAuditedEmbeddable.java @@ -20,52 +20,52 @@ import org.hibernate.envers.Audited; @Audited public abstract class AbstractAuditedEmbeddable { - /** - * Initial Value - */ - protected static final int UNDEFINED = -1; + /** + * Initial Value + */ + protected static final int UNDEFINED = -1; - private int code = UNDEFINED; + private int code = UNDEFINED; - protected AbstractAuditedEmbeddable() { - this( UNDEFINED ); - } + protected AbstractAuditedEmbeddable() { + this( UNDEFINED ); + } - /** - * Constructor with code - */ - public AbstractAuditedEmbeddable(int code) { - this.code = code; - } + /** + * Constructor with code + */ + public AbstractAuditedEmbeddable(int code) { + this.code = code; + } - public int getCode() { - return code; - } + public int getCode() { + return code; + } - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + code; - return result; - } + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + code; + return result; + } - @Override - public boolean equals(Object obj) { - if ( this == obj ) { - return true; - } - if ( obj == null ) { - return false; - } - if ( getClass() != obj.getClass() ) { - return false; - } - AbstractAuditedEmbeddable other = (AbstractAuditedEmbeddable) obj; - if ( code != other.code ) { - return false; - } - return true; - } + @Override + public boolean equals(Object obj) { + if ( this == obj ) { + return true; + } + if ( obj == null ) { + return false; + } + if ( getClass() != obj.getClass() ) { + return false; + } + AbstractAuditedEmbeddable other = (AbstractAuditedEmbeddable) obj; + if ( code != other.code ) { + return false; + } + return true; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/components/mappedsuperclass/AuditedEmbeddableWithDeclaredData.java b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/components/mappedsuperclass/AuditedEmbeddableWithDeclaredData.java index 9acfdae56a..fca24db1b7 100644 --- a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/components/mappedsuperclass/AuditedEmbeddableWithDeclaredData.java +++ b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/components/mappedsuperclass/AuditedEmbeddableWithDeclaredData.java @@ -17,51 +17,51 @@ import org.hibernate.envers.Audited; @Audited public class AuditedEmbeddableWithDeclaredData extends AbstractAuditedEmbeddable { - private String codeArt; + private String codeArt; - public AuditedEmbeddableWithDeclaredData(int code, String codeArt) { - super( code ); - this.codeArt = codeArt; - } + public AuditedEmbeddableWithDeclaredData(int code, String codeArt) { + super( code ); + this.codeArt = codeArt; + } - // Needed for @Embeddable - protected AuditedEmbeddableWithDeclaredData() { - this( UNDEFINED, null ); - } + // Needed for @Embeddable + protected AuditedEmbeddableWithDeclaredData() { + this( UNDEFINED, null ); + } - public String getCodeart() { - return codeArt; - } + public String getCodeart() { + return codeArt; + } - @Override - public int hashCode() { - final int prime = 31; - int result = super.hashCode(); - result = prime * result + ( ( codeArt == null ) ? 0 : codeArt.hashCode() ); - return result; - } + @Override + public int hashCode() { + final int prime = 31; + int result = super.hashCode(); + result = prime * result + ( ( codeArt == null ) ? 0 : codeArt.hashCode() ); + return result; + } - @Override - public boolean equals(Object obj) { - if ( this == obj ) { - return true; - } - if ( !super.equals( obj ) ) { - return false; - } - if ( getClass() != obj.getClass() ) { - return false; - } - AuditedEmbeddableWithDeclaredData other = (AuditedEmbeddableWithDeclaredData) obj; - if ( codeArt == null ) { - if ( other.codeArt != null ) { - return false; - } - } - else if ( !codeArt.equals( other.codeArt ) ) { - return false; - } - return true; - } + @Override + public boolean equals(Object obj) { + if ( this == obj ) { + return true; + } + if ( !super.equals( obj ) ) { + return false; + } + if ( getClass() != obj.getClass() ) { + return false; + } + AuditedEmbeddableWithDeclaredData other = (AuditedEmbeddableWithDeclaredData) obj; + if ( codeArt == null ) { + if ( other.codeArt != null ) { + return false; + } + } + else if ( !codeArt.equals( other.codeArt ) ) { + return false; + } + return true; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/components/mappedsuperclass/AuditedEmbeddableWithDeclaredDataTest.java b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/components/mappedsuperclass/AuditedEmbeddableWithDeclaredDataTest.java index 9cfd031da9..962588cb6b 100644 --- a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/components/mappedsuperclass/AuditedEmbeddableWithDeclaredDataTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/components/mappedsuperclass/AuditedEmbeddableWithDeclaredDataTest.java @@ -25,53 +25,53 @@ import static org.assertj.core.api.Assertions.assertThat; @JiraKey("HHH-17189") public class AuditedEmbeddableWithDeclaredDataTest extends BaseEnversJPAFunctionalTestCase { - private long id; + private long id; - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - EntityWithAuditedEmbeddableWithDeclaredData.class, - AbstractAuditedEmbeddable.class, - AuditedEmbeddableWithDeclaredData.class - }; - } + @Override + protected Class[] getAnnotatedClasses() { + return new Class[] { + EntityWithAuditedEmbeddableWithDeclaredData.class, + AbstractAuditedEmbeddable.class, + AuditedEmbeddableWithDeclaredData.class + }; + } - @Test - @Priority(10) - public void initData() { - this.id = TransactionUtil.doInJPA( this::entityManagerFactory, entityManager -> { - final EntityWithAuditedEmbeddableWithDeclaredData entity = new EntityWithAuditedEmbeddableWithDeclaredData(); - entity.setName( "Entity 1" ); - entity.setValue( new AuditedEmbeddableWithDeclaredData( 42, "Data" ) ); + @Test + @Priority(10) + public void initData() { + this.id = TransactionUtil.doInJPA( this::entityManagerFactory, entityManager -> { + final EntityWithAuditedEmbeddableWithDeclaredData entity = new EntityWithAuditedEmbeddableWithDeclaredData(); + entity.setName( "Entity 1" ); + entity.setValue( new AuditedEmbeddableWithDeclaredData( 42, "Data" ) ); - entityManager.persist(entity); - return entity.getId(); - } ); - } + entityManager.persist(entity); + return entity.getId(); + } ); + } - @Test - public void testEmbeddableThatExtendsAuditedMappedSuperclass() { - TransactionUtil.doInJPA( this::entityManagerFactory, entityManager -> { - final EntityWithAuditedEmbeddableWithDeclaredData entity = entityManager.find( - EntityWithAuditedEmbeddableWithDeclaredData.class, - id - ); + @Test + public void testEmbeddableThatExtendsAuditedMappedSuperclass() { + TransactionUtil.doInJPA( this::entityManagerFactory, entityManager -> { + final EntityWithAuditedEmbeddableWithDeclaredData entity = entityManager.find( + EntityWithAuditedEmbeddableWithDeclaredData.class, + id + ); - final AuditReader auditReader = AuditReaderFactory.get( entityManager ); + final AuditReader auditReader = AuditReaderFactory.get( entityManager ); - final List revisions = auditReader.getRevisions( EntityWithAuditedEmbeddableWithDeclaredData.class, id ); - assertThat( revisions ).hasSize( 1 ); + final List revisions = auditReader.getRevisions( EntityWithAuditedEmbeddableWithDeclaredData.class, id ); + assertThat( revisions ).hasSize( 1 ); - final EntityWithAuditedEmbeddableWithDeclaredData entityRevision1 = auditReader.find( - EntityWithAuditedEmbeddableWithDeclaredData.class, - id, - revisions.get( 0 ) - ); - assertThat( entityRevision1.getName() ).isEqualTo( entity.getName() ); + final EntityWithAuditedEmbeddableWithDeclaredData entityRevision1 = auditReader.find( + EntityWithAuditedEmbeddableWithDeclaredData.class, + id, + revisions.get( 0 ) + ); + assertThat( entityRevision1.getName() ).isEqualTo( entity.getName() ); - // All fields should be audited because the mapped superclass is annotated - assertThat( entity.getValue().getCodeart() ).isEqualTo( entityRevision1.getValue().getCodeart() ); - assertThat( entityRevision1.getValue().getCode() ).isEqualTo( 42 ); - } ); - } + // All fields should be audited because the mapped superclass is annotated + assertThat( entity.getValue().getCodeart() ).isEqualTo( entityRevision1.getValue().getCodeart() ); + assertThat( entityRevision1.getValue().getCode() ).isEqualTo( 42 ); + } ); + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/components/mappedsuperclass/AuditedEmbeddableWithNoDeclaredData.java b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/components/mappedsuperclass/AuditedEmbeddableWithNoDeclaredData.java index 69cfc23af0..174d1e4b78 100644 --- a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/components/mappedsuperclass/AuditedEmbeddableWithNoDeclaredData.java +++ b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/components/mappedsuperclass/AuditedEmbeddableWithNoDeclaredData.java @@ -17,11 +17,11 @@ import org.hibernate.envers.Audited; @Audited public class AuditedEmbeddableWithNoDeclaredData extends AbstractAuditedEmbeddable { - public AuditedEmbeddableWithNoDeclaredData(int code) { - super( code ); - } + public AuditedEmbeddableWithNoDeclaredData(int code) { + super( code ); + } - // Needed for @Embeddable - protected AuditedEmbeddableWithNoDeclaredData() { - } + // Needed for @Embeddable + protected AuditedEmbeddableWithNoDeclaredData() { + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/components/mappedsuperclass/AuditedEmbeddableWithNoDeclaredDataTest.java b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/components/mappedsuperclass/AuditedEmbeddableWithNoDeclaredDataTest.java index 670d77a3cc..776bed87a8 100644 --- a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/components/mappedsuperclass/AuditedEmbeddableWithNoDeclaredDataTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/components/mappedsuperclass/AuditedEmbeddableWithNoDeclaredDataTest.java @@ -25,53 +25,53 @@ import static org.assertj.core.api.Assertions.assertThat; @JiraKey("HHH-17189") public class AuditedEmbeddableWithNoDeclaredDataTest extends BaseEnversJPAFunctionalTestCase { - private long id; + private long id; - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - EntityWithAuditedEmbeddableWithNoDeclaredData.class, - AbstractAuditedEmbeddable.class, - AuditedEmbeddableWithDeclaredData.class, - AuditedEmbeddableWithNoDeclaredData.class, - }; - } + @Override + protected Class[] getAnnotatedClasses() { + return new Class[] { + EntityWithAuditedEmbeddableWithNoDeclaredData.class, + AbstractAuditedEmbeddable.class, + AuditedEmbeddableWithDeclaredData.class, + AuditedEmbeddableWithNoDeclaredData.class, + }; + } - @Test - @Priority(10) - public void initData() { - this.id = TransactionUtil.doInJPA( this::entityManagerFactory, entityManager -> { - final EntityWithAuditedEmbeddableWithNoDeclaredData entity = new EntityWithAuditedEmbeddableWithNoDeclaredData(); - entity.setName( "Entity 1" ); - entity.setValue( new AuditedEmbeddableWithNoDeclaredData( 42 ) ); + @Test + @Priority(10) + public void initData() { + this.id = TransactionUtil.doInJPA( this::entityManagerFactory, entityManager -> { + final EntityWithAuditedEmbeddableWithNoDeclaredData entity = new EntityWithAuditedEmbeddableWithNoDeclaredData(); + entity.setName( "Entity 1" ); + entity.setValue( new AuditedEmbeddableWithNoDeclaredData( 42 ) ); - entityManager.persist(entity); - return entity.getId(); - } ); - } + entityManager.persist(entity); + return entity.getId(); + } ); + } - @Test - public void testEmbeddableThatExtendsAuditedMappedSuperclass() { - TransactionUtil.doInJPA( this::entityManagerFactory, entityManager -> { - final EntityWithAuditedEmbeddableWithNoDeclaredData entity = entityManager.find( - EntityWithAuditedEmbeddableWithNoDeclaredData.class, - id - ); + @Test + public void testEmbeddableThatExtendsAuditedMappedSuperclass() { + TransactionUtil.doInJPA( this::entityManagerFactory, entityManager -> { + final EntityWithAuditedEmbeddableWithNoDeclaredData entity = entityManager.find( + EntityWithAuditedEmbeddableWithNoDeclaredData.class, + id + ); - final AuditReader auditReader = AuditReaderFactory.get( entityManager ); + final AuditReader auditReader = AuditReaderFactory.get( entityManager ); - final List revisions = auditReader.getRevisions( EntityWithAuditedEmbeddableWithNoDeclaredData.class, id ); - assertThat( revisions ).hasSize( 1 ); + final List revisions = auditReader.getRevisions( EntityWithAuditedEmbeddableWithNoDeclaredData.class, id ); + assertThat( revisions ).hasSize( 1 ); - final EntityWithAuditedEmbeddableWithNoDeclaredData entityRevision1 = auditReader.find( - EntityWithAuditedEmbeddableWithNoDeclaredData.class, - id, - revisions.get( 0 ) - ); - assertThat( entityRevision1.getName() ).isEqualTo( entity.getName() ); + final EntityWithAuditedEmbeddableWithNoDeclaredData entityRevision1 = auditReader.find( + EntityWithAuditedEmbeddableWithNoDeclaredData.class, + id, + revisions.get( 0 ) + ); + assertThat( entityRevision1.getName() ).isEqualTo( entity.getName() ); - // All fields should be audited because the mapped superclass is annotated - assertThat( entityRevision1.getValue().getCode() ).isEqualTo( 42 ); - } ); - } + // All fields should be audited because the mapped superclass is annotated + assertThat( entityRevision1.getValue().getCode() ).isEqualTo( 42 ); + } ); + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/components/mappedsuperclass/EntityWithAuditedEmbeddableWithDeclaredData.java b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/components/mappedsuperclass/EntityWithAuditedEmbeddableWithDeclaredData.java index 63eaa14c20..a801f6f6f4 100644 --- a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/components/mappedsuperclass/EntityWithAuditedEmbeddableWithDeclaredData.java +++ b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/components/mappedsuperclass/EntityWithAuditedEmbeddableWithDeclaredData.java @@ -26,63 +26,63 @@ import org.hibernate.envers.Audited; @Audited public class EntityWithAuditedEmbeddableWithDeclaredData { - @Id - @GeneratedValue - private long id; + @Id + @GeneratedValue + private long id; - @Column(name = "NAME", length = 100) - private String name; + @Column(name = "NAME", length = 100) + private String name; - @Embedded - private AuditedEmbeddableWithDeclaredData value; + @Embedded + private AuditedEmbeddableWithDeclaredData value; - public long getId() { - return id; - } + public long getId() { + return id; + } - public void setId(long id) { - this.id = id; - } + public void setId(long id) { + this.id = id; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - public AuditedEmbeddableWithDeclaredData getValue() { - return value; - } + public AuditedEmbeddableWithDeclaredData getValue() { + return value; + } - public void setValue(AuditedEmbeddableWithDeclaredData value) { - this.value = value; - } + public void setValue(AuditedEmbeddableWithDeclaredData value) { + this.value = value; + } - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + (int) ( id ^ ( id >>> 32 ) ); - return result; - } + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + (int) ( id ^ ( id >>> 32 ) ); + return result; + } - @Override - public boolean equals(Object obj) { - if ( this == obj ) { - return true; - } - if ( obj == null ) { - return false; - } - if ( getClass() != obj.getClass() ) { - return false; - } - EntityWithAuditedEmbeddableWithDeclaredData other = (EntityWithAuditedEmbeddableWithDeclaredData) obj; - if ( id != other.id ) { - return false; - } - return true; - } + @Override + public boolean equals(Object obj) { + if ( this == obj ) { + return true; + } + if ( obj == null ) { + return false; + } + if ( getClass() != obj.getClass() ) { + return false; + } + EntityWithAuditedEmbeddableWithDeclaredData other = (EntityWithAuditedEmbeddableWithDeclaredData) obj; + if ( id != other.id ) { + return false; + } + return true; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/components/mappedsuperclass/EntityWithAuditedEmbeddableWithNoDeclaredData.java b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/components/mappedsuperclass/EntityWithAuditedEmbeddableWithNoDeclaredData.java index a5b7624344..63adf0d6aa 100644 --- a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/components/mappedsuperclass/EntityWithAuditedEmbeddableWithNoDeclaredData.java +++ b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/components/mappedsuperclass/EntityWithAuditedEmbeddableWithNoDeclaredData.java @@ -26,63 +26,63 @@ import org.hibernate.envers.Audited; @Audited public class EntityWithAuditedEmbeddableWithNoDeclaredData { - @Id - @GeneratedValue - private long id; + @Id + @GeneratedValue + private long id; - @Column(name = "NAME", length = 100) - private String name; + @Column(name = "NAME", length = 100) + private String name; - @Embedded - private AuditedEmbeddableWithNoDeclaredData value; + @Embedded + private AuditedEmbeddableWithNoDeclaredData value; - public long getId() { - return id; - } + public long getId() { + return id; + } - public void setId(long id) { - this.id = id; - } + public void setId(long id) { + this.id = id; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - public AuditedEmbeddableWithNoDeclaredData getValue() { - return value; - } + public AuditedEmbeddableWithNoDeclaredData getValue() { + return value; + } - public void setValue(AuditedEmbeddableWithNoDeclaredData value) { - this.value = value; - } + public void setValue(AuditedEmbeddableWithNoDeclaredData value) { + this.value = value; + } - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + (int) ( id ^ ( id >>> 32 ) ); - return result; - } + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + (int) ( id ^ ( id >>> 32 ) ); + return result; + } - @Override - public boolean equals(Object obj) { - if ( this == obj ) { - return true; - } - if ( obj == null ) { - return false; - } - if ( getClass() != obj.getClass() ) { - return false; - } - EntityWithAuditedEmbeddableWithNoDeclaredData other = (EntityWithAuditedEmbeddableWithNoDeclaredData) obj; - if ( id != other.id ) { - return false; - } - return true; - } + @Override + public boolean equals(Object obj) { + if ( this == obj ) { + return true; + } + if ( obj == null ) { + return false; + } + if ( getClass() != obj.getClass() ) { + return false; + } + EntityWithAuditedEmbeddableWithNoDeclaredData other = (EntityWithAuditedEmbeddableWithNoDeclaredData) obj; + if ( id != other.id ) { + return false; + } + return true; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/entityNames/singleAssociatedAudited/SingleDomainObjectToMultipleTablesTest.java b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/entityNames/singleAssociatedAudited/SingleDomainObjectToMultipleTablesTest.java index 8f2c334eee..e52d5d9450 100644 --- a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/entityNames/singleAssociatedAudited/SingleDomainObjectToMultipleTablesTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/entityNames/singleAssociatedAudited/SingleDomainObjectToMultipleTablesTest.java @@ -61,11 +61,11 @@ public class SingleDomainObjectToMultipleTablesTest extends AbstractOneSessionTe Person ownerVer1 = getAuditReader().find( Person.class, "Personaje", ownerId, 1 ); Person driverVer1 = getAuditReader().find( Person.class, "Driveraje", driverId, 1 ); - /* Check ids. */ + /* Check ids. */ Assert.assertEquals( ownerVer1.getId(), carVer1.getOwner().getId() ); Assert.assertEquals( driverVer1.getId(), carVer1.getDriver().getId() ); - /* Check object properties. */ + /* Check object properties. */ Assert.assertEquals( "Lukasz", ownerVer1.getName() ); Assert.assertEquals( "Kinga", driverVer1.getName() ); Assert.assertEquals( 1, carVer1.getNumber() ); diff --git a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/ids/embeddedid/PurchaseOrder.java b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/ids/embeddedid/PurchaseOrder.java index 88e7dbf9e7..eba141b862 100644 --- a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/ids/embeddedid/PurchaseOrder.java +++ b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/ids/embeddedid/PurchaseOrder.java @@ -29,10 +29,10 @@ public class PurchaseOrder implements Serializable { @ManyToOne @JoinColumns({ - @JoinColumn(name = "model", referencedColumnName = "model", nullable = true), - @JoinColumn(name = "version", referencedColumnName = "version", nullable = true), - @JoinColumn(name = "producer", referencedColumnName = "producer", nullable = true) - }) + @JoinColumn(name = "model", referencedColumnName = "model", nullable = true), + @JoinColumn(name = "version", referencedColumnName = "version", nullable = true), + @JoinColumn(name = "producer", referencedColumnName = "producer", nullable = true) + }) private Item item; @Column(name = "NOTE") diff --git a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/ids/idclass/ReferenceIdentifierClassId.java b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/ids/idclass/ReferenceIdentifierClassId.java index 22a75bcc7d..1bca9f27a2 100644 --- a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/ids/idclass/ReferenceIdentifierClassId.java +++ b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/ids/idclass/ReferenceIdentifierClassId.java @@ -12,63 +12,63 @@ import java.io.Serializable; * Created by yinzara on 4/1/16. */ public class ReferenceIdentifierClassId implements Serializable { - private Integer iiie; - private String type; + private Integer iiie; + private String type; - public ReferenceIdentifierClassId() { - } + public ReferenceIdentifierClassId() { + } - public ReferenceIdentifierClassId(Integer iiie, String type) { - this.iiie = iiie; - this.type = type; - } + public ReferenceIdentifierClassId(Integer iiie, String type) { + this.iiie = iiie; + this.type = type; + } - @Override - public boolean equals(Object o) { - if ( this == o ) { - return true; - } - if ( !(o instanceof ReferenceIdentifierClassId) ) { - return false; - } + @Override + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof ReferenceIdentifierClassId) ) { + return false; + } - ReferenceIdentifierClassId that = (ReferenceIdentifierClassId) o; + ReferenceIdentifierClassId that = (ReferenceIdentifierClassId) o; - if ( iiie != null ? !iiie.equals( that.iiie) : that.iiie != null ) { - return false; - } - if ( type != null ? !type.equals( that.type ) : that.type != null ) { - return false; - } + if ( iiie != null ? !iiie.equals( that.iiie) : that.iiie != null ) { + return false; + } + if ( type != null ? !type.equals( that.type ) : that.type != null ) { + return false; + } - return true; - } + return true; + } - @Override - public int hashCode() { - int result = iiie != null ? iiie.hashCode() : 0; - result = 31 * result + (type != null ? type.hashCode() : 0); - return result; - } + @Override + public int hashCode() { + int result = iiie != null ? iiie.hashCode() : 0; + result = 31 * result + (type != null ? type.hashCode() : 0); + return result; + } - @Override - public String toString() { - return "ReferenceIdentifierClassId(iiie = " + iiie + ", type = " + type + ")"; - } + @Override + public String toString() { + return "ReferenceIdentifierClassId(iiie = " + iiie + ", type = " + type + ")"; + } - public Integer getIiie() { - return iiie; - } + public Integer getIiie() { + return iiie; + } - public void setIiie(Integer iiie) { - this.iiie = iiie; - } + public void setIiie(Integer iiie) { + this.iiie = iiie; + } - public String getType() { - return type; - } + public String getType() { + return type; + } - public void setType(String type) { - this.type = type; - } + public void setType(String type) { + this.type = type; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/inheritance/mixed/entities/AbstractCheckActivity.java b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/inheritance/mixed/entities/AbstractCheckActivity.java index 4289e07f42..2e15eb3fb5 100644 --- a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/inheritance/mixed/entities/AbstractCheckActivity.java +++ b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/inheritance/mixed/entities/AbstractCheckActivity.java @@ -32,9 +32,9 @@ public abstract class AbstractCheckActivity extends AbstractActivity { private Integer durationInMinutes; @ManyToOne(targetEntity = AbstractActivity.class, cascade = CascadeType.MERGE, fetch = FetchType.LAZY) @JoinColumns({ - @JoinColumn(table = "ACTIVITY_CHECK", referencedColumnName = "id"), - @JoinColumn(table = "ACTIVITY_CHECK", referencedColumnName = "id2") - }) + @JoinColumn(table = "ACTIVITY_CHECK", referencedColumnName = "id"), + @JoinColumn(table = "ACTIVITY_CHECK", referencedColumnName = "id2") + }) private Activity relatedActivity; public Integer getDurationInMinutes() { diff --git a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/manytoone/bidirectional/ManyToOneOwning.java b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/manytoone/bidirectional/ManyToOneOwning.java index 80ee85a753..022b8e8398 100644 --- a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/manytoone/bidirectional/ManyToOneOwning.java +++ b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/manytoone/bidirectional/ManyToOneOwning.java @@ -30,7 +30,7 @@ public class ManyToOneOwning implements Serializable { @ManyToOne @JoinTable(name = "many_to_one_join_table", joinColumns = @JoinColumn(name = "owning_id"), - inverseJoinColumns = @JoinColumn(name = "owned_id")) + inverseJoinColumns = @JoinColumn(name = "owned_id")) private OneToManyOwned references; public ManyToOneOwning() { diff --git a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/modifiedflags/AbstractModifiedFlagsOneSessionTest.java b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/modifiedflags/AbstractModifiedFlagsOneSessionTest.java index ccc779d6f1..32146e8246 100644 --- a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/modifiedflags/AbstractModifiedFlagsOneSessionTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/modifiedflags/AbstractModifiedFlagsOneSessionTest.java @@ -16,7 +16,7 @@ import org.hibernate.orm.test.envers.AbstractOneSessionTest; * @author Michal Skowronek (mskowr at o2 dot pl) */ public abstract class AbstractModifiedFlagsOneSessionTest extends - AbstractOneSessionTest { + AbstractOneSessionTest { @Override protected void addProperties(Configuration configuration) { diff --git a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/modifiedflags/entities/EnumEntity.java b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/modifiedflags/entities/EnumEntity.java index fccd5926ef..75dc41187b 100644 --- a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/modifiedflags/entities/EnumEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/modifiedflags/entities/EnumEntity.java @@ -20,36 +20,36 @@ import org.hibernate.envers.Audited; @Entity @Audited public class EnumEntity { - @Id - private Integer id; + @Id + private Integer id; - @Enumerated(EnumType.STRING) - @Column(name = "client_option") - @Audited(modifiedColumnName = "client_option_mod") - private EnumOption option; + @Enumerated(EnumType.STRING) + @Column(name = "client_option") + @Audited(modifiedColumnName = "client_option_mod") + private EnumOption option; - EnumEntity() { + EnumEntity() { - } + } - public EnumEntity(Integer id, EnumOption option) { - this.id = id; - this.option = option; - } + public EnumEntity(Integer id, EnumOption option) { + this.id = id; + this.option = option; + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public EnumOption getOption() { - return option; - } + public EnumOption getOption() { + return option; + } - public void setOption(EnumOption option) { - this.option = option; - } + public void setOption(EnumOption option) { + this.option = option; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/modifiedflags/entities/EnumOption.java b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/modifiedflags/entities/EnumOption.java index 0b64357e29..3cc55ae5f1 100644 --- a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/modifiedflags/entities/EnumOption.java +++ b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/modifiedflags/entities/EnumOption.java @@ -10,6 +10,6 @@ package org.hibernate.orm.test.envers.integration.modifiedflags.entities; * @author Chris Cranford */ public enum EnumOption { - A, - B, + A, + B, } diff --git a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/modifiedflags/naming/ClientOption.java b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/modifiedflags/naming/ClientOption.java index 2f8d4a14a7..4e86bdad91 100644 --- a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/modifiedflags/naming/ClientOption.java +++ b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/modifiedflags/naming/ClientOption.java @@ -10,6 +10,6 @@ package org.hibernate.orm.test.envers.integration.modifiedflags.naming; * @author Chris Cranford */ public enum ClientOption { - A, - B + A, + B } diff --git a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/multiplerelations/GroupMemberTest.java b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/multiplerelations/GroupMemberTest.java index fc20d26972..d1dcefbbca 100644 --- a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/multiplerelations/GroupMemberTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/multiplerelations/GroupMemberTest.java @@ -43,10 +43,10 @@ public class GroupMemberTest extends BaseEnversJPAFunctionalTestCase { private Integer uniqueGroupId; private Integer groupMemberId; - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { GroupMember.class, MultiGroup.class, UniqueGroup.class }; - } + @Override + protected Class[] getAnnotatedClasses() { + return new Class[] { GroupMember.class, MultiGroup.class, UniqueGroup.class }; + } @Test @Priority(10) diff --git a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/multiplerelations/Person.java b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/multiplerelations/Person.java index 170c298bb4..99384c8260 100644 --- a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/multiplerelations/Person.java +++ b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/multiplerelations/Person.java @@ -34,8 +34,8 @@ public class Person implements Serializable { @ManyToMany(cascade = {CascadeType.PERSIST}) @JoinTable(name = "PERSON_ADDRESS", - joinColumns = {@JoinColumn(name = "personId", nullable = false)}, - inverseJoinColumns = {@JoinColumn(name = "addressId", nullable = false)}) + joinColumns = {@JoinColumn(name = "personId", nullable = false)}, + inverseJoinColumns = {@JoinColumn(name = "addressId", nullable = false)}) private Set
addresses = new HashSet
(); @OneToMany(mappedBy = "landlord", cascade = {CascadeType.PERSIST}, orphanRemoval = true) diff --git a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/naming/DetachedNamingTestEntity.java b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/naming/DetachedNamingTestEntity.java index b4461b9fe5..9b54b05215 100644 --- a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/naming/DetachedNamingTestEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/naming/DetachedNamingTestEntity.java @@ -30,8 +30,8 @@ public class DetachedNamingTestEntity { @Audited @OneToMany @JoinTable(name = "UNI_NAMING_TEST", - joinColumns = @JoinColumn(name = "ID_1"), - inverseJoinColumns = @JoinColumn(name = "ID_2")) + joinColumns = @JoinColumn(name = "ID_1"), + inverseJoinColumns = @JoinColumn(name = "ID_2")) private Set collection; public DetachedNamingTestEntity() { diff --git a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/naming/VersionsJoinTableRangeComponent.java b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/naming/VersionsJoinTableRangeComponent.java index 847485f95b..9517ac3a45 100644 --- a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/naming/VersionsJoinTableRangeComponent.java +++ b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/naming/VersionsJoinTableRangeComponent.java @@ -35,7 +35,7 @@ public final class VersionsJoinTableRangeComponent range = new ArrayList(); // ********************** Accessor Methods ********************** // diff --git a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/naming/VersionsJoinTableRangeComponentTestEntity.java b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/naming/VersionsJoinTableRangeComponentTestEntity.java index 9ea10de1a8..66893ab0d8 100644 --- a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/naming/VersionsJoinTableRangeComponentTestEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/naming/VersionsJoinTableRangeComponentTestEntity.java @@ -41,16 +41,16 @@ public class VersionsJoinTableRangeComponentTestEntity { */ @Embedded @AssociationOverride(name = "range", - joinColumns = { - @JoinColumn(name = "VJTRCTE1_ID", - insertable = true, - updatable = false, - nullable = false) - }) + joinColumns = { + @JoinColumn(name = "VJTRCTE1_ID", + insertable = true, + updatable = false, + nullable = false) + }) @org.hibernate.envers.Audited @AuditOverride(name = "range", - auditJoinTable = @org.hibernate.envers.AuditJoinTable(name = "JOIN_TABLE_COMPONENT_1_AUD", - inverseJoinColumns = @JoinColumn(name = "VJTRTE_ID"))) + auditJoinTable = @org.hibernate.envers.AuditJoinTable(name = "JOIN_TABLE_COMPONENT_1_AUD", + inverseJoinColumns = @JoinColumn(name = "VJTRTE_ID"))) private VersionsJoinTableRangeComponent component1 = new VersionsJoinTableRangeComponent(); /** @@ -59,17 +59,17 @@ public class VersionsJoinTableRangeComponentTestEntity { */ @Embedded @AssociationOverride(name = "range", - joinColumns = { - @JoinColumn(name = "VJTRCTE2_ID", - insertable = true, - updatable = false, - nullable = false) - }) + joinColumns = { + @JoinColumn(name = "VJTRCTE2_ID", + insertable = true, + updatable = false, + nullable = false) + }) @org.hibernate.envers.Audited @AuditOverrides(value = { @AuditOverride(name = "range", - auditJoinTable = @org.hibernate.envers.AuditJoinTable(name = "JOIN_TABLE_COMPONENT_2_AUD", - inverseJoinColumns = @JoinColumn(name = "VJTRTAE_ID"))) + auditJoinTable = @org.hibernate.envers.AuditJoinTable(name = "JOIN_TABLE_COMPONENT_2_AUD", + inverseJoinColumns = @JoinColumn(name = "VJTRTAE_ID"))) }) private VersionsJoinTableRangeComponent component2 = new VersionsJoinTableRangeComponent(); diff --git a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/naming/VersionsJoinTableRangeTestAlternateEntity.java b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/naming/VersionsJoinTableRangeTestAlternateEntity.java index be7f8f99ad..1e6fdcc868 100644 --- a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/naming/VersionsJoinTableRangeTestAlternateEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/naming/VersionsJoinTableRangeTestAlternateEntity.java @@ -20,7 +20,7 @@ import jakarta.persistence.Table; @Table(name = "RANGE_TEST_ALTERNATE_ENT") @org.hibernate.envers.Audited public class VersionsJoinTableRangeTestAlternateEntity extends - VersionsJoinTableRangeTestEntitySuperClass { + VersionsJoinTableRangeTestEntitySuperClass { private String alternateValue; diff --git a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/naming/VersionsJoinTableRangeTestEntity.java b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/naming/VersionsJoinTableRangeTestEntity.java index 110236d68f..a5e751375d 100644 --- a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/naming/VersionsJoinTableRangeTestEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/naming/VersionsJoinTableRangeTestEntity.java @@ -21,7 +21,7 @@ import jakarta.persistence.Table; @Table(name = "RANGE_TEST_ENTITY") @org.hibernate.envers.Audited public class VersionsJoinTableRangeTestEntity extends - VersionsJoinTableRangeTestEntitySuperClass { + VersionsJoinTableRangeTestEntitySuperClass { @Column(name = "val") private String value; diff --git a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/naming/ids/JoinEmbIdNamingRefIngEntity.java b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/naming/ids/JoinEmbIdNamingRefIngEntity.java index db7365535a..670245d4ce 100644 --- a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/naming/ids/JoinEmbIdNamingRefIngEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/naming/ids/JoinEmbIdNamingRefIngEntity.java @@ -32,9 +32,9 @@ public class JoinEmbIdNamingRefIngEntity { @Audited @ManyToOne @JoinColumns({ - @JoinColumn(name = "XX_reference", referencedColumnName = "XX"), - @JoinColumn(name = "YY_reference", referencedColumnName = "YY") - }) + @JoinColumn(name = "XX_reference", referencedColumnName = "XX"), + @JoinColumn(name = "YY_reference", referencedColumnName = "YY") + }) private JoinEmbIdNamingRefEdEntity reference; public JoinEmbIdNamingRefIngEntity() { diff --git a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/naming/ids/JoinMulIdNamingRefIngEntity.java b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/naming/ids/JoinMulIdNamingRefIngEntity.java index a14b500645..1f0adf2731 100644 --- a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/naming/ids/JoinMulIdNamingRefIngEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/naming/ids/JoinMulIdNamingRefIngEntity.java @@ -37,9 +37,9 @@ public class JoinMulIdNamingRefIngEntity { @Audited @ManyToOne @JoinColumns({ - @JoinColumn(name = "ID2_reference", referencedColumnName = "ID_2"), - @JoinColumn(name = "ID1_reference", referencedColumnName = "ID_1") - }) + @JoinColumn(name = "ID2_reference", referencedColumnName = "ID_2"), + @JoinColumn(name = "ID1_reference", referencedColumnName = "ID_1") + }) private JoinMulIdNamingRefEdEntity reference; public JoinMulIdNamingRefIngEntity() { diff --git a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/onetomany/hierarchy/Node.java b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/onetomany/hierarchy/Node.java index 102e0715d1..cc84b4771c 100644 --- a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/onetomany/hierarchy/Node.java +++ b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/onetomany/hierarchy/Node.java @@ -39,8 +39,8 @@ public class Node implements Serializable { @AuditJoinTable(name = "NODES_JOIN_TABLE_AUD", inverseJoinColumns = {@JoinColumn(name = "PARENT_ID", nullable = true, updatable = false)}) @JoinTable(name = "NODES_JOIN_TABLE", - joinColumns = {@JoinColumn(name = "CHILD_ID", nullable = true, updatable = false)}, - inverseJoinColumns = {@JoinColumn(name = "PARENT_ID", nullable = true, updatable = false)}) + joinColumns = {@JoinColumn(name = "CHILD_ID", nullable = true, updatable = false)}, + inverseJoinColumns = {@JoinColumn(name = "PARENT_ID", nullable = true, updatable = false)}) private Node parent; @OneToMany(mappedBy = "parent") diff --git a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/onetoone/bidirectional/primarykeyjoincolumn/Account.java b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/onetoone/bidirectional/primarykeyjoincolumn/Account.java index 7df1777196..168aca24d1 100644 --- a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/onetoone/bidirectional/primarykeyjoincolumn/Account.java +++ b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/onetoone/bidirectional/primarykeyjoincolumn/Account.java @@ -28,7 +28,7 @@ public class Account implements Serializable { @Column(name = "ACCOUNT_ID") @GeneratedValue(generator = "AccountForeignKeyGenerator") @GenericGenerator(name = "AccountForeignKeyGenerator", strategy = "foreign", - parameters = {@Parameter(name = "property", value = "owner")}) + parameters = {@Parameter(name = "property", value = "owner")}) private Long accountId; private String type; diff --git a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/onetoone/bidirectional/primarykeyjoincolumn/NotAuditedNoProxyPerson.java b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/onetoone/bidirectional/primarykeyjoincolumn/NotAuditedNoProxyPerson.java index 0c01ee5906..9e999203c6 100644 --- a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/onetoone/bidirectional/primarykeyjoincolumn/NotAuditedNoProxyPerson.java +++ b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/onetoone/bidirectional/primarykeyjoincolumn/NotAuditedNoProxyPerson.java @@ -27,7 +27,7 @@ public class NotAuditedNoProxyPerson implements Serializable { @Column(name = "PERSON_ID") @GeneratedValue(generator = "NotAuditedNoProxyKeyGenerator") @GenericGenerator(name = "NotAuditedNoProxyKeyGenerator", strategy = "foreign", - parameters = {@Parameter(name = "property", value = "account")}) + parameters = {@Parameter(name = "property", value = "account")}) private Long personId; private String name; diff --git a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/onetoone/bidirectional/primarykeyjoincolumn/NotAuditedPerson.java b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/onetoone/bidirectional/primarykeyjoincolumn/NotAuditedPerson.java index d1bb7727cc..593c7040ca 100644 --- a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/onetoone/bidirectional/primarykeyjoincolumn/NotAuditedPerson.java +++ b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/onetoone/bidirectional/primarykeyjoincolumn/NotAuditedPerson.java @@ -28,7 +28,7 @@ public class NotAuditedPerson implements Serializable { @Column(name = "PERSON_ID") @GeneratedValue(generator = "NotAuditedProxyKeyGenerator") @GenericGenerator(name = "NotAuditedProxyKeyGenerator", strategy = "foreign", - parameters = {@Parameter(name = "property", value = "account")}) + parameters = {@Parameter(name = "property", value = "account")}) private Long personId; private String name; diff --git a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/query/AssociationRevisionsOfEntitiesQueryStoreAtDeletionTest.java b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/query/AssociationRevisionsOfEntitiesQueryStoreAtDeletionTest.java index b915b3d4ab..f5a0f95f2a 100644 --- a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/query/AssociationRevisionsOfEntitiesQueryStoreAtDeletionTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/query/AssociationRevisionsOfEntitiesQueryStoreAtDeletionTest.java @@ -17,9 +17,9 @@ import org.hibernate.testing.orm.junit.JiraKey; */ @JiraKey( value = "HHH-13817" ) public class AssociationRevisionsOfEntitiesQueryStoreAtDeletionTest extends AssociationRevisionsOfEntitiesQueryTest { - @Override - protected void addSettings(Map settings) { - super.addSettings( settings ); - settings.put( EnversSettings.STORE_DATA_AT_DELETE, true ); - } + @Override + protected void addSettings(Map settings) { + super.addSettings( settings ); + settings.put( EnversSettings.STORE_DATA_AT_DELETE, true ); + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/query/AssociationRevisionsOfEntitiesQueryTest.java b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/query/AssociationRevisionsOfEntitiesQueryTest.java index acce02bf46..65fe577108 100644 --- a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/query/AssociationRevisionsOfEntitiesQueryTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/query/AssociationRevisionsOfEntitiesQueryTest.java @@ -31,162 +31,162 @@ import org.hibernate.testing.orm.junit.JiraKey; */ @JiraKey( "HHH-13817" ) public class AssociationRevisionsOfEntitiesQueryTest extends BaseEnversFunctionalTestCase { - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { Template.class, TemplateType.class }; - } + @Override + protected Class[] getAnnotatedClasses() { + return new Class[] { Template.class, TemplateType.class }; + } - @Test - @Priority(10) - public void initData() { - doInHibernate( this::sessionFactory, session -> { - final TemplateType type1 = new TemplateType( 1, "Type1" ); - final TemplateType type2 = new TemplateType( 2, "Type2" ); - session.persist( type1 ); - session.persist( type2 ); + @Test + @Priority(10) + public void initData() { + doInHibernate( this::sessionFactory, session -> { + final TemplateType type1 = new TemplateType( 1, "Type1" ); + final TemplateType type2 = new TemplateType( 2, "Type2" ); + session.persist( type1 ); + session.persist( type2 ); - final Template template = new Template( 1, "Template1", type1 ); - session.persist( template ); - } ); + final Template template = new Template( 1, "Template1", type1 ); + session.persist( template ); + } ); - doInHibernate( this::sessionFactory, session -> { - final TemplateType type = session.find( TemplateType.class, 2 ); - final Template template = session.find( Template.class, 1 ); - template.setName( "Template1-Updated" ); - template.setTemplateType( type ); - session.merge( template ); - } ); + doInHibernate( this::sessionFactory, session -> { + final TemplateType type = session.find( TemplateType.class, 2 ); + final Template template = session.find( Template.class, 1 ); + template.setName( "Template1-Updated" ); + template.setTemplateType( type ); + session.merge( template ); + } ); - doInHibernate( this::sessionFactory, session -> { - final Template template = session.find( Template.class, 1 ); - session.remove( template ); - } ); - } + doInHibernate( this::sessionFactory, session -> { + final Template template = session.find( Template.class, 1 ); + session.remove( template ); + } ); + } - @Test - public void testRevisionsOfEntityWithAssociationQueries() { - doInHibernate( this::sessionFactory, session -> { - List results = getAuditReader().createQuery() - .forRevisionsOfEntity( Template.class, true, true ) - .add( AuditEntity.id().eq( 1 ) ) - .traverseRelation( "templateType", JoinType.INNER ) - .add( AuditEntity.property( "name" ).eq( "Type1" ) ) - .up() - .getResultList(); - assertEquals( 1, results.size() ); - assertEquals( "Template1", ( (Template) results.get( 0 ) ).getName() ); - } ); + @Test + public void testRevisionsOfEntityWithAssociationQueries() { + doInHibernate( this::sessionFactory, session -> { + List results = getAuditReader().createQuery() + .forRevisionsOfEntity( Template.class, true, true ) + .add( AuditEntity.id().eq( 1 ) ) + .traverseRelation( "templateType", JoinType.INNER ) + .add( AuditEntity.property( "name" ).eq( "Type1" ) ) + .up() + .getResultList(); + assertEquals( 1, results.size() ); + assertEquals( "Template1", ( (Template) results.get( 0 ) ).getName() ); + } ); - doInHibernate( this::sessionFactory, session -> { - List results = getAuditReader().createQuery() - .forRevisionsOfEntity( Template.class, true, true ) - .add( AuditEntity.id().eq( 1 ) ) - .traverseRelation( "templateType", JoinType.INNER ) - .add( AuditEntity.property("name" ).eq("Type2" ) ) - .up() - .getResultList(); + doInHibernate( this::sessionFactory, session -> { + List results = getAuditReader().createQuery() + .forRevisionsOfEntity( Template.class, true, true ) + .add( AuditEntity.id().eq( 1 ) ) + .traverseRelation( "templateType", JoinType.INNER ) + .add( AuditEntity.property("name" ).eq("Type2" ) ) + .up() + .getResultList(); - assertEquals( getConfiguration().isStoreDataAtDelete() ? 2 : 1, results.size() ); - for ( Object result : results ) { - assertEquals( "Template1-Updated", ( (Template) result ).getName() ); - } - } ); - } + assertEquals( getConfiguration().isStoreDataAtDelete() ? 2 : 1, results.size() ); + for ( Object result : results ) { + assertEquals( "Template1-Updated", ( (Template) result ).getName() ); + } + } ); + } - @Test - public void testAssociationQueriesNotAllowedWhenNotSelectingJustEntities() { - try { - doInHibernate( this::sessionFactory, session -> { - getAuditReader().createQuery() - .forRevisionsOfEntity( Template.class, false, true ) - .add( AuditEntity.id().eq( 1 ) ) - .traverseRelation("templateType", JoinType.INNER ) - .add( AuditEntity.property( "name" ).eq( "Type1" ) ) - .up() - .getResultList(); - } ); + @Test + public void testAssociationQueriesNotAllowedWhenNotSelectingJustEntities() { + try { + doInHibernate( this::sessionFactory, session -> { + getAuditReader().createQuery() + .forRevisionsOfEntity( Template.class, false, true ) + .add( AuditEntity.id().eq( 1 ) ) + .traverseRelation("templateType", JoinType.INNER ) + .add( AuditEntity.property( "name" ).eq( "Type1" ) ) + .up() + .getResultList(); + } ); - fail( "Test should have thrown IllegalStateException due to selectEntitiesOnly=false" ); - } - catch ( Exception e ) { - assertTyping( IllegalStateException.class, e ); - } - } + fail( "Test should have thrown IllegalStateException due to selectEntitiesOnly=false" ); + } + catch ( Exception e ) { + assertTyping( IllegalStateException.class, e ); + } + } - @Entity(name = "TemplateType") - @Audited - public static class TemplateType { - @Id - private Integer id; - private String name; + @Entity(name = "TemplateType") + @Audited + public static class TemplateType { + @Id + private Integer id; + private String name; - TemplateType() { - this( null, null ); - } + TemplateType() { + this( null, null ); + } - TemplateType(Integer id, String name) { - this.id = id; - this.name = name; - } + TemplateType(Integer id, String name) { + this.id = id; + this.name = name; + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } - } + public void setName(String name) { + this.name = name; + } + } - @Entity(name = "Template") - @Audited - public static class Template { - @Id - private Integer id; - private String name; - @ManyToOne - private TemplateType templateType; + @Entity(name = "Template") + @Audited + public static class Template { + @Id + private Integer id; + private String name; + @ManyToOne + private TemplateType templateType; - Template() { - this( null, null, null ); - } + Template() { + this( null, null, null ); + } - Template(Integer id, String name, TemplateType type) { - this.id = id; - this.name = name; - this.templateType = type; - } + Template(Integer id, String name, TemplateType type) { + this.id = id; + this.name = name; + this.templateType = type; + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - public TemplateType getTemplateType() { - return templateType; - } + public TemplateType getTemplateType() { + return templateType; + } - public void setTemplateType(TemplateType templateType) { - this.templateType = templateType; - } - } + public void setTemplateType(TemplateType templateType) { + this.templateType = templateType; + } + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/query/NullPrecedenceTest.java b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/query/NullPrecedenceTest.java index aa701fbbf5..3dde77d62f 100644 --- a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/query/NullPrecedenceTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/query/NullPrecedenceTest.java @@ -29,50 +29,50 @@ import org.hibernate.testing.transaction.TransactionUtil; @JiraKey( value = "HHH-14981" ) public class NullPrecedenceTest extends BaseEnversJPAFunctionalTestCase { - Integer id1; - Integer id2; + Integer id1; + Integer id2; - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { StrIntTestEntity.class }; - } + @Override + protected Class[] getAnnotatedClasses() { + return new Class[] { StrIntTestEntity.class }; + } - @Test - @Priority(10) - public void initData() { - // Revision 1 - id1 = TransactionUtil.doInJPA(this::entityManagerFactory, entityManager -> { - StrIntTestEntity entity1 = new StrIntTestEntity( null, 1 ); - entityManager.persist( entity1 ); - return entity1.getId(); - } ); - // Revision 2 - id2 = TransactionUtil.doInJPA( this::entityManagerFactory, entityManager -> { - StrIntTestEntity entity2 = new StrIntTestEntity( "two", 2 ); - entityManager.persist( entity2 ); - return entity2.getId(); - } ); - } + @Test + @Priority(10) + public void initData() { + // Revision 1 + id1 = TransactionUtil.doInJPA(this::entityManagerFactory, entityManager -> { + StrIntTestEntity entity1 = new StrIntTestEntity( null, 1 ); + entityManager.persist( entity1 ); + return entity1.getId(); + } ); + // Revision 2 + id2 = TransactionUtil.doInJPA( this::entityManagerFactory, entityManager -> { + StrIntTestEntity entity2 = new StrIntTestEntity( "two", 2 ); + entityManager.persist( entity2 ); + return entity2.getId(); + } ); + } - @Test - public void testNullPrecedenceFirst() { - List results = getAuditReader().createQuery().forRevisionsOfEntity( StrIntTestEntity.class, true, false ) - .addProjection( AuditEntity.property( "number" ) ) - .addOrder( AuditEntity.property( "str1" ).asc().nulls( NullPrecedence.FIRST ) ) - .getResultList(); - List expected = new ArrayList<>(); - expected.addAll( Arrays.asList( 1, 2 ) ); - Assert.assertEquals( expected, results ); - } + @Test + public void testNullPrecedenceFirst() { + List results = getAuditReader().createQuery().forRevisionsOfEntity( StrIntTestEntity.class, true, false ) + .addProjection( AuditEntity.property( "number" ) ) + .addOrder( AuditEntity.property( "str1" ).asc().nulls( NullPrecedence.FIRST ) ) + .getResultList(); + List expected = new ArrayList<>(); + expected.addAll( Arrays.asList( 1, 2 ) ); + Assert.assertEquals( expected, results ); + } - @Test - public void testNullPrecedenceLast() { - List results = getAuditReader().createQuery().forRevisionsOfEntity( StrIntTestEntity.class, true, false ) - .addProjection( AuditEntity.property( "number" ) ) - .addOrder( AuditEntity.property( "str1" ).asc().nulls( NullPrecedence.LAST ) ) - .getResultList(); - List expected = new ArrayList<>(); - expected.addAll( Arrays.asList( 2, 1 ) ); - Assert.assertEquals( expected, results ); - } + @Test + public void testNullPrecedenceLast() { + List results = getAuditReader().createQuery().forRevisionsOfEntity( StrIntTestEntity.class, true, false ) + .addProjection( AuditEntity.property( "number" ) ) + .addOrder( AuditEntity.property( "str1" ).asc().nulls( NullPrecedence.LAST ) ) + .getResultList(); + List expected = new ArrayList<>(); + expected.addAll( Arrays.asList( 2, 1 ) ); + Assert.assertEquals( expected, results ); + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/reventity/CustomBoxedRevEntity.java b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/reventity/CustomBoxedRevEntity.java index a164d683ee..30785a86a8 100644 --- a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/reventity/CustomBoxedRevEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/reventity/CustomBoxedRevEntity.java @@ -21,13 +21,13 @@ import org.hibernate.envers.RevisionTimestamp; */ @Entity @GenericGenerator(name = "EnversTestingRevisionGenerator", - strategy = "org.hibernate.id.enhanced.TableGenerator", - parameters = { - @Parameter(name = "table_name", value = "REVISION_GENERATOR"), - @Parameter(name = "initial_value", value = "1"), - @Parameter(name = "increment_size", value = "1"), - @Parameter(name = "prefer_entity_table_as_segment_value", value = "true") - } + strategy = "org.hibernate.id.enhanced.TableGenerator", + parameters = { + @Parameter(name = "table_name", value = "REVISION_GENERATOR"), + @Parameter(name = "initial_value", value = "1"), + @Parameter(name = "increment_size", value = "1"), + @Parameter(name = "prefer_entity_table_as_segment_value", value = "true") + } ) @RevisionEntity public class CustomBoxedRevEntity { diff --git a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/reventity/CustomInstantRevEntityTest.java b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/reventity/CustomInstantRevEntityTest.java index 568f4219c5..2881b817bb 100644 --- a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/reventity/CustomInstantRevEntityTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/reventity/CustomInstantRevEntityTest.java @@ -28,88 +28,88 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Chris Cranford */ public class CustomInstantRevEntityTest extends BaseEnversJPAFunctionalTestCase { - private Integer id; - private Instant instant1; - private Instant instant2; - private Instant instant3; + private Integer id; + private Instant instant1; + private Instant instant2; + private Instant instant3; - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] {StrTestEntity.class, CustomInstantRevEntity.class}; - } + @Override + protected Class[] getAnnotatedClasses() { + return new Class[] {StrTestEntity.class, CustomInstantRevEntity.class}; + } - @Test - @Priority(10) - public void initData() throws InterruptedException { - instant1 = getCurrentInstant(); + @Test + @Priority(10) + public void initData() throws InterruptedException { + instant1 = getCurrentInstant(); - // Revision 1 - EntityManager em = getEntityManager(); - em.getTransaction().begin(); - StrTestEntity entity = new StrTestEntity( "x" ); - em.persist( entity ); - id = entity.getId(); - em.getTransaction().commit(); + // Revision 1 + EntityManager em = getEntityManager(); + em.getTransaction().begin(); + StrTestEntity entity = new StrTestEntity( "x" ); + em.persist( entity ); + id = entity.getId(); + em.getTransaction().commit(); - instant2 = getCurrentInstant(); + instant2 = getCurrentInstant(); - // Revision 2 - em.getTransaction().begin(); - entity = em.find( StrTestEntity.class, id ); - entity.setStr( "y" ); - em.getTransaction().commit(); + // Revision 2 + em.getTransaction().begin(); + entity = em.find( StrTestEntity.class, id ); + entity.setStr( "y" ); + em.getTransaction().commit(); - instant3 = getCurrentInstant(); - } + instant3 = getCurrentInstant(); + } - @Test(expected = RevisionDoesNotExistException.class) - public void testInstant1() { - getAuditReader().getRevisionNumberForDate( new Date( instant1.toEpochMilli() ) ); - } + @Test(expected = RevisionDoesNotExistException.class) + public void testInstant1() { + getAuditReader().getRevisionNumberForDate( new Date( instant1.toEpochMilli() ) ); + } - @Test - @SkipForDialect(value = CockroachDialect.class, comment = "Fails because of int size") - public void testInstants() { - assertThat( getAuditReader().getRevisionNumberForDate( new Date( instant2.toEpochMilli() ) ).intValue() ).isEqualTo( 1 ); - assertThat( getAuditReader().getRevisionNumberForDate( new Date( instant3.toEpochMilli() ) ).intValue() ).isEqualTo( 2 ); + @Test + @SkipForDialect(value = CockroachDialect.class, comment = "Fails because of int size") + public void testInstants() { + assertThat( getAuditReader().getRevisionNumberForDate( new Date( instant2.toEpochMilli() ) ).intValue() ).isEqualTo( 1 ); + assertThat( getAuditReader().getRevisionNumberForDate( new Date( instant3.toEpochMilli() ) ).intValue() ).isEqualTo( 2 ); - assertThat( getAuditReader().getRevisionNumberForDate( instant2 ).intValue() ).isEqualTo( 1 ); - assertThat( getAuditReader().getRevisionNumberForDate( instant3 ).intValue() ).isEqualTo( 2 ); - } + assertThat( getAuditReader().getRevisionNumberForDate( instant2 ).intValue() ).isEqualTo( 1 ); + assertThat( getAuditReader().getRevisionNumberForDate( instant3 ).intValue() ).isEqualTo( 2 ); + } - @Test - public void testInstantsForRevisions() { - final AuditReader reader = getAuditReader(); - assertThat( reader.getRevisionNumberForDate( reader.getRevisionDate( 1 ) ).intValue() ).isEqualTo( 1 ); - assertThat( reader.getRevisionNumberForDate( reader.getRevisionDate( 2 ) ).intValue() ).isEqualTo( 2 ); - } + @Test + public void testInstantsForRevisions() { + final AuditReader reader = getAuditReader(); + assertThat( reader.getRevisionNumberForDate( reader.getRevisionDate( 1 ) ).intValue() ).isEqualTo( 1 ); + assertThat( reader.getRevisionNumberForDate( reader.getRevisionDate( 2 ) ).intValue() ).isEqualTo( 2 ); + } - @Test - public void testRevisionsForInstants() { - final Instant revInstant1 = getAuditReader().findRevision( CustomInstantRevEntity.class, 1 ).getInstantTimestamp(); - assertThat( revInstant1.toEpochMilli() ).isGreaterThan( instant1.toEpochMilli() ); - assertThat( revInstant1.toEpochMilli() ).isLessThanOrEqualTo( instant2.toEpochMilli() ); + @Test + public void testRevisionsForInstants() { + final Instant revInstant1 = getAuditReader().findRevision( CustomInstantRevEntity.class, 1 ).getInstantTimestamp(); + assertThat( revInstant1.toEpochMilli() ).isGreaterThan( instant1.toEpochMilli() ); + assertThat( revInstant1.toEpochMilli() ).isLessThanOrEqualTo( instant2.toEpochMilli() ); - final Instant revInstant2 = getAuditReader().findRevision( CustomInstantRevEntity.class, 2 ).getInstantTimestamp(); - assertThat( revInstant2.toEpochMilli() ).isGreaterThan( instant2.toEpochMilli() ); - assertThat( revInstant2.toEpochMilli() ).isLessThanOrEqualTo( instant3.toEpochMilli() ); - } + final Instant revInstant2 = getAuditReader().findRevision( CustomInstantRevEntity.class, 2 ).getInstantTimestamp(); + assertThat( revInstant2.toEpochMilli() ).isGreaterThan( instant2.toEpochMilli() ); + assertThat( revInstant2.toEpochMilli() ).isLessThanOrEqualTo( instant3.toEpochMilli() ); + } - @Test - public void testRevisionsCounts() { - assertThat( getAuditReader().getRevisions( StrTestEntity.class, id ) ).isEqualTo( Arrays.asList( 1, 2 ) ); - } + @Test + public void testRevisionsCounts() { + assertThat( getAuditReader().getRevisions( StrTestEntity.class, id ) ).isEqualTo( Arrays.asList( 1, 2 ) ); + } - @Test - public void testHistoryOfId1() { - assertThat( getAuditReader().find( StrTestEntity.class, id, 1 ) ).isEqualTo( new StrTestEntity( "x", id ) ); - assertThat( getAuditReader().find( StrTestEntity.class, id, 2 ) ).isEqualTo( new StrTestEntity( "y", id ) ); - } + @Test + public void testHistoryOfId1() { + assertThat( getAuditReader().find( StrTestEntity.class, id, 1 ) ).isEqualTo( new StrTestEntity( "x", id ) ); + assertThat( getAuditReader().find( StrTestEntity.class, id, 2 ) ).isEqualTo( new StrTestEntity( "y", id ) ); + } - private Instant getCurrentInstant() throws InterruptedException { - Instant now = Instant.now(); - // Some databases default to second-based precision, sleep - Thread.sleep( 1100 ); - return now; - } + private Instant getCurrentInstant() throws InterruptedException { + Instant now = Instant.now(); + // Some databases default to second-based precision, sleep + Thread.sleep( 1100 ); + return now; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/reventity/ExceptionListenerRevEntity.java b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/reventity/ExceptionListenerRevEntity.java index c68c8dfe23..621d2fa68c 100644 --- a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/reventity/ExceptionListenerRevEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/reventity/ExceptionListenerRevEntity.java @@ -21,13 +21,13 @@ import org.hibernate.envers.RevisionTimestamp; */ @Entity @GenericGenerator(name = "EnversTestingRevisionGenerator", - strategy = "org.hibernate.id.enhanced.TableGenerator", - parameters = { - @Parameter(name = "table_name", value = "REVISION_GENERATOR"), - @Parameter(name = "initial_value", value = "1"), - @Parameter(name = "increment_size", value = "1"), - @Parameter(name = "prefer_entity_table_as_segment_value", value = "true") - } + strategy = "org.hibernate.id.enhanced.TableGenerator", + parameters = { + @Parameter(name = "table_name", value = "REVISION_GENERATOR"), + @Parameter(name = "initial_value", value = "1"), + @Parameter(name = "increment_size", value = "1"), + @Parameter(name = "prefer_entity_table_as_segment_value", value = "true") + } ) @RevisionEntity(TestExceptionRevisionListener.class) public class ExceptionListenerRevEntity { diff --git a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/reventity/ListenerRevEntity.java b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/reventity/ListenerRevEntity.java index 9355999845..72b5463174 100644 --- a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/reventity/ListenerRevEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/reventity/ListenerRevEntity.java @@ -21,13 +21,13 @@ import org.hibernate.envers.RevisionTimestamp; */ @Entity @GenericGenerator(name = "EnversTestingRevisionGenerator", - strategy = "org.hibernate.id.enhanced.TableGenerator", - parameters = { - @Parameter(name = "table_name", value = "REVISION_GENERATOR"), - @Parameter(name = "initial_value", value = "1"), - @Parameter(name = "increment_size", value = "1"), - @Parameter(name = "prefer_entity_table_as_segment_value", value = "true") - } + strategy = "org.hibernate.id.enhanced.TableGenerator", + parameters = { + @Parameter(name = "table_name", value = "REVISION_GENERATOR"), + @Parameter(name = "initial_value", value = "1"), + @Parameter(name = "increment_size", value = "1"), + @Parameter(name = "prefer_entity_table_as_segment_value", value = "true") + } ) @RevisionEntity(TestRevisionListener.class) public class ListenerRevEntity { diff --git a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/reventity/LocalDateTimeTest.java b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/reventity/LocalDateTimeTest.java index 02ed94dae0..4ee15ff0f7 100644 --- a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/reventity/LocalDateTimeTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/reventity/LocalDateTimeTest.java @@ -33,61 +33,61 @@ import static org.junit.Assert.fail; */ @JiraKey( value = "HHH-10496" ) public class LocalDateTimeTest extends BaseEnversJPAFunctionalTestCase { - private Instant timestampStart; - private Instant timestampEnd; + private Instant timestampStart; + private Instant timestampEnd; - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - StrTestEntity.class, - CustomLocalDateTimeRevEntity.class - }; - } + @Override + protected Class[] getAnnotatedClasses() { + return new Class[] { + StrTestEntity.class, + CustomLocalDateTimeRevEntity.class + }; + } - @Test - @Priority(10) - public void initData() { - EntityManager em = getEntityManager(); - try { - timestampStart = Instant.now(); + @Test + @Priority(10) + public void initData() { + EntityManager em = getEntityManager(); + try { + timestampStart = Instant.now(); - // some DBMs truncate time to seconds. - Thread.sleep( 1100 ); + // some DBMs truncate time to seconds. + Thread.sleep( 1100 ); - StrTestEntity entity = new StrTestEntity( "x" ); + StrTestEntity entity = new StrTestEntity( "x" ); - // Revision 1 - em.getTransaction().begin(); - em.persist( entity ); - em.getTransaction().commit(); + // Revision 1 + em.getTransaction().begin(); + em.persist( entity ); + em.getTransaction().commit(); - timestampEnd = Instant.now().plus( 1L, ChronoUnit.SECONDS ); - } - catch( InterruptedException x ) { - fail( "Unexpected interrupted exception" ); - } - finally { - em.close(); - } - } + timestampEnd = Instant.now().plus( 1L, ChronoUnit.SECONDS ); + } + catch( InterruptedException x ) { + fail( "Unexpected interrupted exception" ); + } + finally { + em.close(); + } + } - @Test - public void testTimestampsUsingDate() { - // expect just one revision prior to this timestamp. - assertEquals( 1, getAuditReader().getRevisionNumberForDate( Date.from( timestampEnd ) ) ); - } + @Test + public void testTimestampsUsingDate() { + // expect just one revision prior to this timestamp. + assertEquals( 1, getAuditReader().getRevisionNumberForDate( Date.from( timestampEnd ) ) ); + } - @Test - public void testRevisionEntityLocalDateTime() { - // get revision - CustomLocalDateTimeRevEntity revInfo = getAuditReader().findRevision( CustomLocalDateTimeRevEntity.class, 1 ); - assertNotNull( revInfo ); - // verify started before revision timestamp - final LocalDateTime started = LocalDateTime.ofInstant( timestampStart, ZoneId.systemDefault() ); - assertTrue( started.isBefore( revInfo.getLocalDateTimestamp() ) ); - // verify ended after revision timestamp - final LocalDateTime ended = LocalDateTime.ofInstant( timestampEnd, ZoneId.systemDefault() ); - assertTrue( ended.isAfter( revInfo.getLocalDateTimestamp() ) ); - } + @Test + public void testRevisionEntityLocalDateTime() { + // get revision + CustomLocalDateTimeRevEntity revInfo = getAuditReader().findRevision( CustomLocalDateTimeRevEntity.class, 1 ); + assertNotNull( revInfo ); + // verify started before revision timestamp + final LocalDateTime started = LocalDateTime.ofInstant( timestampStart, ZoneId.systemDefault() ); + assertTrue( started.isBefore( revInfo.getLocalDateTimestamp() ) ); + // verify ended after revision timestamp + final LocalDateTime ended = LocalDateTime.ofInstant( timestampEnd, ZoneId.systemDefault() ); + assertTrue( ended.isAfter( revInfo.getLocalDateTimestamp() ) ); + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/reventity/LongRevNumberRevEntity.java b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/reventity/LongRevNumberRevEntity.java index 8d9523e926..72a6eacf0a 100644 --- a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/reventity/LongRevNumberRevEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/reventity/LongRevNumberRevEntity.java @@ -22,13 +22,13 @@ import org.hibernate.envers.RevisionTimestamp; */ @Entity @GenericGenerator(name = "EnversTestingRevisionGenerator", - strategy = "org.hibernate.id.enhanced.TableGenerator", - parameters = { - @Parameter(name = "table_name", value = "REVISION_GENERATOR"), - @Parameter(name = "initial_value", value = "1"), - @Parameter(name = "increment_size", value = "1"), - @Parameter(name = "prefer_entity_table_as_segment_value", value = "true") - } + strategy = "org.hibernate.id.enhanced.TableGenerator", + parameters = { + @Parameter(name = "table_name", value = "REVISION_GENERATOR"), + @Parameter(name = "initial_value", value = "1"), + @Parameter(name = "increment_size", value = "1"), + @Parameter(name = "prefer_entity_table_as_segment_value", value = "true") + } ) @RevisionEntity public class LongRevNumberRevEntity { diff --git a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/reventity/MonotonicRevisionNumberTest.java b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/reventity/MonotonicRevisionNumberTest.java index 4523b85aa5..a8b06905d7 100644 --- a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/reventity/MonotonicRevisionNumberTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/reventity/MonotonicRevisionNumberTest.java @@ -40,7 +40,7 @@ public class MonotonicRevisionNumberTest extends BaseEnversFunctionalTestCase { @Test public void testOracleSequenceOrder() { - EntityPersister persister = sessionFactory().getMappingMetamodel().getEntityDescriptor(SequenceIdRevisionEntity.class.getName()); + EntityPersister persister = sessionFactory().getMappingMetamodel().getEntityDescriptor(SequenceIdRevisionEntity.class.getName()); IdentifierGenerator generator = persister.getIdentifierGenerator(); Assert.assertTrue( OrderedSequenceGenerator.class.isInstance( generator ) ); diff --git a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/secondary/ids/EmbIdSecondary.java b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/secondary/ids/EmbIdSecondary.java index 10cc1ec02a..847fa8aa16 100644 --- a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/secondary/ids/EmbIdSecondary.java +++ b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/secondary/ids/EmbIdSecondary.java @@ -70,9 +70,9 @@ public class EmbIdSecondary extends BaseEnversJPAFunctionalTestCase { @Test public void testTableNames() { Assert.assertEquals( "sec_embid_versions", - metadata().getEntityBinding( - "org.hibernate.orm.test.envers.integration.secondary.ids.SecondaryEmbIdTestEntity_AUD" - ).getJoins().get( 0 ).getTable().getName() + metadata().getEntityBinding( + "org.hibernate.orm.test.envers.integration.secondary.ids.SecondaryEmbIdTestEntity_AUD" + ).getJoins().get( 0 ).getTable().getName() ); } } diff --git a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/strategy/AbstractRevisionEndTimestampTest.java b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/strategy/AbstractRevisionEndTimestampTest.java index dbc6054f68..4fd65bec27 100644 --- a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/strategy/AbstractRevisionEndTimestampTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/strategy/AbstractRevisionEndTimestampTest.java @@ -24,16 +24,16 @@ import org.hibernate.orm.test.envers.BaseEnversJPAFunctionalTestCase; */ public abstract class AbstractRevisionEndTimestampTest extends BaseEnversJPAFunctionalTestCase { - private static final String TIMESTAMP_FIELD = "REVEND_TSTMP"; + private static final String TIMESTAMP_FIELD = "REVEND_TSTMP"; - @Override - @SuppressWarnings("unchecked") - public void addConfigOptions(Map options) { - options.put( EnversSettings.AUDIT_TABLE_SUFFIX, "_AUD" ); - options.put( EnversSettings.AUDIT_STRATEGY_VALIDITY_REVEND_TIMESTAMP_FIELD_NAME, TIMESTAMP_FIELD ); - options.put( EnversSettings.AUDIT_STRATEGY_VALIDITY_STORE_REVEND_TIMESTAMP, "true" ); + @Override + @SuppressWarnings("unchecked") + public void addConfigOptions(Map options) { + options.put( EnversSettings.AUDIT_TABLE_SUFFIX, "_AUD" ); + options.put( EnversSettings.AUDIT_STRATEGY_VALIDITY_REVEND_TIMESTAMP_FIELD_NAME, TIMESTAMP_FIELD ); + options.put( EnversSettings.AUDIT_STRATEGY_VALIDITY_STORE_REVEND_TIMESTAMP, "true" ); options.put( EnversSettings.AUDIT_STRATEGY_VALIDITY_REVEND_TIMESTAMP_LEGACY_PLACEMENT, "false" ); - } + } @SuppressWarnings("unchecked") protected List> getRevisions(Class clazz, Integer id) { diff --git a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/strategy/AuditStraegySelectorTest.java b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/strategy/AuditStraegySelectorTest.java index 0f4084320c..a5d8c2cb37 100644 --- a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/strategy/AuditStraegySelectorTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/strategy/AuditStraegySelectorTest.java @@ -41,30 +41,30 @@ public class AuditStraegySelectorTest { @Test public void testAuditStrategySelectorDefaultSpecified() { - // test old implementations + // test old implementations testAuditStrategySelector( "default", DefaultAuditStrategy.class ); testAuditStrategySelector( DefaultAuditStrategy.class.getSimpleName(), DefaultAuditStrategy.class ); testAuditStrategySelector( DefaultAuditStrategy.class.getName(), DefaultAuditStrategy.class ); - // test new implementation - testAuditStrategySelector( - org.hibernate.envers.strategy.internal.DefaultAuditStrategy.class.getName(), - org.hibernate.envers.strategy.internal.DefaultAuditStrategy.class - ); + // test new implementation + testAuditStrategySelector( + org.hibernate.envers.strategy.internal.DefaultAuditStrategy.class.getName(), + org.hibernate.envers.strategy.internal.DefaultAuditStrategy.class + ); } @Test public void testAuditStrategySelectorValiditySpecified() { - // test old implementations + // test old implementations testAuditStrategySelector( "validity", ValidityAuditStrategy.class ); testAuditStrategySelector( ValidityAuditStrategy.class.getSimpleName(), ValidityAuditStrategy.class ); testAuditStrategySelector( ValidityAuditStrategy.class.getName(), ValidityAuditStrategy.class ); - // test new implementation - testAuditStrategySelector( - org.hibernate.envers.strategy.internal.ValidityAuditStrategy.class.getName(), - org.hibernate.envers.strategy.internal.ValidityAuditStrategy.class - ); + // test new implementation + testAuditStrategySelector( + org.hibernate.envers.strategy.internal.ValidityAuditStrategy.class.getName(), + org.hibernate.envers.strategy.internal.ValidityAuditStrategy.class + ); } private void testAuditStrategySelector(String propertyValue, Class expectedStrategyClass) { @@ -76,7 +76,7 @@ public class AuditStraegySelectorTest { final ServiceRegistry sr = ServiceRegistryBuilder.buildServiceRegistry( properties ); try { final MetadataImplementor metadata = (MetadataImplementor) new MetadataSources( sr ).buildMetadata(); - final Configuration configuration = sr.getService( EnversService.class ).getConfig(); + final Configuration configuration = sr.getService( EnversService.class ).getConfig(); assertTyping( expectedStrategyClass, configuration.getAuditStrategy() ); } finally { diff --git a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/strategy/RevisionEndNumericTypeTest.java b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/strategy/RevisionEndNumericTypeTest.java index da84ecb55d..5eda2112a8 100644 --- a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/strategy/RevisionEndNumericTypeTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/strategy/RevisionEndNumericTypeTest.java @@ -40,7 +40,7 @@ public class RevisionEndNumericTypeTest extends BaseEnversJPAFunctionalTestCase return new Class[] { StrTestEntity.class }; } - @Override + @Override protected void addConfigOptions(Map options) { super.addConfigOptions( options ); options.put( EnversSettings.AUDIT_STRATEGY_VALIDITY_STORE_REVEND_TIMESTAMP, "true" ); diff --git a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/strategy/RevisionEndTimestampTypeTest.java b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/strategy/RevisionEndTimestampTypeTest.java index 95e3b67ef8..356dfbd716 100644 --- a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/strategy/RevisionEndTimestampTypeTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/strategy/RevisionEndTimestampTypeTest.java @@ -35,23 +35,23 @@ import org.hibernate.testing.envers.RequiresAuditStrategy; @RequiresAuditStrategy( value = ValidityAuditStrategy.class, jiraKey = "HHH-6210" ) public class RevisionEndTimestampTypeTest extends BaseEnversJPAFunctionalTestCase { - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { StrTestEntity.class }; - } + @Override + protected Class[] getAnnotatedClasses() { + return new Class[] { StrTestEntity.class }; + } - @Override - protected void addConfigOptions(Map options) { - options.put( EnversSettings.AUDIT_STRATEGY_VALIDITY_STORE_REVEND_TIMESTAMP, "true" ); - } + @Override + protected void addConfigOptions(Map options) { + options.put( EnversSettings.AUDIT_STRATEGY_VALIDITY_STORE_REVEND_TIMESTAMP, "true" ); + } - @Test - public void testRevisionEndTimestampIsLongType() { - // get the entity and verify the revision end timestamp property exists - final PersistentClass clazz = metadata().getEntityBinding( StrTestEntity.class.getName() + "_AUD" ); + @Test + public void testRevisionEndTimestampIsLongType() { + // get the entity and verify the revision end timestamp property exists + final PersistentClass clazz = metadata().getEntityBinding( StrTestEntity.class.getName() + "_AUD" ); - final Property property = clazz.getProperty( "REVEND_TSTMP" ); - assertTyping( BasicType.class, property.getType() ); - assertEquals( Timestamp.class, ( (BasicType) property.getType() ).getJavaType() ); - } + final Property property = clazz.getProperty( "REVEND_TSTMP" ); + assertTyping( BasicType.class, property.getType() ); + assertEquals( Timestamp.class, ( (BasicType) property.getType() ).getJavaType() ); + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/superclass/auditoverride/EmbeddableTest.java b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/superclass/auditoverride/EmbeddableTest.java index 5414e1635c..c64199371d 100644 --- a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/superclass/auditoverride/EmbeddableTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/superclass/auditoverride/EmbeddableTest.java @@ -35,431 +35,431 @@ import static org.junit.Assert.assertTrue; * @author Chris Cranford */ public class EmbeddableTest extends BaseEnversJPAFunctionalTestCase { - private Integer simpleId; - private Integer simpleOverrideId; - private Integer simplePropertyId; - private Integer fullOverrideId; - private Integer notAuditedId; - private Integer overridedId; - private Integer auditedId; - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - AuditedEmbeddable.class, - AuditedEmbeddableOverrideEntity.class, - FullOverrideEmbeddable.class, - FullOverrideEmbeddableEntity.class, - NotAuditedEmbeddableEntity.class, - OverrideEmbeddable.class, - OverrideEmbeddableEntity.class, - SimpleAbstractMappedSuperclass.class, - SimpleEmbeddable.class, - SimpleEmbeddableEntity.class, - SimpleEmbeddableWithOverrideEntity.class, - SimpleEmbeddableWithPropertyOverrideEntity.class - }; - } - - @Test - @Priority( 10 ) - public void initData() { - EntityManager entityManager = getEntityManager(); - try { - - // entity 1 - SimpleEmbeddableEntity simple = new SimpleEmbeddableEntity(); - simple.setEmbeddable( new SimpleEmbeddable() ); - simple.getEmbeddable().setStrValue( "strValueSimple" ); - simple.getEmbeddable().setIntValue( 5 ); - - // entity 2 - SimpleEmbeddableWithOverrideEntity simpleOverride = new SimpleEmbeddableWithOverrideEntity(); - simpleOverride.setEmbeddable( new SimpleEmbeddable() ); - simpleOverride.getEmbeddable().setStrValue( "strValueSimpleOverride" ); - simpleOverride.getEmbeddable().setIntValue( 10 ); - - // entity 3 - SimpleEmbeddableWithPropertyOverrideEntity simpleProperty = new SimpleEmbeddableWithPropertyOverrideEntity(); - simpleProperty.setEmbeddable( new SimpleEmbeddable() ); - simpleProperty.getEmbeddable().setStrValue( "strValueSimpleMapped" ); - simpleProperty.getEmbeddable().setIntValue( 15 ); - - // entity 4 - FullOverrideEmbeddableEntity fullOverride = new FullOverrideEmbeddableEntity(); - fullOverride.setEmbeddable( new FullOverrideEmbeddable() ); - fullOverride.getEmbeddable().setStrValue( "strValueFull" ); - fullOverride.getEmbeddable().setIntValue( 20 ); - - // entity 5 - NotAuditedEmbeddableEntity notAudited = new NotAuditedEmbeddableEntity(); - notAudited.setEmbeddable( new FullOverrideEmbeddable() ); - notAudited.getEmbeddable().setStrValue( "strValueNotAudited" ); - notAudited.getEmbeddable().setIntValue( 25 ); - - // entity 6 - OverrideEmbeddableEntity overrided = new OverrideEmbeddableEntity(); - overrided.setEmbeddable( new OverrideEmbeddable() ); - overrided.getEmbeddable().setStrValue( "strValueOver" ); - overrided.getEmbeddable().setIntValue( 30 ); - - // entity 7 - AuditedEmbeddableOverrideEntity audited = new AuditedEmbeddableOverrideEntity(); - audited.setEmbeddable( new AuditedEmbeddable() ); - audited.getEmbeddable().setStrValue( "strValueAudited" ); - audited.getEmbeddable().setIntValue( 35 ); - audited.getEmbeddable().setValue( 1024 ); - - entityManager.getTransaction().begin(); - entityManager.persist( simple ); - entityManager.persist( simpleOverride ); - entityManager.persist( simpleProperty ); - entityManager.persist( fullOverride ); - entityManager.persist( notAudited ); - entityManager.persist( overrided ); - entityManager.persist( audited ); - entityManager.getTransaction().commit(); - - this.simpleId = simple.getId(); - this.simpleOverrideId = simpleOverride.getId(); - this.simplePropertyId = simpleProperty.getId(); - this.fullOverrideId = fullOverride.getId(); - this.notAuditedId = notAudited.getId(); - this.overridedId = overrided.getId(); - this.auditedId = audited.getId(); - } - finally { - entityManager.close(); - } - } - - @Test - @JiraKey( value = "HHH-9228" ) - public void testAuditOverrideOnAuditedEmbeddable() { - final PersistentClass clazz = getPersistentClass( AuditedEmbeddableOverrideEntity.class, auditedId, 1 ); - assertTrue( clazz.hasProperty( "name" ) ); - // verify non-audited fields are excluded from mappings. - assertFalse( clazz.hasProperty( "embeddable_value" ) ); - assertFalse( clazz.hasProperty( "embeddable_intValue" ) ); - assertFalse( clazz.hasProperty( "embeddable_strValue" ) ); - } - - @Test - @JiraKey( value = "HHH-9229" ) - public void testEmptyEmbeddableWithFullAudit() { - final PersistentClass clazz = getPersistentClass( FullOverrideEmbeddableEntity.class, fullOverrideId, 1 ); - assertTrue( clazz.hasProperty( "embeddable_intValue" ) ); - assertTrue( clazz.hasProperty( "embeddable_strValue" ) ); - } - - @Test - @JiraKey( value = "HHH-9229" ) - public void testEmptyEmbeddableWithNoAudited() { - final PersistentClass clazz = getPersistentClass( NotAuditedEmbeddableEntity.class, notAuditedId, 1 ); - // not mapped because @NotAudited should override any other behavior. - assertFalse( clazz.hasProperty( "embeddable_intValue" ) ); - assertFalse( clazz.hasProperty( "embeddable_strValue" ) ); - } - - @Test - @JiraKey( value = "HHH-9229" ) - public void testEmptyEmbeddableWithAuditOverride() { - final PersistentClass clazz = getPersistentClass( OverrideEmbeddableEntity.class, overridedId, 1 ); - assertFalse( clazz.hasProperty( "embeddable_strValue" ) ); - assertTrue( clazz.hasProperty( "embeddable_intValue" ) ); - } - - @Test - @JiraKey( value = "HHH-9229" ) - public void testEmptyEmbeddableNoAuditOverrides() { - final PersistentClass clazz = getPersistentClass( SimpleEmbeddableEntity.class, simpleId, 1 ); - assertFalse( clazz.hasProperty( "embeddable_strValue" ) ); - assertFalse( clazz.hasProperty( "embeddable_intValue" ) ); - } - - @Test - @JiraKey( value = "HHH-9229" ) - public void testEmptyEmbeddableWithAuditOverrideForMappedSuperclass() { - final PersistentClass clazz = getPersistentClass( - SimpleEmbeddableWithOverrideEntity.class, - simpleOverrideId, - 1 - ); - assertTrue( clazz.hasProperty( "embeddable_strValue" ) ); - assertTrue( clazz.hasProperty( "embeddable_intValue" ) ); - } - - @Test - @JiraKey( value = "HHH-9229" ) - public void testEmptyEmbeddableWithPropertyAuditOverride() { - final PersistentClass clazz = getPersistentClass( - SimpleEmbeddableWithPropertyOverrideEntity.class, - simplePropertyId, - 1 - ); - assertFalse( clazz.hasProperty( "embeddable_strValue" ) ); - assertTrue( clazz.hasProperty( "embeddable_intValue" ) ); - } - - // represents a @MappedSuperclass with no overrides - @MappedSuperclass - public static abstract class SimpleAbstractMappedSuperclass { - private String strValue; - private Integer intValue; - - public Integer getIntValue() { - return intValue; - } - - public void setIntValue(Integer intValue) { - this.intValue = intValue; - } - - public String getStrValue() { - return strValue; - } - - public void setStrValue(String strValue) { - this.strValue = strValue; - } - } - - // an embeddable that should introduce no audited properties - @Embeddable - public static class SimpleEmbeddable extends SimpleAbstractMappedSuperclass { - - } - - // an embeddable that should introduce 'intValue' as audited based on audit overrides locally - @Embeddable - @AuditOverride(forClass = SimpleAbstractMappedSuperclass.class, name = "intValue") - public static class OverrideEmbeddable extends SimpleAbstractMappedSuperclass { - - } - - // an embedddable that introduces all audited values base don audit overrides locally. - @Embeddable - @AuditOverride(forClass = SimpleAbstractMappedSuperclass.class) - public static class FullOverrideEmbeddable extends SimpleAbstractMappedSuperclass { - - } - - @Embeddable - @Audited - public static class AuditedEmbeddable extends SimpleAbstractMappedSuperclass { - @Column(name = "val") - private Integer value; - - public Integer getValue() { - return value; - } - - public void setValue(Integer value) { - this.value = value; - } - } - - @Entity(name = "aeoe") - @Audited - public static class AuditedEmbeddableOverrideEntity { - @Id - @GeneratedValue - private Integer id; - private String name; - @Embedded - @AuditOverrides({ - @AuditOverride(name = "value", isAudited = false), - @AuditOverride(forClass = SimpleAbstractMappedSuperclass.class, isAudited = false) - }) - private AuditedEmbeddable embeddable; - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public AuditedEmbeddable getEmbeddable() { - return embeddable; - } - - public void setEmbeddable(AuditedEmbeddable embeddable) { - this.embeddable = embeddable; - } - - public Integer getId() { - return id; - } - - public void setId(Integer id) { - this.id = id; - } - } - - @Entity(name = "naee") - @Audited - public static class NotAuditedEmbeddableEntity { - @Id - @GeneratedValue - private Integer id; - @Embedded - @NotAudited - private FullOverrideEmbeddable embeddable; - - public FullOverrideEmbeddable getEmbeddable() { - return embeddable; - } - - public void setEmbeddable(FullOverrideEmbeddable embeddable) { - this.embeddable = embeddable; - } - - public Integer getId() { - return id; - } - - public void setId(Integer id) { - this.id = id; - } - } - - @Entity(name = "foee") - @Audited - public static class FullOverrideEmbeddableEntity { - @Id - @GeneratedValue - private Integer id; - @Embedded - private FullOverrideEmbeddable embeddable; - - public FullOverrideEmbeddable getEmbeddable() { - return embeddable; - } - - public void setEmbeddable(FullOverrideEmbeddable embeddable) { - this.embeddable = embeddable; - } - - public Integer getId() { - return id; - } - - public void setId(Integer id) { - this.id = id; - } - } - - @Entity(name = "oee") - @Audited - public static class OverrideEmbeddableEntity { - @Id - @GeneratedValue - private Integer id; - @Embedded - private OverrideEmbeddable embeddable; - - public OverrideEmbeddable getEmbeddable() { - return embeddable; - } - - public void setEmbeddable(OverrideEmbeddable embeddable) { - this.embeddable = embeddable; - } - - public Integer getId() { - return id; - } - - public void setId(Integer id) { - this.id = id; - } - } - - @Entity(name = "sewpoe") - @Audited - public static class SimpleEmbeddableWithPropertyOverrideEntity { - @Id - @GeneratedValue - private Integer id; - @Embedded - @AuditOverride(name = "intValue", forClass = SimpleAbstractMappedSuperclass.class) - private SimpleEmbeddable embeddable; - - public SimpleEmbeddable getEmbeddable() { - return embeddable; - } - - public void setEmbeddable(SimpleEmbeddable embeddable) { - this.embeddable = embeddable; - } - - public Integer getId() { - return id; - } - - public void setId(Integer id) { - this.id = id; - } - } - - @Entity(name = "see") - @Audited - public static class SimpleEmbeddableEntity { - @Id - @GeneratedValue - private Integer id; - @Embedded - private SimpleEmbeddable embeddable; - - public SimpleEmbeddable getEmbeddable() { - return embeddable; - } - - public void setEmbeddable(SimpleEmbeddable embeddable) { - this.embeddable = embeddable; - } - - public Integer getId() { - return id; - } - - public void setId(Integer id) { - this.id = id; - } - } - - - @Entity(name = "sewoe") - @Audited - public static class SimpleEmbeddableWithOverrideEntity { - @Id - @GeneratedValue - private Integer id; - @Embedded - @AuditOverride(forClass = SimpleAbstractMappedSuperclass.class) - private SimpleEmbeddable embeddable; - - public SimpleEmbeddable getEmbeddable() { - return embeddable; - } - - public void setEmbeddable(SimpleEmbeddable embeddable) { - this.embeddable = embeddable; - } - - public Integer getId() { - return id; - } - - public void setId(Integer id) { - this.id = id; - } - } - - private PersistentClass getPersistentClass(Class clazz, Object id, Number revision) { - final Object entity = getAuditReader().find( clazz, id, revision ); - return metadata().getEntityBinding( getAuditReader().getEntityName( id, revision, entity ) + "_AUD" ); - } + private Integer simpleId; + private Integer simpleOverrideId; + private Integer simplePropertyId; + private Integer fullOverrideId; + private Integer notAuditedId; + private Integer overridedId; + private Integer auditedId; + + @Override + protected Class[] getAnnotatedClasses() { + return new Class[] { + AuditedEmbeddable.class, + AuditedEmbeddableOverrideEntity.class, + FullOverrideEmbeddable.class, + FullOverrideEmbeddableEntity.class, + NotAuditedEmbeddableEntity.class, + OverrideEmbeddable.class, + OverrideEmbeddableEntity.class, + SimpleAbstractMappedSuperclass.class, + SimpleEmbeddable.class, + SimpleEmbeddableEntity.class, + SimpleEmbeddableWithOverrideEntity.class, + SimpleEmbeddableWithPropertyOverrideEntity.class + }; + } + + @Test + @Priority( 10 ) + public void initData() { + EntityManager entityManager = getEntityManager(); + try { + + // entity 1 + SimpleEmbeddableEntity simple = new SimpleEmbeddableEntity(); + simple.setEmbeddable( new SimpleEmbeddable() ); + simple.getEmbeddable().setStrValue( "strValueSimple" ); + simple.getEmbeddable().setIntValue( 5 ); + + // entity 2 + SimpleEmbeddableWithOverrideEntity simpleOverride = new SimpleEmbeddableWithOverrideEntity(); + simpleOverride.setEmbeddable( new SimpleEmbeddable() ); + simpleOverride.getEmbeddable().setStrValue( "strValueSimpleOverride" ); + simpleOverride.getEmbeddable().setIntValue( 10 ); + + // entity 3 + SimpleEmbeddableWithPropertyOverrideEntity simpleProperty = new SimpleEmbeddableWithPropertyOverrideEntity(); + simpleProperty.setEmbeddable( new SimpleEmbeddable() ); + simpleProperty.getEmbeddable().setStrValue( "strValueSimpleMapped" ); + simpleProperty.getEmbeddable().setIntValue( 15 ); + + // entity 4 + FullOverrideEmbeddableEntity fullOverride = new FullOverrideEmbeddableEntity(); + fullOverride.setEmbeddable( new FullOverrideEmbeddable() ); + fullOverride.getEmbeddable().setStrValue( "strValueFull" ); + fullOverride.getEmbeddable().setIntValue( 20 ); + + // entity 5 + NotAuditedEmbeddableEntity notAudited = new NotAuditedEmbeddableEntity(); + notAudited.setEmbeddable( new FullOverrideEmbeddable() ); + notAudited.getEmbeddable().setStrValue( "strValueNotAudited" ); + notAudited.getEmbeddable().setIntValue( 25 ); + + // entity 6 + OverrideEmbeddableEntity overrided = new OverrideEmbeddableEntity(); + overrided.setEmbeddable( new OverrideEmbeddable() ); + overrided.getEmbeddable().setStrValue( "strValueOver" ); + overrided.getEmbeddable().setIntValue( 30 ); + + // entity 7 + AuditedEmbeddableOverrideEntity audited = new AuditedEmbeddableOverrideEntity(); + audited.setEmbeddable( new AuditedEmbeddable() ); + audited.getEmbeddable().setStrValue( "strValueAudited" ); + audited.getEmbeddable().setIntValue( 35 ); + audited.getEmbeddable().setValue( 1024 ); + + entityManager.getTransaction().begin(); + entityManager.persist( simple ); + entityManager.persist( simpleOverride ); + entityManager.persist( simpleProperty ); + entityManager.persist( fullOverride ); + entityManager.persist( notAudited ); + entityManager.persist( overrided ); + entityManager.persist( audited ); + entityManager.getTransaction().commit(); + + this.simpleId = simple.getId(); + this.simpleOverrideId = simpleOverride.getId(); + this.simplePropertyId = simpleProperty.getId(); + this.fullOverrideId = fullOverride.getId(); + this.notAuditedId = notAudited.getId(); + this.overridedId = overrided.getId(); + this.auditedId = audited.getId(); + } + finally { + entityManager.close(); + } + } + + @Test + @JiraKey( value = "HHH-9228" ) + public void testAuditOverrideOnAuditedEmbeddable() { + final PersistentClass clazz = getPersistentClass( AuditedEmbeddableOverrideEntity.class, auditedId, 1 ); + assertTrue( clazz.hasProperty( "name" ) ); + // verify non-audited fields are excluded from mappings. + assertFalse( clazz.hasProperty( "embeddable_value" ) ); + assertFalse( clazz.hasProperty( "embeddable_intValue" ) ); + assertFalse( clazz.hasProperty( "embeddable_strValue" ) ); + } + + @Test + @JiraKey( value = "HHH-9229" ) + public void testEmptyEmbeddableWithFullAudit() { + final PersistentClass clazz = getPersistentClass( FullOverrideEmbeddableEntity.class, fullOverrideId, 1 ); + assertTrue( clazz.hasProperty( "embeddable_intValue" ) ); + assertTrue( clazz.hasProperty( "embeddable_strValue" ) ); + } + + @Test + @JiraKey( value = "HHH-9229" ) + public void testEmptyEmbeddableWithNoAudited() { + final PersistentClass clazz = getPersistentClass( NotAuditedEmbeddableEntity.class, notAuditedId, 1 ); + // not mapped because @NotAudited should override any other behavior. + assertFalse( clazz.hasProperty( "embeddable_intValue" ) ); + assertFalse( clazz.hasProperty( "embeddable_strValue" ) ); + } + + @Test + @JiraKey( value = "HHH-9229" ) + public void testEmptyEmbeddableWithAuditOverride() { + final PersistentClass clazz = getPersistentClass( OverrideEmbeddableEntity.class, overridedId, 1 ); + assertFalse( clazz.hasProperty( "embeddable_strValue" ) ); + assertTrue( clazz.hasProperty( "embeddable_intValue" ) ); + } + + @Test + @JiraKey( value = "HHH-9229" ) + public void testEmptyEmbeddableNoAuditOverrides() { + final PersistentClass clazz = getPersistentClass( SimpleEmbeddableEntity.class, simpleId, 1 ); + assertFalse( clazz.hasProperty( "embeddable_strValue" ) ); + assertFalse( clazz.hasProperty( "embeddable_intValue" ) ); + } + + @Test + @JiraKey( value = "HHH-9229" ) + public void testEmptyEmbeddableWithAuditOverrideForMappedSuperclass() { + final PersistentClass clazz = getPersistentClass( + SimpleEmbeddableWithOverrideEntity.class, + simpleOverrideId, + 1 + ); + assertTrue( clazz.hasProperty( "embeddable_strValue" ) ); + assertTrue( clazz.hasProperty( "embeddable_intValue" ) ); + } + + @Test + @JiraKey( value = "HHH-9229" ) + public void testEmptyEmbeddableWithPropertyAuditOverride() { + final PersistentClass clazz = getPersistentClass( + SimpleEmbeddableWithPropertyOverrideEntity.class, + simplePropertyId, + 1 + ); + assertFalse( clazz.hasProperty( "embeddable_strValue" ) ); + assertTrue( clazz.hasProperty( "embeddable_intValue" ) ); + } + + // represents a @MappedSuperclass with no overrides + @MappedSuperclass + public static abstract class SimpleAbstractMappedSuperclass { + private String strValue; + private Integer intValue; + + public Integer getIntValue() { + return intValue; + } + + public void setIntValue(Integer intValue) { + this.intValue = intValue; + } + + public String getStrValue() { + return strValue; + } + + public void setStrValue(String strValue) { + this.strValue = strValue; + } + } + + // an embeddable that should introduce no audited properties + @Embeddable + public static class SimpleEmbeddable extends SimpleAbstractMappedSuperclass { + + } + + // an embeddable that should introduce 'intValue' as audited based on audit overrides locally + @Embeddable + @AuditOverride(forClass = SimpleAbstractMappedSuperclass.class, name = "intValue") + public static class OverrideEmbeddable extends SimpleAbstractMappedSuperclass { + + } + + // an embedddable that introduces all audited values base don audit overrides locally. + @Embeddable + @AuditOverride(forClass = SimpleAbstractMappedSuperclass.class) + public static class FullOverrideEmbeddable extends SimpleAbstractMappedSuperclass { + + } + + @Embeddable + @Audited + public static class AuditedEmbeddable extends SimpleAbstractMappedSuperclass { + @Column(name = "val") + private Integer value; + + public Integer getValue() { + return value; + } + + public void setValue(Integer value) { + this.value = value; + } + } + + @Entity(name = "aeoe") + @Audited + public static class AuditedEmbeddableOverrideEntity { + @Id + @GeneratedValue + private Integer id; + private String name; + @Embedded + @AuditOverrides({ + @AuditOverride(name = "value", isAudited = false), + @AuditOverride(forClass = SimpleAbstractMappedSuperclass.class, isAudited = false) + }) + private AuditedEmbeddable embeddable; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public AuditedEmbeddable getEmbeddable() { + return embeddable; + } + + public void setEmbeddable(AuditedEmbeddable embeddable) { + this.embeddable = embeddable; + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + } + + @Entity(name = "naee") + @Audited + public static class NotAuditedEmbeddableEntity { + @Id + @GeneratedValue + private Integer id; + @Embedded + @NotAudited + private FullOverrideEmbeddable embeddable; + + public FullOverrideEmbeddable getEmbeddable() { + return embeddable; + } + + public void setEmbeddable(FullOverrideEmbeddable embeddable) { + this.embeddable = embeddable; + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + } + + @Entity(name = "foee") + @Audited + public static class FullOverrideEmbeddableEntity { + @Id + @GeneratedValue + private Integer id; + @Embedded + private FullOverrideEmbeddable embeddable; + + public FullOverrideEmbeddable getEmbeddable() { + return embeddable; + } + + public void setEmbeddable(FullOverrideEmbeddable embeddable) { + this.embeddable = embeddable; + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + } + + @Entity(name = "oee") + @Audited + public static class OverrideEmbeddableEntity { + @Id + @GeneratedValue + private Integer id; + @Embedded + private OverrideEmbeddable embeddable; + + public OverrideEmbeddable getEmbeddable() { + return embeddable; + } + + public void setEmbeddable(OverrideEmbeddable embeddable) { + this.embeddable = embeddable; + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + } + + @Entity(name = "sewpoe") + @Audited + public static class SimpleEmbeddableWithPropertyOverrideEntity { + @Id + @GeneratedValue + private Integer id; + @Embedded + @AuditOverride(name = "intValue", forClass = SimpleAbstractMappedSuperclass.class) + private SimpleEmbeddable embeddable; + + public SimpleEmbeddable getEmbeddable() { + return embeddable; + } + + public void setEmbeddable(SimpleEmbeddable embeddable) { + this.embeddable = embeddable; + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + } + + @Entity(name = "see") + @Audited + public static class SimpleEmbeddableEntity { + @Id + @GeneratedValue + private Integer id; + @Embedded + private SimpleEmbeddable embeddable; + + public SimpleEmbeddable getEmbeddable() { + return embeddable; + } + + public void setEmbeddable(SimpleEmbeddable embeddable) { + this.embeddable = embeddable; + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + } + + + @Entity(name = "sewoe") + @Audited + public static class SimpleEmbeddableWithOverrideEntity { + @Id + @GeneratedValue + private Integer id; + @Embedded + @AuditOverride(forClass = SimpleAbstractMappedSuperclass.class) + private SimpleEmbeddable embeddable; + + public SimpleEmbeddable getEmbeddable() { + return embeddable; + } + + public void setEmbeddable(SimpleEmbeddable embeddable) { + this.embeddable = embeddable; + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + } + + private PersistentClass getPersistentClass(Class clazz, Object id, Number revision) { + final Object entity = getAuditReader().find( clazz, id, revision ); + return metadata().getEntityBinding( getAuditReader().getEntityName( id, revision, entity ) + "_AUD" ); + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/performance/AbstractPerformanceTest.java b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/performance/AbstractPerformanceTest.java index 52c96b6b15..0190a4e6cf 100644 --- a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/performance/AbstractPerformanceTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/performance/AbstractPerformanceTest.java @@ -55,11 +55,11 @@ public abstract class AbstractPerformanceTest extends AbstractEntityManagerTest newEntityManager(); - /*System.gc(); + /*System.gc(); System.gc(); - System.gc(); - System.out.println(Runtime.getRuntime().freeMemory() + ", " + Runtime.getRuntime().totalMemory() + ", " - + (Runtime.getRuntime().totalMemory()-Runtime.getRuntime().freeMemory()));*/ + System.gc(); + System.out.println(Runtime.getRuntime().freeMemory() + ", " + Runtime.getRuntime().totalMemory() + ", " + + (Runtime.getRuntime().totalMemory()-Runtime.getRuntime().freeMemory()));*/ } return total; diff --git a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/various/HsqlTest.java b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/various/HsqlTest.java index d5f23411c1..0fd47936de 100644 --- a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/various/HsqlTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/various/HsqlTest.java @@ -20,59 +20,59 @@ import org.hibernate.Session; */ public class HsqlTest { /* - Query generated by Hibernate from an old demo, when criteria was used: (works) + Query generated by Hibernate from an old demo, when criteria was used: (works) - select - this_.id as id2_0_, - this_._revision as column2_2_0_, - this_._revision_type as column3_2_0_, - this_.name as name2_0_, - this_.surname as surname2_0_, - this_.address_id as address6_2_0_ - from - Person_versions this_ - where - this_._revision = ( - select - max(e2_._revision) as y0_ - from - Person_versions e2_ - where - e2_._revision<=1 - and this_.id=e2_.id - ) - and this_.id=1 + select + this_.id as id2_0_, + this_._revision as column2_2_0_, + this_._revision_type as column3_2_0_, + this_.name as name2_0_, + this_.surname as surname2_0_, + this_.address_id as address6_2_0_ + from + Person_versions this_ + where + this_._revision = ( + select + max(e2_._revision) as y0_ + from + Person_versions e2_ + where + e2_._revision<=1 + and this_.id=e2_.id + ) + and this_.id=1 - Query generated by Hibernate from a new demo, when query generator is used: - (throws Column not found: ID in statement because of "person_ver0_.id=person_ver1_.id") + Query generated by Hibernate from a new demo, when query generator is used: + (throws Column not found: ID in statement because of "person_ver0_.id=person_ver1_.id") - select - person_ver0_.id as id3_, - person_ver0_._revision as column2_3_, - person_ver0_._revision_type as column3_3_, - person_ver0_.name as name3_, - person_ver0_.surname as surname3_, - person_ver0_.address_id as address6_3_ - from - Person_versions person_ver0_ - where - person_ver0_._revision_type<>2 - and person_ver0_._revision=( - select - max(person_ver1_._revision) - from - Person_versions person_ver1_ - where - person_ver1_._revision<=1 - and person_ver0_.id=person_ver1_.id - ) - and person_ver0_.id=1 + select + person_ver0_.id as id3_, + person_ver0_._revision as column2_3_, + person_ver0_._revision_type as column3_3_, + person_ver0_.name as name3_, + person_ver0_.surname as surname3_, + person_ver0_.address_id as address6_3_ + from + Person_versions person_ver0_ + where + person_ver0_._revision_type<>2 + and person_ver0_._revision=( + select + max(person_ver1_._revision) + from + Person_versions person_ver1_ + where + person_ver1_._revision<=1 + and person_ver0_.id=person_ver1_.id + ) + and person_ver0_.id=1 - Both queries work from HSQL console - (to run: java -cp hsqldb.jar org.hsqldb.util.DatabaseManager -user sa -url jdbc:hsqldb:file:/tmp/_versions_demo.db) + Both queries work from HSQL console + (to run: java -cp hsqldb.jar org.hsqldb.util.DatabaseManager -user sa -url jdbc:hsqldb:file:/tmp/_versions_demo.db) - TODO: post hibernate bug - */ + TODO: post hibernate bug + */ public static void main(String[] argv) { Map configurationOverrides = new HashMap(); diff --git a/hibernate-jcache/src/test/java/org/hibernate/orm/test/jcache/domain/PhoneNumber.java b/hibernate-jcache/src/test/java/org/hibernate/orm/test/jcache/domain/PhoneNumber.java index ef6e59dcf2..e2a59ce2e8 100644 --- a/hibernate-jcache/src/test/java/org/hibernate/orm/test/jcache/domain/PhoneNumber.java +++ b/hibernate-jcache/src/test/java/org/hibernate/orm/test/jcache/domain/PhoneNumber.java @@ -44,7 +44,7 @@ public class PhoneNumber implements Serializable { final int prime = 31; int result = 1; result = prime * result - + ((numberType == null) ? 0 : numberType.hashCode()); + + ((numberType == null) ? 0 : numberType.hashCode()); result = prime * result + (int)(personId ^ (personId >>> 32)); result = prime * result + (int)(phone ^ (phone >>> 32)); return result; diff --git a/hibernate-micrometer/src/test/java/org/hibernate/test/stat/Account.java b/hibernate-micrometer/src/test/java/org/hibernate/test/stat/Account.java index 3dd4c438ba..a3d4e48de2 100644 --- a/hibernate-micrometer/src/test/java/org/hibernate/test/stat/Account.java +++ b/hibernate-micrometer/src/test/java/org/hibernate/test/stat/Account.java @@ -16,26 +16,26 @@ import org.hibernate.annotations.NaturalId; @Entity @Table( name = "t_acct" ) public class Account { - @EmbeddedId - private AccountId accountId; + @EmbeddedId + private AccountId accountId; - @Basic( optional = false ) - @NaturalId - private String shortCode; + @Basic( optional = false ) + @NaturalId + private String shortCode; - protected Account() { - } + protected Account() { + } - public Account(AccountId accountId, String shortCode) { - this.accountId = accountId; - this.shortCode = shortCode; - } + public Account(AccountId accountId, String shortCode) { + this.accountId = accountId; + this.shortCode = shortCode; + } - public AccountId getAccountId() { - return accountId; - } + public AccountId getAccountId() { + return accountId; + } - public String getShortCode() { - return shortCode; - } + public String getShortCode() { + return shortCode; + } } diff --git a/hibernate-micrometer/src/test/java/org/hibernate/test/stat/AccountId.java b/hibernate-micrometer/src/test/java/org/hibernate/test/stat/AccountId.java index 621bad282f..56078e96ad 100644 --- a/hibernate-micrometer/src/test/java/org/hibernate/test/stat/AccountId.java +++ b/hibernate-micrometer/src/test/java/org/hibernate/test/stat/AccountId.java @@ -10,33 +10,33 @@ import jakarta.persistence.Embeddable; @Embeddable public class AccountId implements java.io.Serializable { - private final int id; + private final int id; - protected AccountId() { - this.id = 0; - } + protected AccountId() { + this.id = 0; + } - public AccountId(int id) { - this.id = id; - } - public int intValue() { - return id; - } - @Override - public int hashCode() { - return id; - } - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - AccountId other = (AccountId) obj; - if (other != null && id != other.id) - return false; - return true; - } + public AccountId(int id) { + this.id = id; + } + public int intValue() { + return id; + } + @Override + public int hashCode() { + return id; + } + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + AccountId other = (AccountId) obj; + if (other != null && id != other.id) + return false; + return true; + } } diff --git a/hibernate-spatial/src/test/java/org/hibernate/spatial/testing/SpatialTest.java b/hibernate-spatial/src/test/java/org/hibernate/spatial/testing/SpatialTest.java index 2aa0c0f7f6..1b3c236601 100644 --- a/hibernate-spatial/src/test/java/org/hibernate/spatial/testing/SpatialTest.java +++ b/hibernate-spatial/src/test/java/org/hibernate/spatial/testing/SpatialTest.java @@ -35,93 +35,93 @@ import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; @Ignore public class SpatialTest extends BaseEntityManagerFunctionalTestCase { - private final GeometryFactory geometryFactory = new GeometryFactory(); + private final GeometryFactory geometryFactory = new GeometryFactory(); - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Event.class, - }; - } + @Override + protected Class[] getAnnotatedClasses() { + return new Class[] { + Event.class, + }; + } - @Test - public void test() { - Long addressId = doInJPA( this::entityManagerFactory, entityManager -> { - //tag::spatial-types-point-creation-example[] - Event event = new Event(); - event.setId( 1L); - event.setName( "Hibernate ORM presentation"); - Point point = geometryFactory.createPoint( new Coordinate( 10, 5 ) ); - event.setLocation( point ); + @Test + public void test() { + Long addressId = doInJPA( this::entityManagerFactory, entityManager -> { + //tag::spatial-types-point-creation-example[] + Event event = new Event(); + event.setId( 1L); + event.setName( "Hibernate ORM presentation"); + Point point = geometryFactory.createPoint( new Coordinate( 10, 5 ) ); + event.setLocation( point ); - entityManager.persist( event ); - //end::spatial-types-point-creation-example[] - return event.getId(); - }); + entityManager.persist( event ); + //end::spatial-types-point-creation-example[] + return event.getId(); + }); - doInJPA( this::entityManagerFactory, entityManager -> { - Event event = entityManager.find( Event.class, addressId); - Coordinate coordinate = event.getLocation().getCoordinate(); - assertEquals( 10.0d, coordinate.getOrdinate( Coordinate.X), 0.1); - assertEquals( 5.0d, coordinate.getOrdinate( Coordinate.Y), 0.1); - }); + doInJPA( this::entityManagerFactory, entityManager -> { + Event event = entityManager.find( Event.class, addressId); + Coordinate coordinate = event.getLocation().getCoordinate(); + assertEquals( 10.0d, coordinate.getOrdinate( Coordinate.X), 0.1); + assertEquals( 5.0d, coordinate.getOrdinate( Coordinate.Y), 0.1); + }); - doInJPA( this::entityManagerFactory, entityManager -> { - Coordinate [] coordinates = new Coordinate[] { - new Coordinate(1,1), new Coordinate(20,1), new Coordinate(20,20), - new Coordinate(1,20), new Coordinate(1,1) - }; - //tag::spatial-types-query-example[] - Polygon window = geometryFactory.createPolygon( coordinates ); - Event event = entityManager.createQuery( - "select e " + - "from Event e " + - "where within(e.location, :window) = true", Event.class) - .setParameter("window", window) - .getSingleResult(); - //end::spatial-types-query-example[] - Coordinate coordinate = event.getLocation().getCoordinate(); - assertEquals( 10.0d, coordinate.getOrdinate( Coordinate.X), 0.1); - assertEquals( 5.0d, coordinate.getOrdinate( Coordinate.Y), 0.1); - }); - } + doInJPA( this::entityManagerFactory, entityManager -> { + Coordinate [] coordinates = new Coordinate[] { + new Coordinate(1,1), new Coordinate(20,1), new Coordinate(20,20), + new Coordinate(1,20), new Coordinate(1,1) + }; + //tag::spatial-types-query-example[] + Polygon window = geometryFactory.createPolygon( coordinates ); + Event event = entityManager.createQuery( + "select e " + + "from Event e " + + "where within(e.location, :window) = true", Event.class) + .setParameter("window", window) + .getSingleResult(); + //end::spatial-types-query-example[] + Coordinate coordinate = event.getLocation().getCoordinate(); + assertEquals( 10.0d, coordinate.getOrdinate( Coordinate.X), 0.1); + assertEquals( 5.0d, coordinate.getOrdinate( Coordinate.Y), 0.1); + }); + } //tag::spatial-types-mapping-example[] @Entity(name = "Event") public static class Event { - @Id - private Long id; + @Id + private Long id; - private String name; + private String name; - private Point location; + private Point location; - //Getters and setters are omitted for brevity + //Getters and setters are omitted for brevity //end::spatial-types-mapping-example[] - public Long getId() { - return id; - } + public Long getId() { + return id; + } - public void setId(Long id) { - this.id = id; - } + public void setId(Long id) { + this.id = id; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - public Point getLocation() { - return location; - } + public Point getLocation() { + return location; + } - public void setLocation(Point location) { - this.location = location; - } + public void setLocation(Point location) { + this.location = location; + } //tag::spatial-types-mapping-example[] } //end::spatial-types-mapping-example[] diff --git a/hibernate-spatial/src/test/java/org/hibernate/spatial/testing/dialects/oracle/OracleSTNativeSqlTemplates.java b/hibernate-spatial/src/test/java/org/hibernate/spatial/testing/dialects/oracle/OracleSTNativeSqlTemplates.java index f3dc8b43ee..d2e3a401af 100644 --- a/hibernate-spatial/src/test/java/org/hibernate/spatial/testing/dialects/oracle/OracleSTNativeSqlTemplates.java +++ b/hibernate-spatial/src/test/java/org/hibernate/spatial/testing/dialects/oracle/OracleSTNativeSqlTemplates.java @@ -67,7 +67,7 @@ public class OracleSTNativeSqlTemplates extends NativeSQLTemplates { "select id, ST_GEOMETRY(t.GEOM).ST_DISJOINT(ST_GEOMETRY.FROM_WKT(:filter, 4326)) as result from %s t" ); sqls.put( ST_RELATE, - "select id, ST_GEOMETRY(t.GEOM).st_relate(st_geometry.from_wkt(:filter, 4326), 'DETERMINE') as result from %s t" ); + "select id, ST_GEOMETRY(t.GEOM).st_relate(st_geometry.from_wkt(:filter, 4326), 'DETERMINE') as result from %s t" ); sqls.put( ST_TOUCHES, "select id, ST_GEOMETRY(t.GEOM).ST_TOUCHES(ST_GEOMETRY.FROM_WKT(:filter, 4326)) as result from %s t" diff --git a/hibernate-spatial/src/test/java/org/hibernate/spatial/testing/dialects/sqlserver/SqlServerNativeSqlTemplates.java b/hibernate-spatial/src/test/java/org/hibernate/spatial/testing/dialects/sqlserver/SqlServerNativeSqlTemplates.java index 9bc00c989d..2d55600791 100644 --- a/hibernate-spatial/src/test/java/org/hibernate/spatial/testing/dialects/sqlserver/SqlServerNativeSqlTemplates.java +++ b/hibernate-spatial/src/test/java/org/hibernate/spatial/testing/dialects/sqlserver/SqlServerNativeSqlTemplates.java @@ -54,7 +54,7 @@ public class SqlServerNativeSqlTemplates extends NativeSQLTemplates { "select id, geom.STIntersects(geometry::::STGeomFromText(:filter, 4326)) as result from %s" ); sqls.put( ST_CROSSES, - "select id, geom.STCrosses(geometry::::STGeomFromText(:filter, 4326)) as result from %s" + "select id, geom.STCrosses(geometry::::STGeomFromText(:filter, 4326)) as result from %s" ); sqls.put( ST_CONTAINS, "select id, geom.STContains(geometry::::STGeomFromText(:filter, 4326)) as result from %s" ); diff --git a/hibernate-vibur/src/test/java/org/hibernate/test/vibur/ViburDBCPConnectionProviderTest.java b/hibernate-vibur/src/test/java/org/hibernate/test/vibur/ViburDBCPConnectionProviderTest.java index 8bf73ad854..0cee6f5810 100644 --- a/hibernate-vibur/src/test/java/org/hibernate/test/vibur/ViburDBCPConnectionProviderTest.java +++ b/hibernate-vibur/src/test/java/org/hibernate/test/vibur/ViburDBCPConnectionProviderTest.java @@ -44,133 +44,133 @@ import static org.vibur.dbcp.stcache.StatementHolder.State.AVAILABLE; @RunWith(MockitoJUnitRunner.class) public class ViburDBCPConnectionProviderTest extends BaseCoreFunctionalTestCase { - private int poolMaxSize; - private int statementCacheMaxSize; + private int poolMaxSize; + private int statementCacheMaxSize; - @Override - protected void configure(Configuration configuration) { - Properties properties = configuration.getProperties(); - properties.put(CONNECTION_PROVIDER, ViburDBCPConnectionProvider.class); - properties.put(SHOW_SQL, Boolean.TRUE); - properties.put(FORMAT_SQL, Boolean.TRUE); + @Override + protected void configure(Configuration configuration) { + Properties properties = configuration.getProperties(); + properties.put(CONNECTION_PROVIDER, ViburDBCPConnectionProvider.class); + properties.put(SHOW_SQL, Boolean.TRUE); + properties.put(FORMAT_SQL, Boolean.TRUE); - properties.put("hibernate.vibur.poolInitialSize", "1"); - properties.put("hibernate.vibur.poolMaxSize", Integer.toString(poolMaxSize)); - properties.put("hibernate.vibur.logQueryExecutionLongerThanMs", "100"); - properties.put("hibernate.vibur.statementCacheMaxSize", Integer.toString(statementCacheMaxSize)); - } + properties.put("hibernate.vibur.poolInitialSize", "1"); + properties.put("hibernate.vibur.poolMaxSize", Integer.toString(poolMaxSize)); + properties.put("hibernate.vibur.logQueryExecutionLongerThanMs", "100"); + properties.put("hibernate.vibur.statementCacheMaxSize", Integer.toString(statementCacheMaxSize)); + } - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { Actor.class }; - } + @Override + protected Class[] getAnnotatedClasses() { + return new Class[] { Actor.class }; + } - public void setUpPoolAndDatabase(int poolMaxSize, int statementCacheMaxSize) { - this.poolMaxSize = poolMaxSize; - this.statementCacheMaxSize = statementCacheMaxSize; - buildSessionFactory(); + public void setUpPoolAndDatabase(int poolMaxSize, int statementCacheMaxSize) { + this.poolMaxSize = poolMaxSize; + this.statementCacheMaxSize = statementCacheMaxSize; + buildSessionFactory(); - doInHibernate(this::sessionFactory, session -> { - addDbRecord(session, 1L, "CHRISTIAN", "GABLE"); - addDbRecord(session, 2L, "CHRISTIAN", "AKROYD"); - addDbRecord(session, 3L, "CHRISTIAN", "NEESON"); - addDbRecord(session, 4L, "CAMERON", "NEESON"); - addDbRecord(session, 5L, "RAY", "JOHANSSON"); - }); - } + doInHibernate(this::sessionFactory, session -> { + addDbRecord(session, 1L, "CHRISTIAN", "GABLE"); + addDbRecord(session, 2L, "CHRISTIAN", "AKROYD"); + addDbRecord(session, 3L, "CHRISTIAN", "NEESON"); + addDbRecord(session, 4L, "CAMERON", "NEESON"); + addDbRecord(session, 5L, "RAY", "JOHANSSON"); + }); + } - private static void addDbRecord(Session session, Long id, String firstName, String lastName) { - Actor actor = new Actor(); - actor.setId( id ); - actor.setFirstName(firstName); - actor.setLastName(lastName); - session.persist(actor); - } + private static void addDbRecord(Session session, Long id, String firstName, String lastName) { + Actor actor = new Actor(); + actor.setId( id ); + actor.setFirstName(firstName); + actor.setLastName(lastName); + session.persist(actor); + } - @After - public void tearDown() { - releaseSessionFactory(); - } + @After + public void tearDown() { + releaseSessionFactory(); + } - @Captor - private ArgumentCaptor key1, key2; - @Captor - private ArgumentCaptor val1; + @Captor + private ArgumentCaptor key1, key2; + @Captor + private ArgumentCaptor val1; - @Test - public void testSelectStatementNoStatementsCache() { - setUpPoolAndDatabase(2, 0 /* disables the statements cache */ ); + @Test + public void testSelectStatementNoStatementsCache() { + setUpPoolAndDatabase(2, 0 /* disables the statements cache */ ); - doInHibernate(this::sessionFactory, ViburDBCPConnectionProviderTest::executeAndVerifySelect); - } + doInHibernate(this::sessionFactory, ViburDBCPConnectionProviderTest::executeAndVerifySelect); + } - @Test - public void testSelectStatementWithStatementsCache() { - setUpPoolAndDatabase(1, 10 /* statement cache is enabled */ ); + @Test + public void testSelectStatementWithStatementsCache() { + setUpPoolAndDatabase(1, 10 /* statement cache is enabled */ ); - ConnectionProvider cp = sessionFactory().getServiceRegistry().getService(ConnectionProvider.class); - ViburDBCPDataSource ds = ((ViburDBCPConnectionProvider) cp).getDataSource(); + ConnectionProvider cp = sessionFactory().getServiceRegistry().getService(ConnectionProvider.class); + ViburDBCPDataSource ds = ((ViburDBCPConnectionProvider) cp).getDataSource(); - ConcurrentMap mockedStatementCache = mockStatementCache(ds); + ConcurrentMap mockedStatementCache = mockStatementCache(ds); - doInHibernate(this::sessionFactory, ViburDBCPConnectionProviderTest::executeAndVerifySelect); + doInHibernate(this::sessionFactory, ViburDBCPConnectionProviderTest::executeAndVerifySelect); - // We set above the poolMaxSize = 1, that's why the second session will get and use the same underlying connection. - doInHibernate(this::sessionFactory, ViburDBCPConnectionProviderTest::executeAndVerifySelect); + // We set above the poolMaxSize = 1, that's why the second session will get and use the same underlying connection. + doInHibernate(this::sessionFactory, ViburDBCPConnectionProviderTest::executeAndVerifySelect); - InOrder inOrder = inOrder(mockedStatementCache); - inOrder.verify(mockedStatementCache).get(key1.capture()); - inOrder.verify(mockedStatementCache).putIfAbsent(same(key1.getValue()), val1.capture()); - inOrder.verify(mockedStatementCache).get(key2.capture()); + InOrder inOrder = inOrder(mockedStatementCache); + inOrder.verify(mockedStatementCache).get(key1.capture()); + inOrder.verify(mockedStatementCache).putIfAbsent(same(key1.getValue()), val1.capture()); + inOrder.verify(mockedStatementCache).get(key2.capture()); - assertEquals(1, mockedStatementCache.size()); - assertTrue(mockedStatementCache.containsKey(key1.getValue())); - assertEquals(key1.getValue(), key2.getValue()); - assertEquals(AVAILABLE, val1.getValue().state().get()); - } + assertEquals(1, mockedStatementCache.size()); + assertTrue(mockedStatementCache.containsKey(key1.getValue())); + assertEquals(key1.getValue(), key2.getValue()); + assertEquals(AVAILABLE, val1.getValue().state().get()); + } - @SuppressWarnings("unchecked") - private static void executeAndVerifySelect(Session session) { - List list = session.createQuery("from Actor where firstName = ?1") - .setParameter(1, "CHRISTIAN").list(); + @SuppressWarnings("unchecked") + private static void executeAndVerifySelect(Session session) { + List list = session.createQuery("from Actor where firstName = ?1") + .setParameter(1, "CHRISTIAN").list(); - Set expectedLastNames = new HashSet<>(Arrays.asList("GABLE", "AKROYD", "NEESON")); - assertEquals(expectedLastNames.size(), list.size()); - for (Actor actor : list) { - assertTrue(expectedLastNames.remove(actor.getLastName())); - } - } + Set expectedLastNames = new HashSet<>(Arrays.asList("GABLE", "AKROYD", "NEESON")); + assertEquals(expectedLastNames.size(), list.size()); + for (Actor actor : list) { + assertTrue(expectedLastNames.remove(actor.getLastName())); + } + } - @Entity(name="Actor") - public static class Actor { - @Id - private Long id; + @Entity(name="Actor") + public static class Actor { + @Id + private Long id; - private String firstName; - private String lastName; + private String firstName; + private String lastName; - public Long getId() { - return id; - } + public Long getId() { + return id; + } - public void setId(Long id) { - this.id = id; - } + public void setId(Long id) { + this.id = id; + } - public String getFirstName() { - return firstName; - } + public String getFirstName() { + return firstName; + } - public void setFirstName(String firstName) { - this.firstName = firstName; - } + public void setFirstName(String firstName) { + this.firstName = firstName; + } - public String getLastName() { - return lastName; - } + public String getLastName() { + return lastName; + } - public void setLastName(String lastName) { - this.lastName = lastName; - } - } + public void setLastName(String lastName) { + this.lastName = lastName; + } + } } diff --git a/tooling/hibernate-enhance-maven-plugin/src/test/java/org/hibernate/orm/tooling/maven/MavenEnhancePluginTest.java b/tooling/hibernate-enhance-maven-plugin/src/test/java/org/hibernate/orm/tooling/maven/MavenEnhancePluginTest.java index e5528229f9..2d895ec8bd 100644 --- a/tooling/hibernate-enhance-maven-plugin/src/test/java/org/hibernate/orm/tooling/maven/MavenEnhancePluginTest.java +++ b/tooling/hibernate-enhance-maven-plugin/src/test/java/org/hibernate/orm/tooling/maven/MavenEnhancePluginTest.java @@ -27,54 +27,54 @@ import java.util.Map; */ public class MavenEnhancePluginTest { - @Test - public void testEnhancePlugin() throws Exception { - File baseDir = new File("target/classes/java/test"); - URL[] baseURLs = { baseDir.toURI().toURL() }; + @Test + public void testEnhancePlugin() throws Exception { + File baseDir = new File("target/classes/java/test"); + URL[] baseURLs = { baseDir.toURI().toURL() }; - MavenEnhancePlugin plugin = new MavenEnhancePlugin(); + MavenEnhancePlugin plugin = new MavenEnhancePlugin(); - Map pluginContext = new HashMap<>(); - pluginContext.put( "project", new MavenProject() ); + Map pluginContext = new HashMap<>(); + pluginContext.put( "project", new MavenProject() ); - setVariableValueToObject( plugin, "pluginContext", pluginContext ); - setVariableValueToObject( plugin, "buildContext", new DefaultBuildContext() ); + setVariableValueToObject( plugin, "pluginContext", pluginContext ); + setVariableValueToObject( plugin, "buildContext", new DefaultBuildContext() ); - setVariableValueToObject( plugin, "base", baseDir.getAbsolutePath() ); - setVariableValueToObject( plugin, "dir", baseDir.getAbsolutePath() ); - setVariableValueToObject( plugin, "classNames", "" ); + setVariableValueToObject( plugin, "base", baseDir.getAbsolutePath() ); + setVariableValueToObject( plugin, "dir", baseDir.getAbsolutePath() ); + setVariableValueToObject( plugin, "classNames", "" ); - setVariableValueToObject( plugin, "failOnError", true ); - setVariableValueToObject( plugin, "enableLazyInitialization", true ); - setVariableValueToObject( plugin, "enableDirtyTracking", true ); - setVariableValueToObject( plugin, "enableAssociationManagement", true ); - setVariableValueToObject( plugin, "enableExtendedEnhancement", false ); + setVariableValueToObject( plugin, "failOnError", true ); + setVariableValueToObject( plugin, "enableLazyInitialization", true ); + setVariableValueToObject( plugin, "enableDirtyTracking", true ); + setVariableValueToObject( plugin, "enableAssociationManagement", true ); + setVariableValueToObject( plugin, "enableExtendedEnhancement", false ); - plugin.execute(); + plugin.execute(); - try ( URLClassLoader classLoader = new URLClassLoader( baseURLs , getClass().getClassLoader() ) ) { + try ( URLClassLoader classLoader = new URLClassLoader( baseURLs , getClass().getClassLoader() ) ) { - Assert.assertTrue( declaresManaged( classLoader.loadClass( ParentEntity.class.getName() ) ) ); - Assert.assertTrue( declaresManaged( classLoader.loadClass( ChildEntity.class.getName() ) ) ); - Assert.assertTrue( declaresManaged( classLoader.loadClass( TestEntity.class.getName() ) ) ); + Assert.assertTrue( declaresManaged( classLoader.loadClass( ParentEntity.class.getName() ) ) ); + Assert.assertTrue( declaresManaged( classLoader.loadClass( ChildEntity.class.getName() ) ) ); + Assert.assertTrue( declaresManaged( classLoader.loadClass( TestEntity.class.getName() ) ) ); - } + } - } + } - private void setVariableValueToObject( Object object, String variable, Object value ) throws IllegalAccessException { - Field field = ReflectionUtils.getFieldByNameIncludingSuperclasses( variable, object.getClass() ); - field.setAccessible( true ); - field.set( object, value ); - } + private void setVariableValueToObject( Object object, String variable, Object value ) throws IllegalAccessException { + Field field = ReflectionUtils.getFieldByNameIncludingSuperclasses( variable, object.getClass() ); + field.setAccessible( true ); + field.set( object, value ); + } - private boolean declaresManaged(Class clazz) { - for ( Class interfaceClazz : clazz.getInterfaces() ) { - if ( Managed.class.isAssignableFrom( interfaceClazz ) ) { - return true; - } - } - return false; - } + private boolean declaresManaged(Class clazz) { + for ( Class interfaceClazz : clazz.getInterfaces() ) { + if ( Managed.class.isAssignableFrom( interfaceClazz ) ) { + return true; + } + } + return false; + } } diff --git a/tooling/metamodel-generator/src/jakartaData/java/org/hibernate/processor/test/data/basic/Author.java b/tooling/metamodel-generator/src/jakartaData/java/org/hibernate/processor/test/data/basic/Author.java index 9814b1d689..290d643393 100644 --- a/tooling/metamodel-generator/src/jakartaData/java/org/hibernate/processor/test/data/basic/Author.java +++ b/tooling/metamodel-generator/src/jakartaData/java/org/hibernate/processor/test/data/basic/Author.java @@ -14,13 +14,13 @@ import java.util.Set; @Entity public class Author { - @Id - String ssn; - String name; + @Id + String ssn; + String name; // @Embedded // Address address; - @ManyToMany - Set books; + @ManyToMany + Set books; } diff --git a/tooling/metamodel-generator/src/jakartaData/java/org/hibernate/processor/test/data/basic/Book.java b/tooling/metamodel-generator/src/jakartaData/java/org/hibernate/processor/test/data/basic/Book.java index 1451276d15..33650f68d2 100644 --- a/tooling/metamodel-generator/src/jakartaData/java/org/hibernate/processor/test/data/basic/Book.java +++ b/tooling/metamodel-generator/src/jakartaData/java/org/hibernate/processor/test/data/basic/Book.java @@ -16,30 +16,30 @@ import java.util.Set; @Entity @Table(name = "books") public class Book { - @Id - String isbn; + @Id + String isbn; - @NaturalId - @Basic(optional = false) - String title; + @NaturalId + @Basic(optional = false) + String title; - @Basic(optional = false) - String text; + @Basic(optional = false) + String text; - @NaturalId - LocalDate publicationDate; + @NaturalId + LocalDate publicationDate; - @ManyToMany(mappedBy = "books") - Set authors; + @ManyToMany(mappedBy = "books") + Set authors; - BigDecimal price; + BigDecimal price; - int pages; + int pages; - public Book(String isbn, String title, String text) { - this.isbn = isbn; - this.title = title; - this.text = text; - } - Book() {} + public Book(String isbn, String title, String text) { + this.isbn = isbn; + this.title = title; + this.text = text; + } + Book() {} } diff --git a/tooling/metamodel-generator/src/jakartaData/java/org/hibernate/processor/test/data/basic/IdOperations.java b/tooling/metamodel-generator/src/jakartaData/java/org/hibernate/processor/test/data/basic/IdOperations.java index dff3bd6997..f171d85d81 100644 --- a/tooling/metamodel-generator/src/jakartaData/java/org/hibernate/processor/test/data/basic/IdOperations.java +++ b/tooling/metamodel-generator/src/jakartaData/java/org/hibernate/processor/test/data/basic/IdOperations.java @@ -15,17 +15,17 @@ import jakarta.data.Sort; import jakarta.data.repository.Query; public interface IdOperations { - @Query("where id(this) between ?1 and ?2") - Stream findByIdBetween(long minimum, long maximum, Sort sort); + @Query("where id(this) between ?1 and ?2") + Stream findByIdBetween(long minimum, long maximum, Sort sort); - @Query("where id(this) >= ?1") - List findByIdGreaterThanEqual(long minimum, - Limit limit, - Order sorts); + @Query("where id(this) >= ?1") + List findByIdGreaterThanEqual(long minimum, + Limit limit, + Order sorts); - @Query("where id(this) > ?1") - T[] findByIdLessThan(long exclusiveMax, Sort primarySort, Sort secondarySort); + @Query("where id(this) > ?1") + T[] findByIdLessThan(long exclusiveMax, Sort primarySort, Sort secondarySort); - @Query("where id(this) <= ?1") - List findByIdLessThanEqual(long maximum, Order sorts); + @Query("where id(this) <= ?1") + List findByIdLessThanEqual(long maximum, Order sorts); } diff --git a/tooling/metamodel-generator/src/jakartaData/java/org/hibernate/processor/test/data/eg/Author.java b/tooling/metamodel-generator/src/jakartaData/java/org/hibernate/processor/test/data/eg/Author.java index 759213f06a..f918152ef4 100644 --- a/tooling/metamodel-generator/src/jakartaData/java/org/hibernate/processor/test/data/eg/Author.java +++ b/tooling/metamodel-generator/src/jakartaData/java/org/hibernate/processor/test/data/eg/Author.java @@ -15,14 +15,14 @@ import java.util.Set; @Entity public class Author { - @Id - String ssn; + @Id + String ssn; - @Basic(optional = false) - String name; + @Basic(optional = false) + String name; - Address address; + Address address; - @ManyToMany - Set books; + @ManyToMany + Set books; } diff --git a/tooling/metamodel-generator/src/jakartaData/java/org/hibernate/processor/test/data/eg/Book.java b/tooling/metamodel-generator/src/jakartaData/java/org/hibernate/processor/test/data/eg/Book.java index c4452a4a85..6c980b3d72 100644 --- a/tooling/metamodel-generator/src/jakartaData/java/org/hibernate/processor/test/data/eg/Book.java +++ b/tooling/metamodel-generator/src/jakartaData/java/org/hibernate/processor/test/data/eg/Book.java @@ -22,43 +22,43 @@ import java.util.Set; @Entity public class Book { - @Id - String isbn; + @Id + String isbn; - @NaturalId - String title; + @NaturalId + String title; - @NaturalId - LocalDate publicationDate; + @NaturalId + LocalDate publicationDate; - String text; + String text; - @Enumerated(EnumType.STRING) - @Basic(optional = false) - Type type = Type.Book; + @Enumerated(EnumType.STRING) + @Basic(optional = false) + Type type = Type.Book; - @ManyToOne(optional = false) - Publisher publisher; + @ManyToOne(optional = false) + Publisher publisher; - @ManyToMany(mappedBy = "books") - Set authors; + @ManyToMany(mappedBy = "books") + Set authors; - @Basic(optional = false) - int pages ; + @Basic(optional = false) + int pages ; - BigDecimal price; - BigInteger quantitySold; + BigDecimal price; + BigInteger quantitySold; - public Book(String isbn, String title, String text) { - this.isbn = isbn; - this.title = title; - this.text = text; - } + public Book(String isbn, String title, String text) { + this.isbn = isbn; + this.title = title; + this.text = text; + } - protected Book() {} + protected Book() {} - @Override - public String toString() { - return isbn + " : " + title + " [" + type + "]"; - } + @Override + public String toString() { + return isbn + " : " + title + " [" + type + "]"; + } } diff --git a/tooling/metamodel-generator/src/jakartaData/java/org/hibernate/processor/test/data/eg/Bookshop.java b/tooling/metamodel-generator/src/jakartaData/java/org/hibernate/processor/test/data/eg/Bookshop.java index 4a7d48f9da..a7b2d77381 100644 --- a/tooling/metamodel-generator/src/jakartaData/java/org/hibernate/processor/test/data/eg/Bookshop.java +++ b/tooling/metamodel-generator/src/jakartaData/java/org/hibernate/processor/test/data/eg/Bookshop.java @@ -18,28 +18,28 @@ import java.util.List; @Repository public interface Bookshop extends CrudRepository { - @Find - @Transactional - List byPublisher(String publisher_name); + @Find + @Transactional + List byPublisher(String publisher_name); - @Query("select isbn where title like ?1 order by isbn") - String[] ssns(@NotBlank String title); + @Query("select isbn where title like ?1 order by isbn") + String[] ssns(@NotBlank String title); - @Query("select count(this) where title like ?1 order by isbn") - long count1(@NotNull String title); + @Query("select count(this) where title like ?1 order by isbn") + long count1(@NotNull String title); - @Query("select count(this) where this.title like ?1 order by this.isbn") - long count2(String title); + @Query("select count(this) where this.title like ?1 order by this.isbn") + long count2(String title); - @Query("select count(this)") - long countAll(); + @Query("select count(this)") + long countAll(); - @Query("where isbn in :isbns and type = Book") - List books(List isbns); + @Query("where isbn in :isbns and type = Book") + List books(List isbns); - @Query("delete from Book where type = org.hibernate.processor.test.data.eg.Type.Book") - long deleteAllBooks(); + @Query("delete from Book where type = org.hibernate.processor.test.data.eg.Type.Book") + long deleteAllBooks(); - @Query("delete from Book where type = Book and isbn in ?1") - int deleteBooks(List isbns); + @Query("delete from Book where type = Book and isbn in ?1") + int deleteBooks(List isbns); } diff --git a/tooling/metamodel-generator/src/jakartaData/java/org/hibernate/processor/test/data/eg/Publisher.java b/tooling/metamodel-generator/src/jakartaData/java/org/hibernate/processor/test/data/eg/Publisher.java index 70ff7b7180..e645a53eeb 100644 --- a/tooling/metamodel-generator/src/jakartaData/java/org/hibernate/processor/test/data/eg/Publisher.java +++ b/tooling/metamodel-generator/src/jakartaData/java/org/hibernate/processor/test/data/eg/Publisher.java @@ -15,11 +15,11 @@ import java.util.Set; @Entity public class Publisher { - @Id long id; + @Id long id; - @Basic(optional = false) - String name; + @Basic(optional = false) + String name; - @OneToMany(mappedBy = "publisher") - Set books; + @OneToMany(mappedBy = "publisher") + Set books; } diff --git a/tooling/metamodel-generator/src/jakartaData/java/org/hibernate/processor/test/data/namedquery/Author.java b/tooling/metamodel-generator/src/jakartaData/java/org/hibernate/processor/test/data/namedquery/Author.java index fb92901ab5..96cd1a4e16 100644 --- a/tooling/metamodel-generator/src/jakartaData/java/org/hibernate/processor/test/data/namedquery/Author.java +++ b/tooling/metamodel-generator/src/jakartaData/java/org/hibernate/processor/test/data/namedquery/Author.java @@ -14,13 +14,13 @@ import java.util.Set; @Entity public class Author { - @Id - String ssn; - String name; + @Id + String ssn; + String name; // @Embedded // Address address; - @ManyToMany - Set books; + @ManyToMany + Set books; } diff --git a/tooling/metamodel-generator/src/jakartaData/java/org/hibernate/processor/test/data/namedquery/Book.java b/tooling/metamodel-generator/src/jakartaData/java/org/hibernate/processor/test/data/namedquery/Book.java index ab0af06b07..5fda236b51 100644 --- a/tooling/metamodel-generator/src/jakartaData/java/org/hibernate/processor/test/data/namedquery/Book.java +++ b/tooling/metamodel-generator/src/jakartaData/java/org/hibernate/processor/test/data/namedquery/Book.java @@ -20,34 +20,34 @@ import java.util.Set; @Entity @Table(name = "books") public class Book { - public enum Type { Book, Magazine, Journal } + public enum Type { Book, Magazine, Journal } - @Id - String isbn; + @Id + String isbn; - @NaturalId - @Basic(optional = false) - String title; + @NaturalId + @Basic(optional = false) + String title; - @Basic(optional = false) - String text; + @Basic(optional = false) + String text; - @NaturalId - LocalDate publicationDate; + @NaturalId + LocalDate publicationDate; - @ManyToMany(mappedBy = "books") - Set authors; + @ManyToMany(mappedBy = "books") + Set authors; - BigDecimal price; + BigDecimal price; - int pages; + int pages; - Type type; + Type type; - public Book(String isbn, String title, String text) { - this.isbn = isbn; - this.title = title; - this.text = text; - } - Book() {} + public Book(String isbn, String title, String text) { + this.isbn = isbn; + this.title = title; + this.text = text; + } + Book() {} } diff --git a/tooling/metamodel-generator/src/jakartaData/java/org/hibernate/processor/test/data/quarkus/JakartaDataBookRepository.java b/tooling/metamodel-generator/src/jakartaData/java/org/hibernate/processor/test/data/quarkus/JakartaDataBookRepository.java index b0db8cb0e3..948f7aecc1 100644 --- a/tooling/metamodel-generator/src/jakartaData/java/org/hibernate/processor/test/data/quarkus/JakartaDataBookRepository.java +++ b/tooling/metamodel-generator/src/jakartaData/java/org/hibernate/processor/test/data/quarkus/JakartaDataBookRepository.java @@ -16,9 +16,9 @@ import jakarta.data.repository.Repository; @Repository public interface JakartaDataBookRepository extends CrudRepository { - @Find - public List findBook(String isbn); + @Find + public List findBook(String isbn); - @Query("WHERE isbn = :isbn") - public List hqlBook(String isbn); + @Query("WHERE isbn = :isbn") + public List hqlBook(String isbn); } diff --git a/tooling/metamodel-generator/src/jakartaData/java/org/hibernate/processor/test/data/quarkus/PanacheBook.java b/tooling/metamodel-generator/src/jakartaData/java/org/hibernate/processor/test/data/quarkus/PanacheBook.java index 56e8268c09..d997981f9d 100644 --- a/tooling/metamodel-generator/src/jakartaData/java/org/hibernate/processor/test/data/quarkus/PanacheBook.java +++ b/tooling/metamodel-generator/src/jakartaData/java/org/hibernate/processor/test/data/quarkus/PanacheBook.java @@ -18,14 +18,14 @@ import jakarta.persistence.Entity; @Entity public class PanacheBook extends PanacheEntity { public @NaturalId String isbn; - public @NaturalId String title; - public @NaturalId String author; - public String text; - public int pages; + public @NaturalId String title; + public @NaturalId String author; + public String text; + public int pages; - @Find - public static native List findBook(String isbn); + @Find + public static native List findBook(String isbn); - @HQL("WHERE isbn = :isbn") - public static native List hqlBook(String isbn); + @HQL("WHERE isbn = :isbn") + public static native List hqlBook(String isbn); } diff --git a/tooling/metamodel-generator/src/jakartaData/java/org/hibernate/processor/test/data/reactive/Author.java b/tooling/metamodel-generator/src/jakartaData/java/org/hibernate/processor/test/data/reactive/Author.java index 7a1df6d972..b16763022a 100644 --- a/tooling/metamodel-generator/src/jakartaData/java/org/hibernate/processor/test/data/reactive/Author.java +++ b/tooling/metamodel-generator/src/jakartaData/java/org/hibernate/processor/test/data/reactive/Author.java @@ -15,14 +15,14 @@ import java.util.Set; @Entity public class Author { - @Id - String ssn; + @Id + String ssn; - @Basic(optional = false) - String name; + @Basic(optional = false) + String name; - Address address; + Address address; - @ManyToMany - Set books; + @ManyToMany + Set books; } diff --git a/tooling/metamodel-generator/src/jakartaData/java/org/hibernate/processor/test/data/reactive/Book.java b/tooling/metamodel-generator/src/jakartaData/java/org/hibernate/processor/test/data/reactive/Book.java index 5446362d21..dff9a2d3b2 100644 --- a/tooling/metamodel-generator/src/jakartaData/java/org/hibernate/processor/test/data/reactive/Book.java +++ b/tooling/metamodel-generator/src/jakartaData/java/org/hibernate/processor/test/data/reactive/Book.java @@ -22,43 +22,43 @@ import java.util.Set; @Entity public class Book { - @Id - String isbn; + @Id + String isbn; - @NaturalId - String title; + @NaturalId + String title; - @NaturalId - LocalDate publicationDate; + @NaturalId + LocalDate publicationDate; - String text; + String text; - @Enumerated(EnumType.STRING) - @Basic(optional = false) + @Enumerated(EnumType.STRING) + @Basic(optional = false) Type type = Type.Book; - @ManyToOne(optional = false) + @ManyToOne(optional = false) Publisher publisher; - @ManyToMany(mappedBy = "books") - Set authors; + @ManyToMany(mappedBy = "books") + Set authors; - @Basic(optional = false) - int pages ; + @Basic(optional = false) + int pages ; - BigDecimal price; - BigInteger quantitySold; + BigDecimal price; + BigInteger quantitySold; - public Book(String isbn, String title, String text) { - this.isbn = isbn; - this.title = title; - this.text = text; - } + public Book(String isbn, String title, String text) { + this.isbn = isbn; + this.title = title; + this.text = text; + } - protected Book() {} + protected Book() {} - @Override - public String toString() { - return isbn + " : " + title + " [" + type + "]"; - } + @Override + public String toString() { + return isbn + " : " + title + " [" + type + "]"; + } } diff --git a/tooling/metamodel-generator/src/jakartaData/java/org/hibernate/processor/test/data/reactive/Publisher.java b/tooling/metamodel-generator/src/jakartaData/java/org/hibernate/processor/test/data/reactive/Publisher.java index c84e92cbe0..c748c6a661 100644 --- a/tooling/metamodel-generator/src/jakartaData/java/org/hibernate/processor/test/data/reactive/Publisher.java +++ b/tooling/metamodel-generator/src/jakartaData/java/org/hibernate/processor/test/data/reactive/Publisher.java @@ -15,11 +15,11 @@ import java.util.Set; @Entity public class Publisher { - @Id long id; + @Id long id; - @Basic(optional = false) - String name; + @Basic(optional = false) + String name; - @OneToMany(mappedBy = "publisher") - Set books; + @OneToMany(mappedBy = "publisher") + Set books; } diff --git a/tooling/metamodel-generator/src/jakartaData/java/org/hibernate/processor/test/data/superdao/Book.java b/tooling/metamodel-generator/src/jakartaData/java/org/hibernate/processor/test/data/superdao/Book.java index 031f8f37a4..305199dd4f 100644 --- a/tooling/metamodel-generator/src/jakartaData/java/org/hibernate/processor/test/data/superdao/Book.java +++ b/tooling/metamodel-generator/src/jakartaData/java/org/hibernate/processor/test/data/superdao/Book.java @@ -17,13 +17,13 @@ import java.time.LocalDate; @Entity public class Book { - @Id String isbn; - @NaturalId String title; - String text; - @NaturalId String authorName; - @ManyToOne + @Id String isbn; + @NaturalId String title; + String text; + @NaturalId String authorName; + @ManyToOne Publisher publisher; - BigDecimal price; - int pages; - LocalDate publicationDate; + BigDecimal price; + int pages; + LocalDate publicationDate; } diff --git a/tooling/metamodel-generator/src/jakartaData/java/org/hibernate/processor/test/data/superdao/Repo.java b/tooling/metamodel-generator/src/jakartaData/java/org/hibernate/processor/test/data/superdao/Repo.java index 7843b1fbcc..80996b6c78 100644 --- a/tooling/metamodel-generator/src/jakartaData/java/org/hibernate/processor/test/data/superdao/Repo.java +++ b/tooling/metamodel-generator/src/jakartaData/java/org/hibernate/processor/test/data/superdao/Repo.java @@ -11,6 +11,6 @@ import org.hibernate.annotations.processing.Find; @Repository public interface Repo extends SuperRepo { - @Find + @Find Book get(String isbn); } diff --git a/tooling/metamodel-generator/src/jakartaData/java/org/hibernate/processor/test/data/superdao/SuperRepo.java b/tooling/metamodel-generator/src/jakartaData/java/org/hibernate/processor/test/data/superdao/SuperRepo.java index 7ff3316e3a..1278cabd11 100644 --- a/tooling/metamodel-generator/src/jakartaData/java/org/hibernate/processor/test/data/superdao/SuperRepo.java +++ b/tooling/metamodel-generator/src/jakartaData/java/org/hibernate/processor/test/data/superdao/SuperRepo.java @@ -15,9 +15,9 @@ import java.util.List; @Repository public interface SuperRepo { - @Find - List books1(@Pattern String title); + @Find + List books1(@Pattern String title); - @HQL("where title like :title") - List books2(String title); + @HQL("where title like :title") + List books2(String title); } diff --git a/tooling/metamodel-generator/src/jakartaData/java/org/hibernate/processor/test/data/superdao/generic/Book.java b/tooling/metamodel-generator/src/jakartaData/java/org/hibernate/processor/test/data/superdao/generic/Book.java index 6d8303ee32..ba6cf5bf47 100644 --- a/tooling/metamodel-generator/src/jakartaData/java/org/hibernate/processor/test/data/superdao/generic/Book.java +++ b/tooling/metamodel-generator/src/jakartaData/java/org/hibernate/processor/test/data/superdao/generic/Book.java @@ -17,13 +17,13 @@ import java.time.LocalDate; @Entity public class Book { - @Id String isbn; - @NaturalId String title; - String text; - @NaturalId String authorName; - @ManyToOne + @Id String isbn; + @NaturalId String title; + String text; + @NaturalId String authorName; + @ManyToOne Publisher publisher; - BigDecimal price; - int pages; - LocalDate publicationDate; + BigDecimal price; + int pages; + LocalDate publicationDate; } diff --git a/tooling/metamodel-generator/src/jakartaData/java/org/hibernate/processor/test/data/superdao/generic/Repo.java b/tooling/metamodel-generator/src/jakartaData/java/org/hibernate/processor/test/data/superdao/generic/Repo.java index 6c180b7e16..c645c3d969 100644 --- a/tooling/metamodel-generator/src/jakartaData/java/org/hibernate/processor/test/data/superdao/generic/Repo.java +++ b/tooling/metamodel-generator/src/jakartaData/java/org/hibernate/processor/test/data/superdao/generic/Repo.java @@ -11,6 +11,6 @@ import org.hibernate.annotations.processing.Find; @Repository public interface Repo extends SuperRepo { - @Find + @Find Book get(String isbn); } diff --git a/tooling/metamodel-generator/src/jakartaData/java/org/hibernate/processor/test/data/superdao/generic/SuperRepo.java b/tooling/metamodel-generator/src/jakartaData/java/org/hibernate/processor/test/data/superdao/generic/SuperRepo.java index fe33a744df..f18abaa289 100644 --- a/tooling/metamodel-generator/src/jakartaData/java/org/hibernate/processor/test/data/superdao/generic/SuperRepo.java +++ b/tooling/metamodel-generator/src/jakartaData/java/org/hibernate/processor/test/data/superdao/generic/SuperRepo.java @@ -21,30 +21,30 @@ import java.util.stream.Stream; public interface SuperRepo { - @Save - S save(S entity); + @Save + S save(S entity); - @Save - List saveAll(List entities); + @Save + List saveAll(List entities); - @Find - Optional findById(@By("#id") K id); + @Find + Optional findById(@By("#id") K id); - @Find - Optional findById2(@By("id(this)") K id); + @Find + Optional findById2(@By("id(this)") K id); - @Find - Stream findAll(); + @Find + Stream findAll(); - @Find - Page findAll(PageRequest pageRequest, Order order); + @Find + Page findAll(PageRequest pageRequest, Order order); // @Delete // void deleteById(@By("#id") K id); - @Delete - void delete(T entity); + @Delete + void delete(T entity); - @Delete - void deleteAll(List entities); + @Delete + void deleteAll(List entities); } diff --git a/tooling/metamodel-generator/src/quarkusHrPanache/java/org/hibernate/processor/test/hrPanache/BookRepositoryWithSession.java b/tooling/metamodel-generator/src/quarkusHrPanache/java/org/hibernate/processor/test/hrPanache/BookRepositoryWithSession.java index 043a6bd67f..b39ef50ac3 100644 --- a/tooling/metamodel-generator/src/quarkusHrPanache/java/org/hibernate/processor/test/hrPanache/BookRepositoryWithSession.java +++ b/tooling/metamodel-generator/src/quarkusHrPanache/java/org/hibernate/processor/test/hrPanache/BookRepositoryWithSession.java @@ -20,6 +20,6 @@ public interface BookRepositoryWithSession { return SessionOperations.getSession(); } - @Find - public Uni> findBook(String isbn); + @Find + public Uni> findBook(String isbn); } diff --git a/tooling/metamodel-generator/src/quarkusHrPanache/java/org/hibernate/processor/test/hrPanache/PanacheBook.java b/tooling/metamodel-generator/src/quarkusHrPanache/java/org/hibernate/processor/test/hrPanache/PanacheBook.java index 188d62a9d0..9412da0292 100644 --- a/tooling/metamodel-generator/src/quarkusHrPanache/java/org/hibernate/processor/test/hrPanache/PanacheBook.java +++ b/tooling/metamodel-generator/src/quarkusHrPanache/java/org/hibernate/processor/test/hrPanache/PanacheBook.java @@ -19,14 +19,14 @@ import jakarta.persistence.Entity; @Entity public class PanacheBook extends PanacheEntity { public @NaturalId String isbn; - public @NaturalId String title; - public @NaturalId String author; - public String text; - public int pages; + public @NaturalId String title; + public @NaturalId String author; + public String text; + public int pages; - @Find - public static native Uni> findBook(String isbn); + @Find + public static native Uni> findBook(String isbn); - @HQL("WHERE isbn = :isbn") - public static native Uni> hqlBook(String isbn); + @HQL("WHERE isbn = :isbn") + public static native Uni> hqlBook(String isbn); } diff --git a/tooling/metamodel-generator/src/quarkusHrPanache/java/org/hibernate/processor/test/hrPanache/PanacheBookRepository.java b/tooling/metamodel-generator/src/quarkusHrPanache/java/org/hibernate/processor/test/hrPanache/PanacheBookRepository.java index aad33567fb..dfdfe37efc 100644 --- a/tooling/metamodel-generator/src/quarkusHrPanache/java/org/hibernate/processor/test/hrPanache/PanacheBookRepository.java +++ b/tooling/metamodel-generator/src/quarkusHrPanache/java/org/hibernate/processor/test/hrPanache/PanacheBookRepository.java @@ -17,9 +17,9 @@ import jakarta.enterprise.context.ApplicationScoped; @ApplicationScoped public class PanacheBookRepository implements PanacheRepository { - @Find - public native Uni> findBook(String isbn); + @Find + public native Uni> findBook(String isbn); - @HQL("WHERE isbn = :isbn") - public native Uni> hqlBook(String isbn); + @HQL("WHERE isbn = :isbn") + public native Uni> hqlBook(String isbn); } diff --git a/tooling/metamodel-generator/src/quarkusHrPanache/java/org/hibernate/processor/test/hrPanache/QuarkusBookRepository.java b/tooling/metamodel-generator/src/quarkusHrPanache/java/org/hibernate/processor/test/hrPanache/QuarkusBookRepository.java index cd394d1f74..77842451bc 100644 --- a/tooling/metamodel-generator/src/quarkusHrPanache/java/org/hibernate/processor/test/hrPanache/QuarkusBookRepository.java +++ b/tooling/metamodel-generator/src/quarkusHrPanache/java/org/hibernate/processor/test/hrPanache/QuarkusBookRepository.java @@ -14,15 +14,15 @@ import org.hibernate.annotations.processing.HQL; import io.smallrye.mutiny.Uni; public interface QuarkusBookRepository { - @Find - public Uni> findBook(String isbn); + @Find + public Uni> findBook(String isbn); - @HQL("WHERE isbn = :isbn") - public Uni> hqlBook(String isbn); + @HQL("WHERE isbn = :isbn") + public Uni> hqlBook(String isbn); - @HQL("DELETE FROM PanacheBook") - public Uni deleteAllBooksVoid(); + @HQL("DELETE FROM PanacheBook") + public Uni deleteAllBooksVoid(); - @HQL("DELETE FROM PanacheBook") - public Uni deleteAllBooksInt(); + @HQL("DELETE FROM PanacheBook") + public Uni deleteAllBooksInt(); } diff --git a/tooling/metamodel-generator/src/quarkusOrmPanache/java/org/hibernate/processor/test/ormPanache/PanacheBook.java b/tooling/metamodel-generator/src/quarkusOrmPanache/java/org/hibernate/processor/test/ormPanache/PanacheBook.java index 78e8a9497a..c4840337de 100644 --- a/tooling/metamodel-generator/src/quarkusOrmPanache/java/org/hibernate/processor/test/ormPanache/PanacheBook.java +++ b/tooling/metamodel-generator/src/quarkusOrmPanache/java/org/hibernate/processor/test/ormPanache/PanacheBook.java @@ -18,14 +18,14 @@ import jakarta.persistence.Entity; @Entity public class PanacheBook extends PanacheEntity { public @NaturalId String isbn; - public @NaturalId String title; - public @NaturalId String author; - public String text; - public int pages; + public @NaturalId String title; + public @NaturalId String author; + public String text; + public int pages; - @Find - public static native List findBook(String isbn); + @Find + public static native List findBook(String isbn); - @HQL("WHERE isbn = :isbn") - public static native List hqlBook(String isbn); + @HQL("WHERE isbn = :isbn") + public static native List hqlBook(String isbn); } diff --git a/tooling/metamodel-generator/src/quarkusOrmPanache/java/org/hibernate/processor/test/ormPanache/PanacheBookRepository.java b/tooling/metamodel-generator/src/quarkusOrmPanache/java/org/hibernate/processor/test/ormPanache/PanacheBookRepository.java index 8842345d44..d4d21c9b44 100644 --- a/tooling/metamodel-generator/src/quarkusOrmPanache/java/org/hibernate/processor/test/ormPanache/PanacheBookRepository.java +++ b/tooling/metamodel-generator/src/quarkusOrmPanache/java/org/hibernate/processor/test/ormPanache/PanacheBookRepository.java @@ -16,9 +16,9 @@ import jakarta.enterprise.context.ApplicationScoped; @ApplicationScoped public class PanacheBookRepository implements PanacheRepository { - @Find - public native List findBook(String isbn); + @Find + public native List findBook(String isbn); - @HQL("WHERE isbn = :isbn") - public native List hqlBook(String isbn); + @HQL("WHERE isbn = :isbn") + public native List hqlBook(String isbn); } diff --git a/tooling/metamodel-generator/src/quarkusOrmPanache/java/org/hibernate/processor/test/ormPanache/QuarkusBookRepository.java b/tooling/metamodel-generator/src/quarkusOrmPanache/java/org/hibernate/processor/test/ormPanache/QuarkusBookRepository.java index 42dc34053e..8192e77921 100644 --- a/tooling/metamodel-generator/src/quarkusOrmPanache/java/org/hibernate/processor/test/ormPanache/QuarkusBookRepository.java +++ b/tooling/metamodel-generator/src/quarkusOrmPanache/java/org/hibernate/processor/test/ormPanache/QuarkusBookRepository.java @@ -12,9 +12,9 @@ import org.hibernate.annotations.processing.Find; import org.hibernate.annotations.processing.HQL; public interface QuarkusBookRepository { - @Find - public List findBook(String isbn); + @Find + public List findBook(String isbn); - @HQL("WHERE isbn = :isbn") - public List hqlBook(String isbn); + @HQL("WHERE isbn = :isbn") + public List hqlBook(String isbn); } diff --git a/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/annotationtype/AnnotationTypeTest.java b/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/annotationtype/AnnotationTypeTest.java index c2a04a8823..283bf5a597 100644 --- a/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/annotationtype/AnnotationTypeTest.java +++ b/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/annotationtype/AnnotationTypeTest.java @@ -19,11 +19,11 @@ import org.junit.Test; @TestForIssue(jiraKey = "HHH-13145") public class AnnotationTypeTest extends CompilationTest { - @Test - @WithClasses({ Entity.class }) - @WithMappingFiles("orm.xml") - public void testXmlConfiguredEntityGenerated() { - TestUtil.assertMetamodelClassGeneratedFor( Entity.class ); - } + @Test + @WithClasses({ Entity.class }) + @WithMappingFiles("orm.xml") + public void testXmlConfiguredEntityGenerated() { + TestUtil.assertMetamodelClassGeneratedFor( Entity.class ); + } } diff --git a/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/annotationtype/Entity.java b/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/annotationtype/Entity.java index 7cd0f3dd44..3b09f9ff9a 100644 --- a/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/annotationtype/Entity.java +++ b/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/annotationtype/Entity.java @@ -16,32 +16,32 @@ import java.lang.annotation.Target; */ public class Entity { - private String id; + private String id; - private String name; + private String name; - public Entity(String id) { - this.id = id; - } + public Entity(String id) { + this.id = id; + } - public String getId() { - return id; - } + public String getId() { + return id; + } - public void setId(String id) { - this.id = id; - } + public void setId(String id) { + this.id = id; + } - public @Custom String getName() { - return name; - } + public @Custom String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - @Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.LOCAL_VARIABLE, ElementType.TYPE_USE}) - @Retention(RetentionPolicy.CLASS) - public static @interface Custom { - } + @Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.LOCAL_VARIABLE, ElementType.TYPE_USE}) + @Retention(RetentionPolicy.CLASS) + public static @interface Custom { + } } diff --git a/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/circulartypevariable/CircularTypeVariableTest.java b/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/circulartypevariable/CircularTypeVariableTest.java index a1e68a82fd..ed1c81a704 100644 --- a/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/circulartypevariable/CircularTypeVariableTest.java +++ b/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/circulartypevariable/CircularTypeVariableTest.java @@ -17,11 +17,11 @@ import org.junit.Test; @TestForIssue(jiraKey = "HHH-17253") public class CircularTypeVariableTest extends CompilationTest { - @Test - @WithClasses({ RoleAccess.class, User.class }) - public void testCircularTypeVariable() { - TestUtil.assertMetamodelClassGeneratedFor( RoleAccess.class ); - TestUtil.assertMetamodelClassGeneratedFor( User.class ); - } + @Test + @WithClasses({ RoleAccess.class, User.class }) + public void testCircularTypeVariable() { + TestUtil.assertMetamodelClassGeneratedFor( RoleAccess.class ); + TestUtil.assertMetamodelClassGeneratedFor( User.class ); + } } diff --git a/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/collectionbasictype/CommaDelimitedStringsJavaType.java b/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/collectionbasictype/CommaDelimitedStringsJavaType.java index 2867f1d9ef..0390bb6de1 100644 --- a/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/collectionbasictype/CommaDelimitedStringsJavaType.java +++ b/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/collectionbasictype/CommaDelimitedStringsJavaType.java @@ -20,39 +20,39 @@ import org.hibernate.type.descriptor.java.MutableMutabilityPlan; */ public class CommaDelimitedStringsJavaType extends AbstractClassJavaType { - public static final String DELIMITER = ","; + public static final String DELIMITER = ","; - public CommaDelimitedStringsJavaType() { - super( - List.class, - new MutableMutabilityPlan() { - @Override - protected List deepCopyNotNull(List value) { - return new ArrayList( value ); - } - } - ); - } + public CommaDelimitedStringsJavaType() { + super( + List.class, + new MutableMutabilityPlan() { + @Override + protected List deepCopyNotNull(List value) { + return new ArrayList( value ); + } + } + ); + } - @Override - public String toString(List value) { - return ( (List) value ).stream().collect( Collectors.joining( DELIMITER ) ); - } + @Override + public String toString(List value) { + return ( (List) value ).stream().collect( Collectors.joining( DELIMITER ) ); + } - @Override - public List fromString(CharSequence string) { - List values = new ArrayList<>(); - Collections.addAll( values, string.toString().split( DELIMITER ) ); - return values; - } + @Override + public List fromString(CharSequence string) { + List values = new ArrayList<>(); + Collections.addAll( values, string.toString().split( DELIMITER ) ); + return values; + } - @Override - public X unwrap(List value, Class type, WrapperOptions options) { - return (X) toString( value ); - } + @Override + public X unwrap(List value, Class type, WrapperOptions options) { + return (X) toString( value ); + } - @Override - public List wrap(X value, WrapperOptions options) { - return fromString( (String) value ); - } + @Override + public List wrap(X value, WrapperOptions options) { + return fromString( (String) value ); + } } diff --git a/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/collectionbasictype/CommaDelimitedStringsMapType.java b/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/collectionbasictype/CommaDelimitedStringsMapType.java index f040eb1d03..2e70d293a5 100644 --- a/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/collectionbasictype/CommaDelimitedStringsMapType.java +++ b/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/collectionbasictype/CommaDelimitedStringsMapType.java @@ -19,33 +19,33 @@ import org.hibernate.usertype.StaticUserTypeSupport; * @author Vlad Mihalcea */ public class CommaDelimitedStringsMapType extends StaticUserTypeSupport> { - public CommaDelimitedStringsMapType() { - super( - new CommaDelimitedStringMapJavaType(), - VarcharJdbcType.INSTANCE - ); - } + public CommaDelimitedStringsMapType() { + super( + new CommaDelimitedStringMapJavaType(), + VarcharJdbcType.INSTANCE + ); + } - @Override - public CommaDelimitedStringMapJavaType getJavaType() { - return (CommaDelimitedStringMapJavaType) super.getJavaType(); - } + @Override + public CommaDelimitedStringMapJavaType getJavaType() { + return (CommaDelimitedStringMapJavaType) super.getJavaType(); + } - @Override - public Map nullSafeGet(ResultSet rs, int position, SharedSessionContractImplementor session) - throws SQLException { - final Object extracted = getJdbcValueExtractor().extract( rs, position, session ); - if ( extracted == null ) { - return null; - } + @Override + public Map nullSafeGet(ResultSet rs, int position, SharedSessionContractImplementor session) + throws SQLException { + final Object extracted = getJdbcValueExtractor().extract( rs, position, session ); + if ( extracted == null ) { + return null; + } - return getJavaType().fromString( (String) extracted ); - } + return getJavaType().fromString( (String) extracted ); + } - @Override - public void nullSafeSet(PreparedStatement st, Map value, int index, SharedSessionContractImplementor session) - throws SQLException { - final String stringValue = getJavaType().toString( value ); - getJdbcValueBinder().bind( st, stringValue, index, session ); - } + @Override + public void nullSafeSet(PreparedStatement st, Map value, int index, SharedSessionContractImplementor session) + throws SQLException { + final String stringValue = getJavaType().toString( value ); + getJdbcValueBinder().bind( st, stringValue, index, session ); + } } diff --git a/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/collectionbasictype/CommaDelimitedStringsType.java b/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/collectionbasictype/CommaDelimitedStringsType.java index e674f6b880..3ccb9653b3 100644 --- a/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/collectionbasictype/CommaDelimitedStringsType.java +++ b/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/collectionbasictype/CommaDelimitedStringsType.java @@ -15,7 +15,7 @@ import org.hibernate.usertype.UserTypeSupport; * @author Vlad Mihalcea */ public class CommaDelimitedStringsType extends UserTypeSupport> { - public CommaDelimitedStringsType() { - super( List.class, Types.VARCHAR ); - } + public CommaDelimitedStringsType() { + super( List.class, Types.VARCHAR ); + } } diff --git a/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/collectionbasictype/Goods.java b/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/collectionbasictype/Goods.java index 1dd7854607..da32fbce11 100644 --- a/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/collectionbasictype/Goods.java +++ b/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/collectionbasictype/Goods.java @@ -18,35 +18,35 @@ import java.util.List; */ @Entity public class Goods { - private Long id; - private List productList; - private List tags; + private Long id; + private List productList; + private List tags; - @Id - public Long getId() { - return id; - } + @Id + public Long getId() { + return id; + } - public void setId(Long id) { - this.id = id; - } + public void setId(Long id) { + this.id = id; + } - @OneToMany - public List getProductList() { - return productList; - } + @OneToMany + public List getProductList() { + return productList; + } - public void setProductList(List productList) { - this.productList = productList; - } + public void setProductList(List productList) { + this.productList = productList; + } - @NotNull - @Convert(converter = StringToListConverter.class) - public List getTags() { - return tags; - } + @NotNull + @Convert(converter = StringToListConverter.class) + public List getTags() { + return tags; + } - public void setTags(List tags) { - this.tags = tags; - } + public void setTags(List tags) { + this.tags = tags; + } } diff --git a/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/collectionbasictype/Product.java b/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/collectionbasictype/Product.java index 8b41aaf3da..c531acebc9 100644 --- a/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/collectionbasictype/Product.java +++ b/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/collectionbasictype/Product.java @@ -14,23 +14,23 @@ import jakarta.persistence.Id; */ @Entity public class Product { - private int proId; - private String proName; + private int proId; + private String proName; - @Id - public int getProId() { - return proId; - } + @Id + public int getProId() { + return proId; + } - public void setProId(int proId) { - this.proId = proId; - } + public void setProId(int proId) { + this.proId = proId; + } - public String getProName() { - return proName; - } + public String getProName() { + return proName; + } - public void setProName(String proName) { - this.proName = proName; - } + public void setProName(String proName) { + this.proName = proName; + } } diff --git a/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/collectionbasictype/StringToListConverter.java b/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/collectionbasictype/StringToListConverter.java index 0678f24109..581f38b108 100644 --- a/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/collectionbasictype/StringToListConverter.java +++ b/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/collectionbasictype/StringToListConverter.java @@ -15,21 +15,21 @@ import java.util.stream.Collectors; * @author helloztt */ public class StringToListConverter implements AttributeConverter, String> { - private static final String COMMA = ","; + private static final String COMMA = ","; - @Override - public String convertToDatabaseColumn(List attribute) { - if (attribute == null || attribute.size() == 0) { - return null; - } - return attribute.stream().collect(Collectors.joining(COMMA)); - } + @Override + public String convertToDatabaseColumn(List attribute) { + if (attribute == null || attribute.size() == 0) { + return null; + } + return attribute.stream().collect(Collectors.joining(COMMA)); + } - @Override - public List convertToEntityAttribute(String dbData) { - if (dbData == null || dbData.length() == 0) { - return null; - } - return Arrays.asList(dbData.split(COMMA)); - } + @Override + public List convertToEntityAttribute(String dbData) { + if (dbData == null || dbData.length() == 0) { + return null; + } + return Arrays.asList(dbData.split(COMMA)); + } } diff --git a/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/dao/Bean.java b/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/dao/Bean.java index 402659b228..00e59caa95 100644 --- a/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/dao/Bean.java +++ b/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/dao/Bean.java @@ -11,11 +11,11 @@ import jakarta.persistence.Id; @Entity public class Bean { - @Id - public Long getKey() { - return 69L; - } - public String getText() { - return "Hello World"; - } + @Id + public Long getKey() { + return 69L; + } + public String getText() { + return "Hello World"; + } } diff --git a/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/dao/Book.java b/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/dao/Book.java index 01a979f907..3fb3533d3d 100644 --- a/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/dao/Book.java +++ b/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/dao/Book.java @@ -12,12 +12,12 @@ import org.hibernate.annotations.NaturalId; @Entity public class Book { - @Id String isbn; - @NaturalId String title; - @NaturalId String author; - String text; - int pages; - Type type; + @Id String isbn; + @NaturalId String title; + @NaturalId String author; + String text; + int pages; + Type type; - enum Type { Book, Magazine, Journal } + enum Type { Book, Magazine, Journal } } diff --git a/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/dao/Dao.java b/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/dao/Dao.java index b0a760ccb4..48d4d8faa6 100644 --- a/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/dao/Dao.java +++ b/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/dao/Dao.java @@ -26,67 +26,67 @@ import java.util.stream.Stream; public interface Dao { - EntityManager getEntityManager(); + EntityManager getEntityManager(); - @Find - Book getBook(String isbn); + @Find + Book getBook(String isbn); - @Find - Book[] getBooks(String[] isbn); + @Find + Book[] getBooks(String[] isbn); - @Find - List getBooks(List isbn); + @Find + List getBooks(List isbn); - @Find - Optional getBookIfAny(String isbn); + @Find + Optional getBookIfAny(String isbn); - @Find(enabledFetchProfiles="Goodbye") - Book getBookFetching(String isbn); + @Find(enabledFetchProfiles="Goodbye") + Book getBookFetching(String isbn); - @Find - Book getBook(@Pattern String title, String author); + @Find + Book getBook(@Pattern String title, String author); - @Find(enabledFetchProfiles="Hello") - Book getBookFetching(String title, String author); + @Find(enabledFetchProfiles="Hello") + Book getBookFetching(String title, String author); - @Find - Book getBook(String title, String isbn, String author); + @Find + Book getBook(String title, String isbn, String author); - @Find - List getBooks(String title); + @Find + List getBooks(String title); - @Find(enabledFetchProfiles="Hello") - List getBooksFetching(String title); + @Find(enabledFetchProfiles="Hello") + List getBooksFetching(String title); - @Find - List getBooks(String title, Page page, Order order); + @Find + List getBooks(String title, Page page, Order order); - @Find - SelectionQuery createBooksSelectionQuery(String title); + @Find + SelectionQuery createBooksSelectionQuery(String title); - @HQL("where isbn in ?1") - List booksGivenIsbnList(List isbns); + @HQL("where isbn in ?1") + List booksGivenIsbnList(List isbns); - @HQL("where isbn in :isbns") - List booksGivenIsbnSet(Set isbns); + @HQL("where isbn in :isbns") + List booksGivenIsbnSet(Set isbns); - @HQL("where isbn in :isbns") - List booksGivenIsbnCollection(Collection isbns); + @HQL("where isbn in :isbns") + List booksGivenIsbnCollection(Collection isbns); - @HQL("where title like ?1") - List findBooksByTitle(String title); + @HQL("where title like ?1") + List findBooksByTitle(String title); - @HQL("where title like ?1") - Stream streamBooksByTitle(String title); + @HQL("where title like ?1") + Stream streamBooksByTitle(String title); - @HQL("from Book where title like ?1") - TypedQuery findByTitle(String title); + @HQL("from Book where title like ?1") + TypedQuery findByTitle(String title); - @HQL("from Book where title like ?1") - SelectionQuery findByTitleSelectionQuery(String title); + @HQL("from Book where title like ?1") + SelectionQuery findByTitleSelectionQuery(String title); - @HQL("from Book where title like ?1 order by title fetch first ?2 rows only") - List findFirstNByTitle(String title, int N); + @HQL("from Book where title like ?1 order by title fetch first ?2 rows only") + List findFirstNByTitle(String title, int N); // // @HQL("from Book where title like :title") // List findByTitleWithPagination(String title, Order order, Page page); @@ -97,63 +97,63 @@ public interface Dao { // @HQL("from Book where title like :title") // SelectionQuery findByTitleWithOrderingByVarargs(String title, Order... order); - @HQL("select count(*) from Book") - long countBooks(); + @HQL("select count(*) from Book") + long countBooks(); - @HQL("select count(*)>1 from Book") - boolean booksExist(); + @HQL("select count(*)>1 from Book") + boolean booksExist(); - @HQL("delete from Book") - int deleteBooks(); + @HQL("delete from Book") + int deleteBooks(); - @HQL("delete from Book book where book.isbn=:isbn") - boolean deleteBook(String isbn); + @HQL("delete from Book book where book.isbn=:isbn") + boolean deleteBook(String isbn); - @HQL("select count(*), count(*)>1 from Book") - Object[] funnyQueryReturningArray(); + @HQL("select count(*), count(*)>1 from Book") + Object[] funnyQueryReturningArray(); - class Record { - Record(Long count, Boolean exists) {} - } - @HQL("select count(*), count(*)>1 from Book") - Record funnyQueryReturningRecord(); + class Record { + Record(Long count, Boolean exists) {} + } + @HQL("select count(*), count(*)>1 from Book") + Record funnyQueryReturningRecord(); - @HQL("from Book where isbn = :isbn") - Book findByIsbn(String isbn); + @HQL("from Book where isbn = :isbn") + Book findByIsbn(String isbn); - @HQL("from Book where isbn = :isbn") - Optional findByIsbnIfExists(String isbn); + @HQL("from Book where isbn = :isbn") + Optional findByIsbnIfExists(String isbn); - @SQL("select * from Book where isbn = :isbn") - Book findByIsbnNative(String isbn); + @SQL("select * from Book where isbn = :isbn") + Book findByIsbnNative(String isbn); - @Find - Bean beanByIdProperty(Long key); + @Find + Bean beanByIdProperty(Long key); - @Find - List beansForText(String text); + @Find + List beansForText(String text); - @Find - Bean[] beansAsArray(String text); + @Find + Bean[] beansAsArray(String text); - @HQL("where isbn = ?1") - List sortedBooksForIsbn(String isbn, Order... order); + @HQL("where isbn = ?1") + List sortedBooksForIsbn(String isbn, Order... order); - @Find - List sortedBooks(String isbn, Order... order); + @Find + List sortedBooks(String isbn, Order... order); - @HQL("select local date") - LocalDate localDate(); + @HQL("select local date") + LocalDate localDate(); - @HQL("select local datetime") - LocalDateTime localDatetime(); + @HQL("select local datetime") + LocalDateTime localDatetime(); - @HQL("select avg(pages) from Book") - double averagePageCount(); + @HQL("select avg(pages) from Book") + double averagePageCount(); - @HQL("select b\nfrom Book b\nwhere b.isbn = :isbn") - Book findByIsbnMultiline(String isbn); + @HQL("select b\nfrom Book b\nwhere b.isbn = :isbn") + Book findByIsbnMultiline(String isbn); - @HQL("from Book b where b.type = Magazine") - List findMagazines(); + @HQL("from Book b where b.type = Magazine") + List findMagazines(); } diff --git a/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/dao/Dao2.java b/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/dao/Dao2.java index e007fb3a32..4c265bd9ff 100644 --- a/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/dao/Dao2.java +++ b/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/dao/Dao2.java @@ -14,21 +14,21 @@ import jakarta.persistence.EntityManager; public interface Dao2 { - EntityManager getEntityManager(); + EntityManager getEntityManager(); - // Simple name - @HQL("from Book b where b.type = Magazine") - List findMagazines1(); + // Simple name + @HQL("from Book b where b.type = Magazine") + List findMagazines1(); - // Simple qualified name - @HQL("from Book b where b.type = Type.Magazine") - List findMagazines2(); + // Simple qualified name + @HQL("from Book b where b.type = Type.Magazine") + List findMagazines2(); - // Canonical FQN - @HQL("from Book b where b.type = org.hibernate.processor.test.dao.Book.Type.Magazine") - List findMagazines3(); + // Canonical FQN + @HQL("from Book b where b.type = org.hibernate.processor.test.dao.Book.Type.Magazine") + List findMagazines3(); - // Binary FQN - @HQL("from Book b where b.type = org.hibernate.processor.test.dao.Book$Type.Magazine") - List findMagazines4(); + // Binary FQN + @HQL("from Book b where b.type = org.hibernate.processor.test.dao.Book$Type.Magazine") + List findMagazines4(); } diff --git a/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/dao/StatefulDao.java b/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/dao/StatefulDao.java index f69ba56327..caf5097ef7 100644 --- a/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/dao/StatefulDao.java +++ b/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/dao/StatefulDao.java @@ -19,49 +19,49 @@ import java.util.Optional; public interface StatefulDao { - Session getSession(); + Session getSession(); - @Find - Book getBook(String isbn); + @Find + Book getBook(String isbn); - @Find @Nullable - Book getBookOrNull(String isbn); + @Find @Nullable + Book getBookOrNull(String isbn); - @Find - Optional getBookMaybe(String isbn); + @Find + Optional getBookMaybe(String isbn); - @Find(enabledFetchProfiles="Goodbye") - Book getBookFetching(String isbn); + @Find(enabledFetchProfiles="Goodbye") + Book getBookFetching(String isbn); - @Find - Book getBook(String title, String author); + @Find + Book getBook(String title, String author); - @Find - Optional getBookMaybe(String title, String author); + @Find + Optional getBookMaybe(String title, String author); - @Find(enabledFetchProfiles="Hello") - Book getBookFetching(String title, String author); + @Find(enabledFetchProfiles="Hello") + Book getBookFetching(String title, String author); - @Find - Book getBook(String title, String isbn, String author); + @Find + Book getBook(String title, String isbn, String author); - @Find - List getBooks(String title); + @Find + List getBooks(String title); - @Find(enabledFetchProfiles="Hello") - List getBooksFetching(String title); + @Find(enabledFetchProfiles="Hello") + List getBooksFetching(String title); - @Find - SelectionQuery createBooksSelectionQuery(String title); + @Find + SelectionQuery createBooksSelectionQuery(String title); - @HQL("from Book where title like ?1") - TypedQuery findByTitle(String title); + @HQL("from Book where title like ?1") + TypedQuery findByTitle(String title); - @HQL("from Book where title like ?1") - SelectionQuery findByTitleSelectionQuery(String title); + @HQL("from Book where title like ?1") + SelectionQuery findByTitleSelectionQuery(String title); - @HQL("from Book where title like ?1 order by title fetch first ?2 rows only") - List findFirstNByTitle(String title, int N); + @HQL("from Book where title like ?1 order by title fetch first ?2 rows only") + List findFirstNByTitle(String title, int N); // // @HQL("from Book where title like :title") // List findByTitleWithPagination(String title, Order order, Page page); @@ -72,9 +72,9 @@ public interface StatefulDao { // @HQL("from Book where title like :title") // SelectionQuery findByTitleWithOrderingByVarargs(String title, Order... order); - @HQL("from Book where isbn = :isbn") - Book findByIsbn(String isbn); + @HQL("from Book where isbn = :isbn") + Book findByIsbn(String isbn); - @SQL("select * from Book where isbn = :isbn") - Book findByIsbnNative(String isbn); + @SQL("select * from Book where isbn = :isbn") + Book findByIsbnNative(String isbn); } diff --git a/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/dao/StatelessDao.java b/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/dao/StatelessDao.java index e99fcaa78e..1842e6146c 100644 --- a/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/dao/StatelessDao.java +++ b/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/dao/StatelessDao.java @@ -19,49 +19,49 @@ import java.util.Optional; public interface StatelessDao { - StatelessSession getSession(); + StatelessSession getSession(); - @Find - Book getBook(String isbn); + @Find + Book getBook(String isbn); - @Find - Optional getBookMaybe(String isbn); + @Find + Optional getBookMaybe(String isbn); - @Find(enabledFetchProfiles="Goodbye") - Book getBookFetching(String isbn); + @Find(enabledFetchProfiles="Goodbye") + Book getBookFetching(String isbn); - @Find - Book getBook(String title, String author); + @Find + Book getBook(String title, String author); - @Find @Nullable - Book getBookOrNull(String isbn); + @Find @Nullable + Book getBookOrNull(String isbn); - @Find - Optional getBookMaybe(String title, String author); + @Find + Optional getBookMaybe(String title, String author); - @Find(enabledFetchProfiles="Hello") - Book getBookFetching(String title, String author); + @Find(enabledFetchProfiles="Hello") + Book getBookFetching(String title, String author); - @Find - Book getBook(String title, String isbn, String author); + @Find + Book getBook(String title, String isbn, String author); - @Find - List getBooks(String title); + @Find + List getBooks(String title); - @Find(enabledFetchProfiles="Hello") - List getBooksFetching(String title); + @Find(enabledFetchProfiles="Hello") + List getBooksFetching(String title); - @Find - SelectionQuery createBooksSelectionQuery(String title); + @Find + SelectionQuery createBooksSelectionQuery(String title); - @HQL("from Book where title like ?1") - TypedQuery findByTitle(String title); + @HQL("from Book where title like ?1") + TypedQuery findByTitle(String title); - @HQL("from Book where title like ?1") - SelectionQuery findByTitleSelectionQuery(String title); + @HQL("from Book where title like ?1") + SelectionQuery findByTitleSelectionQuery(String title); - @HQL("from Book where title like ?1 order by title fetch first ?2 rows only") - List findFirstNByTitle(String title, int N); + @HQL("from Book where title like ?1 order by title fetch first ?2 rows only") + List findFirstNByTitle(String title, int N); // // @HQL("from Book where title like :title") // List findByTitleWithPagination(String title, Order order, Page page); @@ -72,9 +72,9 @@ public interface StatelessDao { // @HQL("from Book where title like :title") // SelectionQuery findByTitleWithOrderingByVarargs(String title, Order... order); - @HQL("from Book where isbn = :isbn") - Book findByIsbn(String isbn); + @HQL("from Book where isbn = :isbn") + Book findByIsbn(String isbn); - @SQL("select * from Book where isbn = :isbn") - Book findByIsbnNative(String isbn); + @SQL("select * from Book where isbn = :isbn") + Book findByIsbnNative(String isbn); } diff --git a/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/elementcollection/Homework.java b/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/elementcollection/Homework.java index e5f8b190b7..65ecb8fc47 100644 --- a/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/elementcollection/Homework.java +++ b/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/elementcollection/Homework.java @@ -20,45 +20,45 @@ import jakarta.persistence.Id; @Entity public class Homework { - private long id; - private List paths; + private long id; + private List paths; - @Id - public long getId() { - return id; - } + @Id + public long getId() { + return id; + } - @ElementCollection - public List getPaths() { - return paths; - } + @ElementCollection + public List getPaths() { + return paths; + } - public Set getPaths(String startPath) { - TreeSet result = new TreeSet<>(); + public Set getPaths(String startPath) { + TreeSet result = new TreeSet<>(); - if ( paths == null ) { - return result; - } + if ( paths == null ) { + return result; + } - for ( String path : paths ) { - if ( path.startsWith( startPath ) ) { - result.add( path ); - } - } - return result; - } + for ( String path : paths ) { + if ( path.startsWith( startPath ) ) { + result.add( path ); + } + } + return result; + } - public void setPaths(List paths) { - this.paths = paths; - } + public void setPaths(List paths) { + this.paths = paths; + } - public Homework setPaths(List paths, boolean append) { - if ( append ) { - this.paths.addAll( paths ); - } - else { - this.paths = paths; - } - return this; - } + public Homework setPaths(List paths, boolean append) { + if ( append ) { + this.paths.addAll( paths ); + } + else { + this.paths = paths; + } + return this; + } } diff --git a/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/embeddable/nested/field/Author.java b/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/embeddable/nested/field/Author.java index 012709d1f1..c37e14e50f 100644 --- a/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/embeddable/nested/field/Author.java +++ b/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/embeddable/nested/field/Author.java @@ -12,13 +12,13 @@ import jakarta.persistence.Id; @Entity public class Author { - @Id - String ssn; + @Id + String ssn; - @Basic(optional = false) - String name; + @Basic(optional = false) + String name; - Address address; + Address address; - Boolean deceased; + Boolean deceased; } diff --git a/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/embeddable/nested/property/Author.java b/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/embeddable/nested/property/Author.java index 24e2a07a7b..6d498fde45 100644 --- a/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/embeddable/nested/property/Author.java +++ b/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/embeddable/nested/property/Author.java @@ -12,45 +12,45 @@ import jakarta.persistence.Id; @Entity public class Author { - String ssn; + String ssn; - String name; + String name; - Address address; + Address address; - Boolean deceased; + Boolean deceased; - @Id - public String getSsn() { - return ssn; - } + @Id + public String getSsn() { + return ssn; + } - public void setSsn(String ssn) { - this.ssn = ssn; - } + public void setSsn(String ssn) { + this.ssn = ssn; + } - @Basic(optional = false) - public String getName() { - return name; - } + @Basic(optional = false) + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - public Address getAddress() { - return address; - } + public Address getAddress() { + return address; + } - public void setAddress(Address address) { - this.address = address; - } + public void setAddress(Address address) { + this.address = address; + } - public Boolean getDeceased() { - return deceased; - } + public Boolean getDeceased() { + return deceased; + } - public void setDeceased(Boolean deceased) { - this.deceased = deceased; - } + public void setDeceased(Boolean deceased) { + this.deceased = deceased; + } } diff --git a/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/fromcore/BaseEmbeddedEntity.java b/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/fromcore/BaseEmbeddedEntity.java index 42e38f4db8..e604d511d4 100644 --- a/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/fromcore/BaseEmbeddedEntity.java +++ b/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/fromcore/BaseEmbeddedEntity.java @@ -17,46 +17,46 @@ import java.io.Serializable; @MappedSuperclass public abstract class BaseEmbeddedEntity implements Serializable { - private I id; + private I id; - public BaseEmbeddedEntity() { - } + public BaseEmbeddedEntity() { + } - public BaseEmbeddedEntity(I id) { - this.id = id; - } + public BaseEmbeddedEntity(I id) { + this.id = id; + } - @EmbeddedId - public I getId() { - return id; - } + @EmbeddedId + public I getId() { + return id; + } - public void setId(I id) { - this.id = id; - } + public void setId(I id) { + this.id = id; + } - @Override - public int hashCode() { - int hash = 3; - hash = 47 * hash + (this.id != null ? this.id.hashCode() : 0); - return hash; - } + @Override + public int hashCode() { + int hash = 3; + hash = 47 * hash + (this.id != null ? this.id.hashCode() : 0); + return hash; + } - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - final BaseEmbeddedEntity other = (BaseEmbeddedEntity) obj; - if (this.id != other.id && (this.id == null || !this.id.equals(other.id))) { - return false; - } - return true; - } + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final BaseEmbeddedEntity other = (BaseEmbeddedEntity) obj; + if (this.id != other.id && (this.id == null || !this.id.equals(other.id))) { + return false; + } + return true; + } } diff --git a/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/fromcore/Person.java b/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/fromcore/Person.java index 0d5a870103..5e4f8cdab1 100644 --- a/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/fromcore/Person.java +++ b/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/fromcore/Person.java @@ -14,31 +14,31 @@ import jakarta.persistence.Entity; @Entity public class Person extends BaseEmbeddedEntity { - private String firstName; - private String lastName; + private String firstName; + private String lastName; - public Person() { - } + public Person() { + } - public Person(PersonId id, String firstName, String lastName) { - super(id); - this.firstName = firstName; - this.lastName = lastName; - } + public Person(PersonId id, String firstName, String lastName) { + super(id); + this.firstName = firstName; + this.lastName = lastName; + } - public String getFirstName() { - return firstName; - } + public String getFirstName() { + return firstName; + } - public void setFirstName(String firstName) { - this.firstName = firstName; - } + public void setFirstName(String firstName) { + this.firstName = firstName; + } - public String getLastName() { - return lastName; - } + public String getLastName() { + return lastName; + } - public void setLastName(String lastName) { - this.lastName = lastName; - } + public void setLastName(String lastName) { + this.lastName = lastName; + } } diff --git a/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/fromcore/PersonId.java b/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/fromcore/PersonId.java index 65692e7fd6..139c477974 100644 --- a/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/fromcore/PersonId.java +++ b/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/fromcore/PersonId.java @@ -16,59 +16,59 @@ import java.io.Serializable; @Embeddable public class PersonId implements Serializable { - private String ssn; - private String name; + private String ssn; + private String name; - public PersonId() { - } + public PersonId() { + } - public PersonId(String ssn, String name) { - this.ssn = ssn; - this.name = name; - } + public PersonId(String ssn, String name) { + this.ssn = ssn; + this.name = name; + } - public String getSsn() { - return ssn; - } + public String getSsn() { + return ssn; + } - public void setSsn(String ssn) { - this.ssn = ssn; - } + public void setSsn(String ssn) { + this.ssn = ssn; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - @Override - public int hashCode() { - int hash = 7; - hash = 67 * hash + (this.ssn != null ? this.ssn.hashCode() : 0); - hash = 67 * hash + (this.name != null ? this.name.hashCode() : 0); - return hash; - } + @Override + public int hashCode() { + int hash = 7; + hash = 67 * hash + (this.ssn != null ? this.ssn.hashCode() : 0); + hash = 67 * hash + (this.name != null ? this.name.hashCode() : 0); + return hash; + } - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - final PersonId other = (PersonId) obj; - if ((this.ssn == null) ? (other.ssn != null) : !this.ssn.equals(other.ssn)) { - return false; - } - if ((this.name == null) ? (other.name != null) : !this.name.equals(other.name)) { - return false; - } - return true; - } + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final PersonId other = (PersonId) obj; + if ((this.ssn == null) ? (other.ssn != null) : !this.ssn.equals(other.ssn)) { + return false; + } + if ((this.name == null) ? (other.name != null) : !this.name.equals(other.name)) { + return false; + } + return true; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } } diff --git a/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/fromcore/ShelfLife.java b/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/fromcore/ShelfLife.java index 21d22f213c..dd24807ba6 100644 --- a/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/fromcore/ShelfLife.java +++ b/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/fromcore/ShelfLife.java @@ -13,8 +13,8 @@ import java.sql.Date; @Embeddable public class ShelfLife implements java.io.Serializable { - private Date inceptionDate; - private Date soldDate; + private Date inceptionDate; + private Date soldDate; public ShelfLife() { } diff --git a/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/generictype/Generic.java b/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/generictype/Generic.java index f2ac6f2a4e..e7b8c901a3 100644 --- a/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/generictype/Generic.java +++ b/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/generictype/Generic.java @@ -15,10 +15,10 @@ import java.util.Set; @Entity public class Generic { - @Id Long id; - @ManyToOne Generic parent; - @OneToMany Set> children; - @ElementCollection List list; - @ElementCollection Map map; - @ManyToAny Set set; + @Id Long id; + @ManyToOne Generic parent; + @OneToMany Set> children; + @ElementCollection List list; + @ElementCollection Map map; + @ManyToAny Set set; } diff --git a/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/hhh17661/Entity.java b/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/hhh17661/Entity.java index c855fd2b2b..cb4b353a40 100644 --- a/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/hhh17661/Entity.java +++ b/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/hhh17661/Entity.java @@ -14,7 +14,7 @@ import java.io.Serializable; @MappedSuperclass public abstract class Entity implements Serializable { - @Id - private Long id; + @Id + private Long id; } diff --git a/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/hhh17661/Tree.java b/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/hhh17661/Tree.java index 486e5c1e68..28d24b13d9 100644 --- a/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/hhh17661/Tree.java +++ b/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/hhh17661/Tree.java @@ -18,12 +18,12 @@ import java.util.Set; @MappedSuperclass public abstract class Tree, TR extends TreeRelation> extends Entity { - @ManyToOne(fetch = FetchType.LAZY) - private T parent; + @ManyToOne(fetch = FetchType.LAZY) + private T parent; - @OneToMany(mappedBy = "parent") - private Set childRelation = new HashSet<>(); + @OneToMany(mappedBy = "parent") + private Set childRelation = new HashSet<>(); - @OneToMany(mappedBy = "child", cascade = {CascadeType.ALL}, orphanRemoval = true) - private Set parentRelation = new HashSet<>(); + @OneToMany(mappedBy = "child", cascade = {CascadeType.ALL}, orphanRemoval = true) + private Set parentRelation = new HashSet<>(); } diff --git a/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/hhh17661/TreeRelation.java b/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/hhh17661/TreeRelation.java index 016b124dcd..cabb537fe8 100644 --- a/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/hhh17661/TreeRelation.java +++ b/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/hhh17661/TreeRelation.java @@ -12,9 +12,9 @@ import jakarta.persistence.MappedSuperclass; @MappedSuperclass public abstract class TreeRelation>> extends Entity { - @ManyToOne(optional = false) - private T parent; + @ManyToOne(optional = false) + private T parent; - @ManyToOne(optional = false) - private T child; + @ManyToOne(optional = false) + private T child; } diff --git a/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/hqlsql/Address.java b/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/hqlsql/Address.java index a874a36933..2847c5a53c 100644 --- a/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/hqlsql/Address.java +++ b/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/hqlsql/Address.java @@ -12,50 +12,50 @@ import java.util.Objects; @Embeddable public final class Address { - private String street; - private String city; - private String zip; + private String street; + private String city; + private String zip; - public Address(String street, String city, String zip) { - this.street = street; - this.city = city; - this.zip = zip; - } + public Address(String street, String city, String zip) { + this.street = street; + this.city = city; + this.zip = zip; + } - Address() {} + Address() {} - public String street() { - return street; - } + public String street() { + return street; + } - public String city() { - return city; - } + public String city() { + return city; + } - public String zip() { - return zip; - } + public String zip() { + return zip; + } - @Override - public boolean equals(Object obj) { - if (obj == this) return true; - if (obj == null || obj.getClass() != this.getClass()) return false; - var that = (Address) obj; - return Objects.equals(this.street, that.street) && - Objects.equals(this.city, that.city) && - Objects.equals(this.zip, that.zip); - } + @Override + public boolean equals(Object obj) { + if (obj == this) return true; + if (obj == null || obj.getClass() != this.getClass()) return false; + var that = (Address) obj; + return Objects.equals(this.street, that.street) && + Objects.equals(this.city, that.city) && + Objects.equals(this.zip, that.zip); + } - @Override - public int hashCode() { - return Objects.hash(street, city, zip); - } + @Override + public int hashCode() { + return Objects.hash(street, city, zip); + } - @Override - public String toString() { - return "Address[" + - "street=" + street + ", " + - "city=" + city + ", " + - "zip=" + zip + ']'; - } + @Override + public String toString() { + return "Address[" + + "street=" + street + ", " + + "city=" + city + ", " + + "zip=" + zip + ']'; + } } diff --git a/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/hqlsql/Book.java b/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/hqlsql/Book.java index 016e0e067b..404a96b80a 100644 --- a/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/hqlsql/Book.java +++ b/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/hqlsql/Book.java @@ -16,12 +16,12 @@ import java.time.LocalDate; @Entity public class Book { - @Id String isbn; - @NaturalId String title; - String text; - @NaturalId String authorName; - @ManyToOne Publisher publisher; - BigDecimal price; - int pages; - LocalDate publicationDate; + @Id String isbn; + @NaturalId String title; + String text; + @NaturalId String authorName; + @ManyToOne Publisher publisher; + BigDecimal price; + int pages; + LocalDate publicationDate; } diff --git a/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/hqlsql/Books.java b/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/hqlsql/Books.java index b5efc6751a..001a6dfa0e 100644 --- a/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/hqlsql/Books.java +++ b/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/hqlsql/Books.java @@ -17,26 +17,26 @@ import org.hibernate.query.Order; import java.util.List; public abstract class Books { - @Find - abstract Book getBook(EntityManager entityManager, String isbn); + @Find + abstract Book getBook(EntityManager entityManager, String isbn); - @Find - abstract Book getBook(StatelessSession session, String title, String isbn); + @Find + abstract Book getBook(StatelessSession session, String title, String isbn); - @Find - abstract Book getBookByNaturalKey(Session session, String authorName, String title); + @Find + abstract Book getBookByNaturalKey(Session session, String authorName, String title); - @HQL("from Book where title is not null") - abstract List allbooks(StatelessSession ss); + @HQL("from Book where title is not null") + abstract List allbooks(StatelessSession ss); - @HQL("from Book where title like ?2") - abstract TypedQuery findByTitle(EntityManager entityManager, String title); + @HQL("from Book where title like ?2") + abstract TypedQuery findByTitle(EntityManager entityManager, String title); - @HQL("from Book where title like ?2 order by title fetch first ?3 rows only") - abstract List findFirstNByTitle(Session session, String title, int N); + @HQL("from Book where title like ?2 order by title fetch first ?3 rows only") + abstract List findFirstNByTitle(Session session, String title, int N); - static class Summary { Summary(String title, String publisher, String isbn) {} } + static class Summary { Summary(String title, String publisher, String isbn) {} } - @HQL("select title, publisher.name, isbn from Book") - abstract List summarize(Session session, Order order); + @HQL("select title, publisher.name, isbn from Book") + abstract List summarize(Session session, Order order); } diff --git a/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/hqlsql/Dao.java b/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/hqlsql/Dao.java index 70b57dbadb..cb53ef1ef1 100644 --- a/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/hqlsql/Dao.java +++ b/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/hqlsql/Dao.java @@ -19,66 +19,66 @@ import java.util.Map; public interface Dao { - @Find - Book getBook(String isbn); + @Find + Book getBook(String isbn); - @Find - Book getBook(String title, String isbn); + @Find + Book getBook(String title, String isbn); - @Find - Book getBookByNaturalKey(String authorName, String title); + @Find + Book getBookByNaturalKey(String authorName, String title); - @HQL("from Book where title like ?1") - TypedQuery findByTitle(String title); + @HQL("from Book where title like ?1") + TypedQuery findByTitle(String title); - @HQL("from Book where title like ?1 order by title fetch first ?2 rows only") - List findFirstNByTitle(String title, int N); + @HQL("from Book where title like ?1 order by title fetch first ?2 rows only") + List findFirstNByTitle(String title, int N); - @HQL("from Book where title like :title") - List findByTitleWithPagination(String title, Order order, Page page); + @HQL("from Book where title like :title") + List findByTitleWithPagination(String title, Order order, Page page); - @HQL("from Book where title like :title") - SelectionQuery findByTitleWithOrdering(String title, List> order); + @HQL("from Book where title like :title") + SelectionQuery findByTitleWithOrdering(String title, List> order); - @HQL("from Book where title like :title") - SelectionQuery findByTitleWithOrderingByVarargs(String title, Order... order); + @HQL("from Book where title like :title") + SelectionQuery findByTitleWithOrderingByVarargs(String title, Order... order); - @HQL("from Book where isbn = :isbn") - Book findByIsbn(String isbn); + @HQL("from Book where isbn = :isbn") + Book findByIsbn(String isbn); - @HQL("order by isbn asc, publicationDate desc") - List allBooks(); + @HQL("order by isbn asc, publicationDate desc") + List allBooks(); - @HQL("order by isbn asc, publicationDate desc") - Book[] allBooksAsArray(); + @HQL("order by isbn asc, publicationDate desc") + Book[] allBooksAsArray(); - @SQL("select * from Book where isbn = :isbn") - Book findByIsbnNative(String isbn); + @SQL("select * from Book where isbn = :isbn") + Book findByIsbnNative(String isbn); - @Find - List publishedBooks(String publisher$name); + @Find + List publishedBooks(String publisher$name); - @HQL("from Book book join fetch book.publisher where book.title like :titlePattern") - List booksWithPublisherByTitle(String titlePattern, Page page, Order order); + @HQL("from Book book join fetch book.publisher where book.title like :titlePattern") + List booksWithPublisherByTitle(String titlePattern, Page page, Order order); - @HQL("select title, pages from Book") - List dtoQuery(); + @HQL("select title, pages from Book") + List dtoQuery(); - @HQL("select new org.hibernate.processor.test.hqlsql.Dto(title, pages) from Book") - List dtoQuery1(); + @HQL("select new org.hibernate.processor.test.hqlsql.Dto(title, pages) from Book") + List dtoQuery1(); - @HQL("select new Dto(title, pages) from Book") - List dtoQuery2(); + @HQL("select new Dto(title, pages) from Book") + List dtoQuery2(); - @HQL("select new map(title as title, pages as pages) from Book") - List dtoQuery3(); + @HQL("select new map(title as title, pages as pages) from Book") + List dtoQuery3(); - @HQL("select new list(title, pages) from Book") - List dtoQuery4(); + @HQL("select new list(title, pages) from Book") + List dtoQuery4(); - @HQL("from Publisher where address = :address") - List publisherAt(Address address); + @HQL("from Publisher where address = :address") + List publisherAt(Address address); - @HQL("where array_contains(:isbns, isbn) is true") - List forIsbnIn(String[] isbns); + @HQL("where array_contains(:isbns, isbn) is true") + List forIsbnIn(String[] isbns); } diff --git a/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/hqlsql/Dto.java b/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/hqlsql/Dto.java index e216d8e168..6ed2f7b713 100644 --- a/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/hqlsql/Dto.java +++ b/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/hqlsql/Dto.java @@ -9,41 +9,41 @@ package org.hibernate.processor.test.hqlsql; import java.util.Objects; public final class Dto { - private final String title; - private final int pages; + private final String title; + private final int pages; - public Dto(String title, int pages) { - this.title = title; - this.pages = pages; - } + public Dto(String title, int pages) { + this.title = title; + this.pages = pages; + } - public String title() { - return title; - } + public String title() { + return title; + } - public int pages() { - return pages; - } + public int pages() { + return pages; + } - @Override - public boolean equals(Object obj) { - if (obj == this) return true; - if (obj == null || obj.getClass() != this.getClass()) return false; - var that = (Dto) obj; - return Objects.equals(this.title, that.title) && - this.pages == that.pages; - } + @Override + public boolean equals(Object obj) { + if (obj == this) return true; + if (obj == null || obj.getClass() != this.getClass()) return false; + var that = (Dto) obj; + return Objects.equals(this.title, that.title) && + this.pages == that.pages; + } - @Override - public int hashCode() { - return Objects.hash(title, pages); - } + @Override + public int hashCode() { + return Objects.hash(title, pages); + } - @Override - public String toString() { - return "Dto[" + - "title=" + title + ", " + - "pages=" + pages + ']'; - } + @Override + public String toString() { + return "Dto[" + + "title=" + title + ", " + + "pages=" + pages + ']'; + } } diff --git a/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/hqlsql/Publisher.java b/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/hqlsql/Publisher.java index 3c6d790bb0..d6bc6ec736 100644 --- a/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/hqlsql/Publisher.java +++ b/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/hqlsql/Publisher.java @@ -11,7 +11,7 @@ import jakarta.persistence.Id; @Entity public class Publisher { - @Id Long id; - String name; - Address address; + @Id Long id; + String name; + Address address; } diff --git a/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/hqlvalidation/Book.java b/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/hqlvalidation/Book.java index f38f1f42f7..aaf88c1d26 100644 --- a/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/hqlvalidation/Book.java +++ b/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/hqlvalidation/Book.java @@ -11,7 +11,7 @@ import jakarta.persistence.Id; @Entity public class Book { - @Id String isbn; - String title; - String text; + @Id String isbn; + String title; + String text; } diff --git a/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/hqlvalidation/Dao1.java b/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/hqlvalidation/Dao1.java index e2f09c90b8..7882aae0f5 100644 --- a/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/hqlvalidation/Dao1.java +++ b/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/hqlvalidation/Dao1.java @@ -13,15 +13,15 @@ import org.hibernate.annotations.processing.SQL; import java.util.List; public interface Dao1 { - @HQL("from Book where title like ?1") - TypedQuery findByTitle(String title); + @HQL("from Book where title like ?1") + TypedQuery findByTitle(String title); - @HQL("from Book where title like ?1 order by title fetch first ?2 rows only") - List findFirstNByTitle(String title, int N); + @HQL("from Book where title like ?1 order by title fetch first ?2 rows only") + List findFirstNByTitle(String title, int N); - @HQL("from Boook where isbn = :isbn") - Book findByIsbn(String isbn); + @HQL("from Boook where isbn = :isbn") + Book findByIsbn(String isbn); - @SQL("select * from Book where isbn = :isbn") - Book findByIsbnNative(String isbn); + @SQL("select * from Book where isbn = :isbn") + Book findByIsbnNative(String isbn); } diff --git a/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/hqlvalidation/Dao2.java b/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/hqlvalidation/Dao2.java index 40266b334b..58f990c132 100644 --- a/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/hqlvalidation/Dao2.java +++ b/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/hqlvalidation/Dao2.java @@ -13,15 +13,15 @@ import org.hibernate.annotations.processing.SQL; import java.util.List; public interface Dao2 { - @HQL("from Book where tile like ?1") - TypedQuery findByTitle(String title); + @HQL("from Book where tile like ?1") + TypedQuery findByTitle(String title); - @HQL("from Book where title like ?1 order by title fetch first ?2 rows only") - List findFirstNByTitle(String title, int N); + @HQL("from Book where title like ?1 order by title fetch first ?2 rows only") + List findFirstNByTitle(String title, int N); - @HQL("from Book where isbn = :isbn") - Book findByIsbn(String isbn); + @HQL("from Book where isbn = :isbn") + Book findByIsbn(String isbn); - @SQL("select * from Book where isbn = :isbn") - Book findByIsbnNative(String isbn); + @SQL("select * from Book where isbn = :isbn") + Book findByIsbnNative(String isbn); } diff --git a/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/keypage/Book.java b/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/keypage/Book.java index b5aeaadc17..88cba8ba03 100644 --- a/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/keypage/Book.java +++ b/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/keypage/Book.java @@ -17,13 +17,13 @@ import java.time.LocalDate; @Entity public class Book { - @Id String isbn; - @NaturalId String title; - String text; - @NaturalId String authorName; - @ManyToOne + @Id String isbn; + @NaturalId String title; + String text; + @NaturalId String authorName; + @ManyToOne Publisher publisher; - BigDecimal price; - int pages; - LocalDate publicationDate; + BigDecimal price; + int pages; + LocalDate publicationDate; } diff --git a/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/keypage/Dao.java b/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/keypage/Dao.java index b35e31e379..4aaee6b1b3 100644 --- a/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/keypage/Dao.java +++ b/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/keypage/Dao.java @@ -14,11 +14,11 @@ import org.hibernate.query.KeyedResultList; public interface Dao { - EntityManager em(); + EntityManager em(); - @Find - KeyedResultList books1(String title, KeyedPage page); + @Find + KeyedResultList books1(String title, KeyedPage page); - @HQL("where title like :title") - KeyedResultList books2(String title, KeyedPage page); + @HQL("where title like :title") + KeyedResultList books2(String title, KeyedPage page); } diff --git a/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/namedquery/Book.java b/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/namedquery/Book.java index 599437b451..f275ebc935 100644 --- a/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/namedquery/Book.java +++ b/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/namedquery/Book.java @@ -14,20 +14,20 @@ import jakarta.persistence.NamedQuery; @Entity @NamedEntityGraph(name = "entityGraph") @NamedQuery(name = "#findByTitle", - query = "from Book where title like :titlePattern") + query = "from Book where title like :titlePattern") @NamedQuery(name = "#findByTitleAndType", - query = "select book from Book book where book.title like :titlePattern and book.type = :type") + query = "select book from Book book where book.title like :titlePattern and book.type = :type") @NamedQuery(name = "#getTitles", - query = "select title from Book") + query = "select title from Book") @NamedQuery(name = "#getUpperLowerTitles", - query = "select upper(title), lower(title), length(title) from Book") + query = "select upper(title), lower(title), length(title) from Book") @NamedQuery(name = "#typeOfBook", - query = "select type from Book where isbn = :isbn") + query = "select type from Book where isbn = :isbn") @NamedQuery(name = "#crazy", - query = "select 1 where :x = :y") + query = "select 1 where :x = :y") public class Book { - @Id String isbn; - String title; - String text; - Type type = Type.Book; + @Id String isbn; + String title; + String text; + Type type = Type.Book; } diff --git a/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/noentity/Dao.java b/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/noentity/Dao.java index 1c14c42f6e..74bfeef9df 100644 --- a/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/noentity/Dao.java +++ b/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/noentity/Dao.java @@ -10,6 +10,6 @@ import jakarta.persistence.TypedQuery; import org.hibernate.annotations.processing.HQL; public interface Dao { - @HQL("select upper('Hibernate')") - TypedQuery getName(); + @HQL("select upper('Hibernate')") + TypedQuery getName(); } diff --git a/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/records/Author.java b/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/records/Author.java index 1843d476ce..1ffca7e013 100644 --- a/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/records/Author.java +++ b/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/records/Author.java @@ -14,46 +14,46 @@ import jakarta.persistence.Id; @Entity public class Author { - @Id - @GeneratedValue - private Long id; + @Id + @GeneratedValue + private Long id; - @Embedded - private Address address; + @Embedded + private Address address; - private String firstName; + private String firstName; - private String lastName; + private String lastName; - public Long getId() { - return id; - } + public Long getId() { + return id; + } - public void setId(Long id) { - this.id = id; - } + public void setId(Long id) { + this.id = id; + } - public Address getAddress() { - return address; - } + public Address getAddress() { + return address; + } - public void setAddress(Address address) { - this.address = address; - } + public void setAddress(Address address) { + this.address = address; + } - public String getFirstName() { - return firstName; - } + public String getFirstName() { + return firstName; + } - public void setFirstName(String firstName) { - this.firstName = firstName; - } + public void setFirstName(String firstName) { + this.firstName = firstName; + } - public String getLastName() { - return lastName; - } + public String getLastName() { + return lastName; + } - public void setLastName(String lastName) { - this.lastName = lastName; - } + public void setLastName(String lastName) { + this.lastName = lastName; + } } diff --git a/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/records/Java14RecordsTest.java b/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/records/Java14RecordsTest.java index 6abea6c8d7..f0561e4d5b 100644 --- a/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/records/Java14RecordsTest.java +++ b/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/records/Java14RecordsTest.java @@ -27,32 +27,32 @@ import static org.junit.Assert.fail; public class Java14RecordsTest extends CompilationTest { - @Test - @TestForIssue(jiraKey = "HHH-16261") - @WithClasses({Address.class, Author.class}) - public void testEmbeddableRecordProperty() { - assertMetamodelClassGeneratedFor(Address.class); - for (final String fieldName : List.of("street", "city", "postalCode")) { - assertNotNull("Address must contain '" + fieldName + "' field", getFieldFromMetamodelFor(Address.class, fieldName)); - } - assertMetamodelClassGeneratedFor(Author.class); + @Test + @TestForIssue(jiraKey = "HHH-16261") + @WithClasses({Address.class, Author.class}) + public void testEmbeddableRecordProperty() { + assertMetamodelClassGeneratedFor(Address.class); + for (final String fieldName : List.of("street", "city", "postalCode")) { + assertNotNull("Address must contain '" + fieldName + "' field", getFieldFromMetamodelFor(Address.class, fieldName)); + } + assertMetamodelClassGeneratedFor(Author.class); - final Field addressField = getFieldFromMetamodelFor(Author.class, "address"); - assertNotNull("Author must contain 'address' field", addressField); - assertTrue(isStatic(addressField.getModifiers())); - if (addressField.getGenericType() instanceof ParameterizedType parameterizedType) { - assertEquals(SingularAttribute.class, parameterizedType.getRawType()); - final Type[] typeArguments = parameterizedType.getActualTypeArguments(); - assertEquals(2, typeArguments.length); - assertEquals(Author.class, typeArguments[0]); - assertEquals(Address.class, typeArguments[1]); - } else { - fail("Address field must be instance of ParameterizedType"); - } + final Field addressField = getFieldFromMetamodelFor(Author.class, "address"); + assertNotNull("Author must contain 'address' field", addressField); + assertTrue(isStatic(addressField.getModifiers())); + if (addressField.getGenericType() instanceof ParameterizedType parameterizedType) { + assertEquals(SingularAttribute.class, parameterizedType.getRawType()); + final Type[] typeArguments = parameterizedType.getActualTypeArguments(); + assertEquals(2, typeArguments.length); + assertEquals(Author.class, typeArguments[0]); + assertEquals(Address.class, typeArguments[1]); + } else { + fail("Address field must be instance of ParameterizedType"); + } - final Field addressNameField = getFieldFromMetamodelFor(Author.class, "address".toUpperCase()); - assertNotNull("Author must contain 'ADDRESS' field", addressNameField); - assertTrue(isStatic(addressNameField.getModifiers())); - assertEquals(String.class, addressNameField.getGenericType()); - } + final Field addressNameField = getFieldFromMetamodelFor(Author.class, "address".toUpperCase()); + assertNotNull("Author must contain 'ADDRESS' field", addressNameField); + assertTrue(isStatic(addressNameField.getModifiers())); + assertEquals(String.class, addressNameField.getGenericType()); + } } diff --git a/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/superdao/Book.java b/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/superdao/Book.java index 09ceace298..528ccd1699 100644 --- a/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/superdao/Book.java +++ b/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/superdao/Book.java @@ -17,13 +17,13 @@ import java.time.LocalDate; @Entity public class Book { - @Id String isbn; - @NaturalId String title; - String text; - @NaturalId String authorName; - @ManyToOne + @Id String isbn; + @NaturalId String title; + String text; + @NaturalId String authorName; + @ManyToOne Publisher publisher; - BigDecimal price; - int pages; - LocalDate publicationDate; + BigDecimal price; + int pages; + LocalDate publicationDate; } diff --git a/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/superdao/Dao.java b/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/superdao/Dao.java index 7871f75bdd..7de7ccf70c 100644 --- a/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/superdao/Dao.java +++ b/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/superdao/Dao.java @@ -9,6 +9,6 @@ package org.hibernate.processor.test.superdao; import org.hibernate.annotations.processing.Find; public interface Dao extends SuperDao { - @Find - Book get(String isbn); + @Find + Book get(String isbn); } diff --git a/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/superdao/SuperDao.java b/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/superdao/SuperDao.java index 0eff974c14..e592532e75 100644 --- a/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/superdao/SuperDao.java +++ b/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/superdao/SuperDao.java @@ -15,12 +15,12 @@ import java.util.List; public interface SuperDao { - EntityManager em(); + EntityManager em(); - @Find - List books1(@Pattern String title); + @Find + List books1(@Pattern String title); - @HQL("where title like :title") - List books2(String title); + @HQL("where title like :title") + List books2(String title); } diff --git a/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/superdao/generic/Book.java b/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/superdao/generic/Book.java index 463c8e0f31..f96cc49d84 100644 --- a/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/superdao/generic/Book.java +++ b/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/superdao/generic/Book.java @@ -17,13 +17,13 @@ import java.time.LocalDate; @Entity public class Book { - @Id String isbn; - @NaturalId String title; - String text; - @NaturalId String authorName; - @ManyToOne + @Id String isbn; + @NaturalId String title; + String text; + @NaturalId String authorName; + @ManyToOne Publisher publisher; - BigDecimal price; - int pages; - LocalDate publicationDate; + BigDecimal price; + int pages; + LocalDate publicationDate; } diff --git a/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/superdao/generic/Dao.java b/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/superdao/generic/Dao.java index df23901426..4d7b38bb0c 100644 --- a/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/superdao/generic/Dao.java +++ b/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/superdao/generic/Dao.java @@ -9,6 +9,6 @@ package org.hibernate.processor.test.superdao.generic; import org.hibernate.annotations.processing.Find; public interface Dao extends SuperDao { - @Find + @Find Book getConc(String isbn); } diff --git a/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/superdao/generic/SuperDao.java b/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/superdao/generic/SuperDao.java index a501127b41..07a886eac5 100644 --- a/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/superdao/generic/SuperDao.java +++ b/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/superdao/generic/SuperDao.java @@ -15,15 +15,15 @@ import java.util.List; public interface SuperDao { - EntityManager em(); + EntityManager em(); - @Find - T get(K isbn); + @Find + T get(K isbn); - @Find - List books1(@Pattern String title); + @Find + List books1(@Pattern String title); - @HQL("where title like :title") - List books2(String title); + @HQL("where title like :title") + List books2(String title); } diff --git a/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/util/CompilationStatement.java b/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/util/CompilationStatement.java index 86e96a3678..4aafcc1320 100644 --- a/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/util/CompilationStatement.java +++ b/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/util/CompilationStatement.java @@ -94,7 +94,7 @@ public class CompilationStatement extends Statement { for ( String source : sources ) { javaFiles.add( new File( resourcesBaseDir, - source.replace( PACKAGE_SEPARATOR, File.separator ) + ".java" ) ); + source.replace( PACKAGE_SEPARATOR, File.separator ) + ".java" ) ); } } diff --git a/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/wildcard/Property.java b/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/wildcard/Property.java index 68b083651d..9a3c9ee406 100644 --- a/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/wildcard/Property.java +++ b/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/wildcard/Property.java @@ -8,7 +8,7 @@ package org.hibernate.processor.test.wildcard; public interface Property { - String getName(); + String getName(); - T getValue(); + T getValue(); } diff --git a/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/wildcard/PropertyRepo.java b/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/wildcard/PropertyRepo.java index b5847fbdb4..633aba08a8 100644 --- a/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/wildcard/PropertyRepo.java +++ b/tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/wildcard/PropertyRepo.java @@ -17,10 +17,10 @@ import java.util.List; @Entity public class PropertyRepo { - @Id - private Long id; + @Id + private Long id; - @ManyToAny - @AnyDiscriminator(DiscriminatorType.STRING) - private List> properties = new ArrayList<>(); + @ManyToAny + @AnyDiscriminator(DiscriminatorType.STRING) + private List> properties = new ArrayList<>(); }