From 2e27e213bb0b0baa859f74f953a49f39b8fa798a Mon Sep 17 00:00:00 2001 From: Jan Schatteman Date: Thu, 9 Oct 2025 17:04:37 +0200 Subject: [PATCH] HHH-19846 - Drop JUnit 4 Usage Signed-off-by: Jan Schatteman HHH-19846 - Remove JUnit4: org.hibernate.bytecode.internal.bytebuddy HHH-19846 - Remove JUnit4: org.hibernate.dialect HHH-19846 - Remove JUnit4: org.hibernate.engine.jdbc.env.internal HHH-19846 - Remove JUnit4: org.hibernate.orm.test.actionqueue HHH-19846 - Remove JUnit4: org.hibernate.orm.test.annotations HHH-19846 - Remove JUnit4: org.hibernate.orm.test.dialect.functional HHH-19846 - Remove JUnit4: org.hibernate.orm.test.dialect.resolver HHH-19846 - Remove JUnit4: org.hibernate.orm.test.dialect.unit.lockhint HHH-19846 - Remove JUnit4: org.hibernate.orm.test.dialect.function HHH-19846 - Remove JUnit4: org.hibernate.orm.test.dialect.unit.locktimeout HHH-19846 - Remove JUnit4: org.hibernate.orm.test.dialect.unit.sequence HHH-19846 - Remove JUnit4: org.hibernate.orm.test.dialect HHH-19846 - Remove JUnit4: org.hibernate.orm.test.mapping HHH-19846 - Remove JUnit4: org.hibernate.orm.test.mapping.access HHH-19846 - Remove JUnit4: org.hibernate.orm.test.mapping.basic/bitset HHH-19846 - Remove JUnit4: org.hibernate.orm.test.dirtiness HHH-19846 - Remove JUnit4: org.hibernate.orm.test.distinct HHH-19846 - Remove JUnit4: org.hibernate.orm.test.mapping.collections HHH-19846 - Remove JUnit4: org.hibernate.orm.test.mapping.collections.custom.basic/declaredtype/parameterized HHH-19846 - Remove JUnit4: org.hibernate.orm.test.mapping.dynamic HHH-19846 - Remove JUnit4: org.hibernate.orm.test.mapping.lazytoone HHH-19846 - Remove JUnit4: org.hibernate.orm.test.mapping.converted.converter HHH-19846 - Remove JUnit4: org.hibernate.orm.test.mapping.converted.enums HHH-19846 - Remove JUnit4: org.hibernate.orm.test.mapping.converter.* HHH-19846 - Remove JUnit4: org.hibernate.orm.test.mapping.embeddable.* HHH-19846 - Remove JUnit4: org.hibernate.orm.test.mapping.fetch/formula/generated HHH-19846 - Remove JUnit4: org.hibernate.orm.test.mapping.identifier/* HHH-19846 - Remove JUnit4: org.hibernate.orm.test.mapping.inheritance/* HHH-19846 - Remove JUnit4: org.hibernate.orm.test.mapping.* HHH-19846 - Remove JUnit4: org.hibernate.orm.test.jpa.callbacks/cascade HHH-19846 - Remove JUnit4: org.hibernate.orm.test.jpa.compliance + tck2_2 HHH-19846 - Remove JUnit4: org.hibernate.orm.test.jpa.graphs/* HHH-19846 - Remove JUnit4: org.hibernate.orm.test.jpa.jointable HHH-19846 - Remove JUnit4: org.hibernate.orm.test.jpa.metamodel/ops HHH-19846 - Remove JUnit4: org.hibernate.orm.test.jpa.orphan/persistenceunit HHH-19846 - Remove JUnit4: org.hibernate.orm.test.jpa.procedure HHH-19846 - Remove JUnit4: org.hibernate.orm.test.jpa.proxy/ql/schemagen Signed-off-by: Jan Schatteman --- .../src/test/java/NoPackageTest.java | 23 +- .../ByteBuddyBasicProxyFactoryTest.java | 10 +- ...eByteCodeNotInProvidedClassLoaderTest.java | 10 +- .../bytebuddy/EnhancerWildFlyNamesTest.java | 8 +- .../bytebuddy/GenerateProxiesTest.java | 4 +- .../bytebuddy/ReflectionOptimizerTests.java | 4 +- .../bytebuddy/SimpleEnhancerTests.java | 2 +- .../bytebuddy/SuperTypesEnhancementTest.java | 30 +- .../dialect/H2DialectDatabaseVersionTest.java | 9 +- .../MySQLDialectDatabaseVersionTest.java | 9 +- .../SkipLoadingSequenceInformationTest.java | 38 +- .../CustomAfterCompletionTest.java | 79 +- .../CustomBeforeCompletionTest.java | 69 +- .../annotations/CreationTimestampTest.java | 58 +- .../GenericConverterAutoApplyTest.java | 30 +- .../orm/test/annotations/HHH16122Test.java | 14 +- ...ryCreationTimestampNullableColumnTest.java | 25 +- .../InMemoryTimestampGenerationBatchTest.java | 18 +- .../InMemoryTimestampGenerationTest.java | 19 +- .../test/annotations/JoinedSubclassTest.java | 57 +- .../orm/test/annotations/SafeMappingTest.java | 4 +- .../UpdateTimeStampInheritanceTest.java | 18 +- .../test/annotations/UpdateTimestampTest.java | 58 +- .../test/dialect/DB2390DialectTestCase.java | 59 +- .../orm/test/dialect/DB2DialectTestCase.java | 41 +- .../dialect/Db2VariantDialectInitTests.java | 4 +- .../dialect/DialectMinimumVersionTest.java | 2 - .../orm/test/dialect/HANADialectTestCase.java | 4 +- .../dialect/PostgreSQLDialectTestCase.java | 28 +- .../dialect/function/HANAFunctionsTest.java | 120 +-- .../function/HSQLTruncFunctionTest.java | 29 +- .../function/MySQLRoundFunctionTest.java | 56 +- .../dialect/functional/HANABooleanTest.java | 236 ++--- .../dialect/functional/HANACalcViewTest.java | 196 ++-- .../dialect/functional/HANADecimalTest.java | 136 ++- ...MariaDBExtractSequenceInformationTest.java | 115 +- .../OracleDialectSequenceInformationTest.java | 100 +- .../SQLServerDialectCollationTest.java | 121 +-- .../SQLServerDialectPaginationTest.java | 51 +- ...LServerDialectSequenceInformationTest.java | 57 +- ...QLServerDialectTempTableCollationTest.java | 66 +- .../functional/SQLServerDialectTest.java | 225 ++-- .../dialect/resolver/DialectFactoryTest.java | 23 +- .../dialect/resolver/DialectResolverTest.java | 16 +- .../resolver/StandardDialectResolverTest.java | 19 +- .../unit/lockhint/AbstractLockHintTest.java | 13 +- .../unit/locktimeout/DB2LockTimeoutTest.java | 7 +- .../unit/locktimeout/HANALockTimeoutTest.java | 7 +- .../locktimeout/OracleLockTimeoutTest.java | 9 +- .../PostgreSQLLockTimeoutTest.java | 7 +- ...tractSequenceInformationExtractorTest.java | 4 +- .../CustomDirtinessStrategyTest.java | 172 ++- .../test/distinct/SelectDistinctHqlTest.java | 80 +- .../jpa/callbacks/CallbackAndDirtyTest.java | 151 ++- .../PrivateConstructorEnhancerTest.java | 10 +- .../MultiCircleJpaCascadeTest.java | 2 +- ...iLevelCascadeCollectionEmbeddableTest.java | 2 - ...ultiLevelCascadeCollectionIdClassTest.java | 2 - .../EmbeddableInQueryResultTest.java | 2 +- .../compliance/tck2_2/ClosedFactoryTests.java | 45 +- .../tck2_2/EntityTransactionTests.java | 320 +++--- .../tck2_2/GeneratedValueTests.java | 407 ++++---- .../tck2_2/GetterAndIsMethodChecks.java | 5 +- .../jpa/compliance/tck2_2/QueryApiTest.java | 70 +- .../compliance/tck2_2/QueryExecutionTest.java | 41 +- .../TableGeneratorMultipleDefinitionTest.java | 36 +- .../tck2_2/TableGeneratorVisibilityTest.java | 47 +- .../CachingWithSecondaryTablesTests.java | 29 +- .../caching/InheritedCacheableTest.java | 91 +- .../caching/SubclassOnlyCachingTests.java | 75 +- .../tck2_2/joincolumn/JoinColumnTest.java | 100 +- .../MapKeyColumnBiDiOneToManyFKTest.java | 57 +- .../MapKeyColumnElementCollectionTest.java | 50 +- .../MapKeyColumnManyToManyTest.java | 61 +- .../MapKeyColumnOneToManyFKTest.java | 57 +- .../MapKeyColumnOneToManyJoinTableTest.java | 61 +- .../jpa/graphs/CacheableEntityGraphTest.java | 58 +- .../EntityGraphAttributeResolutionTest.java | 53 +- .../orm/test/jpa/graphs/EntityGraphTest.java | 982 +++++++++--------- .../jpa/graphs/LoadAndFetchGraphTest.java | 99 +- .../mappedbyid/FetchGraphFindByIdTest.java | 238 ++--- .../queryhint/QueryHintEntityGraphTest.java | 596 +++++------ .../jpa/jointable/ManyToOneJoinTableTest.java | 36 +- .../AbstractJpaMetamodelPopulationTest.java | 49 +- .../JpaMetamodelDisabledPopulationTest.java | 12 + .../JpaMetamodelEnabledPopulationTest.java | 12 + ...amodelIgnoreUnsupportedPopulationTest.java | 12 + .../orm/test/jpa/ops/GetLoadTest.java | 4 +- .../test/jpa/ops/MergeJpaComplianceTest.java | 46 +- .../DeleteMultiLevelOrphansTest.java | 277 +++-- .../DuplicatePersistenceUnitNameTest.java | 45 +- .../ExcludeUnlistedClassesTest.java | 11 +- .../PersistenceXmlParserTest.java | 8 +- ...TwoPersistenceUnits2LCDisabledEnabled.java | 78 -- ...ersistenceUnits2LCDisabledEnabledTest.java | 89 ++ .../AbstractStoredProcedureTest.java | 106 +- .../test/jpa/procedure/AnnotationTest.java | 7 +- .../jpa/procedure/H2StoreProcedureTest.java | 6 +- .../jpa/procedure/HSQLStoreProcedureTest.java | 165 ++- .../orm/test/jpa/procedure/OrmTest.java | 7 +- .../StoreProcedureOutParameterByNameTest.java | 93 +- ...reProcedureOutParameterByPositionTest.java | 93 +- ...cedureRefCursorOutParameterByNameTest.java | 46 +- ...reRefCursorOutParameterByPositionTest.java | 46 +- .../StoredProcedureResultSetMappingTest.java | 102 +- .../orm/test/jpa/proxy/JPAProxyTest.java | 58 +- .../orm/test/jpa/ql/NamedNativeQueryTest.java | 332 +++--- .../orm/test/jpa/ql/TreatKeywordTest.java | 294 +++--- .../test/jpa/removed/RemovedEntityTest.java | 12 +- .../jpa/schemagen/JpaSchemaGeneratorTest.java | 3 +- ...hemaDatabaseFileGenerationFailureTest.java | 26 +- ...SchemaScriptFileGenerationFailureTest.java | 21 +- ...maGeneratorWithHbm2DdlCharsetNameTest.java | 2 +- ...maGeneratorWithHbm2DdlCharsetNameTest.java | 2 +- ...eneratorWithoutHbm2DdlCharsetNameTest.java | 4 +- .../hibernate/orm/test/mapping/AliasTest.java | 2 +- .../orm/test/mapping/SecondaryTableTests.java | 2 +- .../orm/test/mapping/ValueVisitorTest.java | 13 +- .../access/ElementCollectionAccessTest.java | 22 +- .../mapping/access/EmbeddableAccessTest.java | 22 +- .../test/mapping/access/FieldAccessTest.java | 22 +- .../access/PropertyAccessOverrideTest.java | 22 +- .../mapping/access/PropertyAccessTest.java | 22 +- .../test/mapping/basic/AutoQuotingTest.java | 33 +- .../test/mapping/basic/BlobByteArrayTest.java | 25 +- .../orm/test/mapping/basic/BlobTest.java | 28 +- .../CalendarWithTemporalTimestampTest.java | 24 +- .../test/mapping/basic/ClobCharArrayTest.java | 2 +- .../test/mapping/basic/ClobStringTest.java | 25 +- .../orm/test/mapping/basic/ClobTest.java | 26 +- .../mapping/basic/ColumnTransformerTest.java | 26 +- .../basic/DateWithTemporalDateTest.java | 22 +- .../basic/DateWithTemporalTimeTest.java | 25 +- .../basic/DateWithTemporalTimestampTest.java | 22 +- .../basic/EnumerationConverterTest.java | 22 +- .../basic/EnumerationCustomTypeTest.java | 21 +- .../mapping/basic/ExplicitBasicTypeTest.java | 24 +- .../basic/ExplicitColumnNamingTest.java | 24 +- .../test/mapping/basic/ExplicitTypeTest.java | 22 +- .../orm/test/mapping/basic/FormulaTest.java | 24 +- .../mapping/basic/ImplicitBasicTypeTest.java | 24 +- .../test/mapping/basic/JpaQuotingTest.java | 22 +- .../LocalDateTimeWithTemporalTimeTest.java | 25 +- .../mapping/basic/NClobCharArrayTest.java | 24 +- .../test/mapping/basic/NClobStringTest.java | 24 +- .../orm/test/mapping/basic/NClobTest.java | 4 +- .../test/mapping/basic/NationalizedTest.java | 2 +- .../orm/test/mapping/basic/ParentTest.java | 24 +- .../basic/PhoneTypeEnumeratedOrdinalTest.java | 21 +- .../basic/PhoneTypeEnumeratedStringTest.java | 21 +- .../orm/test/mapping/basic/QuotingTest.java | 22 +- .../basic/StringNationalizedMappingTests.java | 2 +- .../orm/test/mapping/basic/SubselectTest.java | 2 +- .../test/mapping/basic/TypeCategoryTest.java | 24 +- .../bitset/BitSetRegisteredUserTypeTest.java | 43 +- .../basic/bitset/BitSetTypeContributor.java | 18 + .../mapping/basic/bitset/BitSetTypeTest.java | 48 +- .../basic/bitset/BitSetUserTypeTest.java | 47 +- .../test/mapping/collections/ArrayTest.java | 24 +- .../BasicTypeElementCollectionTest.java | 65 +- ...cTypeOrderColumnElementCollectionTest.java | 25 +- .../BidirectionalBagOrphanRemovalTest.java | 22 +- .../collections/BidirectionalBagTest.java | 22 +- .../BidirectionalComparatorSortedSetTest.java | 34 +- .../collections/BidirectionalMapTest.java | 29 +- .../BidirectionalOrderByListTest.java | 24 +- .../BidirectionalOrderColumnListTest.java | 26 +- .../collections/BidirectionalSetTest.java | 33 +- .../BidirectionalSortedSetTest.java | 34 +- .../collections/ElementCollectionMapTest.java | 29 +- .../EmbeddableTypeElementCollectionTest.java | 22 +- .../mapping/collections/MapKeyClassTest.java | 25 +- .../mapping/collections/MapKeyTypeTest.java | 8 +- .../OrderColumnListIndexBaseTest.java | 107 +- ...nListIndexHHH18771ListInitializerTest.java | 25 +- .../mapping/collections/OrderedBySQLTest.java | 39 +- .../test/mapping/collections/QueueTest.java | 29 +- .../collections/UnidirectionalBagTest.java | 25 +- ...UnidirectionalComparatorSortedSetTest.java | 34 +- .../collections/UnidirectionalMapTest.java | 29 +- .../UnidirectionalOrderColumnListTest.java | 25 +- .../UnidirectionalOrderedByListTest.java | 25 +- .../collections/UnidirectionalSetTest.java | 33 +- .../UnidirectionalSortedSetTest.java | 34 +- ...rCollectionTypeAnnotationsVariantTest.java | 12 +- .../UserCollectionTypeHbmVariantTest.java | 17 +- .../custom/basic/UserCollectionTypeTest.java | 34 +- ...rCollectionTypeAnnotationsVariantTest.java | 12 +- .../UserCollectionTypeHbmVariantTest.java | 12 +- .../declaredtype/UserCollectionTypeTest.java | 28 +- .../UserWithUnimplementedCollectionTest.java | 2 +- ...rCollectionTypeAnnotationsVariantTest.java | 9 +- ...rizedUserCollectionTypeHbmVariantTest.java | 8 +- .../ParameterizedUserCollectionTypeTest.java | 45 +- .../converted/converter/AndLobTest.java | 4 +- .../converter/AndNationalizedTests.java | 8 +- .../converter/AttributeConverterTest.java | 23 +- .../BasicCustomTimeConversionTest.java | 43 +- .../converter/DirtyCheckingTest.java | 134 +-- .../converter/ExplicitDateConvertersTest.java | 46 +- .../converter/ExplicitEnumConvertersTest.java | 46 +- .../ExplicitJavaTypeDescriptorTest.java | 71 +- .../ExplicitlyNamedConverterClassesTest.java | 33 +- ...toAppliedConverterForIdAndVersionTest.java | 2 +- .../converter/LongToDateConversionTest.java | 2 +- .../converter/NullHandlingTests.java | 119 +-- ...buteConverterEntityManagerFactoryTest.java | 2 +- ...eAttributeConverterSessionFactoryTest.java | 2 +- .../QueryConvertedAttributeTest.java | 41 +- .../converted/converter/QueryTest.java | 96 +- .../SimpleConvertAnnotationTest.java | 44 +- .../SimpleConvertsAnnotationTest.java | 44 +- ...mpleEmbeddableOverriddenConverterTest.java | 27 +- .../SimpleOverriddenConverterTest.java | 27 +- .../converter/SimpleXmlOverriddenTest.java | 42 +- ...XmlWithExplicitConvertAnnotationsTest.java | 52 +- ...lectionCompositeElementConversionTest.java | 6 +- ...ompositeElementExplicitConversionTest.java | 2 +- .../CollectionElementConversionTest.java | 4 +- ...llectionElementExplicitConversionTest.java | 6 +- .../ElementCollectionTests.java | 6 +- ...edAttributeConverterParameterTypeTest.java | 6 +- .../converter/literal/QueryLiteralTest.java | 8 +- .../map/MapElementConversionTest.java | 6 +- .../map/MapKeyAttributeConverterTest.java | 374 +++---- .../converter/map/MapKeyConversionTest.java | 45 +- .../converted/enums/EnumExplicitTypeTest.java | 2 +- .../mapping/converted/enums/EnumTypeTest.java | 108 +- .../enums/InvalidEnumeratedJavaTypeTest.java | 2 +- .../enums/UnspecifiedEnumTypeTest.java | 78 +- .../mapping/converter/MoneyConverterTest.java | 22 +- .../mapping/converter/PeriodStringTest.java | 27 +- .../converter/hbm/MoneyConverterHbmTest.java | 23 +- .../mapping/dynamic/DynamicEntityTest.java | 35 +- .../EmbeddableImplicitOverrideTest.java | 49 +- .../embeddable/EmbeddableOverrideTest.java | 27 +- .../embeddable/JsonEmbeddableArrayTest.java | 122 ++- .../embeddable/JsonEmbeddableTest.java | 136 ++- .../JsonWithArrayEmbeddableTest.java | 56 +- .../embeddable/NestedEmbeddableTest.java | 23 +- .../embeddable/NestedJsonEmbeddableTest.java | 164 ++- .../NestedStructEmbeddableTest.java | 70 +- .../NestedStructWithArrayEmbeddableTest.java | 60 +- .../embeddable/NestedXmlEmbeddableTest.java | 85 +- .../test/mapping/embeddable/ParentTest.java | 24 +- .../SimpleEmbeddableEquivalentTest.java | 22 +- .../embeddable/SimpleEmbeddableTest.java | 22 +- ...dateEntityWithIdClassAndJsonFieldTest.java | 2 +- .../mapping/embeddable/XmlEmbeddableTest.java | 133 ++- .../XmlWithArrayEmbeddableTest.java | 56 +- .../RecordAsCompositeTypeEmbeddableTest.java | 29 +- ...SubselectFetchCollectionFromBatchTest.java | 6 +- .../mapping/formula/FormulaBasicsTest.java | 2 +- .../formula/FormulaNativeQueryTest.java | 2 +- .../test/mapping/formula/FormulaTests.java | 2 +- .../mapping/formula/FormulaWithAliasTest.java | 2 +- .../formula/FormulaWithPartitionByTest.java | 4 +- .../AbstractGeneratedPropertyTest.java | 54 +- .../generated/CreationTimestampTest.java | 21 +- .../DatabaseValueGenerationTest.java | 21 +- .../DefaultGeneratedValueIdentityTest.java | 8 +- .../generated/DefaultGeneratedValueTest.java | 18 +- .../mapping/generated/GeneratorTypeTest.java | 23 +- .../InMemoryValueGenerationTest.java | 21 +- .../InVmGenerationsWithAnnotationsTests.java | 2 +- ...WithAnnotationsWithMixedSqlTypesTests.java | 2 +- ...ationsWithAnnotationsWithSqlDateTests.java | 2 +- ...nerationsWithMultipleAnnotationsTests.java | 2 +- .../PartiallyGeneratedComponentTest.java | 4 +- .../SimpleValueGenerationBaselineTests.java | 2 +- ...mestampGeneratedValuesWithCachingTest.java | 7 +- ...TriggerGeneratedValuesWithCachingTest.java | 7 +- ...ggerGeneratedValuesWithoutCachingTest.java | 11 +- .../generated/UpdateTimestampTest.java | 23 +- .../generated/always/GeneratedAlwaysTest.java | 2 +- .../formula/FormulaGeneratedTest.java | 2 +- .../generated/sql/SqlGeneratedTest.java | 6 +- .../generated/sqldefault/DefaultTest.java | 2 +- .../sqldefault/DynamicDefaultTest.java | 4 +- .../sqldefault/ImmutableDefaultTest.java | 2 +- .../sqldefault/OverriddenDefaultTest.java | 2 +- .../generated/sqldefault/RefreshTest.java | 2 +- .../identifier/AssignedIdentifierTest.java | 26 +- .../identifier/CompositeNaturalIdTest.java | 26 +- .../identifier/EmbeddedIdManyToOneTest.java | 37 +- .../mapping/identifier/EmbeddedIdTest.java | 31 +- .../identifier/EntityTableCatalogTest.java | 17 +- .../identifier/EntityTableSchemaTest.java | 17 +- .../identifier/GeneratedIdentifierTest.java | 25 +- .../identifier/IdClassGeneratedValueTest.java | 31 +- .../identifier/IdClassManyToOneTest.java | 37 +- .../test/mapping/identifier/IdClassTest.java | 31 +- .../mapping/identifier/IdManyToOneTest.java | 30 +- .../identifier/MultipleNaturalIdTest.java | 29 +- .../identifier/MutableNaturalIdTest.java | 26 +- .../identifier/MutableNaturalIdsTest.java | 28 +- .../NaiveEqualsHashCodeEntityTest.java | 50 +- .../NaturalIdEqualsHashCodeEntityTest.java | 35 +- .../identifier/PooledOptimizerTest.java | 20 +- .../SequenceGeneratorAnnotationNameTest.java | 27 +- .../SequenceGeneratorConfiguredTest.java | 27 +- .../SequenceGeneratorNamedTest.java | 28 +- .../SequenceGeneratorUnnamedTest.java | 28 +- .../identifier/SimpleEntityTableTest.java | 16 +- .../mapping/identifier/SimpleEntityTest.java | 77 +- .../identifier/SimpleNaturalIdTest.java | 26 +- .../identifier/SimplePartitionKeyTest.java | 24 +- .../TableGeneratorConfiguredTest.java | 21 +- .../identifier/TableGeneratorUnnamedTest.java | 21 +- .../UuidCustomGeneratedValueTest.java | 27 +- .../identifier/UuidGeneratedValueTest.java | 31 +- .../EmbeddedIdDatabaseGeneratedValueTest.java | 2 +- .../EmbeddedIdInMemoryGeneratedValueTest.java | 26 +- .../JoinedInheritanceEagerTest.java | 4 +- .../MultiInheritanceDiscriminatorTest.java | 4 +- .../joined/JoinedSubclassInheritanceTest.java | 4 +- ...heritanceSameTableDifferentSchemaTest.java | 2 +- .../joined/JoinedInheritanceTest.java | 2 +- ...JoinedInheritanceWithConcreteRootTest.java | 2 +- ...eritanceWithExplicitDiscriminatorTest.java | 2 +- .../joined/JoinedSubclassTest.java | 37 +- .../joined/MixedInheritanceTest.java | 6 +- .../javatime/JavaTimeJdbcTypeTests.java | 24 +- .../JoinFetchedManyToOneAllowProxyTests.java | 2 +- .../LanyProxylessManyToOneTests.java | 2 +- .../test/mapping/lazytoone/LazyToOneTest.java | 48 +- .../ManyToOneExplicitOptionTests.java | 2 +- .../InverseToOneExplicitOptionTests.java | 2 +- .../ManyToManyUnidirectionalFetchTest.java | 2 +- ...ManyToOneBidirectionalCircularityTest.java | 2 +- .../manytoone/ManyToOneBidirectionalTest.java | 2 +- .../ManyToOneWithAnyAndSecondaryTable.java | 2 +- .../manytoone/ManyToOneWithAnyTest.java | 10 +- ...erseManyToOneJoinTableCompositeIdTest.java | 2 +- ...InverseManyToOneJoinTableSimpleIdTest.java | 2 +- .../MappedByCompositeNonAssociationTest.java | 2 +- .../mappedBy/MappedByNonAssociationTest.java | 2 +- .../attribute/AttributeImmutabilityTest.java | 38 +- .../attribute/ImmutableMapAsBasicTests.java | 8 +- .../attribute/MutableMapAsBasicTests.java | 8 +- .../mapping/naturalid/ValidationTests.java | 4 +- .../AbstractCompositeIdAndNaturalIdTest.java | 2 +- .../composite/EmbeddedNaturalIdTest.java | 2 +- ...tableManyToOneNaturalIdAnnotationTest.java | 8 +- .../ImmutableManyToOneNaturalIdHbmTest.java | 10 +- .../immutable/ImmutableNaturalIdTest.java | 15 +- .../ImmutableEntityNaturalIdTest.java | 46 +- .../inheritance/InheritedNaturalIdTest.java | 6 +- .../MappedSuperclassOverrideTest.java | 2 +- .../cache/InheritedNaturalIdCacheTest.java | 6 +- .../cache/InheritedNaturalIdNoCacheTest.java | 2 +- .../spread/SpreadNaturalIdTest.java | 2 +- ...turalIdInUninitializedAssociationTest.java | 12 +- .../NaturalIdInUninitializedProxyTest.java | 8 +- .../mutable/MutableNaturalIdTest.java | 18 +- ...edMutableNaturalIdStrictReadWriteTest.java | 8 +- .../cached/CachedMutableNaturalIdTest.java | 12 +- .../nullable/NullableNaturalIdTest.java | 14 +- .../onetomany/OneToManyBidirectionalTest.java | 13 +- .../test/mapping/onetomany/OneToManyTest.java | 2 +- .../mapping/onetoone/OneToOneErrorTest.java | 4 +- .../OneToOneJoinTableNonOptionalTest.java | 4 +- .../onetoone/ToOneSelfReferenceTest.java | 2 +- .../hhh9798/OneToOneJoinTableTest.java | 2 +- .../primarykey/NullablePrimaryKeyTest.java | 6 +- .../test/mapping/quote/ColumnQuoteTest.java | 6 +- .../typedmanytoone/TypedManyToOneTest.java | 2 +- 367 files changed, 6563 insertions(+), 8146 deletions(-) delete mode 100644 hibernate-core/src/test/java/org/hibernate/orm/test/jpa/persistenceunit/TwoPersistenceUnits2LCDisabledEnabled.java create mode 100644 hibernate-core/src/test/java/org/hibernate/orm/test/jpa/persistenceunit/TwoPersistenceUnits2LCDisabledEnabledTest.java create mode 100644 hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/bitset/BitSetTypeContributor.java diff --git a/hibernate-core/src/test/java/NoPackageTest.java b/hibernate-core/src/test/java/NoPackageTest.java index 2c606c6797ae..e6bfb8740252 100644 --- a/hibernate-core/src/test/java/NoPackageTest.java +++ b/hibernate-core/src/test/java/NoPackageTest.java @@ -4,9 +4,11 @@ */ import org.hibernate.query.Query; +import org.hibernate.testing.orm.junit.DomainModel; import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; -import org.junit.Test; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.junit.jupiter.api.Test; import static org.junit.Assert.assertEquals; @@ -15,18 +17,20 @@ * We had problems with ByteBuddy in the past. */ @JiraKey(value = "HHH-13112") -public class NoPackageTest extends BaseCoreFunctionalTestCase { +@DomainModel(annotatedClasses = {AnnotationMappedNoPackageEntity.class}) +@SessionFactory +public class NoPackageTest { @Test - public void testNoException() { - inTransaction( session -> { + public void testNoException(SessionFactoryScope scope) { + scope.inTransaction( session -> { AnnotationMappedNoPackageEntity box = new AnnotationMappedNoPackageEntity(); box.setId( 42 ); box.setName( "This feels dirty" ); session.persist( box ); } ); - inTransaction( session -> { + scope.inTransaction( session -> { Query query = session.createQuery( "select e from " + AnnotationMappedNoPackageEntity.class.getSimpleName() + " e", AnnotationMappedNoPackageEntity.class @@ -35,11 +39,4 @@ public void testNoException() { assertEquals( (Integer) 42, box.getId() ); } ); } - - @Override - public Class[] getAnnotatedClasses() { - return new Class[] { - AnnotationMappedNoPackageEntity.class - }; - } } diff --git a/hibernate-core/src/test/java/org/hibernate/bytecode/internal/bytebuddy/ByteBuddyBasicProxyFactoryTest.java b/hibernate-core/src/test/java/org/hibernate/bytecode/internal/bytebuddy/ByteBuddyBasicProxyFactoryTest.java index c7c158d4a44d..7a1419dffd29 100644 --- a/hibernate-core/src/test/java/org/hibernate/bytecode/internal/bytebuddy/ByteBuddyBasicProxyFactoryTest.java +++ b/hibernate-core/src/test/java/org/hibernate/bytecode/internal/bytebuddy/ByteBuddyBasicProxyFactoryTest.java @@ -4,14 +4,14 @@ */ package org.hibernate.bytecode.internal.bytebuddy; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.assertNotEquals; import org.hibernate.testing.orm.junit.JiraKey; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class ByteBuddyBasicProxyFactoryTest { diff --git a/hibernate-core/src/test/java/org/hibernate/bytecode/internal/bytebuddy/EnhanceByteCodeNotInProvidedClassLoaderTest.java b/hibernate-core/src/test/java/org/hibernate/bytecode/internal/bytebuddy/EnhanceByteCodeNotInProvidedClassLoaderTest.java index acaf123fda08..85460ecad229 100644 --- a/hibernate-core/src/test/java/org/hibernate/bytecode/internal/bytebuddy/EnhanceByteCodeNotInProvidedClassLoaderTest.java +++ b/hibernate-core/src/test/java/org/hibernate/bytecode/internal/bytebuddy/EnhanceByteCodeNotInProvidedClassLoaderTest.java @@ -14,8 +14,8 @@ import org.hibernate.bytecode.enhance.spi.Enhancer; import org.hibernate.testing.orm.junit.JiraKey; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; /** * Tests that bytecode can be enhanced when the original class cannot be loaded from @@ -31,9 +31,9 @@ public void test() { // Now use a fake class name so it won't be found in the ClassLoader // provided by DefaultEnhancementContext byte[] enhanced = enhancer.enhance( SimpleEntity.class.getName() + "Fake", buffer ); - Assert.assertNotNull( "This is null when there have been swallowed exceptions during enhancement. Check Logs!", enhanced ); + Assertions.assertNotNull( enhanced, "This is null when there have been swallowed exceptions during enhancement. Check Logs!" ); // Make sure enhanced bytecode is different from original bytecode. - Assert.assertFalse( Arrays.equals( buffer, enhanced ) ); + Assertions.assertFalse( Arrays.equals( buffer, enhanced ) ); } private byte[] readResource(Class clazz) { @@ -52,7 +52,7 @@ private byte[] readResource(Class clazz) { os.close(); } catch (IOException ex) { - Assert.fail( "Should not have an IOException here" ); + Assertions.fail( "Should not have an IOException here" ); } return os.toByteArray(); } diff --git a/hibernate-core/src/test/java/org/hibernate/bytecode/internal/bytebuddy/EnhancerWildFlyNamesTest.java b/hibernate-core/src/test/java/org/hibernate/bytecode/internal/bytebuddy/EnhancerWildFlyNamesTest.java index 23bd2808af24..e417ef189161 100644 --- a/hibernate-core/src/test/java/org/hibernate/bytecode/internal/bytebuddy/EnhancerWildFlyNamesTest.java +++ b/hibernate-core/src/test/java/org/hibernate/bytecode/internal/bytebuddy/EnhancerWildFlyNamesTest.java @@ -13,8 +13,8 @@ import org.hibernate.bytecode.enhance.spi.Enhancer; import org.hibernate.testing.orm.junit.JiraKey; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; /** * WildFly will use class names in "internal JVM format" when invoking the enhancer, @@ -34,10 +34,10 @@ public void test() { buffer = readResource( resourceName ); } catch (IOException e) { - Assert.fail( "Should not have an IOException here" ); + Assertions.fail( "Should not have an IOException here" ); } byte[] enhanced = enhancer.enhance( internalName, buffer ); - Assert.assertNotNull( "This is null when there have been swallowed exceptions during enhancement. Check Logs!", enhanced ); + Assertions.assertNotNull( enhanced, "This is null when there have been swallowed exceptions during enhancement. Check Logs!" ); } private byte[] readResource(String resourceName) throws IOException { diff --git a/hibernate-core/src/test/java/org/hibernate/bytecode/internal/bytebuddy/GenerateProxiesTest.java b/hibernate-core/src/test/java/org/hibernate/bytecode/internal/bytebuddy/GenerateProxiesTest.java index 9bd43779263b..8a397ad442a3 100644 --- a/hibernate-core/src/test/java/org/hibernate/bytecode/internal/bytebuddy/GenerateProxiesTest.java +++ b/hibernate-core/src/test/java/org/hibernate/bytecode/internal/bytebuddy/GenerateProxiesTest.java @@ -4,12 +4,12 @@ */ package org.hibernate.bytecode.internal.bytebuddy; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNotNull; import java.lang.reflect.InvocationTargetException; import org.hibernate.proxy.pojo.bytebuddy.ByteBuddyProxyHelper; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class GenerateProxiesTest { diff --git a/hibernate-core/src/test/java/org/hibernate/bytecode/internal/bytebuddy/ReflectionOptimizerTests.java b/hibernate-core/src/test/java/org/hibernate/bytecode/internal/bytebuddy/ReflectionOptimizerTests.java index 03dc4573ceed..44c601e8a48c 100644 --- a/hibernate-core/src/test/java/org/hibernate/bytecode/internal/bytebuddy/ReflectionOptimizerTests.java +++ b/hibernate-core/src/test/java/org/hibernate/bytecode/internal/bytebuddy/ReflectionOptimizerTests.java @@ -6,10 +6,10 @@ import org.hibernate.bytecode.spi.ReflectionOptimizer; import org.hibernate.testing.orm.junit.JiraKey; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNotNull; /** * @author Steve Ebersole diff --git a/hibernate-core/src/test/java/org/hibernate/bytecode/internal/bytebuddy/SimpleEnhancerTests.java b/hibernate-core/src/test/java/org/hibernate/bytecode/internal/bytebuddy/SimpleEnhancerTests.java index 669355a4bb4f..fd7a09dff585 100644 --- a/hibernate-core/src/test/java/org/hibernate/bytecode/internal/bytebuddy/SimpleEnhancerTests.java +++ b/hibernate-core/src/test/java/org/hibernate/bytecode/internal/bytebuddy/SimpleEnhancerTests.java @@ -9,7 +9,7 @@ import org.hibernate.bytecode.enhance.spi.EnhancementException; import org.hibernate.bytecode.enhance.spi.Enhancer; import org.hibernate.bytecode.spi.ByteCodeHelper; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; diff --git a/hibernate-core/src/test/java/org/hibernate/bytecode/internal/bytebuddy/SuperTypesEnhancementTest.java b/hibernate-core/src/test/java/org/hibernate/bytecode/internal/bytebuddy/SuperTypesEnhancementTest.java index 70d58ff69a3e..95504c8e10d9 100644 --- a/hibernate-core/src/test/java/org/hibernate/bytecode/internal/bytebuddy/SuperTypesEnhancementTest.java +++ b/hibernate-core/src/test/java/org/hibernate/bytecode/internal/bytebuddy/SuperTypesEnhancementTest.java @@ -17,12 +17,16 @@ import org.hibernate.proxy.pojo.bytebuddy.ByteBuddyProxyHelper; import org.hibernate.testing.orm.junit.JiraKey; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + /** * Verifies that proxies being generated by ByteBuddyProxyHelper * do not break the contract with PrimeAmongSecondarySupertypes. @@ -58,15 +62,15 @@ private static Stream interfaces() { public void testNamingConventions(Method m) { final Class returnType = m.getReturnType(); final String expectedMethodName = "as" + returnType.getSimpleName(); - Assert.assertEquals( expectedMethodName, m.getName() ); - Assert.assertNotNull( m.isDefault() ); + assertEquals( expectedMethodName, m.getName() ); + assertNotNull( m.isDefault() ); } @ParameterizedTest @MethodSource("superTypeMethods") public void testAllsubInterfacesExtendTheSingleparent(Method m) { final Class returnType = m.getReturnType(); - Assert.assertTrue( PrimeAmongSecondarySupertypes.class.isAssignableFrom( returnType ) ); + assertTrue( PrimeAmongSecondarySupertypes.class.isAssignableFrom( returnType ) ); } @ParameterizedTest @@ -74,20 +78,20 @@ public void testAllsubInterfacesExtendTheSingleparent(Method m) { public void testSubInterfaceOverrides(Method m) throws NoSuchMethodException { final Class returnType = m.getReturnType(); final Method subMethod = returnType.getMethod( m.getName(), m.getParameterTypes() ); - Assert.assertNotNull( subMethod ); - Assert.assertNotNull( subMethod.isDefault() ); + assertNotNull( subMethod ); + assertNotNull( subMethod.isDefault() ); } @Test public void testHibernateProxyGeneration() { ProxyFactory enhancer = createProxyFactory( SampleClass.class, HibernateProxy.class ); final Object proxy = enhancer.getProxy( Integer.valueOf( 1 ), null ); - Assert.assertTrue( HibernateProxy.class.isAssignableFrom( proxy.getClass() ) ); - Assert.assertTrue( proxy instanceof HibernateProxy ); + assertTrue( HibernateProxy.class.isAssignableFrom( proxy.getClass() ) ); + assertTrue( proxy instanceof HibernateProxy ); PrimeAmongSecondarySupertypes casted = (PrimeAmongSecondarySupertypes) proxy; final HibernateProxy extracted = casted.asHibernateProxy(); - Assert.assertNotNull( extracted ); - Assert.assertSame( proxy, extracted ); + assertNotNull( extracted ); + Assertions.assertSame( proxy, extracted ); testForLIE( (SampleClass) proxy ); } @@ -96,8 +100,8 @@ public void testHibernateProxyGeneration() { */ private void testForLIE(SampleClass sampleProxy) { SampleClass other = new SampleClass(); - Assert.assertEquals( 7, other.additionMethod( 3,4 ) ); - Assert.assertThrows( LazyInitializationException.class, () -> sampleProxy.additionMethod( 3, 4 ) ); + assertEquals( 7, other.additionMethod( 3,4 ) ); + Assertions.assertThrows( LazyInitializationException.class, () -> sampleProxy.additionMethod( 3, 4 ) ); } private ProxyFactory createProxyFactory(Class persistentClass, Class... interfaces) { diff --git a/hibernate-core/src/test/java/org/hibernate/dialect/H2DialectDatabaseVersionTest.java b/hibernate-core/src/test/java/org/hibernate/dialect/H2DialectDatabaseVersionTest.java index 7ffa7e97023d..410d1940b4f6 100644 --- a/hibernate-core/src/test/java/org/hibernate/dialect/H2DialectDatabaseVersionTest.java +++ b/hibernate-core/src/test/java/org/hibernate/dialect/H2DialectDatabaseVersionTest.java @@ -4,20 +4,19 @@ */ package org.hibernate.dialect; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.Map; import org.hibernate.engine.jdbc.dialect.spi.DialectResolutionInfo; -import org.hibernate.testing.RequiresDialect; +import org.hibernate.testing.orm.junit.RequiresDialect; import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseUnitTestCase; -import org.junit.Test; +import org.junit.jupiter.api.Test; @RequiresDialect(H2Dialect.class) @JiraKey(value = "HHH-17791") -public class H2DialectDatabaseVersionTest extends BaseUnitTestCase { +public class H2DialectDatabaseVersionTest { @Test public void snapshotVersion() { diff --git a/hibernate-core/src/test/java/org/hibernate/dialect/MySQLDialectDatabaseVersionTest.java b/hibernate-core/src/test/java/org/hibernate/dialect/MySQLDialectDatabaseVersionTest.java index 3c60725e5b95..2dc822a291b6 100644 --- a/hibernate-core/src/test/java/org/hibernate/dialect/MySQLDialectDatabaseVersionTest.java +++ b/hibernate-core/src/test/java/org/hibernate/dialect/MySQLDialectDatabaseVersionTest.java @@ -6,17 +6,16 @@ import java.util.Map; import org.hibernate.engine.jdbc.dialect.spi.DialectResolutionInfo; -import org.hibernate.testing.RequiresDialect; +import org.hibernate.testing.orm.junit.RequiresDialect; import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseUnitTestCase; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; @RequiresDialect(MySQLDialect.class) @JiraKey(value = "HHH-18518") -public class MySQLDialectDatabaseVersionTest extends BaseUnitTestCase { +public class MySQLDialectDatabaseVersionTest { @Test public void versionWithSuffix() { diff --git a/hibernate-core/src/test/java/org/hibernate/engine/jdbc/env/internal/SkipLoadingSequenceInformationTest.java b/hibernate-core/src/test/java/org/hibernate/engine/jdbc/env/internal/SkipLoadingSequenceInformationTest.java index 2d1e1daad9c2..7bf1e314f68d 100644 --- a/hibernate-core/src/test/java/org/hibernate/engine/jdbc/env/internal/SkipLoadingSequenceInformationTest.java +++ b/hibernate-core/src/test/java/org/hibernate/engine/jdbc/env/internal/SkipLoadingSequenceInformationTest.java @@ -11,16 +11,18 @@ import org.hibernate.annotations.GenericGenerator; import org.hibernate.cfg.AvailableSettings; -import org.hibernate.cfg.Configuration; import org.hibernate.cfg.Environment; import org.hibernate.dialect.H2Dialect; -import org.hibernate.id.SequenceMismatchStrategy; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.ServiceRegistry; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.Setting; +import org.hibernate.testing.orm.junit.SettingProvider; import org.hibernate.tool.schema.extract.spi.SequenceInformationExtractor; -import org.hibernate.testing.RequiresDialect; +import org.hibernate.testing.orm.junit.RequiresDialect; import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Verifies that setting {@code AvailableSettings.SEQUENCE_INCREMENT_SIZE_MISMATCH_STRATEGY} to {@code none} @@ -28,13 +30,13 @@ */ @RequiresDialect( H2Dialect.class ) @JiraKey( value = "HHH-14667") -public class SkipLoadingSequenceInformationTest extends BaseCoreFunctionalTestCase { - - @Override - protected void configure(Configuration configuration) { - configuration.setProperty( AvailableSettings.SEQUENCE_INCREMENT_SIZE_MISMATCH_STRATEGY, SequenceMismatchStrategy.NONE ); - configuration.setProperty( Environment.DIALECT, VetoingDialect.class ); - } +@DomainModel(annotatedClasses = {SkipLoadingSequenceInformationTest.SequencingEntity.class}) +@SessionFactory +@ServiceRegistry( + settings = { @Setting( name = AvailableSettings.SEQUENCE_INCREMENT_SIZE_MISMATCH_STRATEGY, value = "NONE") }, + settingProviders = { @SettingProvider( settingName = Environment.DIALECT, provider = SkipLoadingSequenceInformationTest.VetoingDialectClassProvider.class) } +) +public class SkipLoadingSequenceInformationTest { @Entity(name="seqentity") static class SequencingEntity { @@ -51,11 +53,6 @@ static class SequencingEntity { String name; } - @Override - protected Class[] getAnnotatedClasses() { - return new Class[]{SequencingEntity.class}; - } - @Test public void test() { // If it's able to boot, we're good. @@ -68,4 +65,11 @@ public SequenceInformationExtractor getSequenceInformationExtractor() { } } + public static class VetoingDialectClassProvider implements SettingProvider.Provider> { + @Override + public Class getSetting() { + return VetoingDialect.class; + } + } + } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/actionqueue/CustomAfterCompletionTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/actionqueue/CustomAfterCompletionTest.java index 2fd6cb703dd0..6f54f0fb6914 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/actionqueue/CustomAfterCompletionTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/actionqueue/CustomAfterCompletionTest.java @@ -10,63 +10,58 @@ import jakarta.persistence.Id; import org.hibernate.HibernateException; -import org.hibernate.action.spi.AfterTransactionCompletionProcess; -import org.hibernate.engine.spi.SharedSessionContractImplementor; +import org.hibernate.testing.orm.junit.DomainModel; import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; -import org.junit.Assert; -import org.junit.Test; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.instanceOf; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; -public class CustomAfterCompletionTest extends BaseCoreFunctionalTestCase { +@DomainModel(annotatedClasses = {CustomAfterCompletionTest.SimpleEntity.class}) +@SessionFactory +public class CustomAfterCompletionTest { + + @AfterEach + public void cleanup(SessionFactoryScope scope) { + scope.inTransaction( session -> session.getSessionFactory().getSchemaManager().truncate() ); + } @Test @JiraKey(value = "HHH-13666") - public void success() { - inSession( session -> { + public void success(SessionFactoryScope scope) { + scope.inSession( session -> { AtomicBoolean called = new AtomicBoolean( false ); - session.getActionQueue().registerCallback( new AfterTransactionCompletionProcess() { - @Override - public void doAfterTransactionCompletion(boolean success, SharedSessionContractImplementor session) { - called.set( true ); - } - } ); - Assert.assertFalse( called.get() ); - inTransaction( session, theSession -> { - theSession.persist( new SimpleEntity( "jack" ) ); - } ); - Assert.assertTrue( called.get() ); + session.getActionQueue().registerCallback( + (success, session1) -> called.set(true) ); + Assertions.assertFalse( called.get() ); + scope.inTransaction( session, theSession -> theSession.persist(new SimpleEntity("jack")) ); + Assertions.assertTrue( called.get() ); } ); // Check that the transaction was committed - inTransaction( session -> { - long count = session.createQuery( "select count(*) from SimpleEntity", Long.class ) - .uniqueResult(); + scope.inTransaction( session -> { + long count = session.createQuery( "select count(*) from SimpleEntity", Long.class ).uniqueResult(); assertEquals( 1L, count ); } ); } @Test @JiraKey(value = "HHH-13666") - public void failure() { + public void failure(SessionFactoryScope scope) { try { - inSession( session -> { - session.getActionQueue().registerCallback( new AfterTransactionCompletionProcess() { - @Override - public void doAfterTransactionCompletion(boolean success, SharedSessionContractImplementor session) { - throw new RuntimeException( "My exception" ); - } - } ); - inTransaction( session, theSession -> { - theSession.persist( new SimpleEntity( "jack" ) ); - } ); + scope.inSession( session -> { + session.getActionQueue().registerCallback( + (success, session1) -> {throw new RuntimeException( "My exception" );} ); + scope.inTransaction( session, theSession -> theSession.persist(new SimpleEntity("jack")) ); } ); - Assert.fail( "Expected exception to be thrown" ); + Assertions.fail( "Expected exception to be thrown" ); } catch (Exception e) { assertThat( e, instanceOf( HibernateException.class ) ); @@ -80,23 +75,13 @@ public void doAfterTransactionCompletion(boolean success, SharedSessionContractI } // Check that the transaction was committed - inTransaction( session -> { + scope.inTransaction( session -> { long count = session.createQuery( "select count(*) from SimpleEntity", Long.class ) .uniqueResult(); assertEquals( 1L, count ); } ); } - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { SimpleEntity.class }; - } - - @Override - protected boolean isCleanupTestDataRequired() { - return true; - } - @Entity(name = "SimpleEntity") public static class SimpleEntity { @Id diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/actionqueue/CustomBeforeCompletionTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/actionqueue/CustomBeforeCompletionTest.java index 4aa869f83806..ed219c78421e 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/actionqueue/CustomBeforeCompletionTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/actionqueue/CustomBeforeCompletionTest.java @@ -10,36 +10,42 @@ import jakarta.persistence.Id; import org.hibernate.HibernateException; -import org.hibernate.action.spi.BeforeTransactionCompletionProcess; -import org.hibernate.engine.spi.SharedSessionContractImplementor; +import org.hibernate.testing.orm.junit.DomainModel; import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; -import org.junit.Assert; -import org.junit.Test; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.instanceOf; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; -public class CustomBeforeCompletionTest extends BaseCoreFunctionalTestCase { +@DomainModel(annotatedClasses = {CustomBeforeCompletionTest.SimpleEntity.class}) +@SessionFactory +public class CustomBeforeCompletionTest { + + @AfterEach + public void cleanup(SessionFactoryScope scope) { + scope.inTransaction( session -> session.getSessionFactory().getSchemaManager().truncate() ); + } @Test @JiraKey(value = "HHH-13666") - public void success() { - inSession( session -> { + public void success(SessionFactoryScope scope) { + scope.inSession( session -> { AtomicBoolean called = new AtomicBoolean( false ); - session.getActionQueue().registerCallback( s -> called.set( true ) ); - Assert.assertFalse( called.get() ); - inTransaction( session, theSession -> { - theSession.persist( new SimpleEntity( "jack" ) ); - } ); - Assert.assertTrue( called.get() ); + session.getActionQueue().registerCallback( s -> called.set(true) ); + Assertions.assertFalse( called.get() ); + scope.inTransaction( session, theSession -> theSession.persist(new SimpleEntity("jack")) ); + Assertions.assertTrue( called.get() ); } ); // Check that the transaction was committed - inTransaction( session -> { + scope.inTransaction( session -> { long count = session.createQuery( "select count(*) from SimpleEntity", Long.class ) .uniqueResult(); assertEquals( 1L, count ); @@ -48,20 +54,15 @@ public void success() { @Test @JiraKey(value = "HHH-13666") - public void failure() { + public void failure(SessionFactoryScope scope) { try { - inSession( session -> { - session.getActionQueue().registerCallback( new BeforeTransactionCompletionProcess() { - @Override - public void doBeforeTransactionCompletion(SharedSessionContractImplementor session) { - throw new RuntimeException( "My exception" ); - } - } ); - inTransaction( session, theSession -> { - theSession.persist( new SimpleEntity( "jack" ) ); + scope.inSession( session -> { + session.getActionQueue().registerCallback( session1 -> { + throw new RuntimeException( "My exception" ); } ); + scope.inTransaction( session, theSession -> theSession.persist(new SimpleEntity("jack")) ); } ); - Assert.fail( "Expected exception to be thrown" ); + Assertions.fail( "Expected exception to be thrown" ); } catch (Exception e) { assertThat( e, instanceOf( HibernateException.class ) ); @@ -75,23 +76,13 @@ public void doBeforeTransactionCompletion(SharedSessionContractImplementor sessi } // Check that the transaction was rolled back - inTransaction( session -> { + scope.inTransaction( session -> { long count = session.createQuery( "select count(*) from SimpleEntity", Long.class ) .uniqueResult(); assertEquals( 0L, count ); } ); } - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { SimpleEntity.class }; - } - - @Override - protected boolean isCleanupTestDataRequired() { - return true; - } - @Entity(name = "SimpleEntity") public static class SimpleEntity { @Id 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 3082a961b657..fa2f51a65345 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 @@ -7,9 +7,9 @@ import org.hibernate.Session; import org.hibernate.StatelessSession; import org.hibernate.annotations.CreationTimestamp; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; -import org.junit.Assert; -import org.junit.Test; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.Test; import jakarta.persistence.Column; import jakarta.persistence.Entity; @@ -23,22 +23,16 @@ import org.hibernate.testing.orm.junit.JiraKey; -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; +import static org.junit.jupiter.api.Assertions.assertNotNull; /** * @author Borys Piela */ -public class CreationTimestampTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[]{ - Event.class - }; - } +@Jpa(annotatedClasses = {CreationTimestampTest.Event.class}) +public class CreationTimestampTest { @Entity(name = "Event") - private static class Event { + static class Event { @Id @GeneratedValue @@ -173,8 +167,8 @@ public ZonedDateTime getZonedDateTime() { } @Test - public void generatesCurrentTimestamp() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void generatesCurrentTimestamp(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { Event event = new Event(); entityManager.persist(event); entityManager.flush(); @@ -184,8 +178,8 @@ public void generatesCurrentTimestamp() { @Test @JiraKey( value = "HHH-16240") - public void generatesCurrentTimestampInStatelessSession() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void generatesCurrentTimestampInStatelessSession(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { Session session = entityManager.unwrap( Session.class); try (StatelessSession statelessSession = session.getSessionFactory().openStatelessSession()) { Event event = new Event(); @@ -198,20 +192,20 @@ public void generatesCurrentTimestampInStatelessSession() { } 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()); + assertNotNull(event.getDate()); + assertNotNull(event.getCalendar()); + assertNotNull(event.getSqlDate()); + assertNotNull(event.getTime()); + assertNotNull(event.getTimestamp()); + assertNotNull(event.getInstant()); + assertNotNull(event.getLocalDate()); + assertNotNull(event.getLocalDateTime()); + assertNotNull(event.getLocalTime()); + assertNotNull(event.getMonthDay()); + assertNotNull(event.getOffsetDateTime()); + assertNotNull(event.getOffsetTime()); + assertNotNull(event.getYear()); + assertNotNull(event.getYearMonth()); + assertNotNull(event.getZonedDateTime()); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/GenericConverterAutoApplyTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/GenericConverterAutoApplyTest.java index 488410b048f8..53b70261c65a 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/GenericConverterAutoApplyTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/GenericConverterAutoApplyTest.java @@ -7,14 +7,16 @@ import jakarta.persistence.AttributeConverter; import jakarta.persistence.Converter; import jakarta.persistence.Entity; +import jakarta.persistence.EntityManager; import jakarta.persistence.GeneratedValue; import jakarta.persistence.Id; import jakarta.persistence.metamodel.EntityType; import jakarta.persistence.metamodel.SingularAttribute; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; import org.hibernate.testing.orm.junit.JiraKey; +import org.hibernate.testing.orm.junit.Jpa; import org.hibernate.type.BasicType; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.List; @@ -24,25 +26,25 @@ * @author Yanming Zhou */ @JiraKey("HHH-18012") -public class GenericConverterAutoApplyTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[]{IntegerArrayConverter.class, IntegerListConverter.class, TestEntity.class}; - } +@Jpa(annotatedClasses = { + GenericConverterAutoApplyTest.IntegerArrayConverter.class, + GenericConverterAutoApplyTest.IntegerListConverter.class, + GenericConverterAutoApplyTest.TestEntity.class} +) +public class GenericConverterAutoApplyTest { @Test - public void genericArrayIsAutoApplied() { - assertAttributeIsMappingToString("integerArray"); + public void genericArrayIsAutoApplied(EntityManagerFactoryScope scope) { + assertAttributeIsMappingToString( scope.getEntityManagerFactory().createEntityManager(), "integerArray" ); } @Test - public void genericListIsAutoApplied() { - assertAttributeIsMappingToString("integerList"); + public void genericListIsAutoApplied(EntityManagerFactoryScope scope) { + assertAttributeIsMappingToString( scope.getEntityManagerFactory().createEntityManager(), "integerList" ); } - private void assertAttributeIsMappingToString(String name) { - EntityType entityType = getOrCreateEntityManager().getMetamodel().entity(TestEntity.class); + private void assertAttributeIsMappingToString(EntityManager em, String name) { + EntityType entityType = em.getMetamodel().entity(TestEntity.class); assertThat(entityType.getAttribute(name)).isInstanceOfSatisfying(SingularAttribute.class, sa -> assertThat(sa.getType()).isInstanceOfSatisfying(BasicType.class, bt -> assertThat(bt.getJdbcJavaType().getJavaType()).isEqualTo(String.class) 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 8fd64b48d02f..05d4eb2c87c3 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 @@ -9,19 +9,17 @@ import jakarta.persistence.Entity; import jakarta.persistence.Id; import jakarta.persistence.MappedSuperclass; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; import org.hibernate.testing.orm.junit.JiraKey; -import org.junit.Test; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.Test; @JiraKey( value = "HHH-16122" ) -public class HHH16122Test extends BaseEntityManagerFunctionalTestCase { - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { ValueConverter.class, SuperClass.class, SubClass.class }; - } +@Jpa( annotatedClasses = {HHH16122Test.ValueConverter.class, HHH16122Test.SuperClass.class, HHH16122Test.SubClass.class} ) +public class HHH16122Test { @Test - public void testGenericSuperClassWithConverter() { + public void testGenericSuperClassWithConverter(EntityManagerFactoryScope scope) { // The test is successful if the entity manager factory can be built. } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/InMemoryCreationTimestampNullableColumnTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/InMemoryCreationTimestampNullableColumnTest.java index b5f83f2e5716..92dca5727bb9 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/InMemoryCreationTimestampNullableColumnTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/InMemoryCreationTimestampNullableColumnTest.java @@ -12,26 +12,19 @@ import org.hibernate.annotations.CreationTimestamp; import org.hibernate.annotations.NaturalId; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; import org.hibernate.testing.orm.junit.JiraKey; -import org.junit.Assert; -import org.junit.Test; - -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; /** * @author Vlad Mihalcea */ @JiraKey(value = "HHH-11096") -public class InMemoryCreationTimestampNullableColumnTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Person.class - }; - } +@Jpa( annotatedClasses = {InMemoryCreationTimestampNullableColumnTest.Person.class} ) +public class InMemoryCreationTimestampNullableColumnTest { @Entity(name = "Person") public static class Person { @@ -65,14 +58,14 @@ public void setCreationDate(Date creationDate) { } @Test - public void generatesCurrentTimestamp() { - doInJPA( this::entityManagerFactory, entityManager -> { + public void generatesCurrentTimestamp(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { Person person = new Person(); person.setName( "John Doe" ); entityManager.persist( person ); entityManager.flush(); - Assert.assertNotNull( person.getCreationDate() ); + Assertions.assertNotNull( person.getCreationDate() ); } ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/InMemoryTimestampGenerationBatchTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/InMemoryTimestampGenerationBatchTest.java index b79d0be58652..fbadc38d0ff3 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/InMemoryTimestampGenerationBatchTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/InMemoryTimestampGenerationBatchTest.java @@ -19,6 +19,7 @@ import org.hibernate.testing.orm.junit.SessionFactoryScope; import org.hibernate.testing.orm.junit.Setting; import org.hibernate.testing.orm.junit.SettingProvider; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.time.Instant; @@ -34,13 +35,19 @@ @SessionFactory(generateStatistics = true) @ServiceRegistry(settings = @Setting(name = AvailableSettings.STATEMENT_BATCH_SIZE, value = "5"), settingProviders = @SettingProvider(settingName = CurrentTimestampGeneration.CLOCK_SETTING_NAME, - provider = InMemoryTimestampGenerationBatchTest.MutableClockProvider.class)) + provider = MutableClockSettingProvider.class)) @Jira("https://hibernate.atlassian.net/browse/HHH-19840") public class InMemoryTimestampGenerationBatchTest { - private static final MutableClock clock = new MutableClock(); + private MutableClock clock; private static final int PERSON_COUNT = 8; + @BeforeEach + public void setup(SessionFactoryScope scope) { + clock = CurrentTimestampGeneration.getClock( scope.getSessionFactory() ); + clock.reset(); + } + @Test public void test(SessionFactoryScope scope) throws InterruptedException { final var statistics = scope.getSessionFactory().getStatistics(); @@ -94,13 +101,6 @@ public void test(SessionFactoryScope scope) throws InterruptedException { } ); } - public static class MutableClockProvider implements SettingProvider.Provider { - @Override - public Object getSetting() { - return clock; - } - } - @Entity(name = "Person") public static class Person { @Id diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/InMemoryTimestampGenerationTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/InMemoryTimestampGenerationTest.java index 9854a794646b..4ca5ac867345 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/InMemoryTimestampGenerationTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/InMemoryTimestampGenerationTest.java @@ -7,6 +7,7 @@ import jakarta.persistence.Column; import jakarta.persistence.Entity; import jakarta.persistence.Id; +import org.hibernate.SessionFactory; import org.hibernate.annotations.CreationTimestamp; import org.hibernate.annotations.SourceType; import org.hibernate.annotations.UpdateTimestamp; @@ -15,6 +16,7 @@ import org.hibernate.testing.orm.junit.Jira; import org.hibernate.testing.orm.junit.Jpa; import org.hibernate.testing.orm.junit.SettingProvider; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.time.Instant; @@ -26,10 +28,16 @@ @Jpa(annotatedClasses = InMemoryTimestampGenerationTest.Person.class, settingProviders = @SettingProvider(settingName = CurrentTimestampGeneration.CLOCK_SETTING_NAME, - provider = InMemoryTimestampGenerationTest.MutableClockProvider.class)) + provider = MutableClockSettingProvider.class)) @Jira("https://hibernate.atlassian.net/browse/HHH-19840") public class InMemoryTimestampGenerationTest { - private static final MutableClock clock = new MutableClock(); + private MutableClock clock; + + @BeforeEach + public void setup(EntityManagerFactoryScope scope) { + clock = CurrentTimestampGeneration.getClock( scope.getEntityManagerFactory().unwrap( SessionFactory.class ) ); + clock.reset(); + } @Test public void test(EntityManagerFactoryScope scope) throws InterruptedException { @@ -63,13 +71,6 @@ public void test(EntityManagerFactoryScope scope) throws InterruptedException { } ); } - static class MutableClockProvider implements SettingProvider.Provider { - @Override - public Object getSetting() { - return clock; - } - } - @Entity(name = "Person") static class Person { @Id diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/JoinedSubclassTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/JoinedSubclassTest.java index f25c7d3ce5c8..ca958cd7a071 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/JoinedSubclassTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/JoinedSubclassTest.java @@ -7,26 +7,38 @@ import jakarta.persistence.criteria.CriteriaBuilder; import jakarta.persistence.criteria.CriteriaQuery; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; import org.hibernate.orm.test.annotations.inheritance.Carrot; import org.hibernate.orm.test.annotations.inheritance.Tomato; import org.hibernate.orm.test.annotations.inheritance.Vegetable; import org.hibernate.orm.test.annotations.inheritance.VegetablePk; -import org.junit.Test; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertNotNull; /** * @author Emmanuel Bernard */ -public class JoinedSubclassTest extends BaseCoreFunctionalTestCase { +@DomainModel(annotatedClasses = { + Boat.class, + Ferry.class, + AmericaCupClass.class, + Country.class, + Vegetable.class, + Carrot.class, + Tomato.class +}) +@SessionFactory +public class JoinedSubclassTest { @Test - public void testDefaultValues() { + public void testDefaultValues(SessionFactoryScope scope) { Ferry ferry = new Ferry(); - inTransaction( + scope.inTransaction( s -> { ferry.setSize( 2 ); ferry.setSea( "Channel" ); @@ -34,7 +46,7 @@ public void testDefaultValues() { } ); - inTransaction( + scope.inTransaction( s -> { Ferry f = s.get( Ferry.class, ferry.getId() ); assertNotNull( f ); @@ -46,10 +58,10 @@ public void testDefaultValues() { } @Test - public void testDeclaredValues() { + public void testDeclaredValues(SessionFactoryScope scope) { Country country = new Country(); AmericaCupClass americaCupClass = new AmericaCupClass(); - inTransaction( + scope.inTransaction( s -> { country.setName( "France" ); americaCupClass.setSize( 2 ); @@ -59,7 +71,7 @@ public void testDeclaredValues() { } ); - inTransaction( + scope.inTransaction( s -> { AmericaCupClass f = s.get( AmericaCupClass.class, americaCupClass.getId() ); assertNotNull( f ); @@ -72,8 +84,8 @@ public void testDeclaredValues() { } @Test - public void testCompositePk() { - inTransaction( + public void testCompositePk(SessionFactoryScope scope) { + scope.inTransaction( s -> { Carrot c = new Carrot(); VegetablePk pk = new VegetablePk(); @@ -85,30 +97,17 @@ public void testCompositePk() { } ); - inTransaction( + scope.inTransaction( s -> { CriteriaBuilder criteriaBuilder = s.getCriteriaBuilder(); CriteriaQuery criteria = criteriaBuilder.createQuery( Vegetable.class ); criteria.from( Vegetable.class ); Vegetable v = s.createQuery( criteria ).uniqueResult(); -// Vegetable v = (Vegetable) s.createCriteria( Vegetable.class ).uniqueResult(); - assertTrue( v instanceof Carrot ); + assertInstanceOf( Carrot.class, v ); Carrot result = (Carrot) v; assertEquals( 23, result.getLength() ); } ); } - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Boat.class, - Ferry.class, - AmericaCupClass.class, - Country.class, - Vegetable.class, - Carrot.class, - Tomato.class - }; - } } 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 bc107ca4285a..c5bc4d7b00d8 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 @@ -4,7 +4,7 @@ */ package org.hibernate.orm.test.annotations; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.hibernate.AnnotationException; import org.hibernate.SessionFactory; @@ -14,7 +14,7 @@ import org.hibernate.service.ServiceRegistry; import org.hibernate.testing.ServiceRegistryBuilder; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Emmanuel Bernard diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/UpdateTimeStampInheritanceTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/UpdateTimeStampInheritanceTest.java index 509cd49583ae..2f3464804179 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/UpdateTimeStampInheritanceTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/UpdateTimeStampInheritanceTest.java @@ -9,6 +9,7 @@ import java.util.Set; import org.hibernate.Session; +import org.hibernate.SessionFactory; import org.hibernate.annotations.CreationTimestamp; import org.hibernate.annotations.UpdateTimestamp; import org.hibernate.generator.internal.CurrentTimestampGeneration; @@ -46,22 +47,15 @@ UpdateTimeStampInheritanceTest.AbstractPerson.class, UpdateTimeStampInheritanceTest.Address.class }, - settingProviders = @SettingProvider(settingName = CurrentTimestampGeneration.CLOCK_SETTING_NAME, provider = UpdateTimeStampInheritanceTest.ClockProvider.class) + settingProviders = @SettingProvider(settingName = CurrentTimestampGeneration.CLOCK_SETTING_NAME, provider = MutableClockSettingProvider.class) ) public class UpdateTimeStampInheritanceTest { private static final String customerId = "1"; - private static final MutableClock clock = new MutableClock(); - - public static class ClockProvider implements SettingProvider.Provider { - - @Override - public MutableClock getSetting() { - return clock; - } - } + private MutableClock clock; @BeforeEach public void setUp(EntityManagerFactoryScope scope) { + clock = CurrentTimestampGeneration.getClock( scope.getEntityManagerFactory().unwrap( SessionFactory.class ) ); clock.reset(); scope.inTransaction( entityManager -> { Customer customer = new Customer(); @@ -212,9 +206,7 @@ public void mergeDetachedEntity(EntityManagerFactoryScope scope) { entityManager.unwrap( Session.class ).merge( customer ); } ); - scope.inTransaction( entityManager -> { - assertModifiedAtWasNotUpdated( entityManager.find( Customer.class, customerId ) ); - } ); + scope.inTransaction( entityManager -> assertModifiedAtWasNotUpdated(entityManager.find(Customer.class, customerId)) ); } private void assertModifiedAtWasNotUpdated(Customer customer) { 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 8c3080821dab..7b7aa5b9f251 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 @@ -7,9 +7,9 @@ import org.hibernate.Session; import org.hibernate.StatelessSession; import org.hibernate.annotations.UpdateTimestamp; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; -import org.junit.Assert; -import org.junit.Test; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.Test; import jakarta.persistence.Column; import jakarta.persistence.Entity; @@ -23,22 +23,16 @@ import org.hibernate.testing.orm.junit.JiraKey; -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; +import static org.junit.jupiter.api.Assertions.assertNotNull; /** * @author Borys Piela */ -public class UpdateTimestampTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[]{ - Event.class - }; - } +@Jpa( annotatedClasses = {UpdateTimestampTest.Event.class} ) +public class UpdateTimestampTest { @Entity(name = "Event") - private static class Event { + static class Event { @Id @GeneratedValue @@ -173,8 +167,8 @@ public ZonedDateTime getZonedDateTime() { } @Test - public void generatesCurrentTimestamp() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void generatesCurrentTimestamp(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { Event event = new Event(); entityManager.persist(event); entityManager.flush(); @@ -184,8 +178,8 @@ public void generatesCurrentTimestamp() { @Test @JiraKey( value = "HHH-16240") - public void generatesCurrentTimestampInStatelessSession() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void generatesCurrentTimestampInStatelessSession(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { Session session = entityManager.unwrap( Session.class); try (StatelessSession statelessSession = session.getSessionFactory().openStatelessSession()) { Event event = new Event(); @@ -198,20 +192,20 @@ public void generatesCurrentTimestampInStatelessSession() { } 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()); + assertNotNull(event.getDate()); + assertNotNull(event.getCalendar()); + assertNotNull(event.getSqlDate()); + assertNotNull(event.getTime()); + assertNotNull(event.getTimestamp()); + assertNotNull(event.getInstant()); + assertNotNull(event.getLocalDate()); + assertNotNull(event.getLocalDateTime()); + assertNotNull(event.getLocalTime()); + assertNotNull(event.getMonthDay()); + assertNotNull(event.getOffsetDateTime()); + assertNotNull(event.getOffsetTime()); + assertNotNull(event.getYear()); + assertNotNull(event.getYearMonth()); + assertNotNull(event.getZonedDateTime()); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/DB2390DialectTestCase.java b/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/DB2390DialectTestCase.java index cec5a17f54f1..456d31409061 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/DB2390DialectTestCase.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/DB2390DialectTestCase.java @@ -12,31 +12,43 @@ import jakarta.persistence.Id; import org.hibernate.dialect.DB2zDialect; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; -import org.hibernate.testing.RequiresDialect; +import org.hibernate.testing.orm.junit.RequiresDialect; import org.hibernate.testing.orm.junit.JiraKey; -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Chris Cranford */ @JiraKey(value = "HHH-11747") @RequiresDialect(DB2zDialect.class) -public class DB2390DialectTestCase extends BaseEntityManagerFunctionalTestCase { - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { SimpleEntity.class }; +@Jpa(annotatedClasses = {DB2390DialectTestCase.SimpleEntity.class}) +public class DB2390DialectTestCase { + + @BeforeAll + public void populateSchema(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { + for ( int i = 0; i < 10; ++i ) { + final SimpleEntity simpleEntity = new SimpleEntity( i, "Entity" + i ); + entityManager.persist( simpleEntity ); + } + } ); + } + + @AfterAll + public void cleanSchema(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> scope.getEntityManagerFactory().getSchemaManager().truncate() ); } @Test - public void testLegacyLimitHandlerWithNoOffset() { - doInJPA( this::entityManagerFactory, entityManager -> { + public void testLegacyLimitHandlerWithNoOffset(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { List results = entityManager.createQuery( "FROM SimpleEntity", SimpleEntity.class ) .setMaxResults( 2 ) .getResultList(); @@ -45,8 +57,8 @@ public void testLegacyLimitHandlerWithNoOffset() { } @Test - public void testLegacyLimitHandlerWithOffset() { - doInJPA( this::entityManagerFactory, entityManager -> { + public void testLegacyLimitHandlerWithOffset(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { List results = entityManager.createQuery( "FROM SimpleEntity", SimpleEntity.class ) .setFirstResult( 2 ) .setMaxResults( 2 ) @@ -55,23 +67,6 @@ public void testLegacyLimitHandlerWithOffset() { } ); } - @Before - public void populateSchema() { - doInJPA( this::entityManagerFactory, entityManager -> { - for ( int i = 0; i < 10; ++i ) { - final SimpleEntity simpleEntity = new SimpleEntity( i, "Entity" + i ); - entityManager.persist( simpleEntity ); - } - } ); - } - - @After - public void cleanSchema() { - doInJPA( this::entityManagerFactory, entityManager -> { - entityManager.createQuery( "DELETE FROM SimpleEntity" ).executeUpdate(); - } ); - } - @Entity(name = "SimpleEntity") public static class SimpleEntity { @Id diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/DB2DialectTestCase.java b/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/DB2DialectTestCase.java index 688f39bea409..cba605cb4ee0 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/DB2DialectTestCase.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/DB2DialectTestCase.java @@ -12,14 +12,13 @@ import org.hibernate.testing.orm.junit.RequiresDialect; import org.hibernate.type.spi.TypeConfiguration; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseUnitTestCase; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * DB2 dialect related test cases @@ -28,11 +27,11 @@ */ @RequiresDialect(DB2Dialect.class) -public class DB2DialectTestCase extends BaseUnitTestCase { +public class DB2DialectTestCase { private final DB2Dialect dialect = new DB2Dialect(); private TypeConfiguration typeConfiguration; - @Before + @BeforeEach public void setup() { typeConfiguration = new TypeConfiguration(); dialect.contributeTypes( () -> typeConfiguration, null ); @@ -43,9 +42,9 @@ public void setup() { public void testGetDefaultBinaryTypeName() { String actual = typeConfiguration.getDdlTypeRegistry().getTypeName( Types.BINARY, dialect ); assertEquals( - "The default column length is 255, but char length on DB2 is limited to 254", "varbinary($l)", - actual + actual, + "The default column length is 255, but char length on DB2 is limited to 254" ); } @@ -53,27 +52,27 @@ public void testGetDefaultBinaryTypeName() { @JiraKey(value = "HHH-6866") public void testGetExplicitBinaryTypeName() { // lower bound - String actual = typeConfiguration.getDdlTypeRegistry().getTypeName( Types.BINARY, Size.length( 1) ); + String actual = typeConfiguration.getDdlTypeRegistry().getTypeName( Types.BINARY, Size.length(1) ); assertEquals( - "Wrong binary type", "binary(1)", - actual + actual, + "Wrong binary type" ); // upper bound - actual = typeConfiguration.getDdlTypeRegistry().getTypeName( Types.BINARY, Size.length( 254) ); + actual = typeConfiguration.getDdlTypeRegistry().getTypeName( Types.BINARY, Size.length(254) ); assertEquals( - "Wrong binary type. 254 is the max length in DB2", "binary(254)", - actual + actual, + "Wrong binary type. 254 is the max length in DB2" ); // exceeding upper bound - actual = typeConfiguration.getDdlTypeRegistry().getTypeName( Types.BINARY, Size.length( 255) ); + actual = typeConfiguration.getDdlTypeRegistry().getTypeName( Types.BINARY, Size.length(255) ); assertEquals( - "Wrong binary type. Should be varchar for length > 254", "varbinary(255)", - actual + actual, + "Wrong binary type. Should be varchar for length > 254" ); } @@ -85,8 +84,8 @@ public void testIntegerOverflowForMaxResults() { rowSelection.setMaxRows(Integer.MAX_VALUE); String sql = dialect.getLimitHandler().processSql( "select a.id from tbl_a a order by a.id", -1, null, new LimitQueryOptions( rowSelection ) ); assertTrue( - "Integer overflow for max rows in: " + sql, - sql.contains("fetch next ? rows only") - ); + sql.contains("fetch next ? rows only"), + "Integer overflow for max rows in: " + sql + ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/Db2VariantDialectInitTests.java b/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/Db2VariantDialectInitTests.java index bc5324e235aa..bbef28a93019 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/Db2VariantDialectInitTests.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/Db2VariantDialectInitTests.java @@ -8,9 +8,9 @@ import org.hibernate.dialect.DB2zDialect; import org.hibernate.testing.orm.junit.JiraKey; import org.hibernate.testing.orm.junit.RequiresDialect; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNotNull; /** * @author Steve Ebersole diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/DialectMinimumVersionTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/DialectMinimumVersionTest.java index 9b3e014e843c..1a8ed72cf224 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/DialectMinimumVersionTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/DialectMinimumVersionTest.java @@ -15,8 +15,6 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; - - import static org.hibernate.internal.CoreMessageLogger.CORE_LOGGER; /** 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 495bf31098a4..1ff289bfec93 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 @@ -26,8 +26,8 @@ import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; @SuppressWarnings("JUnitMalformedDeclaration") @ServiceRegistry diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/PostgreSQLDialectTestCase.java b/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/PostgreSQLDialectTestCase.java index 6cd45d703c94..d49ff139c8b6 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/PostgreSQLDialectTestCase.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/PostgreSQLDialectTestCase.java @@ -31,19 +31,18 @@ import org.hibernate.query.sqm.function.SqmFunctionRegistry; import org.hibernate.testing.orm.junit.DialectFeatureChecks; import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseUnitTestCase; import org.hibernate.testing.orm.junit.RequiresDialect; import org.hibernate.type.spi.TypeConfiguration; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; import static org.hamcrest.core.Is.is; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; /** * Test case for PostgreSQL specific things. @@ -51,7 +50,7 @@ * @author Christoph Dreis */ @RequiresDialect(PostgreSQLDialect.class) -public class PostgreSQLDialectTestCase extends BaseUnitTestCase { +public class PostgreSQLDialectTestCase { @Test @JiraKey( value = "HHH-7251") @@ -61,7 +60,7 @@ public void testDeadlockException() { assertNotNull(delegate); JDBCException exception = delegate.convert(new SQLException("Deadlock Detected", "40P01"), "", ""); - assertTrue(exception instanceof LockAcquisitionException); + assertInstanceOf( LockAcquisitionException.class, exception ); } @Test @@ -72,7 +71,7 @@ public void testTimeoutException() { assertNotNull(delegate); JDBCException exception = delegate.convert(new SQLException("Lock Not Available", "55P03"), "", ""); - assertTrue(exception instanceof PessimisticLockException); + assertInstanceOf( PessimisticLockException.class, exception ); } @Test @@ -83,7 +82,7 @@ public void testQueryTimeoutException() { assertNotNull( delegate ); final JDBCException exception = delegate.convert( new SQLException("Client cancelled operation", "57014"), "", "" ); - assertTrue( exception instanceof QueryTimeoutException ); + assertInstanceOf( QueryTimeoutException.class, exception ); } /** @@ -91,15 +90,16 @@ public void testQueryTimeoutException() { * that will effect the SELECT ... FOR UPDATE OF tableAlias1, ..., tableAliasN */ @JiraKey( value = "HHH-5654" ) + @Test public void testGetForUpdateStringWithAliasesAndLockOptions() { PostgreSQLDialect dialect = new PostgreSQLDialect(); LockOptions lockOptions = new LockOptions( LockMode.PESSIMISTIC_WRITE ); String forUpdateClause = dialect.getForUpdateString("tableAlias1", lockOptions); - assertEquals( "for update of tableAlias1", forUpdateClause ); + assertEquals( " for no key update of tableAlias1", forUpdateClause ); forUpdateClause = dialect.getForUpdateString("tableAlias1,tableAlias2", lockOptions); - assertEquals("for update of tableAlias1,tableAlias2", forUpdateClause); + assertEquals(" for no key update of tableAlias1,tableAlias2", forUpdateClause); } @Test @@ -121,7 +121,7 @@ public void testMessageException() { fail( "Expected UnsupportedOperationException" ); } catch (Exception e) { - assertTrue( e instanceof UnsupportedOperationException ); + assertInstanceOf( UnsupportedOperationException.class, e ); assertEquals( "PostgreSQL only supports accessing REF_CURSOR parameters by position", e.getMessage() ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/function/HANAFunctionsTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/function/HANAFunctionsTest.java index 5d4a7d5ebd75..024792030f5c 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/function/HANAFunctionsTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/function/HANAFunctionsTest.java @@ -4,114 +4,82 @@ */ package org.hibernate.orm.test.dialect.function; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; import java.math.BigDecimal; -import org.hibernate.Session; -import org.hibernate.Transaction; import org.hibernate.dialect.HANADialect; -import org.hibernate.query.Query; -import org.hibernate.testing.RequiresDialect; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.RequiresDialect; import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; -import org.junit.Test; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; @RequiresDialect(HANADialect.class) -public class HANAFunctionsTest extends BaseCoreFunctionalTestCase { - - @Override - protected String getBaseForMappings() { - return "org/hibernate/orm/test/"; - } - - @Override - public String[] getMappings() { - return new String[]{ "dialect/function/Product.hbm.xml" }; - } - - @Override - protected void afterSessionFactoryBuilt() { - Product product = new Product(); - product.setLength( 100 ); - product.setPrice( new BigDecimal( 1.298 ) ); - try ( Session s = openSession() ) { - Transaction tx = s.beginTransaction(); - s.persist( product ); - tx.commit(); - } +@DomainModel(xmlMappings = {"org/hibernate/orm/test/dialect/function/Product.hbm.xml"}) +@SessionFactory +public class HANAFunctionsTest { + + @BeforeEach + public void setup(SessionFactoryScope scope) { + scope.inTransaction( session -> { + Product product = new Product(); + product.setLength( 100 ); + product.setPrice( new BigDecimal( "1.298" ) ); + session.persist( product ); + } ); } @Test @JiraKey(value = "HHH-12546") - public void testLocateFunction() { - try ( Session s = openSession() ) { - Transaction tx = s.beginTransaction(); - Query q = s.createQuery( "select p from Product p where locate('.', cast(p.price as string)) > 0", Product.class ); - Product p = q.uniqueResult(); + public void testLocateFunction(SessionFactoryScope scope) { + scope.inTransaction( session -> { + Product p = session.createQuery( "select p from Product p where locate('.', cast(p.price as string)) > 0", Product.class ).uniqueResult(); assertNotNull( p ); assertEquals( 100, p.getLength() ); assertEquals( BigDecimal.valueOf( 1.29 ), p.getPrice() ); - tx.commit(); - } - - try ( Session s = openSession() ) { - Transaction tx = s.beginTransaction(); - Query q = s.createQuery( "select p from Product p where locate('.', cast(p.price as string)) = 0", Product.class ); - Product p = q.uniqueResult(); + } ); + scope.inTransaction( session -> { + Product p = session.createQuery( "select p from Product p where locate('.', cast(p.price as string)) = 0", Product.class ).uniqueResult(); assertNull( p ); - tx.commit(); - } + } ); - try ( Session s = openSession() ) { - Transaction tx = s.beginTransaction(); - Query q = s.createQuery( "select p from Product p where locate('.', cast(p.price as string), 3) > 0", Product.class ); - Product p = q.uniqueResult(); + scope.inTransaction( session -> { + Product p = session.createQuery( "select p from Product p where locate('.', cast(p.price as string), 3) > 0", Product.class ).uniqueResult(); assertNull( p ); - tx.commit(); - } + } ); } @Test - public void testSubstringFunction() { - try ( Session s = openSession() ) { - Transaction tx = s.beginTransaction(); - Query q = s.createQuery( "select p from Product p where substring(cast(p.price as string), 1, 2) = '1.'", Product.class ); - Product p = q.uniqueResult(); + public void testSubstringFunction(SessionFactoryScope scope) { + scope.inTransaction( session -> { + Product p = session.createQuery( "select p from Product p where substring(cast(p.price as string), 1, 2) = '1.'", Product.class ).uniqueResult(); assertNotNull( p ); assertEquals( 100, p.getLength() ); assertEquals( BigDecimal.valueOf( 1.29 ), p.getPrice() ); - tx.commit(); - } + } ); - try ( Session s = openSession() ) { - Transaction tx = s.beginTransaction(); - Query q = s.createQuery( "select p from Product p where substring(cast(p.price as string), 1, 2) = '.1'", Product.class ); - Product p = q.uniqueResult(); + scope.inTransaction( session -> { + Product p = session.createQuery( "select p from Product p where substring(cast(p.price as string), 1, 2) = '.1'", Product.class ).uniqueResult(); assertNull( p ); - tx.commit(); - } + } ); - try ( Session s = openSession() ) { - Transaction tx = s.beginTransaction(); - Query q = s.createQuery( "select p from Product p where substring(cast(p.price as string), 1) = '1.29'", Product.class ); - Product p = q.uniqueResult(); + scope.inTransaction( session -> { + Product p = session.createQuery( "select p from Product p where substring(cast(p.price as string), 1) = '1.29'", Product.class ).uniqueResult(); assertNotNull( p ); assertEquals( 100, p.getLength() ); assertEquals( BigDecimal.valueOf( 1.29 ), p.getPrice() ); - tx.commit(); - } + } ); - try ( Session s = openSession() ) { - Transaction tx = s.beginTransaction(); - Query q = s.createQuery( "select p from Product p where substring(cast(p.price as string), 1) = '1.'", Product.class ); - Product p = q.uniqueResult(); + scope.inTransaction( session -> { + Product p = session.createQuery( "select p from Product p where substring(cast(p.price as string), 1) = '1.'", Product.class ).uniqueResult(); assertNull( p ); - tx.commit(); - } + } ); } } 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 450327c9f337..b5e4bead7353 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 @@ -8,37 +8,30 @@ import jakarta.persistence.Id; import org.hibernate.dialect.HSQLDialect; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.hibernate.testing.orm.junit.RequiresDialect; +import org.junit.jupiter.api.Test; -import org.hibernate.testing.RequiresDialect; -import org.junit.Test; - -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** @author Vlad Mihalcea */ @RequiresDialect( HSQLDialect.class ) -public class HSQLTruncFunctionTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Person.class - }; - } +@Jpa(annotatedClasses = {HSQLTruncFunctionTest.Person.class}) +public class HSQLTruncFunctionTest { @Test - public void testTruncateAndTruncFunctions(){ - doInJPA( this::entityManagerFactory, entityManager -> { + public void testTruncateAndTruncFunctions(EntityManagerFactoryScope scope){ + scope.inTransaction( entityManager -> { Person person = new Person(); person.setId( 1L ); person.setHighestScore( 99.56d ); entityManager.persist( person ); } ); - doInJPA( this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { Double score = entityManager.createQuery( "select truncate(p.highestScore, 1) " + "from Person p " + @@ -49,7 +42,7 @@ public void testTruncateAndTruncFunctions(){ assertEquals( 99.5d, score, 0.01 ); } ); - doInJPA( this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { Double score = entityManager.createQuery( "select trunc(p.highestScore, 1) " + "from Person p " + 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 1dfd6b27db0f..18966528f5ba 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 @@ -5,52 +5,36 @@ package org.hibernate.orm.test.dialect.function; import java.math.BigDecimal; -import org.junit.Test; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.junit.jupiter.api.Test; -import org.hibernate.query.Query; -import org.hibernate.Session; -import org.hibernate.Transaction; import org.hibernate.dialect.MySQLDialect; -import org.hibernate.testing.RequiresDialect; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; +import org.hibernate.testing.orm.junit.RequiresDialect; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** @author Strong Liu */ @RequiresDialect( MySQLDialect.class ) -public class MySQLRoundFunctionTest extends BaseCoreFunctionalTestCase { - - @Override - public String[] getMappings() { - return new String[]{"dialect/function/Product.hbm.xml"}; - } - - @Override - protected String getBaseForMappings() { - return "org/hibernate/orm/test/"; - } +@DomainModel(xmlMappings = {"org/hibernate/orm/test/dialect/function/Product.hbm.xml"}) +@SessionFactory +public class MySQLRoundFunctionTest { @Test - public void testRoundFunction(){ - Product product = new Product(); - product.setLength( 100 ); - product.setPrice( new BigDecimal( 1.298 ) ); - Session s=openSession(); - Transaction tx=s.beginTransaction(); - s.persist( product ); - tx.commit(); - s.close(); - s=openSession(); - tx=s.beginTransaction(); - Query q=s.createQuery( "select round(p.price,1) from Product p" ); - Object o=q.uniqueResult(); - assertEquals( BigDecimal.class , o.getClass() ); - assertEquals( BigDecimal.valueOf( 1.3 ) , o ); - tx.commit(); - s.close(); - + public void testRoundFunction(SessionFactoryScope scope){ + scope.inTransaction( session -> { + Product product = new Product(); + product.setLength( 100 ); + product.setPrice( new BigDecimal( 1.298 ) ); + session.persist( product ); + } ); + scope.inTransaction( session -> { + BigDecimal bd = session.createQuery( "select round(p.price,1) from Product p", BigDecimal.class ).uniqueResult(); + assertEquals( BigDecimal.valueOf( 1.3 ), bd ); + } ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/functional/HANABooleanTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/functional/HANABooleanTest.java index c71747603579..53663f0e53ca 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/functional/HANABooleanTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/functional/HANABooleanTest.java @@ -4,9 +4,8 @@ */ package org.hibernate.orm.test.dialect.functional; -import static org.hibernate.testing.transaction.TransactionUtil.doInHibernate; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.sql.PreparedStatement; @@ -14,13 +13,19 @@ import jakarta.persistence.Id; import jakarta.persistence.PersistenceException; -import org.hibernate.Session; import org.hibernate.dialect.HANADialect; import org.hibernate.query.Query; -import org.hibernate.testing.RequiresDialect; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.RequiresDialect; import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; -import org.junit.Test; +import org.hibernate.testing.orm.junit.ServiceRegistry; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.hibernate.testing.orm.junit.Setting; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * Tests the correctness of the parameter hibernate.dialect.hana.use_legacy_boolean_type which controls the mapping of @@ -30,14 +35,15 @@ * @author Jonathan Bregler */ @RequiresDialect(HANADialect.class) -public class HANABooleanTest extends BaseCoreFunctionalTestCase { +@DomainModel(annotatedClasses = {HANABooleanTest.BooleanEntity.class, HANABooleanTest.LegacyBooleanEntity.class}) +public class HANABooleanTest { private static final String ENTITY_NAME = "BooleanEntity"; private static final String LEGACY_ENTITY_NAME = "LegacyBooleanEntity"; - @Override - protected void prepareTest() throws Exception { - doInHibernate( this::sessionFactory, session -> { + @BeforeEach + protected void prepareTest(SessionFactoryScope scope) throws Exception { + scope.inTransaction( session -> { session.doWork( connection -> { try ( PreparedStatement ps = connection .prepareStatement( "CREATE COLUMN TABLE " + ENTITY_NAME + " (key INTEGER, bool BOOLEAN, PRIMARY KEY (key))" ) ) { @@ -52,9 +58,9 @@ protected void prepareTest() throws Exception { } ); } - @Override - protected void cleanupTest() throws Exception { - doInHibernate( this::sessionFactory, session -> { + @AfterEach + protected void cleanupTest(SessionFactoryScope scope) throws Exception { + scope.inTransaction( session -> { session.doWork( connection -> { try ( PreparedStatement ps = connection.prepareStatement( "DROP TABLE " + ENTITY_NAME ) ) { ps.execute(); @@ -75,155 +81,115 @@ protected void cleanupTest() throws Exception { @Test @JiraKey(value = "HHH-12132") - public void testBooleanType() throws Exception { - rebuildSessionFactory( configuration -> { - configuration.setProperty( "hibernate.dialect.hana.use_legacy_boolean_type", Boolean.FALSE.toString() ); + @SessionFactory(exportSchema = false) + @ServiceRegistry(settings = { + @Setting( name = "hibernate.dialect.hana.use_legacy_boolean_type", value = "false") + }) + public void testBooleanType(SessionFactoryScope scope) { + scope.inTransaction( session -> { + BooleanEntity entity = new BooleanEntity(); + entity.key = 1; + entity.bool = Boolean.TRUE; + + session.persist( entity ); } ); - Session s = openSession(); - s.beginTransaction(); + scope.inTransaction( session -> { + Query query = session.createQuery( "select b from " + ENTITY_NAME + " b where bool = true", BooleanEntity.class ); + BooleanEntity retrievedEntity = query.getSingleResult(); - BooleanEntity entity = new BooleanEntity(); - entity.key = Integer.valueOf( 1 ); - entity.bool = Boolean.TRUE; - - s.persist( entity ); - - s.flush(); - - s.getTransaction().commit(); - - s.clear(); - - Query legacyQuery = s.createQuery( "select b from " + ENTITY_NAME + " b where bool = true", BooleanEntity.class ); - - BooleanEntity retrievedEntity = legacyQuery.getSingleResult(); - - assertEquals( Integer.valueOf( 1 ), retrievedEntity.key ); - assertTrue( retrievedEntity.bool ); + assertEquals( Integer.valueOf( 1 ), retrievedEntity.key ); + assertTrue( retrievedEntity.bool ); + } ); } @Test @JiraKey(value = "HHH-12132") - public void testBooleanTypeDefaultBehavior() throws Exception { - rebuildSessionFactory(); - - Session s = openSession(); - s.beginTransaction(); - - BooleanEntity entity = new BooleanEntity(); - entity.key = Integer.valueOf( 1 ); - entity.bool = Boolean.TRUE; - - s.persist( entity ); - - s.flush(); - - s.getTransaction().commit(); - - s.clear(); - - Query legacyQuery = s.createQuery( "select b from " + ENTITY_NAME + " b where bool = true", BooleanEntity.class ); + @SessionFactory(exportSchema = false) + public void testBooleanTypeDefaultBehavior(SessionFactoryScope scope) { + scope.inTransaction( session -> { + BooleanEntity entity = new BooleanEntity(); + entity.key = 1; + entity.bool = Boolean.TRUE; + + session.persist( entity ); + } ); - BooleanEntity retrievedEntity = legacyQuery.getSingleResult(); + scope.inTransaction( session -> { + Query query = session.createQuery( "select b from " + ENTITY_NAME + " b where bool = true", BooleanEntity.class ); + BooleanEntity retrievedEntity = query.getSingleResult(); - assertEquals( Integer.valueOf( 1 ), retrievedEntity.key ); - assertTrue( retrievedEntity.bool ); + assertEquals( Integer.valueOf( 1 ), retrievedEntity.key ); + assertTrue( retrievedEntity.bool ); + } ); } - @Test(expected = PersistenceException.class) + @Test/*(expected = PersistenceException.class)*/ @JiraKey(value = "HHH-12132") - public void testLegacyBooleanType() throws Exception { - rebuildSessionFactory( configuration -> { - configuration.setProperty( "hibernate.dialect.hana.use_legacy_boolean_type", Boolean.FALSE.toString() ); + @SessionFactory(exportSchema = false) + @ServiceRegistry(settings = { + @Setting( name = "hibernate.dialect.hana.use_legacy_boolean_type", value = "false") + }) + public void testLegacyBooleanType(SessionFactoryScope scope) throws Exception { + scope.inTransaction( session -> { + LegacyBooleanEntity entity = new LegacyBooleanEntity(); + entity.key = 2; + entity.bool = Boolean.FALSE; + + session.persist( entity ); } ); - Session s = openSession(); - s.beginTransaction(); - - LegacyBooleanEntity legacyEntity = new LegacyBooleanEntity(); - legacyEntity.key = Integer.valueOf( 2 ); - legacyEntity.bool = Boolean.FALSE; - - s.persist( legacyEntity ); - s.flush(); - - s.getTransaction().commit(); - - s.clear(); - - Query query = s.createQuery( "select b from " + LEGACY_ENTITY_NAME + " b where bool = true", LegacyBooleanEntity.class ); - - query.getSingleResult(); + scope.inTransaction( session -> { + Query query = session.createQuery( "select b from " + LEGACY_ENTITY_NAME + " b where bool = true", LegacyBooleanEntity.class ); + Assertions.assertThrows( PersistenceException.class, () -> query.getSingleResult() ); + } ); } @Test @JiraKey(value = "HHH-12132") - public void testLegacyBooleanTypeLegacyBehavior() throws Exception { - rebuildSessionFactory( configuration -> { - configuration.setProperty( "hibernate.dialect.hana.use_legacy_boolean_type", Boolean.TRUE.toString() ); + @SessionFactory(exportSchema = false) + @ServiceRegistry(settings = { + @Setting( name = "hibernate.dialect.hana.use_legacy_boolean_type", value = "true") + }) + public void testLegacyBooleanTypeLegacyBehavior(SessionFactoryScope scope) throws Exception { + scope.inTransaction( session -> { + LegacyBooleanEntity entity = new LegacyBooleanEntity(); + entity.key = 1; + entity.bool = Boolean.TRUE; + + session.persist( entity ); } ); - Session s = openSession(); - s.beginTransaction(); - - LegacyBooleanEntity legacyEntity = new LegacyBooleanEntity(); - legacyEntity.key = Integer.valueOf( 1 ); - legacyEntity.bool = Boolean.TRUE; - - s.persist( legacyEntity ); - - s.flush(); + scope.inTransaction( session -> { + Query query = session.createQuery( "select b from " + LEGACY_ENTITY_NAME + " b where bool = true", LegacyBooleanEntity.class ); + LegacyBooleanEntity retrievedEntity = query.getSingleResult(); - s.getTransaction().commit(); - - s.clear(); - - Query legacyQuery = s.createQuery( "select b from " + LEGACY_ENTITY_NAME + " b where bool = true", LegacyBooleanEntity.class ); - - LegacyBooleanEntity retrievedEntity = legacyQuery.getSingleResult(); - - assertEquals( Integer.valueOf( 1 ), retrievedEntity.key ); - assertTrue( retrievedEntity.bool ); + assertEquals( Integer.valueOf( 1 ), retrievedEntity.key ); + assertTrue( retrievedEntity.bool ); + } ); } - @Test(expected = PersistenceException.class) + @Test/*(expected = PersistenceException.class)*/ @JiraKey(value = "HHH-12132") - public void testBooleanTypeLegacyBehavior() throws Exception { - rebuildSessionFactory( configuration -> { - configuration.setProperty( "hibernate.dialect.hana.use_legacy_boolean_type", Boolean.TRUE.toString() ); + @SessionFactory(exportSchema = false) + @ServiceRegistry(settings = { + @Setting( name = "hibernate.dialect.hana.use_legacy_boolean_type", value = "true") + }) + public void testBooleanTypeLegacyBehavior(SessionFactoryScope scope) throws Exception { + scope.inTransaction( session -> { + BooleanEntity entity = new BooleanEntity(); + entity.key = 2; + entity.bool = Boolean.FALSE; + + session.persist( entity ); } ); - Session s = openSession(); - s.beginTransaction(); - - BooleanEntity entity = new BooleanEntity(); - entity.key = Integer.valueOf( 2 ); - entity.bool = Boolean.FALSE; - - s.persist( entity ); - s.flush(); - - s.getTransaction().commit(); - - s.clear(); - - Query query = s.createQuery( "select b from " + ENTITY_NAME + " b where bool = true", BooleanEntity.class ); - - query.getSingleResult(); - } - - @Override - protected boolean createSchema() { - return false; + scope.inTransaction( session -> { + Query query = session.createQuery( "select b from " + ENTITY_NAME + " b where bool = true", BooleanEntity.class ); + Assertions.assertThrows( PersistenceException.class, () -> query.getSingleResult() ); + } ); } - @Override - protected Class[] getAnnotatedClasses() { - return new Class[]{ - BooleanEntity.class, LegacyBooleanEntity.class - }; - } @Entity(name = LEGACY_ENTITY_NAME) public static class LegacyBooleanEntity { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/functional/HANACalcViewTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/functional/HANACalcViewTest.java index 35215884b519..d1ec1007e844 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/functional/HANACalcViewTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/functional/HANACalcViewTest.java @@ -4,8 +4,7 @@ */ package org.hibernate.orm.test.dialect.functional; -import static org.hibernate.testing.transaction.TransactionUtil.doInHibernate; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.sql.PreparedStatement; import java.util.List; @@ -17,73 +16,78 @@ import jakarta.persistence.criteria.CriteriaQuery; import jakarta.persistence.criteria.Root; -import org.hibernate.Session; import org.hibernate.dialect.HANADialect; import org.hibernate.query.Query; -import org.hibernate.testing.RequiresDialect; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.RequiresDialect; import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; -import org.junit.Test; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; @RequiresDialect(HANADialect.class) -public class HANACalcViewTest extends BaseCoreFunctionalTestCase { +@DomainModel(annotatedClasses = {HANACalcViewTest.CVEntity.class}) +@SessionFactory(exportSchema = false) +public class HANACalcViewTest { private static final String CALC_VIEW_NAME = "DUMMY_CV_VIEW"; private static final String CALC_SCENARIO_NAME = "DUMMY_CV_SCEN"; private static final String PROJECTION_NODE_NAME = "DUMMY_PROJ"; - @Override - protected void afterSessionFactoryBuilt() { - doInHibernate( this::sessionFactory, session -> { + @BeforeEach + protected void afterSessionFactoryBuilt(SessionFactoryScope scope) { + scope.inSession( session -> { session.doWork( connection -> { try ( PreparedStatement ps = connection .prepareStatement( "CREATE CALCULATION SCENARIO " + CALC_SCENARIO_NAME + " USING '\r\n" + - "\r\n" + - "\r\n" + - " \r\n" + - " \r\n" + - " \r\n" + - " \r\n" + - " \r\n" + - " \r\n" + - " \r\n" + - " \r\n" + - " \r\n" + - " \r\n" + - " \r\n" + - " \r\n" + - " \r\n" + - " \r\n" + - " \r\n" + - " \"DUMMY\" + \"DUMMY\"\r\n" + - " \r\n" + - " \r\n" + - " strlen(\"DUMMY\") * 1.5\r\n" + - " \r\n" + - " \r\n" + - " strlen(\"DUMMY\") + 1\r\n" + - " \r\n" + - " \r\n" + - " \r\n" + - " \r\n" + - "\r\n" + - "'" ) ) { + "\r\n" + + "\r\n" + + " \r\n" + + " \r\n" + + " \r\n" + + " \r\n" + + " \r\n" + + " \r\n" + + " \r\n" + + " \r\n" + + " \r\n" + + " \r\n" + + " \r\n" + + " \r\n" + + " \r\n" + + " \r\n" + + " \r\n" + + " \"DUMMY\" + \"DUMMY\"\r\n" + + " \r\n" + + " \r\n" + + " strlen(\"DUMMY\") * 1.5\r\n" + + " \r\n" + + " \r\n" + + " strlen(\"DUMMY\") + 1\r\n" + + " \r\n" + + " \r\n" + + " \r\n" + + " \r\n" + + "\r\n" + + "'" ) ) { ps.execute(); } try ( PreparedStatement ps = connection .prepareStatement( "CREATE COLUMN VIEW " + CALC_VIEW_NAME + " TYPE CALCULATION WITH PARAMETERS ('PARENTCALCINDEX'='" + CALC_SCENARIO_NAME - + "', 'PARENTCALCNODE'='" + PROJECTION_NODE_NAME + "')" ) ) { + + "', 'PARENTCALCNODE'='" + PROJECTION_NODE_NAME + "')" ) ) { ps.execute(); } } ); } ); } - @Override - protected void releaseSessionFactory() { - doInHibernate( this::sessionFactory, session -> { + @AfterEach + protected void releaseSessionFactory(SessionFactoryScope scope) { + scope.inSession( session -> { session.doWork( connection -> { try ( PreparedStatement ps = connection.prepareStatement( "DROP CALCULATION SCENARIO " + CALC_SCENARIO_NAME + " CASCADE" ) ) { ps.execute(); @@ -93,80 +97,72 @@ protected void releaseSessionFactory() { } } ); } ); - super.releaseSessionFactory(); - } - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[]{ CVEntity.class }; - } - - @Override - protected boolean createSchema() { - return false; } @Test @JiraKey(value = "HHH-12541") - public void testCalcViewEntity() throws Exception { - Session s = openSession(); - CVEntity cvEntity = s.find( CVEntity.class, "X" ); - assertEquals( "X", cvEntity.getDummy() ); - assertEquals( "XX", cvEntity.getDummydummy() ); - assertEquals( 2, cvEntity.getDummyint() ); - assertEquals( 1.5, cvEntity.getDummydouble(), 0.1 ); + public void testCalcViewEntity(SessionFactoryScope scope) { + scope.inSession( session -> { + CVEntity cvEntity = session.find( CVEntity.class, "X" ); + assertEquals( "X", cvEntity.getDummy() ); + assertEquals( "XX", cvEntity.getDummydummy() ); + assertEquals( 2, cvEntity.getDummyint() ); + assertEquals( 1.5, cvEntity.getDummydouble(), 0.1 ); + } ); } @Test @JiraKey(value = "HHH-12541") - public void testCalcViewEntityQuery() throws Exception { - Session s = openSession(); - Query query = s.createQuery( "select e from CVEntity e", CVEntity.class ); - List list = query.list(); - assertEquals( 1, list.size() ); - CVEntity cvEntity = list.get( 0 ); - assertEquals( "X", cvEntity.getDummy() ); - assertEquals( "XX", cvEntity.getDummydummy() ); - assertEquals( 2, cvEntity.getDummyint() ); - assertEquals( 1.5, cvEntity.getDummydouble(), 0.1 ); + public void testCalcViewEntityQuery(SessionFactoryScope scope) { + scope.inSession( session -> { + Query query = session.createQuery( "select e from CVEntity e", CVEntity.class ); + List list = query.list(); + assertEquals( 1, list.size() ); + CVEntity cvEntity = list.get( 0 ); + assertEquals( "X", cvEntity.getDummy() ); + assertEquals( "XX", cvEntity.getDummydummy() ); + assertEquals( 2, cvEntity.getDummyint() ); + assertEquals( 1.5, cvEntity.getDummydouble(), 0.1 ); + } ); } @Test @JiraKey(value = "HHH-12541") - public void testCalcViewEntityCriteriaQuery() throws Exception { - Session s = openSession(); - CriteriaBuilder criteriaBuilder = s.getCriteriaBuilder(); - CriteriaQuery criteriaQuery = criteriaBuilder.createQuery( CVEntity.class ); - Root from = criteriaQuery.from( CVEntity.class ); - criteriaQuery.where( criteriaBuilder.equal( from.get( "dummydummy" ), "XX" ) ); - Query query = this.session.createQuery( criteriaQuery ); - List list = query.list(); - assertEquals( 1, list.size() ); - CVEntity cvEntity = list.get( 0 ); - assertEquals( "X", cvEntity.getDummy() ); - assertEquals( "XX", cvEntity.getDummydummy() ); - assertEquals( 2, cvEntity.getDummyint() ); - assertEquals( 1.5, cvEntity.getDummydouble(), 0.1 ); + public void testCalcViewEntityCriteriaQuery(SessionFactoryScope scope) { + scope.inSession( session -> { + CriteriaBuilder criteriaBuilder = session.getCriteriaBuilder(); + CriteriaQuery criteriaQuery = criteriaBuilder.createQuery( CVEntity.class ); + Root from = criteriaQuery.from( CVEntity.class ); + criteriaQuery.where( criteriaBuilder.equal( from.get( "dummydummy" ), "XX" ) ); + Query query = session.createQuery( criteriaQuery ); + List list = query.list(); + assertEquals( 1, list.size() ); + CVEntity cvEntity = list.get( 0 ); + assertEquals( "X", cvEntity.getDummy() ); + assertEquals( "XX", cvEntity.getDummydummy() ); + assertEquals( 2, cvEntity.getDummyint() ); + assertEquals( 1.5, cvEntity.getDummydouble(), 0.1 ); + } ); } @Test @JiraKey(value = "HHH-12541") - public void testCalcViewDTO() throws Exception { - Session s = openSession(); - Query query = s.createQuery( - "select new " + CVEntityDTO.class.getName() + "(e.dummyint, e.dummy) from CVEntity e", - CVEntityDTO.class ); - List list = query.list(); - assertEquals( 1, list.size() ); - CVEntityDTO cvEntity = list.get( 0 ); - assertEquals( "X", cvEntity.getDummy() ); - assertEquals( 2, cvEntity.getDummyint() ); + public void testCalcViewDTO(SessionFactoryScope scope) { + scope.inSession( session -> { + Query query = session.createQuery( + "select new " + CVEntityDTO.class.getName() + "(e.dummyint, e.dummy) from CVEntity e", + CVEntityDTO.class ); + List list = query.list(); + assertEquals( 1, list.size() ); + CVEntityDTO cvEntity = list.get( 0 ); + assertEquals( "X", cvEntity.getDummy() ); + assertEquals( 2, cvEntity.getDummyint() ); + } ); } @Entity(name = "CVEntity") @Table(name = CALC_VIEW_NAME) - private static class CVEntity { - + static class CVEntity { private String dummydummy; private double dummydouble; private int dummyint; @@ -188,11 +184,9 @@ public int getDummyint() { public String getDummy() { return this.dummy; } - } private static class CVEntityDTO { - private int dummyint; private String dummy; @@ -209,6 +203,6 @@ public int getDummyint() { public String getDummy() { return this.dummy; } - } + } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/functional/HANADecimalTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/functional/HANADecimalTest.java index 0849214a78e4..fe8bc2bc0969 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/functional/HANADecimalTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/functional/HANADecimalTest.java @@ -4,8 +4,7 @@ */ package org.hibernate.orm.test.dialect.functional; -import static org.hibernate.testing.transaction.TransactionUtil.doInHibernate; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.math.BigDecimal; import java.sql.PreparedStatement; @@ -14,13 +13,18 @@ import jakarta.persistence.Entity; import jakarta.persistence.Id; -import org.hibernate.Session; import org.hibernate.dialect.HANADialect; import org.hibernate.query.Query; -import org.hibernate.testing.RequiresDialect; +import org.hibernate.testing.orm.junit.RequiresDialect; +import org.hibernate.testing.orm.junit.DomainModel; import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; -import org.junit.Test; +import org.hibernate.testing.orm.junit.ServiceRegistry; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.hibernate.testing.orm.junit.Setting; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * Tests the correctness of the parameter hibernate.dialect.hana.treat_double_typed_fields_as_decimal which controls the @@ -30,14 +34,17 @@ * @author Jonathan Bregler */ @RequiresDialect(HANADialect.class) -public class HANADecimalTest extends BaseCoreFunctionalTestCase { +@DomainModel(annotatedClasses = {HANADecimalTest.DecimalEntity.class}) +@SessionFactory(exportSchema = false) +@ServiceRegistry(settings = {@Setting(name = "hibernate.dialect.hana.treat_double_typed_fields_as_decimal", value = "true")}) +public class HANADecimalTest { private static final String ENTITY_NAME = "DecimalEntity"; - @Override - protected void prepareTest() throws Exception { - doInHibernate( this::sessionFactory, localSession -> { - localSession.doWork( connection -> { + @BeforeEach + protected void prepareTest(SessionFactoryScope scope) throws Exception { + scope.inSession( session -> { + session.doWork( connection -> { try ( PreparedStatement ps = connection .prepareStatement( "CREATE COLUMN TABLE " + ENTITY_NAME + " (key INTEGER, doubledouble DOUBLE, decimaldecimal DECIMAL(38,15), doubledecimal DECIMAL(38,15), decimaldouble DOUBLE, PRIMARY KEY (key))" ) ) { @@ -47,10 +54,10 @@ protected void prepareTest() throws Exception { } ); } - @Override - protected void cleanupTest() throws Exception { - doInHibernate( this::sessionFactory, localSession -> { - localSession.doWork( connection -> { + @AfterEach + protected void cleanupTest(SessionFactoryScope scope) throws Exception { + scope.inSession( session -> { + session.doWork( connection -> { try ( PreparedStatement ps = connection.prepareStatement( "DROP TABLE " + ENTITY_NAME ) ) { ps.execute(); } @@ -63,74 +70,49 @@ protected void cleanupTest() throws Exception { @Test @JiraKey(value = "HHH-12995") - public void testDecimalTypeTrue() throws Exception { - rebuildSessionFactory( configuration -> { - configuration.setProperty( "hibernate.dialect.hana.treat_double_typed_fields_as_decimal", Boolean.TRUE.toString() ); + public void testDecimalTypeTrue(SessionFactoryScope scope) { + scope.inTransaction( session -> { + DecimalEntity entity = new DecimalEntity(); + entity.key = 1; + entity.doubleDouble = 1.19d; + entity.decimalDecimal = BigDecimal.valueOf( 1.19d ); + entity.doubleDecimal = 1.19d; + entity.decimalDouble = BigDecimal.valueOf( 1.19d ); + session.persist( entity ); + + DecimalEntity entity2 = new DecimalEntity(); + entity2.key = 2; + entity2.doubleDouble = 0.3d; + entity2.decimalDecimal = BigDecimal.valueOf( 0.3d ); + entity2.doubleDecimal = 0.3d; + entity2.decimalDouble = BigDecimal.valueOf( 0.3d ); + session.persist( entity2 ); } ); - Session s = openSession(); - s.beginTransaction(); - - DecimalEntity entity = new DecimalEntity(); - entity.key = Integer.valueOf( 1 ); - entity.doubleDouble = 1.19d; - entity.decimalDecimal = BigDecimal.valueOf( 1.19d ); - entity.doubleDecimal = 1.19d; - entity.decimalDouble = BigDecimal.valueOf( 1.19d ); - - s.persist( entity ); - - DecimalEntity entity2 = new DecimalEntity(); - entity2.key = Integer.valueOf( 2 ); - entity2.doubleDouble = 0.3d; - entity2.decimalDecimal = BigDecimal.valueOf( 0.3d ); - entity2.doubleDecimal = 0.3d; - entity2.decimalDouble = BigDecimal.valueOf( 0.3d ); - - s.persist( entity2 ); - - s.flush(); - - s.getTransaction().commit(); - - s.clear(); - - Query legacyQuery = s.createQuery( "select b from " + ENTITY_NAME + " b order by key asc", DecimalEntity.class ); - - List retrievedEntities = legacyQuery.getResultList(); - - assertEquals(2, retrievedEntities.size()); - - DecimalEntity retrievedEntity = retrievedEntities.get( 0 ); - assertEquals( Integer.valueOf( 1 ), retrievedEntity.key ); - assertEquals( 1.19d, retrievedEntity.doubleDouble, 0 ); - assertEquals( new BigDecimal( "1.190000000000000" ), retrievedEntity.decimalDecimal ); - assertEquals( 1.19d, retrievedEntity.doubleDecimal, 0 ); - assertEquals( new BigDecimal( "1.19" ), retrievedEntity.decimalDouble ); - - retrievedEntity = retrievedEntities.get( 1 ); - assertEquals( Integer.valueOf( 2 ), retrievedEntity.key ); - assertEquals( 0.3d, retrievedEntity.doubleDouble, 0 ); - assertEquals( new BigDecimal( "0.300000000000000" ), retrievedEntity.decimalDecimal ); - assertEquals( 0.3d, retrievedEntity.doubleDecimal, 0 ); - assertEquals( new BigDecimal( "0.3" ), retrievedEntity.decimalDouble ); - } - - @Override - protected boolean createSchema() { - return false; - } - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[]{ - DecimalEntity.class - }; + scope.inTransaction( session -> { + Query legacyQuery = session.createQuery( "select b from " + ENTITY_NAME + " b order by key asc", DecimalEntity.class ); + List retrievedEntities = legacyQuery.getResultList(); + + assertEquals(2, retrievedEntities.size()); + + DecimalEntity retrievedEntity = retrievedEntities.get( 0 ); + assertEquals( Integer.valueOf( 1 ), retrievedEntity.key ); + assertEquals( 1.19d, retrievedEntity.doubleDouble, 0 ); + assertEquals( new BigDecimal( "1.190000000000000" ), retrievedEntity.decimalDecimal ); + assertEquals( 1.19d, retrievedEntity.doubleDecimal, 0 ); + assertEquals( new BigDecimal( "1.19" ), retrievedEntity.decimalDouble ); + + retrievedEntity = retrievedEntities.get( 1 ); + assertEquals( Integer.valueOf( 2 ), retrievedEntity.key ); + assertEquals( 0.3d, retrievedEntity.doubleDouble, 0 ); + assertEquals( new BigDecimal( "0.300000000000000" ), retrievedEntity.decimalDecimal ); + assertEquals( 0.3d, retrievedEntity.doubleDecimal, 0 ); + assertEquals( new BigDecimal( "0.3" ), retrievedEntity.decimalDouble ); + } ); } @Entity(name = ENTITY_NAME) public static class DecimalEntity { - @Id public Integer key; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/functional/MariaDBExtractSequenceInformationTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/functional/MariaDBExtractSequenceInformationTest.java index cdd2d4c6defa..7eeeec57d2d2 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/functional/MariaDBExtractSequenceInformationTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/functional/MariaDBExtractSequenceInformationTest.java @@ -5,80 +5,119 @@ package org.hibernate.orm.test.dialect.functional; import java.sql.Connection; +import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.Optional; import java.util.stream.StreamSupport; import org.hibernate.boot.registry.StandardServiceRegistry; +import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.dialect.MariaDBDialect; +import org.hibernate.engine.jdbc.connections.spi.JdbcConnectionAccess; import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment; +import org.hibernate.engine.jdbc.spi.JdbcServices; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; import org.hibernate.tool.schema.extract.internal.SequenceInformationExtractorMariaDBDatabaseImpl; import org.hibernate.tool.schema.extract.spi.ExtractionContext; import org.hibernate.tool.schema.extract.spi.SequenceInformation; import org.hibernate.testing.orm.junit.JiraKey; import org.hibernate.testing.orm.junit.RequiresDialect; -import org.hibernate.testing.transaction.TransactionUtil; import org.hibernate.testing.util.ServiceRegistryUtil; -import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import static org.hibernate.testing.transaction.TransactionUtil.doInAutoCommit; /** * @author Jan Schatteman */ @RequiresDialect(value = MariaDBDialect.class) +@SessionFactory public class MariaDBExtractSequenceInformationTest { private final static String hhh15665SeqName = "HHH-15665-seq"; - @BeforeAll - public static void setUp() throws Exception { - doInAutoCommit( "CREATE SEQUENCE IF NOT EXISTS `" + hhh15665SeqName + "`" ); + @BeforeEach + public void prepareTest(SessionFactoryScope scope) throws Exception { + scope.inSession( session -> { + session.doWork( connection -> { + try (PreparedStatement ps = connection.prepareStatement( "CREATE SEQUENCE IF NOT EXISTS `" + hhh15665SeqName + "`" )) { + ps.execute(); + } + } ); + } ); } - @AfterAll - public static void tearDown() throws SQLException { - doInAutoCommit( "DROP SEQUENCE IF EXISTS `" + hhh15665SeqName + "`" ); + @AfterEach + public void cleanupTest(SessionFactoryScope scope) throws Exception { + scope.inSession( session -> { + session.doWork( connection -> { + try (PreparedStatement ps = connection.prepareStatement( "DROP SEQUENCE IF EXISTS `" + hhh15665SeqName + "`" )) { + ps.execute(); + } + } ); + } ); } @Test @JiraKey(value = "HHH-15665") - public void testExtractSequenceInformationForSqlServerWithCaseSensitiveCollation() { - try (StandardServiceRegistry ssr = ServiceRegistryUtil.serviceRegistry()) { + public void testExtractSequenceInformationForMariaDB() { + + StandardServiceRegistry ssr = ServiceRegistryUtil.serviceRegistry(); + final JdbcConnectionAccess bootstrapJdbcConnectionAccess = ssr.getService( JdbcServices.class ) + .getBootstrapJdbcConnectionAccess(); + final Connection connection; + try { + connection = bootstrapJdbcConnectionAccess.obtainConnection(); + } + catch (SQLException e) { + throw new RuntimeException( e ); + } + + try { JdbcEnvironment jdbcEnvironment = ssr.getService( JdbcEnvironment.class ); - TransactionUtil.doWithJDBC( ssr, connection -> { - Iterable sequenceInformations = SequenceInformationExtractorMariaDBDatabaseImpl.INSTANCE.extractMetadata( - new ExtractionContext.EmptyExtractionContext() { - @Override - public Connection getJdbcConnection() { - return connection; - } - - @Override - public JdbcEnvironment getJdbcEnvironment() { - return jdbcEnvironment; - } - } ); - - Assertions.assertNotNull( sequenceInformations ); - - Optional seq = StreamSupport.stream( sequenceInformations.spliterator(), false ) - .filter( - sequence -> hhh15665SeqName.equals( sequence.getSequenceName() - .getSequenceName() - .getText() ) - ) - .findFirst(); - - Assertions.assertTrue( seq.isPresent(), hhh15665SeqName + " not found" ); - } ); + + Iterable sequenceInformations = SequenceInformationExtractorMariaDBDatabaseImpl.INSTANCE.extractMetadata( + new ExtractionContext.EmptyExtractionContext() { + @Override + public Connection getJdbcConnection() { + return connection; + } + + @Override + public JdbcEnvironment getJdbcEnvironment() { + return jdbcEnvironment; + } + } ); + + Assertions.assertNotNull( sequenceInformations ); + + Optional seq = StreamSupport.stream( sequenceInformations.spliterator(), false ) + .filter( + sequence -> hhh15665SeqName.equals( sequence.getSequenceName() + .getSequenceName() + .getText() ) + ) + .findFirst(); + + Assertions.assertTrue( seq.isPresent(), hhh15665SeqName + " not found" ); } catch (SQLException e) { Assertions.fail( "Sequence information for " + hhh15665SeqName + " was not retrieved: " + e.getMessage() ); } + finally { + if ( connection != null ) { + try { + bootstrapJdbcConnectionAccess.releaseConnection( connection ); + } + catch (SQLException e) { + // Ignore + } + } + StandardServiceRegistryBuilder.destroy( ssr ); + } } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/functional/OracleDialectSequenceInformationTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/functional/OracleDialectSequenceInformationTest.java index 7d7f07582e5c..e4e47cc5c0d0 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/functional/OracleDialectSequenceInformationTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/functional/OracleDialectSequenceInformationTest.java @@ -6,84 +6,96 @@ import java.math.BigDecimal; import java.sql.Connection; +import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.Optional; import org.hibernate.dialect.OracleDialect; import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment; -import org.hibernate.testing.RequiresDialect; +import org.hibernate.engine.spi.SessionFactoryImplementor; +import org.hibernate.testing.orm.junit.RequiresDialect; import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseNonConfigCoreFunctionalTestCase; -import org.hibernate.testing.transaction.TransactionUtil; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; import org.hibernate.tool.schema.extract.internal.SequenceInformationExtractorOracleDatabaseImpl; import org.hibernate.tool.schema.extract.spi.ExtractionContext; import org.hibernate.tool.schema.extract.spi.SequenceInformation; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; import static java.util.stream.StreamSupport.stream; -import static org.hibernate.testing.transaction.TransactionUtil.doInAutoCommit; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; @RequiresDialect(OracleDialect.class) @JiraKey(value = "HHH-13694") -public class OracleDialectSequenceInformationTest extends BaseNonConfigCoreFunctionalTestCase { +@SessionFactory +public class OracleDialectSequenceInformationTest { private static final String MIN_SEQUENCE_NAME = "SEQ_MIN_TEST"; private static final String MAX_SEQUENCE_NAME = "SEQ_MAX_TEST"; private static final String MIN_VALUE = "-99999999999999999999999999"; private static final String MAX_VALUE = "99999999999999999999999999"; - @Before - public void prepareTest() throws Exception { - doInAutoCommit( - "DROP SEQUENCE " + MIN_SEQUENCE_NAME, - "CREATE SEQUENCE " + MIN_SEQUENCE_NAME + " MINVALUE " + MIN_VALUE + " MAXVALUE -1 INCREMENT BY -1", - "DROP SEQUENCE " + MAX_SEQUENCE_NAME, - "CREATE SEQUENCE " + MAX_SEQUENCE_NAME + " MINVALUE 0 MAXVALUE " + MAX_VALUE + " INCREMENT BY 1" ); + @BeforeAll + public void prepareTest(SessionFactoryScope scope) throws Exception { + scope.inSession( session -> + session.doWork( connection -> { + try (PreparedStatement ps = connection.prepareStatement( "CREATE SEQUENCE " + MIN_SEQUENCE_NAME + " MINVALUE " + MIN_VALUE + " MAXVALUE -1 INCREMENT BY -1" )) { + ps.execute(); + } + try (PreparedStatement ps = connection.prepareStatement( "CREATE SEQUENCE " + MAX_SEQUENCE_NAME + " MINVALUE 0 MAXVALUE " + MAX_VALUE + " INCREMENT BY 1" ) ) { + ps.execute(); + } + } ) + ); } - @After - public void cleanupTest() throws Exception { - doInAutoCommit( - "DROP SEQUENCE " + MIN_SEQUENCE_NAME, - "DROP SEQUENCE " + MAX_SEQUENCE_NAME ); + @AfterAll + public void cleanupTest(SessionFactoryScope scope) throws Exception { + scope.inSession( session -> + session.doWork( connection -> { + try (PreparedStatement ps = connection.prepareStatement( "DROP SEQUENCE " + MIN_SEQUENCE_NAME )) { + ps.execute(); + } + try (PreparedStatement ps = connection.prepareStatement( "DROP SEQUENCE " + MAX_SEQUENCE_NAME )) { + ps.execute(); + } + } ) + ); } @Test - public void testExtractSequenceWithMinValueLowerThanLongMinValue() throws SQLException { - SequenceInformation sequence = fetchSequenceInformation( MIN_SEQUENCE_NAME ); + public void testExtractSequenceWithMinValueLowerThanLongMinValue(SessionFactoryScope scope) { + SequenceInformation sequence = fetchSequenceInformation( MIN_SEQUENCE_NAME, scope.getSessionFactory() ); assertEquals( -1L, sequence.getIncrementValue().longValue() ); assertEquals( new BigDecimal( MIN_VALUE ), sequence.getMinValue() ); } @Test - public void testExtractSequenceWithMaxValueGreaterThanLongMaxValue() throws SQLException { - SequenceInformation sequence = fetchSequenceInformation( MAX_SEQUENCE_NAME ); + public void testExtractSequenceWithMaxValueGreaterThanLongMaxValue(SessionFactoryScope scope) { + SequenceInformation sequence = fetchSequenceInformation( MAX_SEQUENCE_NAME, scope.getSessionFactory() ); assertEquals( 1L, sequence.getIncrementValue().longValue() ); assertEquals( new BigDecimal( MAX_VALUE ), sequence.getMaxValue() ); } - private SequenceInformation fetchSequenceInformation(String sequenceName) throws SQLException { - return TransactionUtil.doWithJDBC( - sessionFactory().getServiceRegistry(), - connection -> { - final JdbcEnvironment jdbcEnvironment = - sessionFactory().getJdbcServices().getJdbcEnvironment(); - // lets skip system sequences - Optional foundSequence = - stream( sequenceInformation( connection, jdbcEnvironment ).spliterator(), false ) + private SequenceInformation fetchSequenceInformation(String sequenceName, SessionFactoryImplementor sessionFactory) { + final JdbcEnvironment jdbcEnvironment = sessionFactory.getJdbcServices().getJdbcEnvironment(); + final SequenceInformationWrapper sequenceInformationWrapper = new SequenceInformationWrapper(); + sessionFactory.openSession().doWork( connection -> { + // let's skip system sequences + Optional foundSequence = + stream( sequenceInformation( connection, jdbcEnvironment ).spliterator(), false ) .filter( sequence -> isSameSequence( sequenceName, sequence ) ) .findFirst(); - assertTrue( sequenceName + " not found", foundSequence.isPresent() ); - return foundSequence.get(); - } - ); + assertTrue( foundSequence.isPresent(), sequenceName + " not found" ); + sequenceInformationWrapper.set( foundSequence.get() ); + } ); + return sequenceInformationWrapper.get(); } private static boolean isSameSequence(String sequenceName, SequenceInformation sequence) { @@ -106,4 +118,14 @@ public JdbcEnvironment getJdbcEnvironment() { } ); } + + private static final class SequenceInformationWrapper { + private SequenceInformation sequenceInformation; + public SequenceInformation get() { + return sequenceInformation; + } + public void set(SequenceInformation sequenceInformation) { + this.sequenceInformation = sequenceInformation; + } + } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/functional/SQLServerDialectCollationTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/functional/SQLServerDialectCollationTest.java index 5bfe2c86708d..b8ac973d2cb0 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/functional/SQLServerDialectCollationTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/functional/SQLServerDialectCollationTest.java @@ -5,7 +5,7 @@ package org.hibernate.orm.test.dialect.functional; import java.io.Serializable; -import java.sql.SQLException; +import java.sql.PreparedStatement; import java.sql.Statement; import java.util.List; import java.util.Objects; @@ -14,21 +14,20 @@ import jakarta.persistence.Id; import jakarta.persistence.Table; -import org.hibernate.boot.registry.BootstrapServiceRegistry; -import org.hibernate.boot.registry.internal.StandardServiceRegistryImpl; import org.hibernate.cfg.AvailableSettings; -import org.hibernate.cfg.Configuration; import org.hibernate.dialect.SQLServerDialect; -import org.hibernate.testing.RequiresDialect; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.RequiresDialect; import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; -import org.hibernate.testing.transaction.TransactionUtil; -import org.junit.Test; +import org.hibernate.testing.orm.junit.ServiceRegistry; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.hibernate.testing.orm.junit.Setting; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; - -import static org.hibernate.testing.transaction.TransactionUtil.doInHibernate; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * used driver hibernate.connection.driver_class com.microsoft.sqlserver.jdbc.SQLServerDriver @@ -36,68 +35,48 @@ * @author Guenther Demetz */ @RequiresDialect(SQLServerDialect.class) -public class SQLServerDialectCollationTest extends BaseCoreFunctionalTestCase { +@DomainModel(annotatedClasses = {SQLServerDialectCollationTest.CustomProduct.class}) +@SessionFactory(exportSchema = false) +@ServiceRegistry(settings = {@Setting(name = AvailableSettings.KEYWORD_AUTO_QUOTING_ENABLED, value = "true")}) +public class SQLServerDialectCollationTest { + + private static final String TABLE_NAME = "CustomProduct"; + private static final String CATALOG = "hibernate_orm_test_collation"; + + + @BeforeEach + protected void setup(SessionFactoryScope scope) { + scope.inTransaction( session -> { + session.doWork( connection -> { + try (PreparedStatement ps = connection.prepareStatement( "DROP DATABASE IF EXISTS " + CATALOG )) { + ps.execute(); + } + } ); + } ); - @Override - protected void configure(Configuration configuration) { - super.configure( configuration ); - configuration.setProperty( AvailableSettings.KEYWORD_AUTO_QUOTING_ENABLED, Boolean.TRUE.toString() ); - } + scope.inTransaction( session -> { + session.doWork( connection -> { + try (Statement statement = connection.createStatement()) { + statement.executeUpdate( "CREATE DATABASE " + CATALOG + " COLLATE Latin1_General_CS_AS" ); + statement.executeUpdate( "ALTER DATABASE [" + CATALOG + "] SET AUTO_CLOSE OFF " ); + } + } ); + } ); - @Override - protected void buildSessionFactory() { - BootstrapServiceRegistry bootRegistry = buildBootstrapServiceRegistry(); - StandardServiceRegistryImpl _serviceRegistry = - buildServiceRegistry( bootRegistry, constructAndConfigureConfiguration( bootRegistry ) ); - - try { - try { - TransactionUtil.doWithJDBC( - _serviceRegistry, - connection -> { - try (Statement statement = connection.createStatement()) { - connection.setAutoCommit( true ); - statement.executeUpdate( "DROP DATABASE hibernate_orm_test_collation" ); - } - } - ); - } - catch (SQLException e) { - log.debug( e.getMessage() ); - } - try { - TransactionUtil.doWithJDBC( - _serviceRegistry, - connection -> { - try (Statement statement = connection.createStatement()) { - connection.setAutoCommit( true ); - statement.executeUpdate( "CREATE DATABASE hibernate_orm_test_collation COLLATE Latin1_General_CS_AS" ); - statement.executeUpdate( "ALTER DATABASE [hibernate_orm_test_collation] SET AUTO_CLOSE OFF " ); - } - } - ); - } - catch (SQLException e) { - log.debug( e.getMessage() ); - } - } - finally { - _serviceRegistry.destroy(); - } - super.buildSessionFactory(); + scope.getSessionFactory().getSchemaManager().exportMappedObjects( false ); } @Test @JiraKey(value = "HHH-7198") - public void testMaxResultsSqlServerWithCaseSensitiveCollation() throws Exception { - doInHibernate( this::sessionFactory, session -> { + public void testMaxResultsSqlServerWithCaseSensitiveCollation(SessionFactoryScope scope) { + scope.inTransaction( session -> { for ( int i = 1; i <= 20; i++ ) { session.persist( new CustomProduct( i, "Kit" + i ) ); } - session.flush(); - session.clear(); + } ); - List list = session.createQuery( "from CustomProduct where description like 'Kit%'" ) + scope.inTransaction( session -> { + List list = session.createQuery( "from CustomProduct where description like 'Kit%'", CustomProduct.class ) .setFirstResult( 2 ) .setMaxResults( 2 ) .list(); @@ -105,16 +84,8 @@ public void testMaxResultsSqlServerWithCaseSensitiveCollation() throws Exception } ); } - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - CustomProduct.class - }; - } - - - @Entity(name = "CustomProduct") - @Table(catalog = "hibernate_orm_test_collation", schema = "dbo") + @Entity(name = TABLE_NAME) + @Table(catalog = CATALOG, schema = "dbo") public static class CustomProduct implements Serializable { @Id public Integer id; @@ -156,8 +127,4 @@ public String toString() { } } - @Override - protected boolean rebuildSessionFactoryOnError() { - return false; - } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/functional/SQLServerDialectPaginationTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/functional/SQLServerDialectPaginationTest.java index f8ad8ad57f94..5bd116c56d14 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/functional/SQLServerDialectPaginationTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/functional/SQLServerDialectPaginationTest.java @@ -12,16 +12,19 @@ import jakarta.persistence.Entity; import jakarta.persistence.Id; +import org.hibernate.cfg.AvailableSettings; import org.hibernate.dialect.Dialect; import org.hibernate.dialect.SQLServerDialect; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; -import org.junit.Test; +import org.hibernate.testing.orm.junit.DialectContext; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.hibernate.testing.orm.junit.SettingProvider; +import org.junit.jupiter.api.Test; -import org.hibernate.testing.RequiresDialect; +import org.hibernate.testing.orm.junit.RequiresDialect; import org.hibernate.testing.orm.junit.JiraKey; -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * Test pagination on newer SQL Server Dialects where the application explicitly specifies @@ -31,28 +34,30 @@ */ @JiraKey(value = "HHH-11642") @RequiresDialect(SQLServerDialect.class) -public class SQLServerDialectPaginationTest extends BaseEntityManagerFunctionalTestCase { - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { SimpleEntity.class }; - } - - @Override - protected Dialect getDialect() { - // if the environment is any version of SQLServerDialect, force the legacy SQLServerDialect instead - // This is so that the legacy's TopLimitHandler will be used here to test the fix necessary when a - // user explicitly configures the legacy dialect but uses a more modern version of SQL Server. - final Dialect environmentDialect = super.getDialect(); - if ( environmentDialect instanceof SQLServerDialect ) { - return new SQLServerDialect(); +@Jpa( + annotatedClasses = { SQLServerDialectPaginationTest.SimpleEntity.class }, + settingProviders = { @SettingProvider(settingName = AvailableSettings.DIALECT, provider = SQLServerDialectPaginationTest.DialectSettingProvider.class) } +) +public class SQLServerDialectPaginationTest { + + static final class DialectSettingProvider implements SettingProvider.Provider { + @Override + public Dialect getSetting() { + // if the environment is any version of SQLServerDialect, force the legacy SQLServerDialect instead + // This is so that the legacy's TopLimitHandler will be used here to test the fix necessary when a + // user explicitly configures the legacy dialect but uses a more modern version of SQL Server. + final Dialect environmentDialect = DialectContext.getDialect(); + if ( environmentDialect instanceof SQLServerDialect ) { + return new SQLServerDialect(); + } + return environmentDialect; } - return environmentDialect; } @Test - public void testPaginationQuery() { + public void testPaginationQuery(EntityManagerFactoryScope scope) { // prepare some test data - doInJPA( this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { for ( int i = 1; i <= 20; ++i ) { final SimpleEntity entity = new SimpleEntity( i, "Entity" + i ); entityManager.persist( entity ); @@ -61,7 +66,7 @@ public void testPaginationQuery() { // This would fail with "index 2 out of range" within TopLimitHandler // The fix addresses this problem which only occurs when using SQLServerDialect explicitly. - doInJPA( this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { List results = entityManager .createQuery( "SELECT o FROM SimpleEntity o WHERE o.id >= :firstId ORDER BY o.id", SimpleEntity.class ) .setParameter( "firstId", 10 ) diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/functional/SQLServerDialectSequenceInformationTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/functional/SQLServerDialectSequenceInformationTest.java index 4910368e374a..7705c0b31216 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/functional/SQLServerDialectSequenceInformationTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/functional/SQLServerDialectSequenceInformationTest.java @@ -5,6 +5,7 @@ package org.hibernate.orm.test.dialect.functional; import java.sql.Connection; +import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.Statement; @@ -18,47 +19,58 @@ import org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentImpl; import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment; import org.hibernate.engine.jdbc.spi.JdbcServices; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; import org.hibernate.tool.schema.extract.internal.SequenceInformationExtractorLegacyImpl; import org.hibernate.tool.schema.extract.spi.ExtractionContext; import org.hibernate.tool.schema.extract.spi.SequenceInformation; -import org.hibernate.testing.RequiresDialect; +import org.hibernate.testing.orm.junit.RequiresDialect; import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseUnitTestCase; import org.hibernate.testing.orm.junit.DialectContext; import org.hibernate.testing.util.ServiceRegistryUtil; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import static org.hibernate.testing.transaction.TransactionUtil.doInAutoCommit; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Frank Doherty */ @RequiresDialect(SQLServerDialect.class) @JiraKey(value = "HHH-13141") -public class SQLServerDialectSequenceInformationTest extends BaseUnitTestCase { +@SessionFactory +public class SQLServerDialectSequenceInformationTest { private final String DATABASE_NAME = "hibernate_orm_test_seq"; - @Before - public void prepareTest() throws Exception { - // Latin1_General_CS_AS is a case-sensitive collation - doInAutoCommit( - "DROP DATABASE " + DATABASE_NAME, - "CREATE DATABASE " + DATABASE_NAME + " COLLATE Latin1_General_CS_AS" - ); + @BeforeEach + public void prepareTest(SessionFactoryScope scope) throws Exception { + scope.inSession( session -> { + session.doWork( connection -> { + try (PreparedStatement ps = connection.prepareStatement( "DROP DATABASE IF EXISTS " + DATABASE_NAME )) { + ps.execute(); + } + // Latin1_General_CS_AS is a case-sensitive collation + try (PreparedStatement ps = connection.prepareStatement( "CREATE DATABASE " + DATABASE_NAME + " COLLATE Latin1_General_CS_AS" )) { + ps.execute(); + } + } ); + } ); } - @After - public void cleanupTest() throws Exception { - doInAutoCommit( - "DROP DATABASE " + DATABASE_NAME - ); + @AfterEach + public void cleanupTest(SessionFactoryScope scope) throws Exception { + scope.inSession( session -> { + session.doWork( connection -> { + try (PreparedStatement ps = connection.prepareStatement( "DROP DATABASE IF EXISTS " + DATABASE_NAME )) { + ps.execute(); + } + } ); + } ); } @Test @@ -110,7 +122,6 @@ public JdbcEnvironment getJdbcEnvironment() { assertEquals( 10, sequenceInformation.getIncrementValue().intValue() ); } catch ( SQLException e ) { - log.error( e ); fail( "Sequence information was not retrieved: " + e.getMessage() ); } finally { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/functional/SQLServerDialectTempTableCollationTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/functional/SQLServerDialectTempTableCollationTest.java index a351e0d007e7..2c0d34338ed9 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/functional/SQLServerDialectTempTableCollationTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/functional/SQLServerDialectTempTableCollationTest.java @@ -13,51 +13,49 @@ import jakarta.persistence.InheritanceType; import jakarta.persistence.Table; -import org.hibernate.boot.registry.BootstrapServiceRegistry; -import org.hibernate.boot.registry.internal.StandardServiceRegistryImpl; +import org.hibernate.boot.registry.StandardServiceRegistry; +import org.hibernate.boot.registry.StandardServiceRegistryBuilder; +import org.hibernate.boot.spi.MetadataImplementor; import org.hibernate.cfg.AvailableSettings; -import org.hibernate.cfg.Configuration; import org.hibernate.dialect.SQLServerDialect; -import org.hibernate.testing.RequiresDialect; +import org.hibernate.engine.spi.SessionFactoryImplementor; +import org.hibernate.testing.orm.junit.RequiresDialect; +import org.hibernate.testing.orm.junit.BaseSessionFactoryFunctionalTest; import org.hibernate.testing.orm.junit.JiraKey; import org.hibernate.testing.jdbc.SharedDriverManagerConnectionProvider; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; import org.hibernate.testing.transaction.TransactionUtil; -import org.junit.Assert; -import org.junit.Test; +import org.hibernate.testing.util.ServiceRegistryUtil; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.AfterEach; import static org.hibernate.testing.transaction.TransactionUtil.doInHibernate; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Nathan Xu */ @RequiresDialect( SQLServerDialect.class ) @JiraKey( value = "HHH-3326" ) -public class SQLServerDialectTempTableCollationTest extends BaseCoreFunctionalTestCase { +public class SQLServerDialectTempTableCollationTest extends BaseSessionFactoryFunctionalTest { private String originalDBCollation; private final String changedDBCollation = "SQL_Latin1_General_CP437_BIN"; private boolean collationChanged; @Override - protected void configure(Configuration configuration) { - super.configure( configuration ); - configuration.setProperty( AvailableSettings.KEYWORD_AUTO_QUOTING_ENABLED, Boolean.TRUE.toString() ); + protected void applySettings(StandardServiceRegistryBuilder builder) { + builder.applySetting( AvailableSettings.KEYWORD_AUTO_QUOTING_ENABLED, Boolean.TRUE ); } - @Override + @AfterEach protected void releaseSessionFactory() { - super.releaseSessionFactory(); if ( originalDBCollation != null && collationChanged && !changedDBCollation.equals( originalDBCollation ) ) { - BootstrapServiceRegistry bootRegistry = buildBootstrapServiceRegistry(); - StandardServiceRegistryImpl serviceRegistry = buildServiceRegistry( - bootRegistry, - constructAndConfigureConfiguration( bootRegistry ) - ); + StandardServiceRegistry ssr = ServiceRegistryUtil.serviceRegistryBuilder().build(); try { TransactionUtil.doWithJDBC( - serviceRegistry, + ssr, connection -> { try (Statement statement = connection.createStatement()) { connection.setAutoCommit( true ); @@ -79,7 +77,7 @@ protected void releaseSessionFactory() { throw new RuntimeException( "Failed to revert back database collation to " + originalDBCollation, e ); } finally { - serviceRegistry.destroy(); + ssr.close(); } } // The alter database calls could lead to issues with existing connections, so we reset the shared pool here @@ -87,33 +85,32 @@ protected void releaseSessionFactory() { } @Override - protected void buildSessionFactory() { - BootstrapServiceRegistry bootRegistry = buildBootstrapServiceRegistry(); - StandardServiceRegistryImpl serviceRegistry = - buildServiceRegistry( bootRegistry, constructAndConfigureConfiguration( bootRegistry ) ); + public SessionFactoryImplementor produceSessionFactory(MetadataImplementor model) { + + StandardServiceRegistry ssr = ServiceRegistryUtil.serviceRegistryBuilder().build(); try { try { TransactionUtil.doWithJDBC( - serviceRegistry, + ssr, connection -> { try (Statement statement = connection.createStatement()) { connection.setAutoCommit( true ); try ( ResultSet rs = statement.executeQuery( "SELECT DATABASEPROPERTYEX(DB_NAME(),'collation')" ) ) { rs.next(); String instanceCollation = rs.getString( 1 ); - Assert.assertNotEquals( instanceCollation, changedDBCollation ); + Assertions.assertNotEquals( instanceCollation, changedDBCollation ); } } } ); } catch (SQLException e) { - log.debug( e.getMessage() ); + fail( e ); } try { TransactionUtil.doWithJDBC( - serviceRegistry, + ssr, connection -> { try (Statement statement = connection.createStatement()) { connection.setAutoCommit( true ); @@ -126,10 +123,10 @@ protected void buildSessionFactory() { ); } catch (SQLException e) { - log.debug( e.getMessage() ); + fail( e ); } TransactionUtil.doWithJDBC( - serviceRegistry, + ssr, connection -> { try (Statement statement = connection.createStatement()) { connection.setAutoCommit( true ); @@ -152,9 +149,9 @@ protected void buildSessionFactory() { throw new RuntimeException( e ); } finally { - serviceRegistry.destroy(); + ssr.close(); } - super.buildSessionFactory(); + return super.produceSessionFactory(model); } @Test @@ -177,11 +174,6 @@ protected Class[] getAnnotatedClasses() { }; } - @Override - protected boolean rebuildSessionFactoryOnError() { - return false; - } - @Entity(name = "Human") @Table(name = "Human") @Inheritance(strategy = InheritanceType.JOINED) diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/functional/SQLServerDialectTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/functional/SQLServerDialectTest.java index a8ab2516377f..bf4fc4799da4 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/functional/SQLServerDialectTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/functional/SQLServerDialectTest.java @@ -18,24 +18,26 @@ import org.hibernate.LockMode; import org.hibernate.LockOptions; -import org.hibernate.Session; import org.hibernate.Transaction; import org.hibernate.cfg.AvailableSettings; -import org.hibernate.cfg.Configuration; import org.hibernate.dialect.SQLServerDialect; import org.hibernate.dialect.lock.PessimisticEntityLockException; import org.hibernate.exception.LockTimeoutException; import org.hibernate.query.Query; -import org.hibernate.testing.RequiresDialect; +import org.hibernate.testing.orm.junit.RequiresDialect; +import org.hibernate.testing.orm.junit.DomainModel; import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; -import org.junit.Test; +import org.hibernate.testing.orm.junit.ServiceRegistry; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.hibernate.testing.orm.junit.Setting; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; -import static org.hibernate.testing.transaction.TransactionUtil.doInHibernate; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * used driver hibernate.connection.driver_class com.microsoft.sqlserver.jdbc.SQLServerDriver @@ -43,19 +45,23 @@ * @author Guenther Demetz */ @RequiresDialect(SQLServerDialect.class) -public class SQLServerDialectTest extends BaseCoreFunctionalTestCase { +@DomainModel(annotatedClasses = {Product2.class, Category.class, Folder.class, Contact.class, SQLServerDialectTest.KeyHolder.class}) +@SessionFactory +@ServiceRegistry( settings = {@Setting(name = AvailableSettings.KEYWORD_AUTO_QUOTING_ENABLED, value = "true")} ) +public class SQLServerDialectTest { - @Override - protected void configure(Configuration configuration) { - super.configure( configuration ); - configuration.setProperty( AvailableSettings.KEYWORD_AUTO_QUOTING_ENABLED, Boolean.TRUE.toString() ); + @AfterEach + public void cleanup(SessionFactoryScope scope) throws InterruptedException { + //SQL Server Driver does not deallocate connections right away + Thread.sleep( 100 ); + scope.getSessionFactory().getSchemaManager().truncateMappedObjects(); } @Test @JiraKey(value = "HHH-8916") - public void testPaginationWithCTEQueryNoOffset() { + public void testPaginationWithCTEQueryNoOffset(SessionFactoryScope scope) { // This used to throw SQLServerException: Incorrect syntax near 'SEL' - doInHibernate( this::sessionFactory, session -> { + scope.inTransaction( session -> { for ( int i = 0; i < 20; ++i ) { session.persist( new Product2( i, "Product" + i ) ); } @@ -74,9 +80,9 @@ public void testPaginationWithCTEQueryNoOffset() { @Test @JiraKey(value = "HHH-8916") - public void testPaginationWithCTEQueryNoOffsetNewLine() { + public void testPaginationWithCTEQueryNoOffsetNewLine(SessionFactoryScope scope) { // This used to throw SQLServerException: Incorrect syntax near 'SEL' - doInHibernate( this::sessionFactory, session -> { + scope.inTransaction( session -> { for ( int i = 0; i < 20; ++i ) { session.persist( new Product2( i, "Product" + i ) ); } @@ -100,9 +106,9 @@ public void testPaginationWithCTEQueryNoOffsetNewLine() { @Test @JiraKey(value = "HHH-8916") - public void testPaginationWithCTEQueryWithOffsetAndOrderBy() { + public void testPaginationWithCTEQueryWithOffsetAndOrderBy(SessionFactoryScope scope) { // This used to throw a StringIndexOutOfBoundsException - doInHibernate( this::sessionFactory, session -> { + scope.inTransaction( session -> { for ( int i = 0; i < 20; ++i ) { session.persist( new Product2( i, "Product" + i ) ); } @@ -127,9 +133,9 @@ public void testPaginationWithCTEQueryWithOffsetAndOrderBy() { @Test @JiraKey(value = "HHH-8916") - public void testPaginationWithCTEQueryWithOffset() { + public void testPaginationWithCTEQueryWithOffset(SessionFactoryScope scope) { // This used to throw a StringIndexOutOfBoundsException - doInHibernate( this::sessionFactory, session -> { + scope.inTransaction( session -> { for ( int i = 0; i < 20; ++i ) { session.persist( new Product2( i, "Product" + i ) ); } @@ -153,8 +159,8 @@ public void testPaginationWithCTEQueryWithOffset() { @Test @JiraKey(value = "HHH-7369") - public void testPaginationWithScalarQuery() throws Exception { - doInHibernate( this::sessionFactory, session -> { + public void testPaginationWithScalarQuery(SessionFactoryScope scope) { + scope.inTransaction( session -> { for ( int i = 0; i < 10; i++ ) { session.persist( new Product2( i, "Kit" + i ) ); } @@ -175,16 +181,16 @@ public void testPaginationWithScalarQuery() throws Exception { @Test @JiraKey(value = "HHH-7368") - public void testPaginationWithTrailingSemicolon() throws Exception { - doInHibernate( this::sessionFactory, session -> { + public void testPaginationWithTrailingSemicolon(SessionFactoryScope scope) { + scope.inTransaction( session -> { session.createNativeQuery( "select id from Product2 where description like 'Kit%' order by id;" ) .setFirstResult( 2 ).setMaxResults( 2 ).list(); } ); } @Test - public void testPaginationWithHQLProjection() { - doInHibernate( this::sessionFactory, session -> { + public void testPaginationWithHQLProjection(SessionFactoryScope scope) { + scope.inTransaction( session -> { for ( int i = 10; i < 20; i++ ) { session.persist( new Product2( i, "Kit" + i ) ); } @@ -205,8 +211,8 @@ public void testPaginationWithHQLProjection() { } @Test - public void testPaginationWithHQL() { - doInHibernate( this::sessionFactory, session -> { + public void testPaginationWithHQL(SessionFactoryScope scope) { + scope.inTransaction( session -> { for ( int i = 20; i < 30; i++ ) { session.persist( new Product2( i, "Kit" + i ) ); } @@ -220,8 +226,8 @@ public void testPaginationWithHQL() { @Test @JiraKey(value = "HHH-7370") - public void testPaginationWithMaxOnly() { - doInHibernate( this::sessionFactory, session -> { + public void testPaginationWithMaxOnly(SessionFactoryScope scope) { + scope.inTransaction( session -> { for ( int i = 30; i < 40; i++ ) { session.persist( new Product2( i, "Kit" + i ) ); } @@ -238,8 +244,8 @@ public void testPaginationWithMaxOnly() { @Test @JiraKey(value = "HHH-6627") - public void testPaginationWithAggregation() { - doInHibernate( this::sessionFactory, session -> { + public void testPaginationWithAggregation(SessionFactoryScope scope) { + scope.inTransaction( session -> { // populating test data Category category1 = new Category( 1, "Category1" ); Category category2 = new Category( 2, "Category2" ); @@ -257,16 +263,6 @@ public void testPaginationWithAggregation() { session.flush(); session.clear(); - // count number of products in each category -// List result = session.createCriteria( Category.class, "c" ).createAlias( "products", "p" ) -// .setProjection( -// Projections.projectionList() -// .add( Projections.groupProperty( "c.id" ) ) -// .add( Projections.countDistinct( "p.id" ) ) -// ) -// .addOrder( Order.asc( "c.id" ) ) -// .setFirstResult( 1 ).setMaxResults( 3 ).list(); - CriteriaBuilder criteriaBuilder = session.getCriteriaBuilder(); CriteriaQuery criteria = criteriaBuilder.createQuery( Object[].class ); Root root = criteria.from( Category.class ); @@ -286,8 +282,8 @@ public void testPaginationWithAggregation() { @Test @JiraKey(value = "HHH-7752") - public void testPaginationWithFormulaSubquery() { - doInHibernate( this::sessionFactory, session -> { + public void testPaginationWithFormulaSubquery(SessionFactoryScope scope) { + scope.inTransaction( session -> { // populating test data Folder folder1 = new Folder( 1L, "Folder1" ); Folder folder2 = new Folder( 2L, "Folder2" ); @@ -314,8 +310,8 @@ public void testPaginationWithFormulaSubquery() { @Test @JiraKey(value = "HHH-7781") - public void testPaginationWithCastOperator() { - doInHibernate( this::sessionFactory, session -> { + public void testPaginationWithCastOperator(SessionFactoryScope scope) { + scope.inTransaction( session -> { for ( int i = 40; i < 50; i++ ) { session.persist( new Product2( i, "Kit" + i ) ); } @@ -332,92 +328,83 @@ public void testPaginationWithCastOperator() { @Test @JiraKey(value = "HHH-3961") - public void testLockNowaitSqlServer() throws Exception { - Session s = openSession(); - s.beginTransaction(); - - final Product2 kit = new Product2(); - kit.id = 4000; - kit.description = "m"; - s.persist( kit ); - s.getTransaction().commit(); - - final Transaction tx = s.beginTransaction(); - - Session s2 = openSession(); - - s2.beginTransaction(); - - Product2 kit2 = s2.byId( Product2.class ).load( kit.id ); - - kit.description = "change!"; - s.flush(); // creates write lock on kit until we end the transaction - - Thread thread = new Thread( - () -> { - sleep( TimeUnit.SECONDS.toMillis( 1 ) ); - tx.commit(); + public void testLockNowaitSqlServer(SessionFactoryScope scope) { + scope.inSession( s -> { + s.beginTransaction(); + final Product2 kit = new Product2(); + kit.id = 4000; + kit.description = "m"; + s.persist( kit ); + s.getTransaction().commit(); + + final Transaction tx = s.beginTransaction(); + scope.inSession( s2 -> { + s2.beginTransaction(); + + Product2 kit2 = s2.byId( Product2.class ).load( kit.id ); + + kit.description = "change!"; + + s.flush(); // creates write lock on kit until we end the transaction + + Thread thread = new Thread( + () -> { + try { + Thread.sleep( TimeUnit.SECONDS.toMillis( 1 ) ); + } + catch (InterruptedException e) { + throw new RuntimeException( e ); + } + tx.commit(); + } + ); + + LockOptions opt = new LockOptions( LockMode.UPGRADE_NOWAIT ); + opt.setTimeOut( 0 ); // seems useless + long start = System.currentTimeMillis(); + thread.start(); + try { + s2.lock( kit2, opt ); + } + catch ( PessimisticEntityLockException e ) { + assertTrue( e.getCause() instanceof LockTimeoutException ); + } + long end = System.currentTimeMillis(); + try { + thread.join(); } - ); - - LockOptions opt = new LockOptions( LockMode.UPGRADE_NOWAIT ); - opt.setTimeOut( 0 ); // seems useless - long start = System.currentTimeMillis(); - thread.start(); - try { - s2.lock( kit2, opt ); - } - catch ( PessimisticEntityLockException e ) { - assertTrue( e.getCause() instanceof LockTimeoutException ); - } - long end = System.currentTimeMillis(); - thread.join(); - long differenceInMillis = end - start; - assertTrue( - "Lock NoWait blocked for " + differenceInMillis + " ms, this is definitely too much for Nowait", - differenceInMillis < 2000 - ); - - s2.getTransaction().rollback(); - s.getTransaction().begin(); - s.remove( kit ); - s.getTransaction().commit(); + catch (InterruptedException e) { + throw new RuntimeException( e ); + } + long differenceInMillis = end - start; + assertTrue( + differenceInMillis < 2000, + "Lock NoWait blocked for " + differenceInMillis + " ms, this is definitely too much for Nowait" + ); + + s2.getTransaction().rollback(); + } ); + + s.getTransaction().begin(); + s.remove( kit ); + s.getTransaction().commit(); + } ); } @Test @JiraKey(value = "HHH-10879") - public void testKeyReservedKeyword() { - doInHibernate( this::sessionFactory, session -> { + public void testKeyReservedKeyword(SessionFactoryScope scope) { + scope.inTransaction( session -> { final KeyHolder keyHolder = new KeyHolder(); keyHolder.key = 4000; session.persist( keyHolder ); } ); } - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Product2.class, Category.class, Folder.class, Contact.class, KeyHolder.class - }; - } - @Entity(name = "KeyHolder") public static class KeyHolder { - @Id public Integer key; } - - @Override - protected boolean rebuildSessionFactoryOnError() { - return false; - } - - @Override - protected boolean isCleanupTestDataRequired() { - //SQL Server Driver does not deallocate connections right away - sleep(100); - return true; - } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/resolver/DialectFactoryTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/resolver/DialectFactoryTest.java index 228d205577bc..28c6b66da890 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/resolver/DialectFactoryTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/resolver/DialectFactoryTest.java @@ -19,26 +19,27 @@ import org.hibernate.engine.jdbc.dialect.spi.DialectResolver; import org.hibernate.orm.test.dialect.TestingDialects; import org.hibernate.service.spi.ServiceRegistryImplementor; -import org.hibernate.testing.junit4.BaseUnitTestCase; import org.hibernate.testing.util.ServiceRegistryUtil; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.Collections; import java.util.HashMap; import java.util.Map; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Steve Ebersole */ -public class DialectFactoryTest extends BaseUnitTestCase { +public class DialectFactoryTest { private StandardServiceRegistry registry; private DialectFactoryImpl dialectFactory; - @Before + @BeforeEach public void setUp() { final BootstrapServiceRegistry bootReg = new BootstrapServiceRegistryBuilder().applyClassLoader( DialectFactoryTest.class.getClassLoader() @@ -49,7 +50,7 @@ public void setUp() { dialectFactory.injectServices( (ServiceRegistryImplementor) registry ); } - @After + @AfterEach public void destroy() { if ( registry != null ) { registry.close(); @@ -80,7 +81,7 @@ public void testExplicitlySuppliedDialectClassName() { fail(); } catch ( HibernateException e ) { - assertEquals( "unexpected exception type", StrategySelectionException.class, e.getClass() ); + assertEquals( StrategySelectionException.class, e.getClass(), "unexpected exception type" ); } configValues.put( Environment.DIALECT, "java.lang.Object" ); @@ -89,7 +90,7 @@ public void testExplicitlySuppliedDialectClassName() { fail(); } catch ( HibernateException e ) { - assertEquals( "unexpected exception type", ClassCastException.class, e.getCause().getClass() ); + assertEquals( ClassCastException.class, e.getCause().getClass(), "unexpected exception type" ); } } @@ -163,8 +164,6 @@ public void testCustomDialects() { resolvers.addResolver( new TestingDialects.MyDialectResolver1() ); resolvers.addResolver( new TestingDialects.MyDialectResolver2() ); resolvers.addResolver( new TestingDialects.MyOverridingDialectResolver1() ); - //DialectFactory.registerDialectResolver( "org.hibernate.dialect.NoSuchDialectResolver" ); - //DialectFactory.registerDialectResolver( "java.lang.Object" ); testDetermination( "MyDatabase1", TestingDialects.MyDialect1.class, resolvers ); testDetermination( "MyDatabase2", 1, TestingDialects.MyDialect21.class, resolvers ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/resolver/DialectResolverTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/resolver/DialectResolverTest.java index ae33c49a8e6d..cb2695185d3f 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/resolver/DialectResolverTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/resolver/DialectResolverTest.java @@ -4,8 +4,8 @@ */ package org.hibernate.orm.test.dialect.resolver; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; import org.hibernate.dialect.Dialect; import org.hibernate.orm.test.dialect.TestingDialects; @@ -14,15 +14,15 @@ import org.hibernate.engine.jdbc.dialect.spi.DialectResolutionInfo; import org.hibernate.engine.jdbc.dialect.spi.DialectResolver; import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseUnitTestCase; -import org.junit.Test; + +import org.junit.jupiter.api.Test; /** * @author Steve Ebersole */ -public class DialectResolverTest extends BaseUnitTestCase { +public class DialectResolverTest { @Test - public void testDialects() throws Exception { + public void testDialects() { DialectResolverSet resolvers = new DialectResolverSet(); resolvers.addResolverAtFirst( new TestingDialects.MyDialectResolver1() ); @@ -39,7 +39,7 @@ public void testDialects() throws Exception { } @Test - public void testErrorAndOrder() throws Exception { + public void testErrorAndOrder() { DialectResolverSet resolvers = new DialectResolverSet(); resolvers.addResolverAtFirst( new TestingDialects.MyDialectResolver1() ); @@ -52,7 +52,7 @@ public void testErrorAndOrder() throws Exception { } @Test - public void testBasicDialectResolver() throws Exception { + public void testBasicDialectResolver() { DialectResolverSet resolvers = new DialectResolverSet(); // Simulating MyDialectResolver1 by BasicDialectResolvers resolvers.addResolver( new BasicDialectResolver( "MyDatabase1", TestingDialects.MyDialect1.class ) ); 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 e72e22b7a8ee..83983d1a5564 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 @@ -11,18 +11,17 @@ import org.hibernate.dialect.SQLServerDialect; import org.hibernate.engine.jdbc.dialect.internal.StandardDialectResolver; -import org.hibernate.testing.junit4.BaseUnitTestCase; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; /** * Unit test of the {@link StandardDialectResolver} class. * * @author Bryan Turner */ -public class StandardDialectResolverTest extends BaseUnitTestCase { +public class StandardDialectResolverTest { @Test public void testResolveDialectInternalForSQLServer2000() { @@ -183,12 +182,12 @@ private static void runDialectTest( } String dbms = builder.toString(); - assertNotNull( "Dialect for " + dbms + " should not be null", dialect ); + assertNotNull( dialect, "Dialect for " + dbms + " should not be null" ); // 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() - ); + assertEquals( expectedDialect, + dialect.getClass(), + "Dialect for " + dbms + " should be " + expectedDialect.getSimpleName() + ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/unit/lockhint/AbstractLockHintTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/unit/lockhint/AbstractLockHintTest.java index 5ff82ba6f52a..82010717a095 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/unit/lockhint/AbstractLockHintTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/unit/lockhint/AbstractLockHintTest.java @@ -11,28 +11,27 @@ import org.hibernate.dialect.Dialect; import org.hibernate.internal.util.StringHelper; -import org.hibernate.testing.junit4.BaseUnitTestCase; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import static org.junit.Assert.assertEquals; /** * @author Steve Ebersole */ -public abstract class AbstractLockHintTest extends BaseUnitTestCase { +public abstract class AbstractLockHintTest { private Dialect dialect; protected abstract String getLockHintUsed(); protected abstract Dialect getDialectUnderTest(); - @Before + @BeforeEach public void setUp() throws Exception { this.dialect = getDialectUnderTest(); } - @After + @AfterEach public void tearDown() throws Exception { this.dialect = null; } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/unit/locktimeout/DB2LockTimeoutTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/unit/locktimeout/DB2LockTimeoutTest.java index ebdc318f25e6..db86053ad068 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/unit/locktimeout/DB2LockTimeoutTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/unit/locktimeout/DB2LockTimeoutTest.java @@ -9,18 +9,17 @@ import org.hibernate.dialect.DB2Dialect; import org.hibernate.dialect.DatabaseVersion; import org.hibernate.dialect.Dialect; -import org.hibernate.testing.junit4.BaseUnitTestCase; import org.hibernate.testing.orm.junit.RequiresDialect; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.hibernate.Timeouts.SKIP_LOCKED; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Gavin King */ @RequiresDialect(DB2Dialect.class) -public class DB2LockTimeoutTest extends BaseUnitTestCase { +public class DB2LockTimeoutTest { private final Dialect dialect = new DB2Dialect( DatabaseVersion.make( 11, 5 ) ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/unit/locktimeout/HANALockTimeoutTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/unit/locktimeout/HANALockTimeoutTest.java index 22e24823d8c2..a225cd2d41fc 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/unit/locktimeout/HANALockTimeoutTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/unit/locktimeout/HANALockTimeoutTest.java @@ -8,13 +8,12 @@ import org.hibernate.LockOptions; import org.hibernate.dialect.Dialect; import org.hibernate.dialect.HANADialect; -import org.hibernate.testing.junit4.BaseUnitTestCase; import org.hibernate.testing.orm.junit.RequiresDialect; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.hibernate.Timeouts.NO_WAIT; import static org.hibernate.Timeouts.SKIP_LOCKED; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * Expected lock clauses according to the official HANA FOR UPDATE clause documentation: @@ -24,7 +23,7 @@ * @author Vlad Mihalcea */ @RequiresDialect(HANADialect.class) -public class HANALockTimeoutTest extends BaseUnitTestCase { +public class HANALockTimeoutTest { private final Dialect dialect = new HANADialect(); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/unit/locktimeout/OracleLockTimeoutTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/unit/locktimeout/OracleLockTimeoutTest.java index 1abe4401d845..d5dc68480cbb 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/unit/locktimeout/OracleLockTimeoutTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/unit/locktimeout/OracleLockTimeoutTest.java @@ -9,19 +9,18 @@ import org.hibernate.dialect.DatabaseVersion; import org.hibernate.dialect.Dialect; import org.hibernate.dialect.OracleDialect; -import org.hibernate.testing.RequiresDialect; -import org.hibernate.testing.junit4.BaseUnitTestCase; -import org.junit.Test; +import org.hibernate.testing.orm.junit.RequiresDialect; +import org.junit.jupiter.api.Test; import static org.hibernate.Timeouts.NO_WAIT; import static org.hibernate.Timeouts.SKIP_LOCKED; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Vlad Mihalcea */ @RequiresDialect(OracleDialect.class) -public class OracleLockTimeoutTest extends BaseUnitTestCase { +public class OracleLockTimeoutTest { private final Dialect dialect = new OracleDialect( DatabaseVersion.make( 12 ) ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/unit/locktimeout/PostgreSQLLockTimeoutTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/unit/locktimeout/PostgreSQLLockTimeoutTest.java index c6c7f54c3978..a2aadefbb169 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/unit/locktimeout/PostgreSQLLockTimeoutTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/unit/locktimeout/PostgreSQLLockTimeoutTest.java @@ -9,19 +9,18 @@ import org.hibernate.dialect.Dialect; import org.hibernate.dialect.PostgreSQLDialect; -import org.hibernate.testing.junit4.BaseUnitTestCase; import org.hibernate.testing.orm.junit.RequiresDialect; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.hibernate.Timeouts.NO_WAIT; import static org.hibernate.Timeouts.SKIP_LOCKED; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Vlad Mihalcea */ @RequiresDialect(PostgreSQLDialect.class) -public class PostgreSQLLockTimeoutTest extends BaseUnitTestCase { +public class PostgreSQLLockTimeoutTest { private final Dialect dialect = new PostgreSQLDialect(); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/unit/sequence/AbstractSequenceInformationExtractorTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/unit/sequence/AbstractSequenceInformationExtractorTest.java index 13da85fc7a8c..7b25055dd8fb 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/unit/sequence/AbstractSequenceInformationExtractorTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/dialect/unit/sequence/AbstractSequenceInformationExtractorTest.java @@ -11,11 +11,11 @@ import org.hibernate.dialect.Dialect; import org.hibernate.tool.schema.extract.spi.SequenceInformationExtractor; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.hamcrest.core.Is.is; import static org.hamcrest.core.IsInstanceOf.instanceOf; -import static org.junit.Assert.assertThat; +import static org.hamcrest.MatcherAssert.assertThat; /** * @author Andrea Boriero diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/dirtiness/CustomDirtinessStrategyTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/dirtiness/CustomDirtinessStrategyTest.java index 5cbaa9d8ba07..2b0d943e7182 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/dirtiness/CustomDirtinessStrategyTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/dirtiness/CustomDirtinessStrategyTest.java @@ -8,88 +8,89 @@ import org.hibernate.Interceptor; import org.hibernate.Session; import org.hibernate.SessionBuilder; -import org.hibernate.SessionFactory; import org.hibernate.cfg.AvailableSettings; -import org.hibernate.cfg.Configuration; import org.hibernate.persister.entity.EntityPersister; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.ServiceRegistry; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.hibernate.testing.orm.junit.SettingProvider; import org.hibernate.type.Type; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Steve Ebersole */ -public class CustomDirtinessStrategyTest extends BaseCoreFunctionalTestCase { +@DomainModel(annotatedClasses = {Thing.class}) +@SessionFactory +@ServiceRegistry( + settingProviders = + @SettingProvider( + settingName = AvailableSettings.CUSTOM_ENTITY_DIRTINESS_STRATEGY, + provider = CustomDirtinessStrategyTest.StrategySettingProvider.class + ) +) +public class CustomDirtinessStrategyTest { private static final String INITIAL_NAME = "thing 1"; private static final String SUBSEQUENT_NAME = "thing 2"; - @Override - protected void configure(Configuration configuration) { - super.configure( configuration ); - configuration.getProperties().put( AvailableSettings.CUSTOM_ENTITY_DIRTINESS_STRATEGY, Strategy.INSTANCE ); - } - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { Thing.class }; + public static class StrategySettingProvider implements SettingProvider.Provider { + @Override + public Strategy getSetting() { + return Strategy.INSTANCE; + } } @Test - public void testOnlyCustomStrategy() { - Session session = openSession(); - session.beginTransaction(); - Thing t = new Thing( INITIAL_NAME ); - session.persist( t ); - Long id = t.getId(); - session.getTransaction().commit(); - session.close(); + public void testOnlyCustomStrategy(SessionFactoryScope scope) { + Long id = scope.fromTransaction( session -> { + Thing t = new Thing( INITIAL_NAME ); + session.persist( t ); + return t.getId(); + } ); Strategy.INSTANCE.resetState(); - session = openSession(); - session.beginTransaction(); - Thing thing = session.get( Thing.class, id ); - thing.setName( SUBSEQUENT_NAME ); - session.getTransaction().commit(); - session.close(); + scope.inTransaction( session -> { + Thing thing = session.find( Thing.class, id ); + thing.setName( SUBSEQUENT_NAME ); + } ); assertEquals( 1, Strategy.INSTANCE.canDirtyCheckCount ); assertEquals( 1, Strategy.INSTANCE.isDirtyCount ); assertEquals( 2, Strategy.INSTANCE.resetDirtyCount ); assertEquals( 1, Strategy.INSTANCE.findDirtyCount ); - session = openSession(); - session.beginTransaction(); - thing = session.get( Thing.class, id ); - assertEquals( SUBSEQUENT_NAME, thing.getName() ); - session.remove( thing ); - session.getTransaction().commit(); - session.close(); + scope.inTransaction( session -> { + Thing thing = session.find( Thing.class, id ); + assertEquals( SUBSEQUENT_NAME, thing.getName() ); + session.remove( thing ); + } ); } @Test - public void testCustomStrategyWithFlushInterceptor() { - Session session = openSession(); - session.beginTransaction(); - Thing t = new Thing( INITIAL_NAME ); - session.persist( t ); - Long id = t.getId(); - session.getTransaction().commit(); - session.close(); + public void testCustomStrategyWithFlushInterceptor(SessionFactoryScope scope) { + Long id = scope.fromTransaction( session -> { + Thing t = new Thing( INITIAL_NAME ); + session.persist( t ); + return t.getId(); + } ); Strategy.INSTANCE.resetState(); - session = sessionWithInterceptor().openSession(); - session.beginTransaction(); - Thing thing = session.get( Thing.class, id ); - thing.setName( SUBSEQUENT_NAME ); - session.getTransaction().commit(); - session.close(); + { + Session session = sessionWithInterceptor(scope).openSession(); + session.beginTransaction(); + Thing thing = session.find( Thing.class, id ); + thing.setName( SUBSEQUENT_NAME ); + session.getTransaction().commit(); + session.close(); + } // As we used an interceptor, the custom strategy should have been called twice to find dirty properties assertEquals( 1, Strategy.INSTANCE.canDirtyCheckCount ); @@ -97,48 +98,40 @@ public void testCustomStrategyWithFlushInterceptor() { assertEquals( 2, Strategy.INSTANCE.resetDirtyCount ); assertEquals( 2, Strategy.INSTANCE.findDirtyCount ); - session = openSession(); - session.beginTransaction(); - thing = session.get( Thing.class, id ); - assertEquals( SUBSEQUENT_NAME, thing.getName() ); - session.remove( thing ); - session.getTransaction().commit(); - session.close(); + scope.inTransaction( session -> { + Thing thing = session.find( Thing.class, id ); + assertEquals( SUBSEQUENT_NAME, thing.getName() ); + session.remove( thing ); + } ); } @Test - public void testOnlyCustomStrategyConsultedOnNonDirty() { - Session session = openSession(); - session.beginTransaction(); - Thing t = new Thing( INITIAL_NAME ); - session.persist( t ); - Long id = t.getId(); - session.getTransaction().commit(); - session.close(); - - session = openSession(); - session.beginTransaction(); - Thing thing = session.get( Thing.class, id ); - // lets change the name - thing.setName( SUBSEQUENT_NAME ); - assertTrue( Strategy.INSTANCE.isDirty( thing, null, null ) ); - // but fool the dirty map - thing.changedValues.clear(); - assertFalse( Strategy.INSTANCE.isDirty( thing, null, null ) ); - session.getTransaction().commit(); - session.close(); - - session = openSession(); - session.beginTransaction(); - thing = session.get( Thing.class, id ); - assertEquals( INITIAL_NAME, thing.getName() ); - session.createQuery( "delete Thing" ).executeUpdate(); - session.getTransaction().commit(); - session.close(); + public void testOnlyCustomStrategyConsultedOnNonDirty(SessionFactoryScope scope) { + Long id = scope.fromTransaction( session -> { + Thing t = new Thing( INITIAL_NAME ); + session.persist( t ); + return t.getId(); + } ); + + scope.inTransaction( session -> { + Thing thing = session.find( Thing.class, id ); + // let's change the name + thing.setName( SUBSEQUENT_NAME ); + assertTrue( Strategy.INSTANCE.isDirty( thing, null, null ) ); + // but fool the dirty map + thing.changedValues.clear(); + assertFalse( Strategy.INSTANCE.isDirty( thing, null, null ) ); + } ); + + scope.inTransaction( session -> { + Thing thing = session.find( Thing.class, id ); + assertEquals( INITIAL_NAME, thing.getName() ); + session.createMutationQuery( "delete Thing" ).executeUpdate(); + } ); } - private SessionBuilder sessionWithInterceptor() { - return sessionFactory().unwrap( SessionFactory.class ) + private SessionBuilder sessionWithInterceptor(SessionFactoryScope scope) { + return scope.getSessionFactory() .withOptions() .interceptor( OnFlushDirtyInterceptor.INSTANCE ); } @@ -192,7 +185,6 @@ void resetState() { } } - public static class OnFlushDirtyInterceptor implements Interceptor { private static final OnFlushDirtyInterceptor INSTANCE = new OnFlushDirtyInterceptor(); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/distinct/SelectDistinctHqlTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/distinct/SelectDistinctHqlTest.java index 584d74963750..a0ab2bc4af95 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/distinct/SelectDistinctHqlTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/distinct/SelectDistinctHqlTest.java @@ -7,12 +7,14 @@ import java.util.ArrayList; import java.util.List; -import org.hibernate.boot.SessionFactoryBuilder; - +import org.hibernate.testing.jdbc.SQLStatementInspector; +import org.hibernate.testing.orm.junit.DomainModel; import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.jdbc.SQLStatementInterceptor; -import org.hibernate.testing.junit4.BaseNonConfigCoreFunctionalTestCase; -import org.junit.Test; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import jakarta.persistence.CascadeType; import jakarta.persistence.Column; @@ -23,34 +25,23 @@ import jakarta.persistence.NamedQuery; import jakarta.persistence.OneToMany; -import static org.hibernate.testing.transaction.TransactionUtil.doInHibernate; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Vlad Mihalcea */ @JiraKey(value = "HHH-10965") -public class SelectDistinctHqlTest extends BaseNonConfigCoreFunctionalTestCase { +@DomainModel(annotatedClasses = {SelectDistinctHqlTest.Person.class, SelectDistinctHqlTest.Phone.class}) +@SessionFactory(useCollectingStatementInspector = true) +public class SelectDistinctHqlTest { private static final String DISTINCT_NAMED_QUERY = "distinct"; - private SQLStatementInterceptor sqlStatementInterceptor; - - @Override - protected void configureSessionFactoryBuilder(SessionFactoryBuilder sfb) { - sqlStatementInterceptor = new SQLStatementInterceptor( sfb ); - } + private SQLStatementInspector SQLStatementInspector; - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Person.class, - Phone.class, - }; - } - - protected void prepareTest() { - doInHibernate( this::sessionFactory, session -> { + @BeforeEach + protected void setup(SessionFactoryScope scope) { + scope.inTransaction( session -> { Person person = new Person(); person.id = 1L; session.persist( person ); @@ -58,52 +49,55 @@ protected void prepareTest() { person.addPhone( new Phone( "027-123-4567" ) ); person.addPhone( new Phone( "028-234-9876" ) ); } ); + + SQLStatementInspector = scope.getCollectingStatementInspector(); + SQLStatementInspector.clear(); } - @Override - protected boolean isCleanupTestDataRequired() { - return true; + @AfterEach + protected void tearDown(SessionFactoryScope scope) { + scope.dropData(); } @Test - public void test() { - doInHibernate( this::sessionFactory, session -> { - sqlStatementInterceptor.getSqlQueries().clear(); - List persons = session.createQuery( "select distinct p from Person p" ) + public void test(SessionFactoryScope scope) { + scope.inTransaction( session -> { + SQLStatementInspector.getSqlQueries().clear(); + List persons = session.createQuery( "select distinct p from Person p", Person.class ) .getResultList(); - String sqlQuery = sqlStatementInterceptor.getSqlQueries().getLast(); + String sqlQuery = SQLStatementInspector.getSqlQueries().get(0); assertEquals( 1, persons.size() ); assertTrue( sqlQuery.contains( " distinct " ) ); } ); - doInHibernate( this::sessionFactory, session -> { - List persons = session.createQuery( "select p from Person p left join fetch p.phones " ) + scope.inTransaction( session -> { + List persons = session.createQuery( "select p from Person p left join fetch p.phones ", Person.class ) .getResultList(); // with Hibernate ORM 6 it is not necessary to use *distinct* to not duplicate the instances which own the association assertEquals( 1, persons.size() ); } ); - doInHibernate( this::sessionFactory, session -> { - sqlStatementInterceptor.getSqlQueries().clear(); - List persons = session.createQuery( "select distinct p from Person p left join fetch p.phones " ) + scope.inTransaction( session -> { + SQLStatementInspector.getSqlQueries().clear(); + List persons = session.createQuery( "select distinct p from Person p left join fetch p.phones ", Person.class ) .getResultList(); assertEquals( 1, persons.size() ); - String sqlQuery = sqlStatementInterceptor.getSqlQueries().getLast(); + String sqlQuery = SQLStatementInspector.getSqlQueries().get(0); assertTrue( sqlQuery.contains( " distinct " ) ); } ); } @Test @JiraKey(value = "HHH-13780") - public void testNamedQueryDistinctPassThroughTrueWhenNotSpecified() { - doInHibernate( this::sessionFactory, session -> { - sqlStatementInterceptor.getSqlQueries().clear(); + public void testNamedQueryDistinctPassThroughTrueWhenNotSpecified(SessionFactoryScope scope) { + scope.inTransaction( session -> { + SQLStatementInspector.getSqlQueries().clear(); List persons = session.createNamedQuery( DISTINCT_NAMED_QUERY, Person.class ) .setMaxResults( 5 ) .getResultList(); assertEquals( 1, persons.size() ); - String sqlQuery = sqlStatementInterceptor.getSqlQueries().getLast(); + String sqlQuery = SQLStatementInspector.getSqlQueries().get(0); assertTrue( sqlQuery.contains( " distinct " ) ); } ); } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/callbacks/CallbackAndDirtyTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/callbacks/CallbackAndDirtyTest.java index d454e4ec68a3..acab327d4027 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/callbacks/CallbackAndDirtyTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/callbacks/CallbackAndDirtyTest.java @@ -4,99 +4,94 @@ */ package org.hibernate.orm.test.jpa.callbacks; -import java.util.Iterator; import java.util.List; -import jakarta.persistence.EntityManager; -import org.junit.Test; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.Test; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Emmanuel Bernard */ -public class CallbackAndDirtyTest extends BaseEntityManagerFunctionalTestCase { +@Jpa(annotatedClasses = { + Customer.class, + Employee.class, + Person.class +}) +public class CallbackAndDirtyTest { @Test - public void testDirtyButNotDirty() throws Exception { - EntityManager manager = getOrCreateEntityManager(); - manager.getTransaction().begin(); - Employee mark = new Employee(); - mark.setName( "Mark" ); - mark.setTitle( "internal sales" ); - mark.setSex( 'M' ); - mark.setAddress( "buckhead" ); - mark.setZip( "30305" ); - mark.setCountry( "USA" ); - - Customer joe = new Customer(); - joe.setName( "Joe" ); - joe.setSex( 'M' ); - joe.setAddress( "San Francisco" ); - joe.setZip( "XXXXX" ); - joe.setCountry( "USA" ); - joe.setComments( "Very demanding" ); - joe.setSalesperson( mark ); + public void testDirtyButNotDirty(EntityManagerFactoryScope scope) { + scope.inEntityManager( entityManager -> { + entityManager.getTransaction().begin(); + Employee mark = new Employee(); + mark.setName( "Mark" ); + mark.setTitle( "internal sales" ); + mark.setSex( 'M' ); + mark.setAddress( "buckhead" ); + mark.setZip( "30305" ); + mark.setCountry( "USA" ); - Person yomomma = new Person(); - yomomma.setName( "mum" ); - yomomma.setSex( 'F' ); + Customer joe = new Customer(); + joe.setName( "Joe" ); + joe.setSex( 'M' ); + joe.setAddress( "San Francisco" ); + joe.setZip( "XXXXX" ); + joe.setCountry( "USA" ); + joe.setComments( "Very demanding" ); + joe.setSalesperson( mark ); - manager.persist( mark ); - manager.persist( joe ); - manager.persist( yomomma ); - long[] ids = {mark.getId(), joe.getId(), yomomma.getId()}; - manager.getTransaction().commit(); + Person yomomma = new Person(); + yomomma.setName( "mum" ); + yomomma.setSex( 'F' ); - manager.getTransaction().begin(); - assertEquals( - manager.createQuery( "select p.address, p.name from Person p order by p.name" ).getResultList().size(), - 3 - ); - assertEquals( manager.createQuery( "select p from Person p where p.class = Customer" ).getResultList().size(), 1 ); - manager.getTransaction().commit(); + entityManager.persist( mark ); + entityManager.persist( joe ); + entityManager.persist( yomomma ); + long[] ids = {mark.getId(), joe.getId(), yomomma.getId()}; + entityManager.getTransaction().commit(); + entityManager.getTransaction().begin(); + assertEquals( + 3, + entityManager.createQuery( "select p.address, p.name from Person p order by p.name" ).getResultList().size() + ); + assertEquals( 1, + entityManager.createQuery( "select p from Person p where p.class = Customer" ).getResultList().size() ); + entityManager.getTransaction().commit(); - manager.getTransaction().begin(); - List customers = manager.createQuery( "select c from Customer c left join fetch c.salesperson" ).getResultList(); - for ( Iterator iter = customers.iterator(); iter.hasNext() ; ) { - Customer c = (Customer) iter.next(); - assertEquals( c.getSalesperson().getName(), "Mark" ); - } - assertEquals( customers.size(), 1 ); - manager.getTransaction().commit(); + entityManager.getTransaction().begin(); + List customers = entityManager.createQuery( "select c from Customer c left join fetch c.salesperson" ).getResultList(); + for ( Object customer : customers ) { + Customer c = (Customer) customer; + assertEquals( "Mark", c.getSalesperson().getName() ); + } + assertEquals( 1, customers.size() ); + entityManager.getTransaction().commit(); - manager.getTransaction().begin(); - customers = manager.createQuery( "select c from Customer c" ).getResultList(); - for ( Iterator iter = customers.iterator(); iter.hasNext() ; ) { - Customer c = (Customer) iter.next(); - assertEquals( c.getSalesperson().getName(), "Mark" ); - } - assertEquals( customers.size(), 1 ); - manager.getTransaction().commit(); + entityManager.getTransaction().begin(); + customers = entityManager.createQuery( "select c from Customer c" ).getResultList(); + for ( Object customer : customers ) { + Customer c = (Customer) customer; + assertEquals( "Mark", c.getSalesperson().getName() ); + } + assertEquals( 1, customers.size() ); + entityManager.getTransaction().commit(); - manager.getTransaction().begin(); - mark = manager.find( Employee.class, Long.valueOf( ids[0] ) ); - joe = manager.find( Customer.class, Long.valueOf( ids[1] ) ); - yomomma = manager.find( Person.class, Long.valueOf( ids[2] ) ); + entityManager.getTransaction().begin(); + mark = entityManager.find( Employee.class, ids[0] ); + joe = entityManager.find( Customer.class, ids[1] ); + yomomma = entityManager.find( Person.class, ids[2] ); - mark.setZip( "30306" ); - assertEquals( 1, manager.createQuery( "select p from Person p where p.zip = '30306'" ).getResultList().size() ); - manager.remove( mark ); - manager.remove( joe ); - manager.remove( yomomma ); - assertTrue( manager.createQuery( "select p from Person p" ).getResultList().isEmpty() ); - manager.getTransaction().commit(); - manager.close(); + mark.setZip( "30306" ); + assertEquals( 1, entityManager.createQuery( "select p from Person p where p.zip = '30306'" ).getResultList().size() ); + entityManager.remove( mark ); + entityManager.remove( joe ); + entityManager.remove( yomomma ); + assertTrue( entityManager.createQuery( "select p from Person p" ).getResultList().isEmpty() ); + entityManager.getTransaction().commit(); + } ); } - @Override - public Class[] getAnnotatedClasses() { - return new Class[]{ - Customer.class, - Employee.class, - Person.class - }; - } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/callbacks/PrivateConstructorEnhancerTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/callbacks/PrivateConstructorEnhancerTest.java index 33bb229d0f29..1cf62f88aae3 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/callbacks/PrivateConstructorEnhancerTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/callbacks/PrivateConstructorEnhancerTest.java @@ -58,7 +58,7 @@ public void testFindEntity(SessionFactoryScope scope) { try { Country country = session.find( Country.class, this.country.id ); - assertNotNull( "Romania", country.getName() ); + assertNotNull( country.getName(), "Romania" ); fail( "Should have thrown exception" ); } catch (Exception expected) { @@ -73,7 +73,7 @@ public void testGetReferenceEntity(SessionFactoryScope scope) { try { Country country = session.getReference( Country.class, this.country.id ); - assertNotNull( "Romania", country.getName() ); + assertNotNull( country.getName(), "Romania" ); fail( "Should have thrown exception" ); } catch (Exception expected) { @@ -88,7 +88,7 @@ public void testLoadProxyAssociation(SessionFactoryScope scope) { try { Person person = session.find( Person.class, this.person.id ); - assertNotNull( "Romania", person.getCountry().getName() ); + assertNotNull( person.getCountry().getName(), "Romania" ); fail( "Should have thrown exception" ); } catch (Exception expected) { @@ -101,7 +101,7 @@ public void testLoadProxyAssociation(SessionFactoryScope scope) { public void testListEntity(SessionFactoryScope scope) { scope.inTransaction( session -> { try { - List persons = session.createQuery( "select p from Person p" ).getResultList(); + List persons = session.createQuery( "select p from Person p", Person.class ).getResultList(); assertTrue( persons.stream().anyMatch( p -> p.getCountry().getName().equals( "Romania" ) ) ); fail( "Should have thrown exception" ); @@ -116,7 +116,7 @@ public void testListEntity(SessionFactoryScope scope) { public void testListJoinFetchEntity(SessionFactoryScope scope) { scope.inTransaction( session -> { try { - List persons = session.createQuery( "select p from Person p join fetch p.country" ) + List persons = session.createQuery( "select p from Person p join fetch p.country", Person.class ) .getResultList(); assertTrue( persons.stream().anyMatch( p -> p.getCountry().getName().equals( "Romania" ) ) ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/cascade/multicircle/MultiCircleJpaCascadeTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/cascade/multicircle/MultiCircleJpaCascadeTest.java index 115d105f7a38..164d1f9a5206 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/cascade/multicircle/MultiCircleJpaCascadeTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/cascade/multicircle/MultiCircleJpaCascadeTest.java @@ -15,7 +15,7 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import static org.hibernate.testing.junit4.ExtraAssertions.assertTyping; +import static org.hibernate.testing.orm.junit.ExtraAssertions.assertTyping; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.assertSame; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/cascade/multilevel/MultiLevelCascadeCollectionEmbeddableTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/cascade/multilevel/MultiLevelCascadeCollectionEmbeddableTest.java index 124109513072..e400c3a4af86 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/cascade/multilevel/MultiLevelCascadeCollectionEmbeddableTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/cascade/multilevel/MultiLevelCascadeCollectionEmbeddableTest.java @@ -24,7 +24,6 @@ import jakarta.persistence.SequenceGenerator; import jakarta.persistence.Table; -import org.hibernate.testing.FailureExpected; import org.hibernate.testing.orm.junit.JiraKey; import org.hibernate.testing.orm.junit.ImplicitListAsBagProvider; import org.hibernate.testing.orm.junit.Jpa; @@ -70,7 +69,6 @@ protected void initialize(EntityManagerFactoryScope scope) { } @Test - @FailureExpected( jiraKey = "HHH-12291" ) public void testHibernateDeleteEntityWithoutInitializingCollections(EntityManagerFactoryScope scope) { if ( !initialized ) { initialize(scope); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/cascade/multilevel/MultiLevelCascadeCollectionIdClassTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/cascade/multilevel/MultiLevelCascadeCollectionIdClassTest.java index cc0d004127c8..269d71b6e370 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/cascade/multilevel/MultiLevelCascadeCollectionIdClassTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/cascade/multilevel/MultiLevelCascadeCollectionIdClassTest.java @@ -23,7 +23,6 @@ import jakarta.persistence.SequenceGenerator; import jakarta.persistence.Table; -import org.hibernate.testing.FailureExpected; import org.hibernate.testing.orm.junit.JiraKey; import org.hibernate.testing.orm.junit.ImplicitListAsBagProvider; import org.hibernate.testing.orm.junit.Jpa; @@ -72,7 +71,6 @@ protected void initialize(EntityManagerFactoryScope scope) { } @Test - @FailureExpected( jiraKey = "HHH-12291" ) public void testHibernateDeleteEntityWithoutInitializingCollections(EntityManagerFactoryScope scope) { if ( !initialized ) { initialize(scope); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/compliance/EmbeddableInQueryResultTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/compliance/EmbeddableInQueryResultTest.java index 4efed8f38e70..cc07c4bbf8b0 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/compliance/EmbeddableInQueryResultTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/compliance/EmbeddableInQueryResultTest.java @@ -19,7 +19,7 @@ import jakarta.persistence.Table; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertNotSame; @Jpa( annotatedClasses = { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/compliance/tck2_2/ClosedFactoryTests.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/compliance/tck2_2/ClosedFactoryTests.java index 081eae6ce5d1..0f30f4e3905b 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/compliance/tck2_2/ClosedFactoryTests.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/compliance/tck2_2/ClosedFactoryTests.java @@ -8,32 +8,28 @@ import org.hibernate.SessionFactory; import org.hibernate.boot.MetadataSources; -import org.hibernate.boot.registry.StandardServiceRegistry; -import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.boot.spi.SessionFactoryBuilderImplementor; import org.hibernate.cfg.AvailableSettings; import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseUnitTestCase; -import org.hibernate.testing.util.ServiceRegistryUtil; -import org.junit.Test; +import org.hibernate.testing.orm.junit.ServiceRegistry; +import org.hibernate.testing.orm.junit.ServiceRegistryScope; +import org.hibernate.testing.orm.junit.Setting; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Steve Ebersole */ @JiraKey( value = "12097") -public class ClosedFactoryTests extends BaseUnitTestCase { +@ServiceRegistry(settings = {@Setting(name = AvailableSettings.JPA_CLOSED_COMPLIANCE, value = "true")}) +public class ClosedFactoryTests { @Test - public void testClosedChecks() { - final StandardServiceRegistry ssr = ServiceRegistryUtil.serviceRegistryBuilder() - .applySetting( AvailableSettings.JPA_CLOSED_COMPLIANCE, "true" ) - .build(); + public void testClosedChecks(ServiceRegistryScope scope) { - try { - final SessionFactoryBuilderImplementor factoryBuilder = (SessionFactoryBuilderImplementor) new MetadataSources( ssr ) + final SessionFactoryBuilderImplementor factoryBuilder = (SessionFactoryBuilderImplementor) new MetadataSources( scope.getRegistry() ) .buildMetadata() .getSessionFactoryBuilder(); final SessionFactory sf = factoryBuilder.build(); @@ -52,7 +48,7 @@ public void testClosedChecks() { // this is the expected outcome } catch (Exception e) { - fail( "#getCache failed, but not with the expected IllegalStateException : " + e.toString() ); + fail( "#getCache failed, but not with the expected IllegalStateException : " + e ); } try { @@ -63,7 +59,7 @@ public void testClosedChecks() { // this is the expected outcome } catch (Exception e) { - fail( "#getMetamodel failed, but not with the expected IllegalStateException : " + e.toString() ); + fail( "#getMetamodel failed, but not with the expected IllegalStateException : " + e ); } try { @@ -74,7 +70,7 @@ public void testClosedChecks() { // this is the expected outcome } catch (Exception e) { - fail( "#getCriteriaBuilder failed, but not with the expected IllegalStateException : " + e.toString() ); + fail( "#getCriteriaBuilder failed, but not with the expected IllegalStateException : " + e ); } try { @@ -85,7 +81,7 @@ public void testClosedChecks() { // this is the expected outcome } catch (Exception e) { - fail( "#getProperties failed, but not with the expected IllegalStateException : " + e.toString() ); + fail( "#getProperties failed, but not with the expected IllegalStateException : " + e ); } try { @@ -96,7 +92,7 @@ public void testClosedChecks() { // this is the expected outcome } catch (Exception e) { - fail( "#getPersistenceUnitUtil failed, but not with the expected IllegalStateException : " + e.toString() ); + fail( "#getPersistenceUnitUtil failed, but not with the expected IllegalStateException : " + e ); } try { @@ -107,7 +103,7 @@ public void testClosedChecks() { // this is the expected outcome } catch (Exception e) { - fail( "#close failed, but not with the expected IllegalStateException : " + e.toString() ); + fail( "#close failed, but not with the expected IllegalStateException : " + e ); } try { @@ -118,7 +114,7 @@ public void testClosedChecks() { // this is the expected outcome } catch (Exception e) { - fail( "#createEntityManager failed, but not with the expected IllegalStateException : " + e.toString() ); + fail( "#createEntityManager failed, but not with the expected IllegalStateException : " + e ); } try { @@ -129,12 +125,7 @@ public void testClosedChecks() { // this is the expected outcome } catch (Exception e) { - fail( "#createEntityManager(Map) failed, but not with the expected IllegalStateException : " + e.toString() ); + fail( "#createEntityManager(Map) failed, but not with the expected IllegalStateException : " + e ); } - } - catch (Exception e) { - // if an exception is - StandardServiceRegistryBuilder.destroy( ssr ); - } } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/compliance/tck2_2/EntityTransactionTests.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/compliance/tck2_2/EntityTransactionTests.java index 7a6d011b6d59..eae6bf74261c 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/compliance/tck2_2/EntityTransactionTests.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/compliance/tck2_2/EntityTransactionTests.java @@ -8,238 +8,178 @@ import org.hibernate.Transaction; import org.hibernate.boot.MetadataSources; -import org.hibernate.boot.registry.StandardServiceRegistry; -import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.AvailableSettings; import org.hibernate.engine.spi.SessionFactoryImplementor; import org.hibernate.resource.transaction.spi.TransactionStatus; -import org.hibernate.testing.junit4.BaseUnitTestCase; -import org.hibernate.testing.util.ServiceRegistryUtil; -import org.junit.Test; +import org.hibernate.testing.orm.junit.ServiceRegistry; +import org.hibernate.testing.orm.junit.ServiceRegistryScope; +import org.hibernate.testing.orm.junit.Setting; +import org.junit.jupiter.api.Test; import org.hamcrest.CoreMatchers; import static org.hamcrest.MatcherAssert.assertThat; import static org.hibernate.testing.transaction.TransactionUtil2.inSession; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Steve Ebersole */ -public class EntityTransactionTests extends BaseUnitTestCase { +@ServiceRegistry(settings = {@Setting(name = AvailableSettings.JPA_TRANSACTION_COMPLIANCE, value = "true")}) +public class EntityTransactionTests { @Test - public void testGetRollbackOnlyExpectations() { - final StandardServiceRegistry ssr = ServiceRegistryUtil.serviceRegistryBuilder() - .applySetting( AvailableSettings.JPA_TRANSACTION_COMPLIANCE, "true" ) - .build(); - - try { - final SessionFactoryImplementor sessionFactory = (SessionFactoryImplementor) new MetadataSources( ssr ) - .buildMetadata() - .buildSessionFactory(); - - try { - inSession( - sessionFactory, - session -> { - final Transaction transaction = session.getTransaction(); - assertFalse( transaction.isActive() ); - try { - transaction.getRollbackOnly(); - fail( "Expecting failure #getRollbackOnly on non-active txn" ); - } - catch (IllegalStateException expected) { - } + public void testGetRollbackOnlyExpectations(ServiceRegistryScope scope) { + + try (SessionFactoryImplementor sessionFactory = (SessionFactoryImplementor) new MetadataSources( + scope.getRegistry() ) + .buildMetadata() + .buildSessionFactory()) { + inSession( + sessionFactory, + session -> { + final Transaction transaction = session.getTransaction(); + assertFalse( transaction.isActive() ); + try { + transaction.getRollbackOnly(); + fail( "Expecting failure #getRollbackOnly on non-active txn" ); } - ); - } - finally { - sessionFactory.close(); - } - } - finally { - StandardServiceRegistryBuilder.destroy( ssr ); + catch (IllegalStateException expected) { + } + } + ); } } @Test - public void testMarkRollbackOnlyNoTransaction() { - final StandardServiceRegistry ssr = ServiceRegistryUtil.serviceRegistryBuilder() - .applySetting( AvailableSettings.JPA_TRANSACTION_COMPLIANCE, "true" ) - .build(); - - try { - final SessionFactoryImplementor sessionFactory = (SessionFactoryImplementor) new MetadataSources( ssr ) - .buildMetadata() - .buildSessionFactory(); - - try { - inSession( - sessionFactory, - session -> { - final Transaction transaction = session.getTransaction(); - assertFalse( transaction.isActive() ); - - // should just happen silently because there is no transaction - transaction.markRollbackOnly(); - - transaction.begin(); - transaction.commit(); - } - ); - } - finally { - sessionFactory.close(); - } - } - finally { - StandardServiceRegistryBuilder.destroy( ssr ); + public void testMarkRollbackOnlyNoTransaction(ServiceRegistryScope scope) { + + try (SessionFactoryImplementor sessionFactory = (SessionFactoryImplementor) new MetadataSources( + scope.getRegistry() ) + .buildMetadata() + .buildSessionFactory()) { + inSession( + sessionFactory, + session -> { + final Transaction transaction = session.getTransaction(); + assertFalse( transaction.isActive() ); + + // should just happen silently because there is no transaction + transaction.markRollbackOnly(); + + transaction.begin(); + transaction.commit(); + } + ); } } @Test - public void testSetRollbackOnlyOutcomeExpectations() { - final StandardServiceRegistry ssr = ServiceRegistryUtil.serviceRegistryBuilder() - .applySetting( AvailableSettings.JPA_TRANSACTION_COMPLIANCE, "true" ) - .build(); - - try { - final SessionFactoryImplementor sessionFactory = (SessionFactoryImplementor) new MetadataSources( ssr ) - .buildMetadata() - .buildSessionFactory(); - - try { - inSession( - sessionFactory, - session -> { - final Transaction transaction = session.getTransaction(); - transaction.begin(); - - try { - assertTrue( transaction.isActive() ); - - transaction.setRollbackOnly(); - assertTrue( transaction.isActive() ); - assertTrue( transaction.getRollbackOnly() ); - } - finally { - if ( transaction.isActive() ) { - transaction.rollback(); - } + public void testSetRollbackOnlyOutcomeExpectations(ServiceRegistryScope scope) { + + try (SessionFactoryImplementor sessionFactory = (SessionFactoryImplementor) new MetadataSources( + scope.getRegistry() ) + .buildMetadata() + .buildSessionFactory()) { + inSession( + sessionFactory, + session -> { + final Transaction transaction = session.getTransaction(); + transaction.begin(); + + try { + assertTrue( transaction.isActive() ); + + transaction.setRollbackOnly(); + assertTrue( transaction.isActive() ); + assertTrue( transaction.getRollbackOnly() ); + } + finally { + if ( transaction.isActive() ) { + transaction.rollback(); } } - ); + } + ); + + inSession( + sessionFactory, + session -> { + final Transaction transaction = session.getTransaction(); + transaction.begin(); + + try { + assertTrue( transaction.isActive() ); - inSession( - sessionFactory, - session -> { - final Transaction transaction = session.getTransaction(); - transaction.begin(); + transaction.setRollbackOnly(); + assertTrue( transaction.isActive() ); + assertTrue( transaction.getRollbackOnly() ); + // now try to commit, this should force a rollback try { - assertTrue( transaction.isActive() ); - - transaction.setRollbackOnly(); - assertTrue( transaction.isActive() ); - assertTrue( transaction.getRollbackOnly() ); - - // now try to commit, this should force a rollback - try { - transaction.commit(); - } - catch (RollbackException e) { - assertFalse( transaction.isActive() ); - assertThat( transaction.getStatus(), CoreMatchers.is( TransactionStatus.ROLLED_BACK ) ); - } + transaction.commit(); } - finally { - if ( transaction.isActive() ) { - transaction.rollback(); - } + catch (RollbackException e) { + assertFalse( transaction.isActive() ); + assertThat( transaction.getStatus(), CoreMatchers.is( TransactionStatus.ROLLED_BACK ) ); } } - ); - } - finally { - sessionFactory.close(); - } - } - finally { - StandardServiceRegistryBuilder.destroy( ssr ); + finally { + if ( transaction.isActive() ) { + transaction.rollback(); + } + } + } + ); } } @Test - public void testSetRollbackOnlyExpectations() { - final StandardServiceRegistry ssr = ServiceRegistryUtil.serviceRegistryBuilder() - .applySetting( AvailableSettings.JPA_TRANSACTION_COMPLIANCE, "true" ) - .build(); - - try { - final SessionFactoryImplementor sessionFactory = (SessionFactoryImplementor) new MetadataSources( ssr ) - .buildMetadata() - .buildSessionFactory(); - - try { - inSession( - sessionFactory, - session -> { - final Transaction transaction = session.getTransaction(); - assertFalse( transaction.isActive() ); - try { - transaction.setRollbackOnly(); - fail( "Expecting failure #setRollbackOnly on non-active txn" ); - } - catch (IllegalStateException expected) { - } + public void testSetRollbackOnlyExpectations(ServiceRegistryScope scope) { + + try (SessionFactoryImplementor sessionFactory = (SessionFactoryImplementor) new MetadataSources( + scope.getRegistry() ) + .buildMetadata() + .buildSessionFactory()) { + inSession( + sessionFactory, + session -> { + final Transaction transaction = session.getTransaction(); + assertFalse( transaction.isActive() ); + try { + transaction.setRollbackOnly(); + fail( "Expecting failure #setRollbackOnly on non-active txn" ); } - ); - } - finally { - sessionFactory.close(); - } - } - finally { - StandardServiceRegistryBuilder.destroy( ssr ); + catch (IllegalStateException expected) { + } + } + ); } } @Test - public void testRollbackExpectations() { - final StandardServiceRegistry ssr = ServiceRegistryUtil.serviceRegistryBuilder() - .applySetting( AvailableSettings.JPA_TRANSACTION_COMPLIANCE, "true" ) - .build(); - - try { - final SessionFactoryImplementor sessionFactory = (SessionFactoryImplementor) new MetadataSources( ssr ) - .buildMetadata() - .buildSessionFactory(); - - try { - inSession( - sessionFactory, - session -> { - final Transaction transaction = session.getTransaction(); - assertFalse( transaction.isActive() ); - try { - transaction.rollback(); - fail( "Expecting failure #rollback on non-active txn" ); - } - catch (IllegalStateException expected) { - } + public void testRollbackExpectations(ServiceRegistryScope scope) { + + try (SessionFactoryImplementor sessionFactory = (SessionFactoryImplementor) new MetadataSources( + scope.getRegistry() ) + .buildMetadata() + .buildSessionFactory()) { + inSession( + sessionFactory, + session -> { + final Transaction transaction = session.getTransaction(); + assertFalse( transaction.isActive() ); + try { + transaction.rollback(); + fail( "Expecting failure #rollback on non-active txn" ); } - ); - } - finally { - sessionFactory.close(); - } - } - finally { - StandardServiceRegistryBuilder.destroy( ssr ); + catch (IllegalStateException expected) { + } + } + ); } } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/compliance/tck2_2/GeneratedValueTests.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/compliance/tck2_2/GeneratedValueTests.java index feb9074e34ba..3d91f81e5e9f 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/compliance/tck2_2/GeneratedValueTests.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/compliance/tck2_2/GeneratedValueTests.java @@ -11,7 +11,6 @@ import org.hibernate.boot.model.relational.Sequence; import org.hibernate.boot.model.relational.SqlStringGenerationContext; import org.hibernate.boot.model.relational.internal.SqlStringGenerationContextImpl; -import org.hibernate.boot.registry.StandardServiceRegistry; import org.hibernate.boot.spi.MetadataImplementor; import org.hibernate.dialect.Dialect; import org.hibernate.dialect.H2Dialect; @@ -25,10 +24,10 @@ import org.hibernate.mapping.PersistentClass; import org.hibernate.mapping.RootClass; -import org.hibernate.testing.RequiresDialect; -import org.hibernate.testing.junit4.BaseUnitTestCase; -import org.hibernate.testing.util.ServiceRegistryUtil; -import org.junit.Test; +import org.hibernate.testing.orm.junit.RequiresDialect; +import org.hibernate.testing.orm.junit.ServiceRegistry; +import org.hibernate.testing.orm.junit.ServiceRegistryScope; +import org.junit.jupiter.api.Test; import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; @@ -39,246 +38,230 @@ import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.notNullValue; import static org.hamcrest.MatcherAssert.assertThat; -import static org.hibernate.testing.junit4.ExtraAssertions.assertTyping; -import static org.junit.Assert.assertTrue; +import static org.hibernate.testing.orm.junit.ExtraAssertions.assertTyping; +import static org.junit.jupiter.api.Assertions.assertTrue; /** - * Tests of various aspects of {@link GeneratedValue} handling in regards to determining + * Tests of various aspects of {@link GeneratedValue} handling in regard to determining * the {@link IdentifierGenerator} to use * * @author Steve Ebersole */ -@RequiresDialect( value = H2Dialect.class, comment = "Really, these tests are independent of the underlying database - but Dialects that do not support sequences cause some assertions to erroneously fail" ) -public class GeneratedValueTests extends BaseUnitTestCase { +@RequiresDialect( value = H2Dialect.class, comment = "Really, these tests are independent of the underlying database - " + + "but Dialects that do not support sequences cause some assertions to erroneously fail" ) +@ServiceRegistry +public class GeneratedValueTests { @Test - public void baseline() { - try (final StandardServiceRegistry ssr = ServiceRegistryUtil.serviceRegistry()) { - final MetadataImplementor bootModel = (MetadataImplementor) new MetadataSources( ssr ) - .addAnnotatedClass( ExplicitGeneratorEntity.class ) - .buildMetadata(); - final PersistentClass entityMapping = bootModel.getEntityBinding( ExplicitGeneratorEntity.class.getName() ); - KeyValue keyValue = entityMapping.getIdentifier(); - Dialect dialect = ssr.getService( JdbcEnvironment.class ).getDialect(); - final Generator generator1 = keyValue.createGenerator( dialect, (RootClass) entityMapping); - final IdentifierGenerator generator = generator1 instanceof IdentifierGenerator ? (IdentifierGenerator) generator1 : null; - generator.initialize( SqlStringGenerationContextImpl.forTests( bootModel.getDatabase().getJdbcEnvironment() ) ); - - final SequenceStyleGenerator sequenceStyleGenerator = assertTyping( - SequenceStyleGenerator.class, - generator - ); - assertThat( sequenceStyleGenerator.getDatabaseStructure().getPhysicalName().render(), is( "my_real_db_sequence" ) ); - - // all the JPA defaults since they were not defined - assertThat( sequenceStyleGenerator.getDatabaseStructure().getInitialValue(), is( 100 ) ); - assertThat( sequenceStyleGenerator.getDatabaseStructure().getIncrementSize(), is( 500 ) ); - } + public void baseline(ServiceRegistryScope scope) { + final MetadataImplementor bootModel = (MetadataImplementor) new MetadataSources( scope.getRegistry() ) + .addAnnotatedClass( ExplicitGeneratorEntity.class ) + .buildMetadata(); + final PersistentClass entityMapping = bootModel.getEntityBinding( ExplicitGeneratorEntity.class.getName() ); + KeyValue keyValue = entityMapping.getIdentifier(); + Dialect dialect = scope.getRegistry().getService( JdbcEnvironment.class ).getDialect(); + final Generator generator1 = keyValue.createGenerator( dialect, (RootClass) entityMapping); + final IdentifierGenerator generator = generator1 instanceof IdentifierGenerator ? (IdentifierGenerator) generator1 : null; + generator.initialize( SqlStringGenerationContextImpl.forTests( bootModel.getDatabase().getJdbcEnvironment() ) ); + + final SequenceStyleGenerator sequenceStyleGenerator = assertTyping( + SequenceStyleGenerator.class, + generator + ); + assertThat( sequenceStyleGenerator.getDatabaseStructure().getPhysicalName().render(), is( "my_real_db_sequence" ) ); + + // all the JPA defaults since they were not defined + assertThat( sequenceStyleGenerator.getDatabaseStructure().getInitialValue(), is( 100 ) ); + assertThat( sequenceStyleGenerator.getDatabaseStructure().getIncrementSize(), is( 500 ) ); } @Test - public void testImplicitSequenceGenerator() { - try (final StandardServiceRegistry ssr = ServiceRegistryUtil.serviceRegistry()) { - final MetadataImplementor bootModel = (MetadataImplementor) new MetadataSources( ssr ) - .addAnnotatedClass( ImplicitSequenceGeneratorEntity.class ) - .buildMetadata(); - final PersistentClass entityMapping = bootModel.getEntityBinding( ImplicitSequenceGeneratorEntity.class.getName() ); - KeyValue keyValue = entityMapping.getIdentifier(); - Dialect dialect = ssr.getService( JdbcEnvironment.class ).getDialect(); - final Generator generator1 = keyValue.createGenerator( dialect, (RootClass) entityMapping); - final IdentifierGenerator generator = generator1 instanceof IdentifierGenerator ? (IdentifierGenerator) generator1 : null; - generator.initialize( SqlStringGenerationContextImpl.forTests( bootModel.getDatabase().getJdbcEnvironment() ) ); - - final SequenceStyleGenerator sequenceStyleGenerator = assertTyping( - SequenceStyleGenerator.class, - generator - ); - - // PREFER_GENERATOR_NAME_AS_DEFAULT_SEQUENCE_NAME == false indicates that the legacy - // default (hibernate_sequence) should be used - assertThat( sequenceStyleGenerator.getDatabaseStructure().getPhysicalName().render(), is( "my_db_sequence" ) ); - - // the JPA defaults since they were not defined - assertThat( sequenceStyleGenerator.getDatabaseStructure().getInitialValue(), is( 1 ) ); - assertThat( sequenceStyleGenerator.getDatabaseStructure().getIncrementSize(), is( 50 ) ); - } + public void testImplicitSequenceGenerator(ServiceRegistryScope scope) { + final MetadataImplementor bootModel = (MetadataImplementor) new MetadataSources( scope.getRegistry() ) + .addAnnotatedClass( ImplicitSequenceGeneratorEntity.class ) + .buildMetadata(); + final PersistentClass entityMapping = bootModel.getEntityBinding( ImplicitSequenceGeneratorEntity.class.getName() ); + KeyValue keyValue = entityMapping.getIdentifier(); + Dialect dialect = scope.getRegistry().getService( JdbcEnvironment.class ).getDialect(); + final Generator generator1 = keyValue.createGenerator( dialect, (RootClass) entityMapping); + final IdentifierGenerator generator = generator1 instanceof IdentifierGenerator ? (IdentifierGenerator) generator1 : null; + generator.initialize( SqlStringGenerationContextImpl.forTests( bootModel.getDatabase().getJdbcEnvironment() ) ); + + final SequenceStyleGenerator sequenceStyleGenerator = assertTyping( + SequenceStyleGenerator.class, + generator + ); + + // PREFER_GENERATOR_NAME_AS_DEFAULT_SEQUENCE_NAME == false indicates that the legacy + // default (hibernate_sequence) should be used + assertThat( sequenceStyleGenerator.getDatabaseStructure().getPhysicalName().render(), is( "my_db_sequence" ) ); + + // the JPA defaults since they were not defined + assertThat( sequenceStyleGenerator.getDatabaseStructure().getInitialValue(), is( 1 ) ); + assertThat( sequenceStyleGenerator.getDatabaseStructure().getIncrementSize(), is( 50 ) ); } @Test - public void testImplicitSequenceGeneratorGeneratorName() { - try (final StandardServiceRegistry ssr = ServiceRegistryUtil.serviceRegistry()) { - final MetadataImplementor bootModel = (MetadataImplementor) new MetadataSources( ssr ) - .addAnnotatedClass( ImplicitSequenceGeneratorEntity.class ) - .buildMetadata(); - final PersistentClass entityMapping = bootModel.getEntityBinding( ImplicitSequenceGeneratorEntity.class.getName() ); - KeyValue keyValue = entityMapping.getIdentifier(); - Dialect dialect = ssr.getService( JdbcEnvironment.class ).getDialect(); - final Generator generator1 = keyValue.createGenerator( dialect, (RootClass) entityMapping); - final IdentifierGenerator generator = generator1 instanceof IdentifierGenerator ? (IdentifierGenerator) generator1 : null; - generator.initialize( SqlStringGenerationContextImpl.forTests( bootModel.getDatabase().getJdbcEnvironment() ) ); - - final SequenceStyleGenerator sequenceStyleGenerator = assertTyping( - SequenceStyleGenerator.class, - generator - ); - - // PREFER_GENERATOR_NAME_AS_DEFAULT_SEQUENCE_NAME == true (the default) indicates that the generator-name - // should be used as the default instead. - assertThat( sequenceStyleGenerator.getDatabaseStructure().getPhysicalName().render(), is( "my_db_sequence" ) ); - - // the JPA defaults since they were not defined - assertThat( sequenceStyleGenerator.getDatabaseStructure().getInitialValue(), is( 1 ) ); - assertThat( sequenceStyleGenerator.getDatabaseStructure().getIncrementSize(), is( 50 ) ); - } + public void testImplicitSequenceGeneratorGeneratorName(ServiceRegistryScope scope) { + final MetadataImplementor bootModel = (MetadataImplementor) new MetadataSources( scope.getRegistry() ) + .addAnnotatedClass( ImplicitSequenceGeneratorEntity.class ) + .buildMetadata(); + final PersistentClass entityMapping = bootModel.getEntityBinding( ImplicitSequenceGeneratorEntity.class.getName() ); + KeyValue keyValue = entityMapping.getIdentifier(); + Dialect dialect = scope.getRegistry().getService( JdbcEnvironment.class ).getDialect(); + final Generator generator1 = keyValue.createGenerator( dialect, (RootClass) entityMapping); + final IdentifierGenerator generator = generator1 instanceof IdentifierGenerator ? (IdentifierGenerator) generator1 : null; + generator.initialize( SqlStringGenerationContextImpl.forTests( bootModel.getDatabase().getJdbcEnvironment() ) ); + + final SequenceStyleGenerator sequenceStyleGenerator = assertTyping( + SequenceStyleGenerator.class, + generator + ); + + // PREFER_GENERATOR_NAME_AS_DEFAULT_SEQUENCE_NAME == true (the default) indicates that the generator-name + // should be used as the default instead. + assertThat( sequenceStyleGenerator.getDatabaseStructure().getPhysicalName().render(), is( "my_db_sequence" ) ); + + // the JPA defaults since they were not defined + assertThat( sequenceStyleGenerator.getDatabaseStructure().getInitialValue(), is( 1 ) ); + assertThat( sequenceStyleGenerator.getDatabaseStructure().getIncrementSize(), is( 50 ) ); } @Test - public void testExplicitSequenceGeneratorImplicitNamePreferGeneratorName() { + public void testExplicitSequenceGeneratorImplicitNamePreferGeneratorName(ServiceRegistryScope scope) { // this should be the default behavior - try (final StandardServiceRegistry ssr = ServiceRegistryUtil.serviceRegistry()) { - final MetadataImplementor bootModel = (MetadataImplementor) new MetadataSources( ssr ) - .addAnnotatedClass( ExplicitSequenceGeneratorImplicitNameEntity.class ) - .buildMetadata(); - final PersistentClass entityMapping = bootModel.getEntityBinding( - ExplicitSequenceGeneratorImplicitNameEntity.class.getName() ); - KeyValue keyValue = entityMapping.getIdentifier(); - Dialect dialect = ssr.getService( JdbcEnvironment.class ).getDialect(); - final Generator generator1 = keyValue.createGenerator( dialect, (RootClass) entityMapping); - final IdentifierGenerator generator = generator1 instanceof IdentifierGenerator ? (IdentifierGenerator) generator1 : null; - Database database = bootModel.getDatabase(); - SqlStringGenerationContext sqlStringGenerationContext = - SqlStringGenerationContextImpl.forTests( database.getJdbcEnvironment() ); - generator.initialize( sqlStringGenerationContext ); - - final SequenceStyleGenerator sequenceStyleGenerator = assertTyping( - SequenceStyleGenerator.class, - generator - ); - // all the JPA defaults since they were not defined - assertThat( sequenceStyleGenerator.getDatabaseStructure().getPhysicalName().render(), is( "my_db_sequence" ) ); - assertThat( sequenceStyleGenerator.getDatabaseStructure().getInitialValue(), is( 100 ) ); - assertThat( sequenceStyleGenerator.getDatabaseStructure().getIncrementSize(), is( 500 ) ); - - final Sequence sequence = database.getDefaultNamespace() - .locateSequence( Identifier.toIdentifier( "my_db_sequence" ) ); - assertThat( sequence, notNullValue() ); - assertThat( sequence.getName().getSequenceName().getText(), is( "my_db_sequence" ) ); - assertThat( sequence.getInitialValue(), is( 100 ) ); - assertThat( sequence.getIncrementSize(), is( 500 ) ); - - final String[] sqlCreateStrings = new H2Dialect().getSequenceExporter().getSqlCreateStrings( - sequence, - bootModel, - sqlStringGenerationContext - ); - assertThat( sqlCreateStrings.length, is( 1 ) ); - final String cmd = sqlCreateStrings[0].toLowerCase(); - assertTrue( cmd.startsWith( "create sequence my_db_sequence start with 100 increment by 500" ) ); - } + final MetadataImplementor bootModel = (MetadataImplementor) new MetadataSources( scope.getRegistry() ) + .addAnnotatedClass( ExplicitSequenceGeneratorImplicitNameEntity.class ) + .buildMetadata(); + final PersistentClass entityMapping = bootModel.getEntityBinding( + ExplicitSequenceGeneratorImplicitNameEntity.class.getName() ); + KeyValue keyValue = entityMapping.getIdentifier(); + Dialect dialect = scope.getRegistry().getService( JdbcEnvironment.class ).getDialect(); + final Generator generator1 = keyValue.createGenerator( dialect, (RootClass) entityMapping); + final IdentifierGenerator generator = generator1 instanceof IdentifierGenerator ? (IdentifierGenerator) generator1 : null; + Database database = bootModel.getDatabase(); + SqlStringGenerationContext sqlStringGenerationContext = + SqlStringGenerationContextImpl.forTests( database.getJdbcEnvironment() ); + generator.initialize( sqlStringGenerationContext ); + + final SequenceStyleGenerator sequenceStyleGenerator = assertTyping( + SequenceStyleGenerator.class, + generator + ); + // all the JPA defaults since they were not defined + assertThat( sequenceStyleGenerator.getDatabaseStructure().getPhysicalName().render(), is( "my_db_sequence" ) ); + assertThat( sequenceStyleGenerator.getDatabaseStructure().getInitialValue(), is( 100 ) ); + assertThat( sequenceStyleGenerator.getDatabaseStructure().getIncrementSize(), is( 500 ) ); + + final Sequence sequence = database.getDefaultNamespace() + .locateSequence( Identifier.toIdentifier( "my_db_sequence" ) ); + assertThat( sequence, notNullValue() ); + assertThat( sequence.getName().getSequenceName().getText(), is( "my_db_sequence" ) ); + assertThat( sequence.getInitialValue(), is( 100 ) ); + assertThat( sequence.getIncrementSize(), is( 500 ) ); + + final String[] sqlCreateStrings = new H2Dialect().getSequenceExporter().getSqlCreateStrings( + sequence, + bootModel, + sqlStringGenerationContext + ); + assertThat( sqlCreateStrings.length, is( 1 ) ); + final String cmd = sqlCreateStrings[0].toLowerCase(); + assertTrue( cmd.startsWith( "create sequence my_db_sequence start with 100 increment by 500" ) ); } @Test - public void testImplicitTableGenerator() { - try (final StandardServiceRegistry ssr = ServiceRegistryUtil.serviceRegistry()) { - final MetadataImplementor bootModel = (MetadataImplementor) new MetadataSources( ssr ) - .addAnnotatedClass( ImplicitTableGeneratorEntity.class ) - .buildMetadata(); - final PersistentClass entityMapping = bootModel.getEntityBinding( ImplicitTableGeneratorEntity.class.getName() ); - KeyValue keyValue = entityMapping.getIdentifier(); - Dialect dialect = ssr.getService( JdbcEnvironment.class ).getDialect(); - final Generator generator1 = keyValue.createGenerator( dialect, (RootClass) entityMapping); - final IdentifierGenerator generator = generator1 instanceof IdentifierGenerator ? (IdentifierGenerator) generator1 : null; - generator.initialize( SqlStringGenerationContextImpl.forTests( bootModel.getDatabase().getJdbcEnvironment() ) ); - - final TableGenerator tableGenerator = assertTyping( TableGenerator.class, generator ); - - assertThat( tableGenerator.getTableName(), is( "my_id_table" ) ); - - // all the JPA defaults since they were not defined - assertThat( tableGenerator.getInitialValue(), is( 1 ) ); - assertThat( tableGenerator.getIncrementSize(), is( 50 ) ); - } + public void testImplicitTableGenerator(ServiceRegistryScope scope) { + final MetadataImplementor bootModel = (MetadataImplementor) new MetadataSources( scope.getRegistry() ) + .addAnnotatedClass( ImplicitTableGeneratorEntity.class ) + .buildMetadata(); + final PersistentClass entityMapping = bootModel.getEntityBinding( ImplicitTableGeneratorEntity.class.getName() ); + KeyValue keyValue = entityMapping.getIdentifier(); + Dialect dialect = scope.getRegistry().getService( JdbcEnvironment.class ).getDialect(); + final Generator generator1 = keyValue.createGenerator( dialect, (RootClass) entityMapping); + final IdentifierGenerator generator = generator1 instanceof IdentifierGenerator ? (IdentifierGenerator) generator1 : null; + generator.initialize( SqlStringGenerationContextImpl.forTests( bootModel.getDatabase().getJdbcEnvironment() ) ); + + final TableGenerator tableGenerator = assertTyping( TableGenerator.class, generator ); + + assertThat( tableGenerator.getTableName(), is( "my_id_table" ) ); + + // all the JPA defaults since they were not defined + assertThat( tableGenerator.getInitialValue(), is( 1 ) ); + assertThat( tableGenerator.getIncrementSize(), is( 50 ) ); } @Test - public void testExplicitTableGeneratorImplicitName() { - try (final StandardServiceRegistry ssr = ServiceRegistryUtil.serviceRegistry()) { - final MetadataImplementor bootModel = (MetadataImplementor) new MetadataSources( ssr ) - .addAnnotatedClass( ExplicitTableGeneratorImplicitNameEntity.class ) - .buildMetadata(); - final PersistentClass entityMapping = bootModel.getEntityBinding( ExplicitTableGeneratorImplicitNameEntity.class.getName() ); - KeyValue keyValue = entityMapping.getIdentifier(); - Dialect dialect = ssr.getService( JdbcEnvironment.class ).getDialect(); - final Generator generator1 = keyValue.createGenerator( dialect, (RootClass) entityMapping); - final IdentifierGenerator generator = generator1 instanceof IdentifierGenerator ? (IdentifierGenerator) generator1 : null; - generator.initialize( SqlStringGenerationContextImpl.forTests( bootModel.getDatabase().getJdbcEnvironment() ) ); - - final TableGenerator tableGenerator = assertTyping( TableGenerator.class, generator ); - - assertThat( tableGenerator.getTableName(), is( "my_id_table" ) ); - - // - note : currently initialValue=1 in mapping is shows up here as 2 - assertThat( tableGenerator.getInitialValue(), is( 1 ) ); - assertThat( tableGenerator.getIncrementSize(), is( 25 ) ); - } + public void testExplicitTableGeneratorImplicitName(ServiceRegistryScope scope) { + final MetadataImplementor bootModel = (MetadataImplementor) new MetadataSources( scope.getRegistry() ) + .addAnnotatedClass( ExplicitTableGeneratorImplicitNameEntity.class ) + .buildMetadata(); + final PersistentClass entityMapping = bootModel.getEntityBinding( ExplicitTableGeneratorImplicitNameEntity.class.getName() ); + KeyValue keyValue = entityMapping.getIdentifier(); + Dialect dialect = scope.getRegistry().getService( JdbcEnvironment.class ).getDialect(); + final Generator generator1 = keyValue.createGenerator( dialect, (RootClass) entityMapping); + final IdentifierGenerator generator = generator1 instanceof IdentifierGenerator ? (IdentifierGenerator) generator1 : null; + generator.initialize( SqlStringGenerationContextImpl.forTests( bootModel.getDatabase().getJdbcEnvironment() ) ); + + final TableGenerator tableGenerator = assertTyping( TableGenerator.class, generator ); + + assertThat( tableGenerator.getTableName(), is( "my_id_table" ) ); + + // - note : currently initialValue=1 in mapping is shows up here as 2 + assertThat( tableGenerator.getInitialValue(), is( 1 ) ); + assertThat( tableGenerator.getIncrementSize(), is( 25 ) ); } @Test - public void testExplicitTableGenerator() { - try (final StandardServiceRegistry ssr = ServiceRegistryUtil.serviceRegistry()) { - final MetadataImplementor bootModel = (MetadataImplementor) new MetadataSources( ssr ) - .addAnnotatedClass( ExplicitTableGeneratorEntity.class ) - .buildMetadata(); - final PersistentClass entityMapping = bootModel.getEntityBinding( ExplicitTableGeneratorEntity.class.getName() ); - KeyValue keyValue = entityMapping.getIdentifier(); - Dialect dialect = ssr.getService( JdbcEnvironment.class ).getDialect(); - final Generator generator1 = keyValue.createGenerator( dialect, (RootClass) entityMapping); - final IdentifierGenerator generator = generator1 instanceof IdentifierGenerator ? (IdentifierGenerator) generator1 : null; - generator.initialize( SqlStringGenerationContextImpl.forTests( bootModel.getDatabase().getJdbcEnvironment() ) ); - - final TableGenerator tableGenerator = assertTyping( TableGenerator.class, generator ); - - assertThat( tableGenerator.getTableName(), is( "my_real_id_table" ) ); - - // all the JPA defaults since they were not defined - // - note : currently initialValue=1 in mapping is shows up here - // as 2 + public void testExplicitTableGenerator(ServiceRegistryScope scope) { + final MetadataImplementor bootModel = (MetadataImplementor) new MetadataSources( scope.getRegistry() ) + .addAnnotatedClass( ExplicitTableGeneratorEntity.class ) + .buildMetadata(); + final PersistentClass entityMapping = bootModel.getEntityBinding( ExplicitTableGeneratorEntity.class.getName() ); + KeyValue keyValue = entityMapping.getIdentifier(); + Dialect dialect = scope.getRegistry().getService( JdbcEnvironment.class ).getDialect(); + final Generator generator1 = keyValue.createGenerator( dialect, (RootClass) entityMapping); + final IdentifierGenerator generator = generator1 instanceof IdentifierGenerator ? (IdentifierGenerator) generator1 : null; + generator.initialize( SqlStringGenerationContextImpl.forTests( bootModel.getDatabase().getJdbcEnvironment() ) ); + + final TableGenerator tableGenerator = assertTyping( TableGenerator.class, generator ); + + assertThat( tableGenerator.getTableName(), is( "my_real_id_table" ) ); + + // all the JPA defaults since they were not defined + // - note : currently initialValue=1 in mapping is shows up here + // as 2 // assertThat( tableGenerator.getInitialValue(), is( 1 ) ); - assertThat( tableGenerator.getIncrementSize(), is( 25 ) ); - } + assertThat( tableGenerator.getIncrementSize(), is( 25 ) ); } @Test - public void testExplicitIncrementGenerator() { - try (final StandardServiceRegistry ssr = ServiceRegistryUtil.serviceRegistry()) { - final MetadataImplementor bootModel = (MetadataImplementor) new MetadataSources( ssr ) - .addAnnotatedClass( ExplicitIncrementGeneratorEntity.class ) - .buildMetadata(); - final PersistentClass entityMapping = bootModel.getEntityBinding( ExplicitIncrementGeneratorEntity.class.getName() ); - KeyValue keyValue = entityMapping.getIdentifier(); - Dialect dialect = ssr.getService( JdbcEnvironment.class ).getDialect(); - final Generator generator1 = keyValue.createGenerator( dialect, (RootClass) entityMapping); - final IdentifierGenerator generator = generator1 instanceof IdentifierGenerator ? (IdentifierGenerator) generator1 : null; - generator.initialize( SqlStringGenerationContextImpl.forTests( bootModel.getDatabase().getJdbcEnvironment() ) ); - - assertTyping( IncrementGenerator.class, generator ); - } + public void testExplicitIncrementGenerator(ServiceRegistryScope scope) { + final MetadataImplementor bootModel = (MetadataImplementor) new MetadataSources( scope.getRegistry() ) + .addAnnotatedClass( ExplicitIncrementGeneratorEntity.class ) + .buildMetadata(); + final PersistentClass entityMapping = bootModel.getEntityBinding( ExplicitIncrementGeneratorEntity.class.getName() ); + KeyValue keyValue = entityMapping.getIdentifier(); + Dialect dialect = scope.getRegistry().getService( JdbcEnvironment.class ).getDialect(); + final Generator generator1 = keyValue.createGenerator( dialect, (RootClass) entityMapping); + final IdentifierGenerator generator = generator1 instanceof IdentifierGenerator ? (IdentifierGenerator) generator1 : null; + generator.initialize( SqlStringGenerationContextImpl.forTests( bootModel.getDatabase().getJdbcEnvironment() ) ); + + assertTyping( IncrementGenerator.class, generator ); } @Test - public void testImplicitIncrementGenerator() { - try (final StandardServiceRegistry ssr = ServiceRegistryUtil.serviceRegistry()) { - final MetadataImplementor bootModel = (MetadataImplementor) new MetadataSources( ssr ) - .addAnnotatedClass( ImplicitIncrementGeneratorEntity.class ) - .buildMetadata(); - final PersistentClass entityMapping = bootModel.getEntityBinding( ImplicitIncrementGeneratorEntity.class.getName() ); - KeyValue keyValue = entityMapping.getIdentifier(); - Dialect dialect = ssr.getService( JdbcEnvironment.class ).getDialect(); - final Generator generator1 = keyValue.createGenerator( dialect, (RootClass) entityMapping); - final IdentifierGenerator generator = generator1 instanceof IdentifierGenerator ? (IdentifierGenerator) generator1 : null; - generator.initialize( SqlStringGenerationContextImpl.forTests( bootModel.getDatabase().getJdbcEnvironment() ) ); - - assertTyping( IncrementGenerator.class, generator ); - } + public void testImplicitIncrementGenerator(ServiceRegistryScope scope) { + final MetadataImplementor bootModel = (MetadataImplementor) new MetadataSources( scope.getRegistry() ) + .addAnnotatedClass( ImplicitIncrementGeneratorEntity.class ) + .buildMetadata(); + final PersistentClass entityMapping = bootModel.getEntityBinding( ImplicitIncrementGeneratorEntity.class.getName() ); + KeyValue keyValue = entityMapping.getIdentifier(); + Dialect dialect = scope.getRegistry().getService( JdbcEnvironment.class ).getDialect(); + final Generator generator1 = keyValue.createGenerator( dialect, (RootClass) entityMapping); + final IdentifierGenerator generator = generator1 instanceof IdentifierGenerator ? (IdentifierGenerator) generator1 : null; + generator.initialize( SqlStringGenerationContextImpl.forTests( bootModel.getDatabase().getJdbcEnvironment() ) ); + + assertTyping( IncrementGenerator.class, generator ); } @Entity diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/compliance/tck2_2/GetterAndIsMethodChecks.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/compliance/tck2_2/GetterAndIsMethodChecks.java index 9b5e70409007..7c2db6948533 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/compliance/tck2_2/GetterAndIsMethodChecks.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/compliance/tck2_2/GetterAndIsMethodChecks.java @@ -11,15 +11,14 @@ import org.hibernate.boot.MetadataSources; import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseUnitTestCase; import org.hibernate.testing.util.ServiceRegistryUtil; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * @author Steve Ebersole */ @JiraKey( value = "12096") -public class GetterAndIsMethodChecks extends BaseUnitTestCase { +public class GetterAndIsMethodChecks { @Test public void testIt() { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/compliance/tck2_2/QueryApiTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/compliance/tck2_2/QueryApiTest.java index 72998a5c3aea..42bc477ad622 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/compliance/tck2_2/QueryApiTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/compliance/tck2_2/QueryApiTest.java @@ -5,7 +5,6 @@ package org.hibernate.orm.test.jpa.compliance.tck2_2; import java.util.Date; -import java.util.Map; import jakarta.persistence.Entity; import jakarta.persistence.Id; import jakarta.persistence.Parameter; @@ -14,21 +13,27 @@ import jakarta.persistence.TemporalType; import jakarta.persistence.TransactionRequiredException; -import org.hibernate.boot.MetadataSources; import org.hibernate.cfg.AvailableSettings; import org.hibernate.query.Query; -import org.hibernate.testing.junit4.BaseNonConfigCoreFunctionalTestCase; -import org.junit.Test; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.ServiceRegistry; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.hibernate.testing.orm.junit.Setting; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Steve Ebersole */ -public class QueryApiTest extends BaseNonConfigCoreFunctionalTestCase { +@DomainModel(annotatedClasses = {QueryApiTest.Person.class}) +@SessionFactory +@ServiceRegistry(settings = {@Setting(name = AvailableSettings.JPA_TRANSACTION_COMPLIANCE, value = "true")}) +public class QueryApiTest { @Entity( name = "Person" ) @Table( name = "person" ) public static class Person { @@ -39,22 +44,9 @@ public static class Person { Date dob; } - @Override - protected void addSettings(Map settings) { - super.addSettings( settings ); - settings.put( AvailableSettings.JPA_TRANSACTION_COMPLIANCE, "true" ); - } - - @Override - protected void applyMetadataSources(MetadataSources sources) { - super.applyMetadataSources( sources ); - - sources.addAnnotatedClass( Person.class ); - } - @Test - public void testGetParameterNotBound() { - inTransaction( + public void testGetParameterNotBound(SessionFactoryScope scope) { + scope.inTransaction( session -> { try { // Query @@ -80,8 +72,8 @@ public void testGetParameterNotBound() { } @Test - public void testGetParameterFromAnotherQuery() { - inTransaction( + public void testGetParameterFromAnotherQuery(SessionFactoryScope scope) { + scope.inTransaction( session -> { try { // Query @@ -110,8 +102,8 @@ public void testGetParameterFromAnotherQuery() { } @Test - public void testGetParameterValueByUnknownName() { - inTransaction( + public void testGetParameterValueByUnknownName(SessionFactoryScope scope) { + scope.inTransaction( session -> { try { // Query @@ -128,8 +120,8 @@ public void testGetParameterValueByUnknownName() { } @Test - public void testGetParameterValueByUnknownPosition() { - inTransaction( + public void testGetParameterValueByUnknownPosition(SessionFactoryScope scope) { + scope.inTransaction( session -> { try { // Query @@ -146,8 +138,8 @@ public void testGetParameterValueByUnknownPosition() { } @Test - public void testSetParameterValueByUnknownReference() { - inTransaction( + public void testSetParameterValueByUnknownReference(SessionFactoryScope scope) { + scope.inTransaction( session -> { try { // Query @@ -167,8 +159,8 @@ public void testSetParameterValueByUnknownReference() { } @Test - public void testSetInvalidFirstResult() { - inTransaction( + public void testSetInvalidFirstResult(SessionFactoryScope scope) { + scope.inTransaction( session -> { try { // Query @@ -183,8 +175,8 @@ public void testSetInvalidFirstResult() { } @Test - public void testSetInvalidMaxResults() { - inTransaction( + public void testSetInvalidMaxResults(SessionFactoryScope scope) { + scope.inTransaction( session -> { try { // Query @@ -199,8 +191,8 @@ public void testSetInvalidMaxResults() { } @Test - public void testUpdateRequiresTxn() { - inSession( + public void testUpdateRequiresTxn(SessionFactoryScope scope) { + scope.inSession( session -> { try { assertFalse( session.getTransaction().isActive() ); @@ -216,8 +208,8 @@ public void testUpdateRequiresTxn() { } @Test - public void testInvalidQueryMarksTxnForRollback() { - inSession( + public void testInvalidQueryMarksTxnForRollback(SessionFactoryScope scope) { + scope.inSession( session -> { try { assertFalse( session.getTransaction().isActive() ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/compliance/tck2_2/QueryExecutionTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/compliance/tck2_2/QueryExecutionTest.java index 8c4fa976830b..c7db3f0beebd 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/compliance/tck2_2/QueryExecutionTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/compliance/tck2_2/QueryExecutionTest.java @@ -14,13 +14,13 @@ import jakarta.persistence.OneToMany; import jakarta.persistence.Table; -import org.hibernate.boot.MetadataSources; - -import org.hibernate.testing.junit4.BaseNonConfigCoreFunctionalTestCase; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; import org.hibernate.transform.ResultTransformer; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.hamcrest.CoreMatchers; @@ -31,10 +31,12 @@ /** * @author Steve Ebersole */ -public class QueryExecutionTest extends BaseNonConfigCoreFunctionalTestCase { +@DomainModel(annotatedClasses = {QueryExecutionTest.Customer.class, QueryExecutionTest.Order.class}) +@SessionFactory +public class QueryExecutionTest { @Test - public void testCollectionFetch() { - inTransaction( + public void testCollectionFetch(SessionFactoryScope scope) { + scope.inTransaction( session -> { final List nonDistinctResult = session.createQuery( "select c from Customer c join fetch c.orders" ).list(); // note: this was historically `2` because Hibernate would return a root result for each of its fetched rows. @@ -96,16 +98,9 @@ public Order(Integer id, Customer customer, String receivableLocator) { } } - @Override - protected void applyMetadataSources(MetadataSources sources) { - super.applyMetadataSources( sources ); - sources.addAnnotatedClass( Customer.class ); - sources.addAnnotatedClass( Order.class ); - } - - @Before - public void createData() { - inTransaction( + @BeforeEach + public void createData(SessionFactoryScope scope) { + scope.inTransaction( session -> { final Customer cust = new Customer( 1, "Acme Corp"); final Order order1 = new Order( 1, cust, "123" ); @@ -115,11 +110,11 @@ public void createData() { ); } - @After - public void dropData() { - inTransaction( + @AfterEach + public void dropData(SessionFactoryScope scope) { + scope.inTransaction( session -> { - final Customer customer = session.byId( Customer.class ).load( 1 ); + final Customer customer = session.find( Customer.class, 1 ); if ( customer != null ) { session.remove( customer ); } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/compliance/tck2_2/TableGeneratorMultipleDefinitionTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/compliance/tck2_2/TableGeneratorMultipleDefinitionTest.java index 6226bb907a28..6c5ddf5a2395 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/compliance/tck2_2/TableGeneratorMultipleDefinitionTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/compliance/tck2_2/TableGeneratorMultipleDefinitionTest.java @@ -11,35 +11,31 @@ import jakarta.persistence.TableGenerator; import org.hibernate.boot.MetadataSources; -import org.hibernate.boot.registry.StandardServiceRegistry; -import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.AvailableSettings; import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseUnitTestCase; -import org.hibernate.testing.util.ServiceRegistryUtil; -import org.junit.Test; +import org.hibernate.testing.orm.junit.ServiceRegistry; +import org.hibernate.testing.orm.junit.ServiceRegistryScope; +import org.hibernate.testing.orm.junit.Setting; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; /** * @author Andrea Boriero */ @JiraKey(value = "HHH-12157") -public class TableGeneratorMultipleDefinitionTest extends BaseUnitTestCase { +@ServiceRegistry(settings = {@Setting(name = AvailableSettings.JPA_ID_GENERATOR_GLOBAL_SCOPE_COMPLIANCE, value = "true")}) +public class TableGeneratorMultipleDefinitionTest { - @Test(expected = IllegalArgumentException.class) - public void testDuplicateGeneratorNamesDefinition() { - StandardServiceRegistry ssr = ServiceRegistryUtil.serviceRegistryBuilder() - .applySetting( AvailableSettings.JPA_ID_GENERATOR_GLOBAL_SCOPE_COMPLIANCE, "true" ) - .build(); - try { - new MetadataSources( ssr ) - .addAnnotatedClass( TestEntity2.class ) - .addAnnotatedClass( TestEntity1.class ) - .buildMetadata(); - } - finally { - StandardServiceRegistryBuilder.destroy( ssr ); - } + @Test + public void testDuplicateGeneratorNamesDefinition(ServiceRegistryScope scope) { + Assertions.assertThrows( IllegalArgumentException.class, () -> { + new MetadataSources( scope.getRegistry() ) + .addAnnotatedClass( TestEntity2.class ) + .addAnnotatedClass( TestEntity1.class ) + .buildMetadata(); + } + ); } @Entity(name = "TestEntity1") diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/compliance/tck2_2/TableGeneratorVisibilityTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/compliance/tck2_2/TableGeneratorVisibilityTest.java index a50e05fb1644..efcb52fcc313 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/compliance/tck2_2/TableGeneratorVisibilityTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/compliance/tck2_2/TableGeneratorVisibilityTest.java @@ -11,46 +11,35 @@ import jakarta.persistence.TableGenerator; import org.hibernate.cfg.AvailableSettings; -import org.hibernate.cfg.Configuration; +import org.hibernate.testing.orm.junit.DomainModel; import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; -import org.hibernate.testing.transaction.TransactionUtil; -import org.junit.Test; +import org.hibernate.testing.orm.junit.ServiceRegistry; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.hibernate.testing.orm.junit.Setting; +import org.junit.jupiter.api.Test; /** * @author Andrea Boriero */ @JiraKey(value = "HHH-12157") -public class TableGeneratorVisibilityTest extends BaseCoreFunctionalTestCase { - - @Override - protected void configure(Configuration configuration) { - configuration.setProperty( AvailableSettings.JPA_ID_GENERATOR_GLOBAL_SCOPE_COMPLIANCE, true ); - } - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - TestEntity1.class, - TestEntity2.class, - TestEntity3.class - }; - } +@DomainModel(annotatedClasses = { + TableGeneratorVisibilityTest.TestEntity1.class, + TableGeneratorVisibilityTest.TestEntity2.class, + TableGeneratorVisibilityTest.TestEntity3.class +}) +@SessionFactory +@ServiceRegistry(settings = {@Setting(name = AvailableSettings.JPA_ID_GENERATOR_GLOBAL_SCOPE_COMPLIANCE, value = "true")}) +public class TableGeneratorVisibilityTest { @Test - public void testGeneratorIsVisible() { - TransactionUtil.doInHibernate( this::sessionFactory, session -> { - session.persist( new TestEntity1() ); - } ); + public void testGeneratorIsVisible(SessionFactoryScope scope) { + scope.inTransaction( session -> session.persist( new TestEntity1() ) ); - TransactionUtil.doInHibernate( this::sessionFactory, session -> { - session.persist( new TestEntity2() ); - } ); + scope.inTransaction( session -> session.persist( new TestEntity2() ) ); - TransactionUtil.doInHibernate( this::sessionFactory, session -> { - session.persist( new TestEntity3() ); - } ); + scope.inTransaction( session -> session.persist( new TestEntity3() ) ); } @Entity(name = "TestEntity1") diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/compliance/tck2_2/caching/CachingWithSecondaryTablesTests.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/compliance/tck2_2/caching/CachingWithSecondaryTablesTests.java index 5850fab6e4e9..a4f88331d9c5 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/compliance/tck2_2/caching/CachingWithSecondaryTablesTests.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/compliance/tck2_2/caching/CachingWithSecondaryTablesTests.java @@ -22,23 +22,24 @@ import org.hibernate.engine.spi.SessionFactoryImplementor; import org.hibernate.stat.spi.StatisticsImplementor; -import org.hibernate.testing.junit4.BaseUnitTestCase; +import org.hibernate.testing.orm.junit.BaseUnitTest; import org.hibernate.testing.util.ServiceRegistryUtil; -import org.junit.After; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; import org.hamcrest.CoreMatchers; import static org.hamcrest.MatcherAssert.assertThat; import static org.hibernate.testing.transaction.TransactionUtil2.inTransaction; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Steve Ebersole */ -public class CachingWithSecondaryTablesTests extends BaseUnitTestCase { +@BaseUnitTest +public class CachingWithSecondaryTablesTests { private SessionFactoryImplementor sessionFactory; @Test @@ -53,7 +54,7 @@ public void testUnstrictUnversioned() { ); // it should not be in the cache because it should be invalidated instead - assertEquals( statistics.getSecondLevelCachePutCount(), 0 ); + assertEquals( 0, statistics.getSecondLevelCachePutCount() ); assertFalse( sessionFactory.getCache().contains( Person.class, "1" ) ); inTransaction( @@ -61,7 +62,7 @@ public void testUnstrictUnversioned() { s -> { statistics.clear(); - final Person person = s.get( Person.class, "1" ); + final Person person = s.find( Person.class, "1" ); assertTrue( Hibernate.isInitialized( person ) ); assertThat( statistics.getSecondLevelCacheHitCount(), CoreMatchers.is( 0L) ); @@ -82,7 +83,7 @@ public void testStrictUnversioned() { ); // this time it should be iun the cache because we enabled JPA compliance - assertEquals( statistics.getSecondLevelCachePutCount(), 1 ); + assertEquals( 1, statistics.getSecondLevelCachePutCount() ); assertTrue( sessionFactory.getCache().contains( Person.class, "1" ) ); inTransaction( @@ -90,7 +91,7 @@ public void testStrictUnversioned() { s -> { statistics.clear(); - final Person person = s.get( Person.class, "1" ); + final Person person = s.find( Person.class, "1" ); assertTrue( Hibernate.isInitialized( person ) ); assertThat( statistics.getSecondLevelCacheHitCount(), CoreMatchers.is( 1L) ); @@ -111,7 +112,7 @@ public void testVersioned() { ); // versioned data should be cacheable regardless - assertEquals( statistics.getSecondLevelCachePutCount(), 1 ); + assertEquals( 1, statistics.getSecondLevelCachePutCount() ); assertTrue( sessionFactory.getCache().contains( VersionedPerson.class, "1" ) ); inTransaction( @@ -119,7 +120,7 @@ public void testVersioned() { s -> { statistics.clear(); - final VersionedPerson person = s.get( VersionedPerson.class, "1" ); + final VersionedPerson person = s.find( VersionedPerson.class, "1" ); assertTrue( Hibernate.isInitialized( person ) ); assertThat( statistics.getSecondLevelCacheHitCount(), CoreMatchers.is( 1L ) ); @@ -155,7 +156,7 @@ private SessionFactoryImplementor buildSessionFactory(Class entityClass, bool } } - @After + @AfterEach public void cleanupData() { if ( sessionFactory == null ) { return; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/compliance/tck2_2/caching/InheritedCacheableTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/compliance/tck2_2/caching/InheritedCacheableTest.java index 1b2b09d02caf..5b77404775d8 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/compliance/tck2_2/caching/InheritedCacheableTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/compliance/tck2_2/caching/InheritedCacheableTest.java @@ -4,98 +4,112 @@ */ package org.hibernate.orm.test.jpa.compliance.tck2_2.caching; -import java.util.Map; import jakarta.persistence.Cacheable; import jakarta.persistence.Entity; import jakarta.persistence.Id; import jakarta.persistence.Inheritance; import jakarta.persistence.InheritanceType; -import jakarta.persistence.SharedCacheMode; import jakarta.persistence.Table; import org.hibernate.Hibernate; -import org.hibernate.boot.MetadataSources; import org.hibernate.cfg.AvailableSettings; import org.hibernate.stat.spi.StatisticsImplementor; -import org.hibernate.testing.junit4.BaseNonConfigCoreFunctionalTestCase; -import org.junit.After; -import org.junit.Test; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.ServiceRegistry; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.hibernate.testing.orm.junit.Setting; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; import org.hamcrest.CoreMatchers; import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Steve Ebersole */ -public class InheritedCacheableTest extends BaseNonConfigCoreFunctionalTestCase { +@DomainModel( + annotatedClasses = { + InheritedCacheableTest.Person.class, + InheritedCacheableTest.Employee.class, + InheritedCacheableTest.Customer.class + } +) +@SessionFactory(generateStatistics = true) +@ServiceRegistry( settings = { + @Setting(name = AvailableSettings.USE_SECOND_LEVEL_CACHE, value = "true"), + @Setting(name = AvailableSettings.JPA_SHARED_CACHE_MODE, value = "ENABLE_SELECTIVE") + } +) +public class InheritedCacheableTest { @Test - public void testMapping() { + public void testMapping(SessionFactoryScope scope) { assertThat( - sessionFactory().getMappingMetamodel().getEntityDescriptor( Person.class ).hasCache(), + scope.getSessionFactory().getMappingMetamodel().getEntityDescriptor( Person.class ).hasCache(), CoreMatchers.is( true ) ); assertThat( - sessionFactory().getMappingMetamodel().getEntityDescriptor( Employee.class ).hasCache(), + scope.getSessionFactory().getMappingMetamodel().getEntityDescriptor( Employee.class ).hasCache(), CoreMatchers.is( true ) ); assertThat( - sessionFactory().getMappingMetamodel().getEntityDescriptor( Customer.class ).hasCache(), + scope.getSessionFactory().getMappingMetamodel().getEntityDescriptor( Customer.class ).hasCache(), CoreMatchers.is( false ) ); } @Test - public void testOnlySubclassIsCached() { - final StatisticsImplementor statistics = sessionFactory().getStatistics(); + public void testOnlySubclassIsCached(SessionFactoryScope scope) { + final StatisticsImplementor statistics = scope.getSessionFactory().getStatistics(); - inTransaction( + scope.inTransaction( s -> { s.persist( new Employee( "1", "John Doe", "987", "engineering") ); s.persist( new Customer( "2", "Acme Corp", "123" ) ); } ); - assertTrue( sessionFactory().getCache().contains( Employee.class, "1" ) ); - assertTrue( sessionFactory().getCache().contains( Person.class, "1" ) ); + assertTrue( scope.getSessionFactory().getCache().contains( Employee.class, "1" ) ); + assertTrue( scope.getSessionFactory().getCache().contains( Person.class, "1" ) ); - assertFalse( sessionFactory().getCache().contains( Customer.class, "2" ) ); - assertFalse( sessionFactory().getCache().contains( Person.class, "2" ) ); + assertFalse( scope.getSessionFactory().getCache().contains( Customer.class, "2" ) ); + assertFalse( scope.getSessionFactory().getCache().contains( Person.class, "2" ) ); - inTransaction( + scope.inTransaction( s -> { statistics.clear(); - final Customer customer = s.get( Customer.class, "2" ); + final Customer customer = s.find( Customer.class, "2" ); assertTrue( Hibernate.isInitialized( customer ) ); assertThat( statistics.getSecondLevelCacheHitCount(), CoreMatchers.is(0L) ); assertThat( statistics.getSecondLevelCachePutCount(), CoreMatchers.is(0L) ); statistics.clear(); - final Employee emp = s.get( Employee.class, "1" ); + final Employee emp = s.find( Employee.class, "1" ); assertTrue( Hibernate.isInitialized( emp ) ); assertThat( statistics.getSecondLevelCacheHitCount(), CoreMatchers.is(1L) ); assertThat( statistics.getSecondLevelCachePutCount(), CoreMatchers.is(0L) ); } ); - inTransaction( + scope.inTransaction( s -> { statistics.clear(); - final Person customer = s.get( Person.class, "2" ); + final Person customer = s.find( Person.class, "2" ); assertTrue( Hibernate.isInitialized( customer ) ); assertThat( statistics.getSecondLevelCacheHitCount(), CoreMatchers.is(0L) ); assertThat( statistics.getSecondLevelCachePutCount(), CoreMatchers.is(0L) ); statistics.clear(); - final Person emp = s.get( Person.class, "1" ); + final Person emp = s.find( Person.class, "1" ); assertTrue( Hibernate.isInitialized( emp ) ); assertThat( statistics.getSecondLevelCacheHitCount(), CoreMatchers.is(1L) ); assertThat( statistics.getSecondLevelCachePutCount(), CoreMatchers.is(0L) ); @@ -104,28 +118,9 @@ public void testOnlySubclassIsCached() { } - @After - public void cleanupData() { - inTransaction( - s -> s.createQuery( "delete from Person" ).executeUpdate() - ); - } - - @Override - protected void addSettings(Map settings) { - super.addSettings( settings ); - - settings.put( AvailableSettings.USE_SECOND_LEVEL_CACHE, "true" ); - settings.put( AvailableSettings.GENERATE_STATISTICS, "true" ); - settings.put( AvailableSettings.JPA_SHARED_CACHE_MODE, SharedCacheMode.ENABLE_SELECTIVE ); - } - - @Override - protected void applyMetadataSources(MetadataSources sources) { - super.applyMetadataSources( sources ); - sources.addAnnotatedClass( Person.class ); - sources.addAnnotatedClass( Employee.class ); - sources.addAnnotatedClass( Customer.class ); + @AfterEach + public void cleanupData(SessionFactoryScope scope) { + scope.dropData(); } @Entity( name = "Person" ) diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/compliance/tck2_2/caching/SubclassOnlyCachingTests.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/compliance/tck2_2/caching/SubclassOnlyCachingTests.java index f72f9fbcd136..a49dbbfa0f90 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/compliance/tck2_2/caching/SubclassOnlyCachingTests.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/compliance/tck2_2/caching/SubclassOnlyCachingTests.java @@ -4,64 +4,78 @@ */ package org.hibernate.orm.test.jpa.compliance.tck2_2.caching; -import java.util.Map; import jakarta.persistence.Cacheable; import jakarta.persistence.Entity; import jakarta.persistence.Id; import jakarta.persistence.Inheritance; import jakarta.persistence.InheritanceType; -import jakarta.persistence.SharedCacheMode; import jakarta.persistence.Table; import org.hibernate.Hibernate; -import org.hibernate.boot.MetadataSources; import org.hibernate.cfg.AvailableSettings; import org.hibernate.stat.spi.StatisticsImplementor; -import org.hibernate.testing.junit4.BaseNonConfigCoreFunctionalTestCase; -import org.junit.After; -import org.junit.Test; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.ServiceRegistry; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.hibernate.testing.orm.junit.Setting; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; import org.hamcrest.CoreMatchers; import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Steve Ebersole */ -public class SubclassOnlyCachingTests extends BaseNonConfigCoreFunctionalTestCase { +@DomainModel( + annotatedClasses = { + SubclassOnlyCachingTests.Person.class, + SubclassOnlyCachingTests.Employee.class, + SubclassOnlyCachingTests.Customer.class + } +) +@SessionFactory(generateStatistics = true) +@ServiceRegistry( settings = { + @Setting(name = AvailableSettings.USE_SECOND_LEVEL_CACHE, value = "true"), + @Setting(name = AvailableSettings.JPA_SHARED_CACHE_MODE, value = "ENABLE_SELECTIVE") +} +) +public class SubclassOnlyCachingTests { @Test - public void testMapping() { + public void testMapping(SessionFactoryScope scope) { assertThat( - sessionFactory().getMappingMetamodel().getEntityDescriptor( Person.class ).hasCache(), + scope.getSessionFactory().getMappingMetamodel().getEntityDescriptor( Person.class ).hasCache(), CoreMatchers.is( false ) ); assertThat( - sessionFactory().getMappingMetamodel().getEntityDescriptor( Employee.class ).hasCache(), + scope.getSessionFactory().getMappingMetamodel().getEntityDescriptor( Employee.class ).hasCache(), CoreMatchers.is( false ) ); assertThat( - sessionFactory().getMappingMetamodel().getEntityDescriptor( Customer.class ).hasCache(), + scope.getSessionFactory().getMappingMetamodel().getEntityDescriptor( Customer.class ).hasCache(), CoreMatchers.is( true ) ); } @Test - public void testOnlySubclassIsCached() { - final StatisticsImplementor statistics = sessionFactory().getStatistics(); + public void testOnlySubclassIsCached(SessionFactoryScope scope) { + final StatisticsImplementor statistics = scope.getSessionFactory().getStatistics(); - inTransaction( + scope.inTransaction( s -> s.persist( new Customer( 1, "Acme Corp", "123" ) ) ); - assertTrue( sessionFactory().getCache().contains( Customer.class, 1 ) ); + assertTrue( scope.getSessionFactory().getCache().contains( Customer.class, 1 ) ); - inTransaction( + scope.inTransaction( s -> { statistics.clear(); - final Customer customer = s.get( Customer.class, 1 ); + final Customer customer = s.find( Customer.class, 1 ); assertTrue( Hibernate.isInitialized( customer ) ); @@ -70,28 +84,9 @@ public void testOnlySubclassIsCached() { ); } - @After - public void cleanupData() { - inTransaction( - s -> s.createQuery( "delete from Person" ).executeUpdate() - ); - } - - @Override - protected void addSettings(Map settings) { - super.addSettings( settings ); - - settings.put( AvailableSettings.USE_SECOND_LEVEL_CACHE, "true" ); - settings.put( AvailableSettings.GENERATE_STATISTICS, "true" ); - settings.put( AvailableSettings.JPA_SHARED_CACHE_MODE, SharedCacheMode.ENABLE_SELECTIVE ); - } - - @Override - protected void applyMetadataSources(MetadataSources sources) { - super.applyMetadataSources( sources ); - sources.addAnnotatedClass( Person.class ); - sources.addAnnotatedClass( Employee.class ); - sources.addAnnotatedClass( Customer.class ); + @AfterEach + public void cleanupData(SessionFactoryScope scope) { + scope.dropData(); } @Entity( name = "Person" ) diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/compliance/tck2_2/joincolumn/JoinColumnTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/compliance/tck2_2/joincolumn/JoinColumnTest.java index 00f6985298c4..cabf61121886 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/compliance/tck2_2/joincolumn/JoinColumnTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/compliance/tck2_2/joincolumn/JoinColumnTest.java @@ -5,17 +5,16 @@ package org.hibernate.orm.test.jpa.compliance.tck2_2.joincolumn; import org.hibernate.boot.MetadataSources; -import org.hibernate.boot.registry.StandardServiceRegistry; -import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.AvailableSettings; import org.hibernate.dialect.H2Dialect; import org.hibernate.engine.spi.SessionFactoryImplementor; -import org.hibernate.testing.FailureExpected; -import org.hibernate.testing.RequiresDialect; -import org.hibernate.testing.junit4.BaseUnitTestCase; -import org.hibernate.testing.util.ServiceRegistryUtil; -import org.junit.Test; +import org.hibernate.testing.orm.junit.FailureExpected; +import org.hibernate.testing.orm.junit.RequiresDialect; +import org.hibernate.testing.orm.junit.ServiceRegistry; +import org.hibernate.testing.orm.junit.ServiceRegistryScope; +import org.hibernate.testing.orm.junit.Setting; +import org.junit.jupiter.api.Test; import static org.hibernate.testing.transaction.TransactionUtil2.inTransaction; @@ -24,41 +23,37 @@ */ @RequiresDialect(H2Dialect.class ) @FailureExpected( jiraKey = "tck-challenge" ) -public class JoinColumnTest extends BaseUnitTestCase { +@ServiceRegistry( settings = {@Setting(name = AvailableSettings.HBM2DDL_AUTO, value = "create-drop")} ) +public class JoinColumnTest { @Test - public void testIt() { - final StandardServiceRegistry ssr = ServiceRegistryUtil.serviceRegistryBuilder() - .applySetting( AvailableSettings.HBM2DDL_AUTO, "create-drop" ) - .build(); + public void testIt(ServiceRegistryScope scope) { - try { + try (SessionFactoryImplementor sf = (SessionFactoryImplementor) new MetadataSources( scope.getRegistry() ) + .addAnnotatedClass( Company.class ) + .addAnnotatedClass( Location.class ) + .buildMetadata() + .buildSessionFactory()) { + try { + inTransaction( + sf, + session -> { + final Company acme = new Company( 1, "Acme Corp" ); + new Location( 1, "86-215", acme ); + new Location( 2, "20-759", acme ); - try (SessionFactoryImplementor sf = (SessionFactoryImplementor) new MetadataSources( ssr ) - .addAnnotatedClass( Company.class ) - .addAnnotatedClass( Location.class ) - .buildMetadata() - .buildSessionFactory()) { - try { - inTransaction( - sf, - session -> { - final Company acme = new Company( 1, "Acme Corp" ); - new Location( 1, "86-215", acme ); - new Location( 2, "20-759", acme ); + session.persist( acme ); + } + ); - session.persist( acme ); - } - ); - - inTransaction( - sf, - session -> { - final Company acme = session.get( Company.class, 1 ); - assert acme.getLocations().size() == 2; + inTransaction( + sf, + session -> { + final Company acme = session.find( Company.class, 1 ); + assert acme.getLocations().size() == 2; - // this fails. however it is due to a number of bad assumptions - // in the TCK: + // this fails. however it is due to a number of bad assumptions + // in the TCK: // First the spec says: // @@ -89,26 +84,23 @@ public void testIt() { // so that deleting Company wont cause FK violations. But again this is made impossible // by the TCK because it defines the column as non-nullable (and not even in the @JoinColumn // btw which would be another basis for challenge). - session.remove( acme ); - for ( Location location : acme.getLocations() ) { - session.remove( location ); - } - } - ); - } - finally { - inTransaction( - sf, - session -> { - session.createQuery( "delete Location" ).executeUpdate(); - session.createQuery( "delete Company" ).executeUpdate(); + session.remove( acme ); + for ( Location location : acme.getLocations() ) { + session.remove( location ); } - ); - } + } + ); + } + finally { + inTransaction( + sf, + session -> { + session.createQuery( "delete Location" ).executeUpdate(); + session.createQuery( "delete Company" ).executeUpdate(); + } + ); } - } - finally { - StandardServiceRegistryBuilder.destroy( ssr ); } } + } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/compliance/tck2_2/mapkeycolumn/MapKeyColumnBiDiOneToManyFKTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/compliance/tck2_2/mapkeycolumn/MapKeyColumnBiDiOneToManyFKTest.java index 4fe305455bb6..76e99dedecd2 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/compliance/tck2_2/mapkeycolumn/MapKeyColumnBiDiOneToManyFKTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/compliance/tck2_2/mapkeycolumn/MapKeyColumnBiDiOneToManyFKTest.java @@ -15,24 +15,31 @@ import jakarta.persistence.OneToMany; import jakarta.persistence.Table; -import org.hibernate.boot.MetadataSources; - +import org.hibernate.testing.orm.junit.DomainModel; import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseNonConfigCoreFunctionalTestCase; -import org.junit.Test; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.junit.jupiter.api.Test; -import static junit.framework.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Steve Ebersole * @author Gail Badner */ -public class MapKeyColumnBiDiOneToManyFKTest extends BaseNonConfigCoreFunctionalTestCase { +@DomainModel(annotatedClasses = { + MapKeyColumnBiDiOneToManyFKTest.AddressCapable.class, + MapKeyColumnBiDiOneToManyFKTest.AddressCapable2.class, + MapKeyColumnBiDiOneToManyFKTest.Address.class, + MapKeyColumnBiDiOneToManyFKTest.Address2.class +}) +@SessionFactory +public class MapKeyColumnBiDiOneToManyFKTest { @Test @JiraKey( value = "HHH-12150" ) - public void testReferenceToAlreadyMappedColumn() { - inTransaction( + public void testReferenceToAlreadyMappedColumn(SessionFactoryScope scope) { + scope.inTransaction( session -> { AddressCapable2 holder = new AddressCapable2( 1, "osd"); Address2 address = new Address2( 1, "123 Main St" ); @@ -41,10 +48,10 @@ public void testReferenceToAlreadyMappedColumn() { session.persist( address ); } ); - inTransaction( + scope.inTransaction( session -> { - AddressCapable2 holder = session.get( AddressCapable2.class, 1 ); - Address2 address = session.get( Address2.class, 1 ); + AddressCapable2 holder = session.find( AddressCapable2.class, 1 ); + Address2 address = session.find( Address2.class, 1 ); address.holder = holder; address.type = "work"; @@ -53,9 +60,9 @@ public void testReferenceToAlreadyMappedColumn() { session.persist( holder ); } ); - inTransaction( + scope.inTransaction( session -> { - AddressCapable2 holder = session.get( AddressCapable2.class, 1 ); + AddressCapable2 holder = session.find( AddressCapable2.class, 1 ); assertEquals( 1, holder.addresses.size() ); final Map.Entry entry = holder.addresses.entrySet().iterator().next(); assertEquals( "work", entry.getKey() ); @@ -67,8 +74,8 @@ public void testReferenceToAlreadyMappedColumn() { @Test @JiraKey( value = "HHH-12150" ) - public void testReferenceToNonMappedColumn() { - inTransaction( + public void testReferenceToNonMappedColumn(SessionFactoryScope scope) { + scope.inTransaction( session -> { AddressCapable holder = new AddressCapable( 1, "osd"); Address address = new Address( 1, "123 Main St" ); @@ -77,10 +84,10 @@ public void testReferenceToNonMappedColumn() { session.persist( address ); } ); - inTransaction( + scope.inTransaction( session -> { - AddressCapable holder = session.get( AddressCapable.class, 1 ); - Address address = session.get( Address.class, 1 ); + AddressCapable holder = session.find( AddressCapable.class, 1 ); + Address address = session.find( Address.class, 1 ); address.holder = holder; holder.addresses.put( "work", address ); @@ -88,9 +95,9 @@ public void testReferenceToNonMappedColumn() { session.persist( holder ); } ); - inTransaction( + scope.inTransaction( session -> { - AddressCapable holder = session.get( AddressCapable.class, 1 ); + AddressCapable holder = session.find( AddressCapable.class, 1 ); assertEquals( 1, holder.addresses.size() ); final Map.Entry entry = holder.addresses.entrySet().iterator().next(); assertEquals( "work", entry.getKey() ); @@ -99,16 +106,6 @@ public void testReferenceToNonMappedColumn() { ); } - @Override - protected void applyMetadataSources(MetadataSources sources) { - super.applyMetadataSources( sources ); - - sources.addAnnotatedClass( AddressCapable.class ); - sources.addAnnotatedClass( AddressCapable2.class ); - sources.addAnnotatedClass( Address.class ); - sources.addAnnotatedClass( Address2.class ); - } - @Entity( name = "AddressCapable" ) @Table( name = "address_capables" ) public static class AddressCapable { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/compliance/tck2_2/mapkeycolumn/MapKeyColumnElementCollectionTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/compliance/tck2_2/mapkeycolumn/MapKeyColumnElementCollectionTest.java index 33a1de6facaf..25e8349ecd23 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/compliance/tck2_2/mapkeycolumn/MapKeyColumnElementCollectionTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/compliance/tck2_2/mapkeycolumn/MapKeyColumnElementCollectionTest.java @@ -14,32 +14,38 @@ import jakarta.persistence.MapKeyColumn; import jakarta.persistence.Table; -import org.hibernate.boot.MetadataSources; - +import org.hibernate.testing.orm.junit.DomainModel; import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseNonConfigCoreFunctionalTestCase; -import org.junit.Test; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; -import static junit.framework.Assert.assertEquals; /** * @author Steve Ebersole */ -public class MapKeyColumnElementCollectionTest extends BaseNonConfigCoreFunctionalTestCase { +@DomainModel(annotatedClasses = { + MapKeyColumnElementCollectionTest.AddressCapable.class, + MapKeyColumnElementCollectionTest.AddressCapable2.class +}) +@SessionFactory +public class MapKeyColumnElementCollectionTest { @Test @JiraKey( value = "HHH-12150" ) - public void testReferenceToAlreadyMappedColumn() { - inTransaction( + public void testReferenceToAlreadyMappedColumn(SessionFactoryScope scope) { + scope.inTransaction( session -> { AddressCapable2 holder = new AddressCapable2( 1, "osd"); session.persist( holder ); } ); - inTransaction( + scope.inTransaction( session -> { - AddressCapable2 holder = session.get( AddressCapable2.class, 1 ); + AddressCapable2 holder = session.find( AddressCapable2.class, 1 ); Address2 address = new Address2( 1, "123 Main St" ); address.type = "work"; @@ -48,9 +54,9 @@ public void testReferenceToAlreadyMappedColumn() { session.persist( holder ); } ); - inTransaction( + scope.inTransaction( session -> { - AddressCapable2 holder = session.get( AddressCapable2.class, 1 ); + AddressCapable2 holder = session.find( AddressCapable2.class, 1 ); assertEquals( 1, holder.addresses.size() ); final Map.Entry entry = holder.addresses.entrySet().iterator().next(); assertEquals( "work", entry.getKey() ); @@ -62,26 +68,26 @@ public void testReferenceToAlreadyMappedColumn() { @Test @JiraKey( value = "HHH-12150" ) - public void testReferenceToNonMappedColumn() { - inTransaction( + public void testReferenceToNonMappedColumn(SessionFactoryScope scope) { + scope.inTransaction( session -> { AddressCapable holder = new AddressCapable( 1, "osd"); session.persist( holder ); } ); - inTransaction( + scope.inTransaction( session -> { - AddressCapable holder = session.get( AddressCapable.class, 1 ); + AddressCapable holder = session.find( AddressCapable.class, 1 ); holder.addresses.put( "work", new Address( 1, "123 Main St" ) ); session.persist( holder ); } ); - inTransaction( + scope.inTransaction( session -> { - AddressCapable holder = session.get( AddressCapable.class, 1 ); + AddressCapable holder = session.find( AddressCapable.class, 1 ); assertEquals( 1, holder.addresses.size() ); final Map.Entry entry = holder.addresses.entrySet().iterator().next(); assertEquals( "work", entry.getKey() ); @@ -90,14 +96,6 @@ public void testReferenceToNonMappedColumn() { ); } - @Override - protected void applyMetadataSources(MetadataSources sources) { - super.applyMetadataSources( sources ); - - sources.addAnnotatedClass( AddressCapable.class ); - sources.addAnnotatedClass( AddressCapable2.class ); - } - @Entity( name = "AddressCapable" ) @Table( name = "address_capables" ) public static class AddressCapable { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/compliance/tck2_2/mapkeycolumn/MapKeyColumnManyToManyTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/compliance/tck2_2/mapkeycolumn/MapKeyColumnManyToManyTest.java index f1e74e92f44c..1c3bf13c889d 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/compliance/tck2_2/mapkeycolumn/MapKeyColumnManyToManyTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/compliance/tck2_2/mapkeycolumn/MapKeyColumnManyToManyTest.java @@ -14,23 +14,32 @@ import jakarta.persistence.MapKeyColumn; import jakarta.persistence.Table; -import org.hibernate.boot.MetadataSources; - +import org.hibernate.testing.orm.junit.DomainModel; import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseNonConfigCoreFunctionalTestCase; -import org.junit.Test; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; -import static junit.framework.Assert.assertEquals; /** * @author Steve Ebersole */ -public class MapKeyColumnManyToManyTest extends BaseNonConfigCoreFunctionalTestCase { +@DomainModel(annotatedClasses = { + MapKeyColumnManyToManyTest.AddressCapable.class, + MapKeyColumnManyToManyTest.AddressCapable2.class, + MapKeyColumnManyToManyTest.Address.class, + MapKeyColumnManyToManyTest.Address2.class +}) +@SessionFactory +public class MapKeyColumnManyToManyTest { @Test @JiraKey( value = "HHH-12150" ) - public void testReferenceToAlreadyMappedColumn() { - inTransaction( + public void testReferenceToAlreadyMappedColumn(SessionFactoryScope scope) { + scope.inTransaction( session -> { AddressCapable2 holder = new AddressCapable2( 1, "osd"); Address2 address = new Address2( 1, "123 Main St" ); @@ -39,23 +48,23 @@ public void testReferenceToAlreadyMappedColumn() { session.persist( address ); } ); - inTransaction( + scope.inTransaction( session -> { - AddressCapable2 holder = session.get( AddressCapable2.class, 1 ); - Address2 address = session.get( Address2.class, 1 ); + AddressCapable2 holder = session.find( AddressCapable2.class, 1 ); + Address2 address = session.find( Address2.class, 1 ); holder.addresses.put( "work", address ); session.persist( holder ); } ); - inTransaction( + scope.inTransaction( session -> { - AddressCapable2 holder = session.get( AddressCapable2.class, 1 ); + AddressCapable2 holder = session.find( AddressCapable2.class, 1 ); assertEquals( 1, holder.addresses.size() ); final Map.Entry entry = holder.addresses.entrySet().iterator().next(); assertEquals( "work", entry.getKey() ); - assertEquals( null, entry.getValue().type ); + assertNull( entry.getValue().type ); session.remove( holder ); } ); @@ -63,8 +72,8 @@ public void testReferenceToAlreadyMappedColumn() { @Test @JiraKey( value = "HHH-12150" ) - public void testReferenceToNonMappedColumn() { - inTransaction( + public void testReferenceToNonMappedColumn(SessionFactoryScope scope) { + scope.inTransaction( session -> { AddressCapable holder = new AddressCapable( 1, "osd"); Address address = new Address( 1, "123 Main St" ); @@ -73,19 +82,19 @@ public void testReferenceToNonMappedColumn() { session.persist( address ); } ); - inTransaction( + scope.inTransaction( session -> { - AddressCapable holder = session.get( AddressCapable.class, 1 ); - Address address = session.get( Address.class, 1 ); + AddressCapable holder = session.find( AddressCapable.class, 1 ); + Address address = session.find( Address.class, 1 ); holder.addresses.put( "work", address ); session.persist( holder ); } ); - inTransaction( + scope.inTransaction( session -> { - AddressCapable holder = session.get( AddressCapable.class, 1 ); + AddressCapable holder = session.find( AddressCapable.class, 1 ); assertEquals( 1, holder.addresses.size() ); final Map.Entry entry = holder.addresses.entrySet().iterator().next(); assertEquals( "work", entry.getKey() ); @@ -94,16 +103,6 @@ public void testReferenceToNonMappedColumn() { ); } - @Override - protected void applyMetadataSources(MetadataSources sources) { - super.applyMetadataSources( sources ); - - sources.addAnnotatedClass( AddressCapable.class ); - sources.addAnnotatedClass( AddressCapable2.class ); - sources.addAnnotatedClass( Address.class ); - sources.addAnnotatedClass( Address2.class ); - } - @Entity( name = "AddressCapable" ) @Table( name = "address_capables" ) public static class AddressCapable { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/compliance/tck2_2/mapkeycolumn/MapKeyColumnOneToManyFKTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/compliance/tck2_2/mapkeycolumn/MapKeyColumnOneToManyFKTest.java index 1566b185adab..7515b6524e57 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/compliance/tck2_2/mapkeycolumn/MapKeyColumnOneToManyFKTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/compliance/tck2_2/mapkeycolumn/MapKeyColumnOneToManyFKTest.java @@ -15,23 +15,30 @@ import jakarta.persistence.OneToMany; import jakarta.persistence.Table; -import org.hibernate.boot.MetadataSources; - +import org.hibernate.testing.orm.junit.DomainModel; import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseNonConfigCoreFunctionalTestCase; -import org.junit.Test; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.junit.jupiter.api.Test; -import static junit.framework.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Steve Ebersole */ -public class MapKeyColumnOneToManyFKTest extends BaseNonConfigCoreFunctionalTestCase { +@DomainModel(annotatedClasses = { + MapKeyColumnOneToManyFKTest.AddressCapable.class, + MapKeyColumnOneToManyFKTest.AddressCapable2.class, + MapKeyColumnOneToManyFKTest.Address.class, + MapKeyColumnOneToManyFKTest.Address2.class +}) +@SessionFactory +public class MapKeyColumnOneToManyFKTest { @Test @JiraKey( value = "HHH-12150" ) - public void testReferenceToAlreadyMappedColumn() { - inTransaction( + public void testReferenceToAlreadyMappedColumn(SessionFactoryScope scope) { + scope.inTransaction( session -> { AddressCapable2 holder = new AddressCapable2( 1, "osd"); Address2 address = new Address2( 1, "123 Main St" ); @@ -40,19 +47,19 @@ public void testReferenceToAlreadyMappedColumn() { session.persist( address ); } ); - inTransaction( + scope.inTransaction( session -> { - AddressCapable2 holder = session.get( AddressCapable2.class, 1 ); - Address2 address = session.get( Address2.class, 1 ); + AddressCapable2 holder = session.find( AddressCapable2.class, 1 ); + Address2 address = session.find( Address2.class, 1 ); holder.addresses.put( "work", address ); session.persist( holder ); } ); - inTransaction( + scope.inTransaction( session -> { - AddressCapable2 holder = session.get( AddressCapable2.class, 1 ); + AddressCapable2 holder = session.find( AddressCapable2.class, 1 ); assertEquals( 1, holder.addresses.size() ); final Map.Entry entry = holder.addresses.entrySet().iterator().next(); assertEquals( "work", entry.getKey() ); @@ -64,8 +71,8 @@ public void testReferenceToAlreadyMappedColumn() { @Test @JiraKey( value = "HHH-12150" ) - public void testReferenceToNonMappedColumn() { - inTransaction( + public void testReferenceToNonMappedColumn(SessionFactoryScope scope) { + scope.inTransaction( session -> { AddressCapable holder = new AddressCapable( 1, "osd"); Address address = new Address( 1, "123 Main St" ); @@ -74,19 +81,19 @@ public void testReferenceToNonMappedColumn() { session.persist( address ); } ); - inTransaction( + scope.inTransaction( session -> { - AddressCapable holder = session.get( AddressCapable.class, 1 ); - Address address = session.get( Address.class, 1 ); + AddressCapable holder = session.find( AddressCapable.class, 1 ); + Address address = session.find( Address.class, 1 ); holder.addresses.put( "work", address ); session.persist( holder ); } ); - inTransaction( + scope.inTransaction( session -> { - AddressCapable holder = session.get( AddressCapable.class, 1 ); + AddressCapable holder = session.find( AddressCapable.class, 1 ); assertEquals( 1, holder.addresses.size() ); final Map.Entry entry = holder.addresses.entrySet().iterator().next(); assertEquals( "work", entry.getKey() ); @@ -95,16 +102,6 @@ public void testReferenceToNonMappedColumn() { ); } - @Override - protected void applyMetadataSources(MetadataSources sources) { - super.applyMetadataSources( sources ); - - sources.addAnnotatedClass( AddressCapable.class ); - sources.addAnnotatedClass( AddressCapable2.class ); - sources.addAnnotatedClass( Address.class ); - sources.addAnnotatedClass( Address2.class ); - } - @Entity( name = "AddressCapable" ) @Table( name = "address_capables" ) public static class AddressCapable { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/compliance/tck2_2/mapkeycolumn/MapKeyColumnOneToManyJoinTableTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/compliance/tck2_2/mapkeycolumn/MapKeyColumnOneToManyJoinTableTest.java index 8fe313257ac1..f992da669509 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/compliance/tck2_2/mapkeycolumn/MapKeyColumnOneToManyJoinTableTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/compliance/tck2_2/mapkeycolumn/MapKeyColumnOneToManyJoinTableTest.java @@ -14,23 +14,32 @@ import jakarta.persistence.OneToMany; import jakarta.persistence.Table; -import org.hibernate.boot.MetadataSources; - +import org.hibernate.testing.orm.junit.DomainModel; import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseNonConfigCoreFunctionalTestCase; -import org.junit.Test; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; -import static junit.framework.Assert.assertEquals; /** * @author Steve Ebersole */ -public class MapKeyColumnOneToManyJoinTableTest extends BaseNonConfigCoreFunctionalTestCase { +@DomainModel(annotatedClasses = { + MapKeyColumnOneToManyJoinTableTest.AddressCapable.class, + MapKeyColumnOneToManyJoinTableTest.AddressCapable2.class, + MapKeyColumnOneToManyJoinTableTest.Address.class, + MapKeyColumnOneToManyJoinTableTest.Address2.class +}) +@SessionFactory +public class MapKeyColumnOneToManyJoinTableTest { @Test @JiraKey( value = "HHH-12150" ) - public void testReferenceToAlreadyMappedColumn() { - inTransaction( + public void testReferenceToAlreadyMappedColumn(SessionFactoryScope scope) { + scope.inTransaction( session -> { AddressCapable2 holder = new AddressCapable2( 1, "osd"); Address2 address = new Address2( 1, "123 Main St" ); @@ -39,23 +48,23 @@ public void testReferenceToAlreadyMappedColumn() { session.persist( address ); } ); - inTransaction( + scope.inTransaction( session -> { - AddressCapable2 holder = session.get( AddressCapable2.class, 1 ); - Address2 address = session.get( Address2.class, 1 ); + AddressCapable2 holder = session.find( AddressCapable2.class, 1 ); + Address2 address = session.find( Address2.class, 1 ); holder.addresses.put( "work", address ); session.persist( holder ); } ); - inTransaction( + scope.inTransaction( session -> { - AddressCapable2 holder = session.get( AddressCapable2.class, 1 ); + AddressCapable2 holder = session.find( AddressCapable2.class, 1 ); assertEquals( 1, holder.addresses.size() ); final Map.Entry entry = holder.addresses.entrySet().iterator().next(); assertEquals( "work", entry.getKey() ); - assertEquals( null, entry.getValue().type ); + assertNull( entry.getValue().type ); session.remove( holder ); } ); @@ -63,8 +72,8 @@ public void testReferenceToAlreadyMappedColumn() { @Test @JiraKey( value = "HHH-12150" ) - public void testReferenceToNonMappedColumn() { - inTransaction( + public void testReferenceToNonMappedColumn(SessionFactoryScope scope) { + scope.inTransaction( session -> { AddressCapable holder = new AddressCapable( 1, "osd"); Address address = new Address( 1, "123 Main St" ); @@ -73,19 +82,19 @@ public void testReferenceToNonMappedColumn() { session.persist( address ); } ); - inTransaction( + scope.inTransaction( session -> { - AddressCapable holder = session.get( AddressCapable.class, 1 ); - Address address = session.get( Address.class, 1 ); + AddressCapable holder = session.find( AddressCapable.class, 1 ); + Address address = session.find( Address.class, 1 ); holder.addresses.put( "work", address ); session.persist( holder ); } ); - inTransaction( + scope.inTransaction( session -> { - AddressCapable holder = session.get( AddressCapable.class, 1 ); + AddressCapable holder = session.find( AddressCapable.class, 1 ); assertEquals( 1, holder.addresses.size() ); final Map.Entry entry = holder.addresses.entrySet().iterator().next(); assertEquals( "work", entry.getKey() ); @@ -94,16 +103,6 @@ public void testReferenceToNonMappedColumn() { ); } - @Override - protected void applyMetadataSources(MetadataSources sources) { - super.applyMetadataSources( sources ); - - sources.addAnnotatedClass( AddressCapable.class ); - sources.addAnnotatedClass( AddressCapable2.class ); - sources.addAnnotatedClass( Address.class ); - sources.addAnnotatedClass( Address2.class ); - } - @Entity( name = "AddressCapable" ) @Table( name = "address_capables" ) public static class AddressCapable { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/graphs/CacheableEntityGraphTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/graphs/CacheableEntityGraphTest.java index 4ec896fa446d..923b1d5619e5 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/graphs/CacheableEntityGraphTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/graphs/CacheableEntityGraphTest.java @@ -11,7 +11,6 @@ import jakarta.persistence.ElementCollection; import jakarta.persistence.Entity; import jakarta.persistence.EntityGraph; -import jakarta.persistence.EntityManager; import jakarta.persistence.EnumType; import jakarta.persistence.Enumerated; import jakarta.persistence.FetchType; @@ -23,43 +22,38 @@ import org.hibernate.annotations.Cache; import org.hibernate.annotations.CacheConcurrencyStrategy; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; import org.hibernate.testing.orm.junit.JiraKey; -import org.junit.Test; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.Test; -public class CacheableEntityGraphTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { Product.class, Color.class, Tag.class }; - } +@Jpa(annotatedClasses = {CacheableEntityGraphTest.Product.class, CacheableEntityGraphTest.Color.class, CacheableEntityGraphTest.Tag.class}) +public class CacheableEntityGraphTest { @Test @JiraKey(value = "HHH-15964") - public void test() { - EntityManager em = getOrCreateEntityManager(); - - em.getTransaction().begin(); - Tag tag = new Tag( Set.of( TagType.FOO ) ); - em.persist( tag ); - - Color color = new Color(); - em.persist( color ); - - Product product = new Product( tag, color ); - em.persist( product ); - em.getTransaction().commit(); - - em.clear(); - - EntityGraph entityGraph = em.createEntityGraph( Product.class ); - entityGraph.addAttributeNodes( "tag" ); - - em.createQuery( "select p from Product p", Product.class ) - .setMaxResults( 2 ) - .setHint( "jakarta.persistence.loadgraph", entityGraph ) - .getSingleResult(); + public void test(EntityManagerFactoryScope scope) { + scope.inEntityManager( entityManager -> { + entityManager.getTransaction().begin(); + Tag tag = new Tag( Set.of( TagType.FOO ) ); + entityManager.persist( tag ); + + Color color = new Color(); + entityManager.persist( color ); + + Product product = new Product( tag, color ); + entityManager.persist( product ); + entityManager.getTransaction().commit(); + + EntityGraph entityGraph = entityManager.createEntityGraph( Product.class ); + entityGraph.addAttributeNodes( "tag" ); + + entityManager.createQuery( "select p from Product p", Product.class ) + .setMaxResults( 2 ) + .setHint( "jakarta.persistence.loadgraph", entityGraph ) + .getSingleResult(); + } ); } @Entity(name = "Product") diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/graphs/EntityGraphAttributeResolutionTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/graphs/EntityGraphAttributeResolutionTest.java index 5f1873f2e6f1..f9c8f49886aa 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/graphs/EntityGraphAttributeResolutionTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/graphs/EntityGraphAttributeResolutionTest.java @@ -25,15 +25,14 @@ import jakarta.persistence.Table; import org.hibernate.graph.GraphSemantic; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; import org.hibernate.testing.orm.junit.JiraKey; -import org.junit.Before; -import org.junit.Test; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; - /** * @author Benjamin M. @@ -41,40 +40,36 @@ */ @JiraKey( value = "HHH-14113" ) @SuppressWarnings({ "unchecked", "rawtypes" }) -public class EntityGraphAttributeResolutionTest extends BaseEntityManagerFunctionalTestCase { +@Jpa(annotatedClasses = {EntityGraphAttributeResolutionTest.User.class, EntityGraphAttributeResolutionTest.Group.class}) +public class EntityGraphAttributeResolutionTest { private User u; private Group g1, g2; - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { User.class, Group.class }; - } - - @Before - public void setUp() { - doInJPA( this::entityManagerFactory, em -> { + @BeforeEach + public void setUp(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { g1 = new Group(); g1.addPermission( Permission.BAR ); - em.persist( g1 ); + entityManager.persist( g1 ); g2 = new Group(); g2.addPermission( Permission.BAZ ); - em.persist( g2 ); + entityManager.persist( g2 ); u = new User(); - em.persist( u ); + entityManager.persist( u ); u.addGroup( g1 ); u.addGroup( g2 ); } ); } @Test - public void fetchAssocWithNamedFetchGraph() { - doInJPA( this::entityManagerFactory, em -> { - List result = em.createQuery( "SELECT u.groups FROM User u WHERE u.id = ?1" ) + public void fetchAssocWithNamedFetchGraph(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { + List result = entityManager.createQuery( "SELECT u.groups FROM User u WHERE u.id = ?1" ) .setParameter(1, u.getId() ) - .setHint( GraphSemantic.FETCH.getJpaHintName(), em.getEntityGraph( Group.ENTITY_GRAPH ) ) + .setHint( GraphSemantic.FETCH.getJpaHintName(), entityManager.getEntityGraph( Group.ENTITY_GRAPH ) ) .getResultList(); assertThat( result ).containsExactlyInAnyOrder( g1, g2 ); @@ -82,11 +77,11 @@ public void fetchAssocWithNamedFetchGraph() { } @Test - public void fetchAssocWithNamedFetchGraphAndJoin() { - doInJPA( this::entityManagerFactory, em -> { - List result = em.createQuery( "SELECT g FROM User u JOIN u.groups g WHERE u.id = ?1" ) + public void fetchAssocWithNamedFetchGraphAndJoin(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { + List result = entityManager.createQuery( "SELECT g FROM User u JOIN u.groups g WHERE u.id = ?1" ) .setParameter( 1, u.getId() ) - .setHint( GraphSemantic.FETCH.getJpaHintName(), em.getEntityGraph( Group.ENTITY_GRAPH ) ) + .setHint( GraphSemantic.FETCH.getJpaHintName(), entityManager.getEntityGraph( Group.ENTITY_GRAPH ) ) .getResultList(); assertThat( result ).containsExactlyInAnyOrder( g1, g2 ); @@ -94,12 +89,12 @@ public void fetchAssocWithNamedFetchGraphAndJoin() { } @Test - public void fetchAssocWithAdhocFetchGraph() { - doInJPA( this::entityManagerFactory, em -> { - EntityGraph eg = em.createEntityGraph( Group.class ); + public void fetchAssocWithAdhocFetchGraph(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { + EntityGraph eg = entityManager.createEntityGraph( Group.class ); eg.addAttributeNodes( "permissions" ); - List result = em.createQuery( "SELECT u.groups FROM User u WHERE u.id = ?1" ) + List result = entityManager.createQuery( "SELECT u.groups FROM User u WHERE u.id = ?1" ) .setParameter(1, u.getId() ) .setHint( GraphSemantic.FETCH.getJpaHintName(), eg ) .getResultList(); 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 77d4bae2e456..24293ce213ba 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 @@ -19,7 +19,6 @@ import jakarta.persistence.DiscriminatorValue; import jakarta.persistence.Entity; import jakarta.persistence.EntityGraph; -import jakarta.persistence.EntityManager; import jakarta.persistence.FetchType; import jakarta.persistence.GeneratedValue; import jakarta.persistence.Id; @@ -38,144 +37,142 @@ import jakarta.persistence.metamodel.Attribute; import jakarta.persistence.metamodel.PluralAttribute; import org.hibernate.Hibernate; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; import org.hibernate.testing.util.uuid.SafeRandomUUIDGenerator; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; import org.hibernate.testing.orm.junit.JiraKey; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Christian Bauer * @author Brett Meyer */ -public class EntityGraphTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Foo.class, Bar.class, Baz.class, Author.class, Book.class, Prize.class, Company.class, - Employee.class, Manager.class, Location.class, AnimalOwner.class, Animal.class, Dog.class, Cat.class, - Kennel.class - }; - } +@Jpa(annotatedClasses = { + EntityGraphTest.Foo.class, EntityGraphTest.Bar.class, EntityGraphTest.Baz.class, EntityGraphTest.Author.class, + EntityGraphTest.Book.class, EntityGraphTest.Prize.class, Company.class, Employee.class, Manager.class, + Location.class, EntityGraphTest.AnimalOwner.class, EntityGraphTest.Animal.class, EntityGraphTest.Dog.class, + EntityGraphTest.Cat.class, EntityGraphTest.Kennel.class +}) +public class EntityGraphTest { @Test @JiraKey(value = "HHH-8857") - public void loadMultipleAssociations() { - EntityManager em = getOrCreateEntityManager(); - em.getTransaction().begin(); + public void loadMultipleAssociations(EntityManagerFactoryScope scope) { + scope.inEntityManager( em -> { + em.getTransaction().begin(); - Bar bar = new Bar(); - em.persist( bar ); + Bar bar = new Bar(); + em.persist( bar ); - Baz baz = new Baz(); - em.persist( baz ); + Baz baz = new Baz(); + em.persist( baz ); - Foo foo = new Foo(); - foo.bar = bar; - foo.baz = baz; - em.persist( foo ); + Foo foo = new Foo(); + foo.bar = bar; + foo.baz = baz; + 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", "baz" ); + EntityGraph fooGraph = em.createEntityGraph( Foo.class ); + fooGraph.addAttributeNodes( "bar", "baz" ); - 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.baz ) ); + assertTrue( Hibernate.isInitialized( result ) ); + assertTrue( Hibernate.isInitialized( result.bar ) ); + assertTrue( Hibernate.isInitialized( result.baz ) ); - em.getTransaction().commit(); - em.close(); + em.getTransaction().commit(); + } ); } @Test - public void loadCollection() { - EntityManager em = getOrCreateEntityManager(); - em.getTransaction().begin(); + public void loadCollection(EntityManagerFactoryScope scope) { + scope.inEntityManager( em -> { + 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(); + } ); } @Test - public void loadInverseCollection() { - EntityManager em = getOrCreateEntityManager(); - em.getTransaction().begin(); - - 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 ); - - em.getTransaction().commit(); - em.clear(); - - 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"); - - Map properties = new HashMap(); - properties.put( "javax.persistence.loadgraph", fooGraph ); - - 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 bidirectional fetch was the one identified by the graph - assertFalse( Hibernate.isInitialized( result.baz.getFoos()) ); - - em.getTransaction().commit(); - em.close(); + public void loadInverseCollection(EntityManagerFactoryScope scope) { + scope.inEntityManager( em -> { + em.getTransaction().begin(); + + 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 ); + + em.getTransaction().commit(); + em.clear(); + + 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" ); + + Map properties = new HashMap<>(); + properties.put( "javax.persistence.loadgraph", fooGraph ); + + 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 bidirectional fetch was the one identified by the graph + assertFalse( Hibernate.isInitialized( result.baz.getFoos() ) ); + + em.getTransaction().commit(); + } ); } /** @@ -185,462 +182,461 @@ public void loadInverseCollection() { */ @Test @JiraKey(value = "HHH-8640") - public void inheritanceTest() { - EntityManager em = getOrCreateEntityManager(); - em.getTransaction().begin(); - - Manager manager = new Manager(); - em.persist( manager ); - Employee employee = new Employee(); - employee.friends.add( manager ); - employee.managers.add( manager ); - em.persist( employee ); - Company company = new Company(); - company.employees.add( employee ); - company.employees.add( manager ); - em.persist( company ); - - em.getTransaction().commit(); - em.clear(); - - em.getTransaction().begin(); - - EntityGraph entityGraph = em.createEntityGraph( Company.class ); - Subgraph subgraph = entityGraph.addSubgraph( "employees" ); - subgraph.addAttributeNodes( "managers" ); - subgraph.addAttributeNodes( "friends" ); - Subgraph subSubgraph = subgraph.addSubgraph( "managers", Manager.class ); - subSubgraph.addAttributeNodes( "managers" ); - subSubgraph.addAttributeNodes( "friends" ); - - Map properties = new HashMap(); - properties.put( "javax.persistence.loadgraph", entityGraph ); - - Company result = em.find( Company.class, company.id, properties ); - - assertTrue( Hibernate.isInitialized( result ) ); - assertTrue( Hibernate.isInitialized( result.employees ) ); - assertEquals( 2, result.employees.size() ); - for (Employee resultEmployee : result.employees) { - assertTrue( Hibernate.isInitialized( resultEmployee.managers ) ); - assertTrue( Hibernate.isInitialized( resultEmployee.friends ) ); - } + public void inheritanceTest(EntityManagerFactoryScope scope) { + scope.inEntityManager( em -> { + em.getTransaction().begin(); + + Manager manager = new Manager(); + em.persist( manager ); + Employee employee = new Employee(); + employee.friends.add( manager ); + employee.managers.add( manager ); + em.persist( employee ); + Company company = new Company(); + company.employees.add( employee ); + company.employees.add( manager ); + em.persist( company ); + + em.getTransaction().commit(); + em.clear(); + + em.getTransaction().begin(); + + EntityGraph entityGraph = em.createEntityGraph( Company.class ); + Subgraph subgraph = entityGraph.addSubgraph( "employees" ); + subgraph.addAttributeNodes( "managers" ); + subgraph.addAttributeNodes( "friends" ); + Subgraph subSubgraph = subgraph.addSubgraph( "managers", Manager.class ); + subSubgraph.addAttributeNodes( "managers" ); + subSubgraph.addAttributeNodes( "friends" ); + + Map properties = new HashMap<>(); + properties.put( "javax.persistence.loadgraph", entityGraph ); + + Company result = em.find( Company.class, company.id, properties ); + + assertTrue( Hibernate.isInitialized( result ) ); + assertTrue( Hibernate.isInitialized( result.employees ) ); + assertEquals( 2, result.employees.size() ); + for ( Employee resultEmployee : result.employees ) { + assertTrue( Hibernate.isInitialized( resultEmployee.managers ) ); + assertTrue( Hibernate.isInitialized( resultEmployee.friends ) ); + } - em.getTransaction().commit(); - em.close(); + em.getTransaction().commit(); + } ); } @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(); - - em.getTransaction().begin(); - - EntityGraph entityGraph = em.createEntityGraph( Manager.class ); - entityGraph.addAttributeNodes( "friends" ); - entityGraph.addAttributeNodes( "managers" ); - - Map properties = new HashMap(); - properties.put( "javax.persistence.loadgraph", entityGraph ); - - Manager result = em.find( Manager.class, manager.id, properties ); - - assertTrue( Hibernate.isInitialized( result ) ); - assertTrue( Hibernate.isInitialized( result.friends ) ); - assertEquals( 1, result.friends.size() ); - assertTrue( Hibernate.isInitialized( result.managers) ); - assertEquals( 1, result.managers.size() ); - - em.getTransaction().commit(); - em.close(); + public void attributeNodeInheritanceTest(EntityManagerFactoryScope scope) { + scope.inEntityManager( em -> { + 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(); + + em.getTransaction().begin(); + + EntityGraph entityGraph = em.createEntityGraph( Manager.class ); + entityGraph.addAttributeNodes( "friends" ); + entityGraph.addAttributeNodes( "managers" ); + + Map properties = new HashMap<>(); + properties.put( "javax.persistence.loadgraph", entityGraph ); + + Manager result = em.find( Manager.class, manager.id, properties ); + + assertTrue( Hibernate.isInitialized( result ) ); + assertTrue( Hibernate.isInitialized( result.friends ) ); + assertEquals( 1, result.friends.size() ); + assertTrue( Hibernate.isInitialized( result.managers ) ); + assertEquals( 1, result.managers.size() ); + + em.getTransaction().commit(); + } ); } @Test @JiraKey(value = "HHH-9735") - public void loadIsMemberQueriedCollection() { - - EntityManager em = getOrCreateEntityManager(); - em.getTransaction().begin(); + public void loadIsMemberQueriedCollection(EntityManagerFactoryScope scope) { + scope.inEntityManager( em -> { + 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(); + } ); } @Test @JiraKey(value = "HHH-15859") - public void mapAttributeTest() { - EntityManager em = getOrCreateEntityManager(); - em.getTransaction().begin(); + public void mapAttributeTest(EntityManagerFactoryScope scope) { + scope.inEntityManager( em -> { + em.getTransaction().begin(); - Author author = new Author(); - em.persist(author); + Author author = new Author(); + em.persist( author ); - Book book = new Book(); - author.books.put(1, book); - em.persist(author); - em.persist(book); + Book book = new Book(); + author.books.put( 1, book ); + em.persist( author ); + em.persist( book ); - em.getTransaction().commit(); - em.clear(); + em.getTransaction().commit(); + em.clear(); - em.getTransaction().begin(); - EntityGraph entityGraph = em.createEntityGraph(Author.class); - entityGraph.addAttributeNodes("books"); - Map properties = new HashMap<>(); - properties.put("javax.persistence.loadgraph", entityGraph); + em.getTransaction().begin(); + EntityGraph entityGraph = em.createEntityGraph( Author.class ); + entityGraph.addAttributeNodes( "books" ); + Map properties = new HashMap<>(); + properties.put( "javax.persistence.loadgraph", entityGraph ); - Author result = em.find(Author.class, author.id, properties); - assertTrue(Hibernate.isInitialized(result)); - assertTrue(Hibernate.isInitialized(result.books)); + Author result = em.find( Author.class, author.id, properties ); + assertTrue( Hibernate.isInitialized( result ) ); + assertTrue( Hibernate.isInitialized( result.books ) ); - em.getTransaction().commit(); - em.close(); + em.getTransaction().commit(); + } ); } @Test @JiraKey(value = "HHH-15964") - public void paginationOverCollectionFetch() { - EntityManager em = getOrCreateEntityManager(); - em.getTransaction().begin(); - - String authorName = SafeRandomUUIDGenerator.safeRandomUUIDAsString(); - Set authorIds = IntStream.range(0, 3) - .mapToObj(v -> { - Author author = new Author(authorName); - em.persist(author); - em.persist(new Book(author)); - em.persist(new Book(author)); - return author; - }) - .map(author -> author.id) - .collect(Collectors.toSet()); - - em.getTransaction().commit(); - em.clear(); - - em.getTransaction().begin(); - EntityGraph entityGraph = em.createEntityGraph(Author.class); - entityGraph.addAttributeNodes("books"); - - CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder(); - CriteriaQuery query = criteriaBuilder.createQuery(Author.class); - Root root = query.from(Author.class); - query.where(criteriaBuilder.equal(root.get("name"), authorName)); - - List fetchedAuthorIds = em.createQuery(query) - .setFirstResult(0) - .setMaxResults(4) - .setHint("jakarta.persistence.loadgraph", entityGraph) - .getResultList() - .stream() - .map(author -> author.id) - .collect(Collectors.toList()); - - assertEquals(3, fetchedAuthorIds.size()); - assertTrue(fetchedAuthorIds.containsAll(authorIds)); - - em.getTransaction().commit(); - em.close(); + public void paginationOverCollectionFetch(EntityManagerFactoryScope scope) { + scope.inEntityManager( em -> { + em.getTransaction().begin(); + + String authorName = SafeRandomUUIDGenerator.safeRandomUUIDAsString(); + Set authorIds = IntStream.range( 0, 3 ) + .mapToObj( v -> { + Author author = new Author( authorName ); + em.persist( author ); + em.persist( new Book( author ) ); + em.persist( new Book( author ) ); + return author; + } ) + .map( author -> author.id ) + .collect( Collectors.toSet() ); + + em.getTransaction().commit(); + em.clear(); + + em.getTransaction().begin(); + EntityGraph entityGraph = em.createEntityGraph( Author.class ); + entityGraph.addAttributeNodes( "books" ); + + CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder(); + CriteriaQuery query = criteriaBuilder.createQuery( Author.class ); + Root root = query.from( Author.class ); + query.where( criteriaBuilder.equal( root.get( "name" ), authorName ) ); + + List fetchedAuthorIds = em.createQuery( query ) + .setFirstResult( 0 ) + .setMaxResults( 4 ) + .setHint( "jakarta.persistence.loadgraph", entityGraph ) + .getResultList() + .stream() + .map( author -> author.id ) + .collect( Collectors.toList() ); + + assertEquals( 3, fetchedAuthorIds.size() ); + assertTrue( fetchedAuthorIds.containsAll( authorIds ) ); + + em.getTransaction().commit(); + } ); } @Test @JiraKey(value = "HHH-15964") - public void paginationOverEagerCollectionWithEmptyEG() { - EntityManager em = getOrCreateEntityManager(); - em.getTransaction().begin(); - - String authorName = SafeRandomUUIDGenerator.safeRandomUUIDAsString(); - Set authorIds = IntStream.range(0, 3) - .mapToObj(v -> { - Author author = new Author(authorName); - em.persist(author); - em.persist(new Prize(author)); - em.persist(new Prize(author)); - return author; - }) - .map(author -> author.id) - .collect(Collectors.toSet()); - - em.getTransaction().commit(); - em.clear(); - - em.getTransaction().begin(); - EntityGraph entityGraph = em.createEntityGraph(Author.class); - - CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder(); - CriteriaQuery query = criteriaBuilder.createQuery(Author.class); - Root root = query.from(Author.class); - query.where(criteriaBuilder.equal(root.get("name"), authorName)); - - List fetchedAuthorIds = em.createQuery(query) - .setFirstResult(0) - .setMaxResults(4) - .setHint("jakarta.persistence.loadgraph", entityGraph) - .getResultList() - .stream() - .map(author -> author.id) - .collect(Collectors.toList()); - - assertEquals(3, fetchedAuthorIds.size()); - assertTrue(fetchedAuthorIds.containsAll(authorIds)); - - em.getTransaction().commit(); - em.close(); + public void paginationOverEagerCollectionWithEmptyEG(EntityManagerFactoryScope scope) { + scope.inEntityManager( em -> { + em.getTransaction().begin(); + + String authorName = SafeRandomUUIDGenerator.safeRandomUUIDAsString(); + Set authorIds = IntStream.range( 0, 3 ) + .mapToObj( v -> { + Author author = new Author( authorName ); + em.persist( author ); + em.persist( new Prize( author ) ); + em.persist( new Prize( author ) ); + return author; + } ) + .map( author -> author.id ) + .collect( Collectors.toSet() ); + + em.getTransaction().commit(); + em.clear(); + + em.getTransaction().begin(); + EntityGraph entityGraph = em.createEntityGraph( Author.class ); + + CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder(); + CriteriaQuery query = criteriaBuilder.createQuery( Author.class ); + Root root = query.from( Author.class ); + query.where( criteriaBuilder.equal( root.get( "name" ), authorName ) ); + + List fetchedAuthorIds = em.createQuery( query ) + .setFirstResult( 0 ) + .setMaxResults( 4 ) + .setHint( "jakarta.persistence.loadgraph", entityGraph ) + .getResultList() + .stream() + .map( author -> author.id ) + .collect( Collectors.toList() ); + + assertEquals( 3, fetchedAuthorIds.size() ); + assertTrue( fetchedAuthorIds.containsAll( authorIds ) ); + + em.getTransaction().commit(); + } ); } @Test @JiraKey(value = "HHH-15972") - public void joinedInheritanceWithAttributeConflictTest() { - EntityManager em = getOrCreateEntityManager(); - em.getTransaction().begin(); + public void joinedInheritanceWithAttributeConflictTest(EntityManagerFactoryScope scope) { + scope.inEntityManager( em -> { + em.getTransaction().begin(); - Dog dog = new Dog(); - em.persist( dog ); + Dog dog = new Dog(); + em.persist( dog ); - em.getTransaction().commit(); - em.clear(); + em.getTransaction().commit(); + em.clear(); - em.getTransaction().begin(); - Map properties = new HashMap<>(); - properties.put( "jakarta.persistence.loadgraph", em.createEntityGraph( Animal.class ) ); + em.getTransaction().begin(); + Map properties = new HashMap<>(); + properties.put( "jakarta.persistence.loadgraph", em.createEntityGraph( Animal.class ) ); - Animal animal = em.find( Animal.class, dog.id, properties ); - assertTrue( animal instanceof Dog ); - assertEquals( dog.id, animal.id ); + Animal animal = em.find( Animal.class, dog.id, properties ); + assertTrue( animal instanceof Dog ); + assertEquals( dog.id, animal.id ); - em.getTransaction().commit(); - em.close(); + em.getTransaction().commit(); + } ); } @Test @JiraKey("HHH-17192") - public void joinedInheritanceWithSubEntityAttributeFiltering() { - EntityManager em = getOrCreateEntityManager(); - em.getTransaction().begin(); - Dog dog = new Dog(); - em.persist( dog ); - AnimalOwner animalOwner = new AnimalOwner(); - animalOwner.animal = dog; - em.persist( animalOwner ); - em.flush(); - em.clear(); - - EntityGraph entityGraph = em.createEntityGraph( AnimalOwner.class ); - entityGraph.addAttributeNodes( "animal" ); - CriteriaBuilder cb = em.getCriteriaBuilder(); - CriteriaQuery query = cb.createQuery( AnimalOwner.class ); - Root root = query.from( AnimalOwner.class ); - query.where( cb.equal( root.get( "animal" ).get( "id" ), dog.id ) ); - AnimalOwner owner = em.createQuery( query ) - .setHint( "jakarta.persistence.loadgraph", entityGraph ) - .getResultList() - .get( 0 ); - assertTrue( Hibernate.isInitialized( owner.animal ) ); - assertTrue( owner.animal instanceof Dog ); - - em.getTransaction().commit(); - em.close(); + public void joinedInheritanceWithSubEntityAttributeFiltering(EntityManagerFactoryScope scope) { + scope.inEntityManager( em -> { + em.getTransaction().begin(); + Dog dog = new Dog(); + em.persist( dog ); + AnimalOwner animalOwner = new AnimalOwner(); + animalOwner.animal = dog; + em.persist( animalOwner ); + em.flush(); + em.clear(); + + EntityGraph entityGraph = em.createEntityGraph( AnimalOwner.class ); + entityGraph.addAttributeNodes( "animal" ); + CriteriaBuilder cb = em.getCriteriaBuilder(); + CriteriaQuery query = cb.createQuery( AnimalOwner.class ); + Root root = query.from( AnimalOwner.class ); + query.where( cb.equal( root.get( "animal" ).get( "id" ), dog.id ) ); + AnimalOwner owner = em.createQuery( query ) + .setHint( "jakarta.persistence.loadgraph", entityGraph ) + .getResultList() + .get( 0 ); + assertTrue( Hibernate.isInitialized( owner.animal ) ); + assertTrue( owner.animal instanceof Dog ); + + em.getTransaction().commit(); + } ); } @Test - public void testTreatedSubgraph() { - EntityManager em = getOrCreateEntityManager(); - em.getTransaction().begin(); - Kennel kennel = new Kennel(); - em.persist( kennel ); - Dog dog = new Dog(); - dog.kennel = kennel; - em.persist( dog ); - em.flush(); - em.clear(); - - EntityGraph graph = em.createEntityGraph( Dog.class ); - graph.addAttributeNode( "kennel" ); - Dog doggie = em.find( graph, dog.id ); - assertTrue( Hibernate.isInitialized( doggie.kennel ) ); - - em.clear(); - - EntityGraph withKennel = em.createEntityGraph( Animal.class ); - withKennel.addTreatedSubgraph( Dog.class ).addAttributeNode( "kennel" ); - Animal animal = em.find( withKennel, doggie.id ); - assertTrue( Hibernate.isInitialized( ( (Dog) animal ).kennel ) ); - - em.clear(); - - EntityGraph withoutKennel = em.createEntityGraph( Animal.class ); - animal = em.find( withoutKennel, doggie.id ); - assertFalse( Hibernate.isInitialized( ( (Dog) animal ).kennel ) ); - - em.getTransaction().rollback(); - em.close(); + public void testTreatedSubgraph(EntityManagerFactoryScope scope) { + scope.inEntityManager( em -> { + em.getTransaction().begin(); + Kennel kennel = new Kennel(); + em.persist( kennel ); + Dog dog = new Dog(); + dog.kennel = kennel; + em.persist( dog ); + em.flush(); + em.clear(); + + EntityGraph graph = em.createEntityGraph( Dog.class ); + graph.addAttributeNode( "kennel" ); + Dog doggie = em.find( graph, dog.id ); + assertTrue( Hibernate.isInitialized( doggie.kennel ) ); + + em.clear(); + + EntityGraph withKennel = em.createEntityGraph( Animal.class ); + withKennel.addTreatedSubgraph( Dog.class ).addAttributeNode( "kennel" ); + Animal animal = em.find( withKennel, doggie.id ); + assertTrue( Hibernate.isInitialized( ((Dog) animal).kennel ) ); + + em.clear(); + + EntityGraph withoutKennel = em.createEntityGraph( Animal.class ); + animal = em.find( withoutKennel, doggie.id ); + assertFalse( Hibernate.isInitialized( ((Dog) animal).kennel ) ); + + em.getTransaction().rollback(); + } ); } @Test - public void testElementSubgraph() { - EntityManager em = getOrCreateEntityManager(); - em.getTransaction().begin(); - Bar bar = new Bar(); - Foo foo = new Foo(); - Baz baz = new Baz(); - foo.baz = baz; - foo.bar = bar; - bar.foos.add( foo ); - baz.foos.add( foo ); - em.persist( bar ); - em.persist( baz ); - em.persist( foo ); - em.flush(); - em.clear(); - - EntityGraph graph = em.createEntityGraph( Bar.class ); - Subgraph subgraph = graph.addElementSubgraph( "foos", Foo.class ); - subgraph.addAttributeNode( "baz" ); - Bar b = em.find( graph, bar.id ); - assertTrue( Hibernate.isInitialized( b.foos ) ); - assertTrue( Hibernate.isInitialized( b.foos.iterator().next().baz ) ); - - em.getTransaction().rollback(); - em.close(); + public void testElementSubgraph(EntityManagerFactoryScope scope) { + scope.inEntityManager( em -> { + em.getTransaction().begin(); + Bar bar = new Bar(); + Foo foo = new Foo(); + Baz baz = new Baz(); + foo.baz = baz; + foo.bar = bar; + bar.foos.add( foo ); + baz.foos.add( foo ); + em.persist( bar ); + em.persist( baz ); + em.persist( foo ); + em.flush(); + em.clear(); + + EntityGraph graph = em.createEntityGraph( Bar.class ); + Subgraph subgraph = graph.addElementSubgraph( "foos", Foo.class ); + subgraph.addAttributeNode( "baz" ); + Bar b = em.find( graph, bar.id ); + assertTrue( Hibernate.isInitialized( b.foos ) ); + assertTrue( Hibernate.isInitialized( b.foos.iterator().next().baz ) ); + + em.getTransaction().rollback(); + } ); } @Test - public void testTreatedElementSubgraph() { - EntityManager em = getOrCreateEntityManager(); - em.getTransaction().begin(); - AnimalOwner animalOwner = new AnimalOwner(); - Dog dog = new Dog(); - Cat cat = new Cat(); - Kennel kennel = new Kennel(); - dog.kennel = kennel; - animalOwner.animals.add( dog ); - animalOwner.animals.add( cat ); - em.persist( animalOwner ); - em.persist( kennel ); - em.persist( dog ); - em.persist( cat ); - em.flush(); - em.clear(); - - PluralAttribute animalsAttribute = - (PluralAttribute) - em.getEntityManagerFactory().getMetamodel() - .entity( AnimalOwner.class ) - .getAttribute( "animals" ); - - EntityGraph graph = em.createEntityGraph( AnimalOwner.class ); - Subgraph subgraph = graph.addElementSubgraph( animalsAttribute ); - AnimalOwner owner = em.find( graph, animalOwner.id ); - assertTrue( Hibernate.isInitialized( owner.animals ) ); - assertEquals( 2, owner.animals.size() ); - owner.animals.forEach( animal -> { - if (animal instanceof Dog d ) { - assertFalse( Hibernate.isInitialized( d.kennel ) ); - } + public void testTreatedElementSubgraph(EntityManagerFactoryScope scope) { + scope.inEntityManager( em -> { + em.getTransaction().begin(); + AnimalOwner animalOwner = new AnimalOwner(); + Dog dog = new Dog(); + Cat cat = new Cat(); + Kennel kennel = new Kennel(); + dog.kennel = kennel; + animalOwner.animals.add( dog ); + animalOwner.animals.add( cat ); + em.persist( animalOwner ); + em.persist( kennel ); + em.persist( dog ); + em.persist( cat ); + em.flush(); + em.clear(); + + PluralAttribute animalsAttribute = + (PluralAttribute) + em.getEntityManagerFactory().getMetamodel() + .entity( AnimalOwner.class ) + .getAttribute( "animals" ); + + EntityGraph graph = em.createEntityGraph( AnimalOwner.class ); + Subgraph subgraph = graph.addElementSubgraph( animalsAttribute ); + AnimalOwner owner = em.find( graph, animalOwner.id ); + assertTrue( Hibernate.isInitialized( owner.animals ) ); + assertEquals( 2, owner.animals.size() ); + owner.animals.forEach( animal -> { + if ( animal instanceof Dog d ) { + assertFalse( Hibernate.isInitialized( d.kennel ) ); + } + } ); + + em.clear(); + + graph = em.createEntityGraph( AnimalOwner.class ); + subgraph = graph.addElementSubgraph( animalsAttribute ); + Subgraph treated = graph.addTreatedElementSubgraph( animalsAttribute, Dog.class ); + treated.addAttributeNode( "kennel" ); + owner = em.find( graph, animalOwner.id ); + assertTrue( Hibernate.isInitialized( owner.animals ) ); + assertEquals( 2, owner.animals.size() ); + owner.animals.forEach( animal -> { + if ( animal instanceof Dog d ) { + assertTrue( Hibernate.isInitialized( d.kennel ) ); + } + } ); + + em.getTransaction().rollback(); } ); - - em.clear(); - - graph = em.createEntityGraph( AnimalOwner.class ); - subgraph = graph.addElementSubgraph( animalsAttribute ); - Subgraph treated = graph.addTreatedElementSubgraph( animalsAttribute, Dog.class ); - treated.addAttributeNode( "kennel" ); - owner = em.find( graph, animalOwner.id ); - assertTrue( Hibernate.isInitialized( owner.animals ) ); - assertEquals( 2, owner.animals.size() ); - owner.animals.forEach( animal -> { - if (animal instanceof Dog d ) { - assertTrue( Hibernate.isInitialized( d.kennel ) ); - } - } ); - - em.getTransaction().rollback(); - em.close(); } @Test - public void testTreatedElementSubgraph2() { - EntityManager em = getOrCreateEntityManager(); - em.getTransaction().begin(); - AnimalOwner animalOwner = new AnimalOwner(); - Dog dog = new Dog(); - Cat cat = new Cat(); - Kennel kennel = new Kennel(); - dog.kennel = kennel; - animalOwner.animals.add( dog ); - animalOwner.animals.add( cat ); - em.persist( animalOwner ); - em.persist( kennel ); - em.persist( dog ); - em.persist( cat ); - em.flush(); - em.clear(); - - Attribute kennelAttribute = - (Attribute) - em.getEntityManagerFactory().getMetamodel() - .entity( Dog.class ) - .getAttribute( "kennel" ); - - EntityGraph graph = em.createEntityGraph( Animal.class ); - Animal animal = em.find( graph, dog.id ); - assertFalse( Hibernate.isInitialized( ((Dog) animal).kennel ) ); - - em.clear(); - - graph = em.createEntityGraph( Animal.class ); - graph.addTreatedSubgraph( Dog.class ).addAttributeNode( kennelAttribute ); - animal = em.find( graph, dog.id ); - assertTrue( Hibernate.isInitialized( ((Dog) animal).kennel ) ); - - em.getTransaction().rollback(); - em.close(); + public void testTreatedElementSubgraph2(EntityManagerFactoryScope scope) { + scope.inEntityManager( em -> { + em.getTransaction().begin(); + AnimalOwner animalOwner = new AnimalOwner(); + Dog dog = new Dog(); + Cat cat = new Cat(); + Kennel kennel = new Kennel(); + dog.kennel = kennel; + animalOwner.animals.add( dog ); + animalOwner.animals.add( cat ); + em.persist( animalOwner ); + em.persist( kennel ); + em.persist( dog ); + em.persist( cat ); + em.flush(); + em.clear(); + + Attribute kennelAttribute = + (Attribute) + em.getEntityManagerFactory().getMetamodel() + .entity( Dog.class ) + .getAttribute( "kennel" ); + + EntityGraph graph = em.createEntityGraph( Animal.class ); + Animal animal = em.find( graph, dog.id ); + assertFalse( Hibernate.isInitialized( ((Dog) animal).kennel ) ); + + em.clear(); + + graph = em.createEntityGraph( Animal.class ); + graph.addTreatedSubgraph( Dog.class ).addAttributeNode( kennelAttribute ); + animal = em.find( graph, dog.id ); + assertTrue( Hibernate.isInitialized( ((Dog) animal).kennel ) ); + + em.getTransaction().rollback(); + } ); } @Entity(name = "Foo") diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/graphs/LoadAndFetchGraphTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/graphs/LoadAndFetchGraphTest.java index 6479ac0d33b6..02e30b0c0702 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/graphs/LoadAndFetchGraphTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/graphs/LoadAndFetchGraphTest.java @@ -7,7 +7,6 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.List; -import java.util.Map; import jakarta.persistence.CascadeType; import jakarta.persistence.Entity; import jakarta.persistence.EntityGraph; @@ -22,46 +21,39 @@ import org.hibernate.Hibernate; import org.hibernate.SessionFactory; -import org.hibernate.cfg.Environment; import org.hibernate.graph.GraphSemantic; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; import org.hibernate.stat.Statistics; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; import org.hibernate.testing.orm.junit.JiraKey; -import org.junit.Before; -import org.junit.Test; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Andrea Boriero * @author Nathan Xu */ -public class LoadAndFetchGraphTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - AEntity.class, - BEntity.class, - CEntity.class, - DEntity.class, - EEntity.class - }; - } - - @Override - protected void addConfigOptions(Map options) { - options.put( Environment.GENERATE_STATISTICS, "true" ); - super.addConfigOptions( options ); - } - - @Before - public void setUp() { - doInJPA( this::entityManagerFactory, entityManager -> { +@Jpa( + annotatedClasses = { + LoadAndFetchGraphTest.AEntity.class, + LoadAndFetchGraphTest.BEntity.class, + LoadAndFetchGraphTest.CEntity.class, + LoadAndFetchGraphTest.DEntity.class, + LoadAndFetchGraphTest.EEntity.class + }, + generateStatistics = true +) +public class LoadAndFetchGraphTest { + + @BeforeEach + public void setUp(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { // Create the model twice, with different IDs, // because we also need to test what happens when multiple results are loaded by a query. for ( int offset : new int[]{ 0, 10000 } ) { @@ -176,13 +168,17 @@ public void setUp() { } ); } + @AfterEach + public void tearDown(EntityManagerFactoryScope scope) { + scope.getEntityManagerFactory().getSchemaManager().truncate(); + } + @Test @JiraKey(value = "HHH-14097") - public void testQueryById() { - Statistics statistics = entityManagerFactory().unwrap( SessionFactory.class ).getStatistics(); + public void testQueryById(EntityManagerFactoryScope scope) { + Statistics statistics = scope.getEntityManagerFactory().unwrap( SessionFactory.class ).getStatistics(); statistics.clear(); - doInJPA( - this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { TypedQuery query = entityManager.createQuery( "select c from CEntity as c where c.id = :cid ", CEntity.class @@ -204,11 +200,10 @@ public void testQueryById() { @Test @JiraKey(value = "HHH-14097") - public void testQueryByIdWithLoadGraph() { - Statistics statistics = entityManagerFactory().unwrap( SessionFactory.class ).getStatistics(); + public void testQueryByIdWithLoadGraph(EntityManagerFactoryScope scope) { + Statistics statistics = scope.getEntityManagerFactory().unwrap( SessionFactory.class ).getStatistics(); statistics.clear(); - doInJPA( - this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { EntityGraph entityGraph = entityManager.createEntityGraph( CEntity.class ); entityGraph.addAttributeNodes( "a", "b" ); entityGraph.addSubgraph( "dList" ).addAttributeNodes( "e" ); @@ -240,11 +235,10 @@ public void testQueryByIdWithLoadGraph() { @Test @JiraKey(value = "HHH-14097") - public void testQueryByIdWithFetchGraph() { - Statistics statistics = entityManagerFactory().unwrap( SessionFactory.class ).getStatistics(); + public void testQueryByIdWithFetchGraph(EntityManagerFactoryScope scope) { + Statistics statistics = scope.getEntityManagerFactory().unwrap( SessionFactory.class ).getStatistics(); statistics.clear(); - doInJPA( - this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { EntityGraph entityGraph = entityManager.createEntityGraph( CEntity.class ); entityGraph.addAttributeNodes( "a", "b" ); entityGraph.addSubgraph( "dList" ).addAttributeNodes( "e" ); @@ -275,11 +269,10 @@ public void testQueryByIdWithFetchGraph() { @Test @JiraKey(value = "HHH-14097") - public void testQueryByIdWithFetchGraph2() { - Statistics statistics = entityManagerFactory().unwrap( SessionFactory.class ).getStatistics(); + public void testQueryByIdWithFetchGraph2(EntityManagerFactoryScope scope) { + Statistics statistics = scope.getEntityManagerFactory().unwrap( SessionFactory.class ).getStatistics(); statistics.clear(); - doInJPA( - this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { EntityGraph entityGraph = entityManager.createEntityGraph( CEntity.class ); entityGraph.addSubgraph( "c" ).addAttributeNodes( "a" ); @@ -305,10 +298,10 @@ public void testQueryByIdWithFetchGraph2() { @Test @JiraKey(value = "HHH-14124") - public void testQueryByIdWithLoadGraphMultipleResults() { - Statistics statistics = entityManagerFactory().unwrap( SessionFactory.class ).getStatistics(); + public void testQueryByIdWithLoadGraphMultipleResults(EntityManagerFactoryScope scope) { + Statistics statistics = scope.getEntityManagerFactory().unwrap( SessionFactory.class ).getStatistics(); statistics.clear(); - doInJPA( this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { EntityGraph entityGraph = entityManager.createEntityGraph( CEntity.class ); entityGraph.addAttributeNodes( "a", "b" ); entityGraph.addSubgraph( "dList" ).addAttributeNodes( "e" ); @@ -343,10 +336,10 @@ public void testQueryByIdWithLoadGraphMultipleResults() { @Test @JiraKey(value = "HHH-14124") - public void testQueryByIdWithFetchGraphMultipleResults() { - Statistics statistics = entityManagerFactory().unwrap( SessionFactory.class ).getStatistics(); + public void testQueryByIdWithFetchGraphMultipleResults(EntityManagerFactoryScope scope) { + Statistics statistics = scope.getEntityManagerFactory().unwrap( SessionFactory.class ).getStatistics(); statistics.clear(); - doInJPA( this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { EntityGraph entityGraph = entityManager.createEntityGraph( CEntity.class ); entityGraph.addAttributeNodes( "a", "b" ); entityGraph.addSubgraph( "dList" ).addAttributeNodes( "e" ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/graphs/mappedbyid/FetchGraphFindByIdTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/graphs/mappedbyid/FetchGraphFindByIdTest.java index 899934a29304..3c501aaa4cb4 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/graphs/mappedbyid/FetchGraphFindByIdTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/graphs/mappedbyid/FetchGraphFindByIdTest.java @@ -6,7 +6,6 @@ import org.hibernate.Hibernate; import org.hibernate.Session; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; import org.hibernate.orm.test.jpa.graphs.Company; import org.hibernate.orm.test.jpa.graphs.CompanyFetchProfile; import org.hibernate.orm.test.jpa.graphs.Course; @@ -16,23 +15,35 @@ import org.hibernate.orm.test.jpa.graphs.Market; import org.hibernate.orm.test.jpa.graphs.Student; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; import org.hibernate.testing.orm.junit.JiraKey; -import org.junit.Before; -import org.junit.Test; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import jakarta.persistence.EntityGraph; -import jakarta.persistence.EntityManager; import jakarta.persistence.Subgraph; import java.util.Collections; -import java.util.Iterator; import java.util.Map; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; /** * @author Nathan Xu */ -public class FetchGraphFindByIdTest extends BaseEntityManagerFunctionalTestCase { +@Jpa( + annotatedClasses = { + Company.class, + CompanyFetchProfile.class, + Employee.class, + Manager.class, + Location.class, + Course.class, + Student.class + } +) +public class FetchGraphFindByIdTest { private long companyId; @@ -40,20 +51,18 @@ public class FetchGraphFindByIdTest extends BaseEntityManagerFunctionalTestCase @Test @JiraKey(value = "HHH-8776") - public void testFetchGraphByFind() { - EntityManager entityManager = getOrCreateEntityManager(); - entityManager.getTransaction().begin(); - - EntityGraph entityGraph = entityManager.createEntityGraph( Company.class ); - entityGraph.addAttributeNodes( "location" ); - entityGraph.addAttributeNodes( "markets" ); - - Map properties = Collections.singletonMap( "javax.persistence.fetchgraph", entityGraph ); - - Company company = entityManager.find( Company.class, companyId, properties ); - - entityManager.getTransaction().commit(); - entityManager.close(); + public void testFetchGraphByFind(EntityManagerFactoryScope scope) { + EntityGraph entityGraph = scope.fromTransaction( entityManager -> { + EntityGraph _entityGraph = entityManager.createEntityGraph( Company.class ); + _entityGraph.addAttributeNodes( "location" ); + _entityGraph.addAttributeNodes( "markets" ); + return _entityGraph; + } ); + + Company company = scope.fromTransaction( entityManager -> { + Map properties = Collections.singletonMap( "javax.persistence.fetchgraph", entityGraph ); + return entityManager.find( Company.class, companyId, properties ); + } ); assertFalse( Hibernate.isInitialized( company.employees ) ); assertTrue( Hibernate.isInitialized( company.location ) ); @@ -62,20 +71,17 @@ public void testFetchGraphByFind() { // @ElementCollection(fetch = FetchType.EAGER) should not be initialized. assertFalse( Hibernate.isInitialized( company.phoneNumbers ) ); - entityManager = getOrCreateEntityManager(); - entityManager.getTransaction().begin(); - - Subgraph subgraph = entityGraph.addSubgraph( "employees" ); - subgraph.addAttributeNodes( "managers" ); - subgraph.addAttributeNodes( "friends" ); - Subgraph subSubgraph = subgraph.addSubgraph( "managers", Manager.class ); - subSubgraph.addAttributeNodes( "managers" ); - subSubgraph.addAttributeNodes( "friends" ); - - company = entityManager.find( Company.class, companyId, properties ); + company = scope.fromTransaction( entityManager -> { + Subgraph subgraph = entityGraph.addSubgraph( "employees" ); + subgraph.addAttributeNodes( "managers" ); + subgraph.addAttributeNodes( "friends" ); + Subgraph subSubgraph = subgraph.addSubgraph( "managers", Manager.class ); + subSubgraph.addAttributeNodes( "managers" ); + subSubgraph.addAttributeNodes( "friends" ); - entityManager.getTransaction().commit(); - entityManager.close(); + Map properties = Collections.singletonMap( "javax.persistence.fetchgraph", entityGraph ); + return entityManager.find( Company.class, companyId, properties ); + } ); assertTrue( Hibernate.isInitialized( company.employees ) ); assertTrue( Hibernate.isInitialized( company.location ) ); @@ -86,16 +92,12 @@ public void testFetchGraphByFind() { assertFalse( Hibernate.isInitialized( company.phoneNumbers ) ); boolean foundManager = false; - Iterator employeeItr = company.employees.iterator(); - while (employeeItr.hasNext()) { - Employee employee = employeeItr.next(); + for ( Employee employee : company.employees ) { assertTrue( Hibernate.isInitialized( employee.managers ) ); assertTrue( Hibernate.isInitialized( employee.friends ) ); // test 1 more level - Iterator managerItr = employee.managers.iterator(); - while (managerItr.hasNext()) { + for ( Manager manager : employee.managers ) { foundManager = true; - Manager manager = managerItr.next(); assertTrue( Hibernate.isInitialized( manager.managers ) ); assertTrue( Hibernate.isInitialized( manager.friends ) ); } @@ -105,21 +107,18 @@ public void testFetchGraphByFind() { @Test @JiraKey(value = "HHH-8776") - public void testFetchGraphByFindTakingPrecedenceOverFetchProfile() { - EntityManager entityManager = getOrCreateEntityManager(); - entityManager.getTransaction().begin(); - - entityManager.unwrap( Session.class ).enableFetchProfile("company.location"); - - EntityGraph entityGraph = entityManager.createEntityGraph( CompanyFetchProfile.class ); - entityGraph.addAttributeNodes( "markets" ); - - Map properties = Collections.singletonMap( "javax.persistence.fetchgraph", entityGraph ); - - CompanyFetchProfile company = entityManager.find( CompanyFetchProfile.class, companyWithFetchProfileId, properties ); - - entityManager.getTransaction().commit(); - entityManager.close(); + public void testFetchGraphByFindTakingPrecedenceOverFetchProfile(EntityManagerFactoryScope scope) { + EntityGraph entityGraph = scope.fromTransaction( entityManager -> { + entityManager.unwrap( Session.class ).enableFetchProfile("company.location"); + EntityGraph _entityGraph = entityManager.createEntityGraph( CompanyFetchProfile.class ); + _entityGraph.addAttributeNodes( "markets" ); + return _entityGraph; + } ); + + CompanyFetchProfile company = scope.fromTransaction( entityManager -> { + Map properties = Collections.singletonMap( "javax.persistence.fetchgraph", entityGraph ); + return entityManager.find( CompanyFetchProfile.class, companyWithFetchProfileId, properties ); + } ); assertFalse( Hibernate.isInitialized( company.employees ) ); assertFalse( Hibernate.isInitialized( company.location ) ); // should be initialized if 'company.location' fetch profile takes effect @@ -128,20 +127,17 @@ public void testFetchGraphByFindTakingPrecedenceOverFetchProfile() { // @ElementCollection(fetch = FetchType.EAGER) should not be initialized. assertFalse( Hibernate.isInitialized( company.phoneNumbers ) ); - entityManager = getOrCreateEntityManager(); - entityManager.getTransaction().begin(); - - Subgraph subgraph = entityGraph.addSubgraph( "employees" ); - subgraph.addAttributeNodes( "managers" ); - subgraph.addAttributeNodes( "friends" ); - Subgraph subSubgraph = subgraph.addSubgraph( "managers", Manager.class ); - subSubgraph.addAttributeNodes( "managers" ); - subSubgraph.addAttributeNodes( "friends" ); - - company = entityManager.find( CompanyFetchProfile.class, companyWithFetchProfileId, properties ); + company = scope.fromTransaction( entityManager -> { + Subgraph subgraph = entityGraph.addSubgraph( "employees" ); + subgraph.addAttributeNodes( "managers" ); + subgraph.addAttributeNodes( "friends" ); + Subgraph subSubgraph = subgraph.addSubgraph( "managers", Manager.class ); + subSubgraph.addAttributeNodes( "managers" ); + subSubgraph.addAttributeNodes( "friends" ); - entityManager.getTransaction().commit(); - entityManager.close(); + Map properties = Collections.singletonMap( "javax.persistence.fetchgraph", entityGraph ); + return entityManager.find( CompanyFetchProfile.class, companyWithFetchProfileId, properties ); + } ); assertTrue( Hibernate.isInitialized( company.employees ) ); assertFalse( Hibernate.isInitialized( company.location ) ); // should be initialized if 'company.location' fetch profile takes effect @@ -151,16 +147,12 @@ public void testFetchGraphByFindTakingPrecedenceOverFetchProfile() { assertFalse( Hibernate.isInitialized( company.phoneNumbers ) ); boolean foundManager = false; - Iterator employeeItr = company.employees.iterator(); - while (employeeItr.hasNext()) { - Employee employee = employeeItr.next(); + for ( Employee employee : company.employees ) { assertTrue( Hibernate.isInitialized( employee.managers ) ); assertTrue( Hibernate.isInitialized( employee.friends ) ); // test 1 more level - Iterator managerItr = employee.managers.iterator(); - while (managerItr.hasNext()) { + for ( Manager manager : employee.managers ) { foundManager = true; - Manager manager = managerItr.next(); assertTrue( Hibernate.isInitialized( manager.managers ) ); assertTrue( Hibernate.isInitialized( manager.friends ) ); } @@ -168,58 +160,56 @@ public void testFetchGraphByFindTakingPrecedenceOverFetchProfile() { assertTrue(foundManager); } - @Before - public void createData() { - EntityManager entityManager = getOrCreateEntityManager(); - entityManager.getTransaction().begin(); - - Manager manager1 = new Manager(); - entityManager.persist( manager1 ); - - Manager manager2 = new Manager(); - manager2.managers.add( manager1 ); - entityManager.persist( manager2 ); - - Employee employee = new Employee(); - employee.managers.add( manager1 ); - entityManager.persist( employee ); - - Location location = new Location(); - location.address = "123 somewhere"; - location.zip = 12345; - entityManager.persist( location ); - - Company company = new Company(); - company.employees.add( employee ); - company.employees.add( manager1 ); - company.employees.add( manager2 ); - company.location = location; - company.markets.add( Market.SERVICES ); - company.markets.add( Market.TECHNOLOGY ); - company.phoneNumbers.add( "012-345-6789" ); - company.phoneNumbers.add( "987-654-3210" ); - entityManager.persist( company ); - companyId = company.id; - - CompanyFetchProfile companyFetchProfile = new CompanyFetchProfile(); - companyFetchProfile.employees.add( employee ); - companyFetchProfile.employees.add( manager1 ); - companyFetchProfile.employees.add( manager2 ); - companyFetchProfile.location = location; - companyFetchProfile.markets.add( Market.SERVICES ); - companyFetchProfile.markets.add( Market.TECHNOLOGY ); - companyFetchProfile.phoneNumbers.add( "012-345-6789" ); - companyFetchProfile.phoneNumbers.add( "987-654-3210" ); - entityManager.persist( companyFetchProfile ); - companyWithFetchProfileId = companyFetchProfile.id; - - entityManager.getTransaction().commit(); - entityManager.close(); + @BeforeEach + public void createData(EntityManagerFactoryScope scope) { + scope.inTransaction( + entityManager -> { + Manager manager1 = new Manager(); + entityManager.persist( manager1 ); + + Manager manager2 = new Manager(); + manager2.managers.add( manager1 ); + entityManager.persist( manager2 ); + + Employee employee = new Employee(); + employee.managers.add( manager1 ); + entityManager.persist( employee ); + + Location location = new Location(); + location.address = "123 somewhere"; + location.zip = 12345; + entityManager.persist( location ); + + Company company = new Company(); + company.employees.add( employee ); + company.employees.add( manager1 ); + company.employees.add( manager2 ); + company.location = location; + company.markets.add( Market.SERVICES ); + company.markets.add( Market.TECHNOLOGY ); + company.phoneNumbers.add( "012-345-6789" ); + company.phoneNumbers.add( "987-654-3210" ); + entityManager.persist( company ); + companyId = company.id; + + CompanyFetchProfile companyFetchProfile = new CompanyFetchProfile(); + companyFetchProfile.employees.add( employee ); + companyFetchProfile.employees.add( manager1 ); + companyFetchProfile.employees.add( manager2 ); + companyFetchProfile.location = location; + companyFetchProfile.markets.add( Market.SERVICES ); + companyFetchProfile.markets.add( Market.TECHNOLOGY ); + companyFetchProfile.phoneNumbers.add( "012-345-6789" ); + companyFetchProfile.phoneNumbers.add( "987-654-3210" ); + entityManager.persist( companyFetchProfile ); + companyWithFetchProfileId = companyFetchProfile.id; + } + ); } - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { Company.class, CompanyFetchProfile.class, Employee.class, Manager.class, Location.class, Course.class, Student.class }; + @AfterEach + public void cleanup(EntityManagerFactoryScope scope) { + scope.getEntityManagerFactory().getSchemaManager().truncate(); } } 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 d42db59745e5..6351e16fe868 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 @@ -5,15 +5,12 @@ package org.hibernate.orm.test.jpa.graphs.queryhint; import java.util.HashSet; -import java.util.Iterator; import java.util.List; -import java.util.Map; import java.util.Set; import org.hibernate.Hibernate; import org.hibernate.Session; -import org.hibernate.metamodel.CollectionClassification; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; +import org.hibernate.engine.spi.SessionFactoryImplementor; import org.hibernate.orm.test.jpa.graphs.Company; import org.hibernate.orm.test.jpa.graphs.CompanyFetchProfile; import org.hibernate.orm.test.jpa.graphs.Course; @@ -23,13 +20,17 @@ import org.hibernate.orm.test.jpa.graphs.Market; import org.hibernate.orm.test.jpa.graphs.Student; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; import org.hibernate.testing.orm.junit.JiraKey; +import org.hibernate.testing.orm.junit.Jpa; +import org.hibernate.testing.orm.junit.ServiceRegistry; +import org.hibernate.testing.orm.junit.Setting; import org.hibernate.testing.transaction.TransactionUtil2; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import jakarta.persistence.EntityGraph; -import jakarta.persistence.EntityManager; import jakarta.persistence.Query; import jakarta.persistence.Subgraph; import jakarta.persistence.TypedQuery; @@ -38,31 +39,42 @@ import static org.hibernate.jpa.LegacySpecHints.HINT_JAVAEE_FETCH_GRAPH; import static org.hibernate.jpa.SpecHints.HINT_SPEC_FETCH_GRAPH; import static org.hibernate.jpa.SpecHints.HINT_SPEC_LOAD_GRAPH; -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Brett Meyer * @author Nathan Xu */ -public class QueryHintEntityGraphTest extends BaseEntityManagerFunctionalTestCase { +@Jpa( + annotatedClasses = { + Company.class, + CompanyFetchProfile.class, + Employee.class, + Manager.class, + Location.class, + Course.class, + Student.class + } +) +@ServiceRegistry(settings = {@Setting(name = DEFAULT_LIST_SEMANTICS, value = "BAG")}) +public class QueryHintEntityGraphTest { @Test - public void testLoadGraph() { - EntityManager entityManager = getOrCreateEntityManager(); - entityManager.getTransaction().begin(); - - EntityGraph entityGraph = entityManager.createEntityGraph( Company.class ); - entityGraph.addAttributeNodes( "location" ); - entityGraph.addAttributeNodes( "markets" ); - Query query = entityManager.createQuery( "from " + Company.class.getName() ); - query.setHint( HINT_SPEC_LOAD_GRAPH, entityGraph ); - Company company = (Company) query.getSingleResult(); + public void testLoadGraph(EntityManagerFactoryScope scope) { + EntityGraph entityGraph = scope.fromTransaction( entityManager -> { + EntityGraph _entityGraph = entityManager.createEntityGraph( Company.class ); + _entityGraph.addAttributeNodes( "location" ); + _entityGraph.addAttributeNodes( "markets" ); + return _entityGraph; + } ); - entityManager.getTransaction().commit(); - entityManager.close(); + Company company = scope.fromTransaction( entityManager -> { + Query query = entityManager.createQuery( "from " + Company.class.getName() ); + query.setHint( HINT_SPEC_LOAD_GRAPH, entityGraph ); + return (Company) query.getSingleResult(); + } ); assertFalse( Hibernate.isInitialized( company.employees ) ); assertTrue( Hibernate.isInitialized( company.location ) ); @@ -71,22 +83,20 @@ public void testLoadGraph() { // @ElementCollection(fetch = FetchType.EAGER) should cause the follow-on selects to happen. assertTrue( Hibernate.isInitialized( company.phoneNumbers ) ); - entityManager = getOrCreateEntityManager(); - entityManager.getTransaction().begin(); - - Subgraph subgraph = entityGraph.addSubgraph( "employees" ); - subgraph.addAttributeNodes( "managers" ); - subgraph.addAttributeNodes( "friends" ); - Subgraph subSubgraph = subgraph.addSubgraph( "managers", Manager.class ); - subSubgraph.addAttributeNodes( "managers" ); - subSubgraph.addAttributeNodes( "friends" ); - - query = entityManager.createQuery( "from " + Company.class.getName() ); - query.setHint( HINT_SPEC_LOAD_GRAPH, entityGraph ); - company = (Company) query.getSingleResult(); + scope.inTransaction( entityManager -> { + Subgraph subgraph = entityGraph.addSubgraph( "employees" ); + subgraph.addAttributeNodes( "managers" ); + subgraph.addAttributeNodes( "friends" ); + Subgraph subSubgraph = subgraph.addSubgraph( "managers", Manager.class ); + subSubgraph.addAttributeNodes( "managers" ); + subSubgraph.addAttributeNodes( "friends" ); + } ); - entityManager.getTransaction().commit(); - entityManager.close(); + company = scope.fromTransaction( entityManager -> { + Query query = entityManager.createQuery( "from " + Company.class.getName() ); + query.setHint( HINT_SPEC_LOAD_GRAPH, entityGraph ); + return (Company) query.getSingleResult(); + } ); assertTrue( Hibernate.isInitialized( company.employees ) ); assertTrue( Hibernate.isInitialized( company.location ) ); @@ -97,16 +107,12 @@ public void testLoadGraph() { assertTrue( Hibernate.isInitialized( company.phoneNumbers ) ); boolean foundManager = false; - Iterator employeeItr = company.employees.iterator(); - while (employeeItr.hasNext()) { - Employee employee = employeeItr.next(); + for ( Employee employee : company.employees ) { assertTrue( Hibernate.isInitialized( employee.managers ) ); assertTrue( Hibernate.isInitialized( employee.friends ) ); // test 1 more level - Iterator managerItr = employee.managers.iterator(); - while (managerItr.hasNext()) { + for ( Manager manager : employee.managers ) { foundManager = true; - Manager manager = managerItr.next(); assertTrue( Hibernate.isInitialized( manager.managers ) ); assertTrue( Hibernate.isInitialized( manager.friends ) ); } @@ -116,8 +122,8 @@ public void testLoadGraph() { @Test @JiraKey(value = "https://hibernate.atlassian.net/browse/HHH-14855") - public void testEntityGraphStringQueryHint() { - TransactionUtil2.inTransaction( entityManagerFactory(), (session) -> { + public void testEntityGraphStringQueryHint(EntityManagerFactoryScope scope) { + TransactionUtil2.inTransaction( scope.getEntityManagerFactory().unwrap( SessionFactoryImplementor.class ), (session) -> { final String hql = "from Company c"; final String graphString = "Company( location, markets )"; @@ -142,19 +148,19 @@ public void testEntityGraphStringQueryHint() { @Test @JiraKey(value = "HHH-8776") - public void testFetchGraph() { - EntityManager entityManager = getOrCreateEntityManager(); - entityManager.getTransaction().begin(); - - EntityGraph entityGraph = entityManager.createEntityGraph( Company.class ); - entityGraph.addAttributeNodes( "location" ); - entityGraph.addAttributeNodes( "markets" ); - Query query = entityManager.createQuery( "from " + Company.class.getName() ); - query.setHint( HINT_JAVAEE_FETCH_GRAPH, entityGraph ); - Company company = (Company) query.getSingleResult(); + public void testFetchGraph(EntityManagerFactoryScope scope) { + EntityGraph entityGraph = scope.fromTransaction( entityManager -> { + EntityGraph _entityGraph = entityManager.createEntityGraph( Company.class ); + _entityGraph.addAttributeNodes( "location" ); + _entityGraph.addAttributeNodes( "markets" ); + return _entityGraph; + } ); - entityManager.getTransaction().commit(); - entityManager.close(); + Company company = scope.fromTransaction( entityManager -> { + Query query = entityManager.createQuery( "from " + Company.class.getName() ); + query.setHint( HINT_JAVAEE_FETCH_GRAPH, entityGraph ); + return (Company) query.getSingleResult(); + } ); assertFalse( Hibernate.isInitialized( company.employees ) ); assertTrue( Hibernate.isInitialized( company.location ) ); @@ -163,22 +169,18 @@ public void testFetchGraph() { // @ElementCollection(fetch = FetchType.EAGER) should not be initialized. assertFalse( Hibernate.isInitialized( company.phoneNumbers ) ); - entityManager = getOrCreateEntityManager(); - entityManager.getTransaction().begin(); - - Subgraph subgraph = entityGraph.addSubgraph( "employees" ); - subgraph.addAttributeNodes( "managers" ); - subgraph.addAttributeNodes( "friends" ); - Subgraph subSubgraph = subgraph.addSubgraph( "managers", Manager.class ); - subSubgraph.addAttributeNodes( "managers" ); - subSubgraph.addAttributeNodes( "friends" ); - - query = entityManager.createQuery( "from " + Company.class.getName() ); - query.setHint( HINT_JAVAEE_FETCH_GRAPH, entityGraph ); - company = (Company) query.getSingleResult(); - - entityManager.getTransaction().commit(); - entityManager.close(); + company = scope.fromTransaction( entityManager -> { + Subgraph subgraph = entityGraph.addSubgraph( "employees" ); + subgraph.addAttributeNodes( "managers" ); + subgraph.addAttributeNodes( "friends" ); + Subgraph subSubgraph = subgraph.addSubgraph( "managers", Manager.class ); + subSubgraph.addAttributeNodes( "managers" ); + subSubgraph.addAttributeNodes( "friends" ); + + Query query = entityManager.createQuery( "from " + Company.class.getName() ); + query.setHint( HINT_JAVAEE_FETCH_GRAPH, entityGraph ); + return (Company) query.getSingleResult(); + } ); assertTrue( Hibernate.isInitialized( company.employees ) ); assertTrue( Hibernate.isInitialized( company.location ) ); @@ -189,169 +191,152 @@ public void testFetchGraph() { assertFalse( Hibernate.isInitialized( company.phoneNumbers ) ); boolean foundManager = false; - Iterator employeeItr = company.employees.iterator(); - while (employeeItr.hasNext()) { - Employee employee = employeeItr.next(); + for ( Employee employee : company.employees ) { assertTrue( Hibernate.isInitialized( employee.managers ) ); assertTrue( Hibernate.isInitialized( employee.friends ) ); // test 1 more level - Iterator managerItr = employee.managers.iterator(); - while (managerItr.hasNext()) { + for ( Manager manager : employee.managers ) { foundManager = true; - Manager manager = managerItr.next(); assertTrue( Hibernate.isInitialized( manager.managers ) ); assertTrue( Hibernate.isInitialized( manager.friends ) ); } } - assertTrue(foundManager); + assertTrue( foundManager ); } @Test @JiraKey(value = "HHH-8776") - public void testFetchGraphTakingPrecedenceOverFetchProfile() { - EntityManager entityManager = getOrCreateEntityManager(); - entityManager.getTransaction().begin(); - - entityManager.unwrap( Session.class ).enableFetchProfile( "company.location" ); - - EntityGraph entityGraph = entityManager.createEntityGraph( CompanyFetchProfile.class ); - entityGraph.addAttributeNodes( "markets" ); - Query query = entityManager.createQuery( "from " + CompanyFetchProfile.class.getName() ); - query.setHint( HINT_JAVAEE_FETCH_GRAPH, entityGraph ); - CompanyFetchProfile company = (CompanyFetchProfile) query.getSingleResult(); + public void testFetchGraphTakingPrecedenceOverFetchProfile(EntityManagerFactoryScope scope) { + EntityGraph entityGraph = scope.fromTransaction( entityManager -> { + entityManager.unwrap( Session.class ).enableFetchProfile( "company.location" ); + EntityGraph _entityGraph = entityManager.createEntityGraph( + CompanyFetchProfile.class ); + _entityGraph.addAttributeNodes( "markets" ); + return _entityGraph; + } ); - entityManager.getTransaction().commit(); - entityManager.close(); + CompanyFetchProfile company = scope.fromTransaction( entityManager -> { + Query query = entityManager.createQuery( "from " + CompanyFetchProfile.class.getName() ); + query.setHint( HINT_JAVAEE_FETCH_GRAPH, entityGraph ); + return (CompanyFetchProfile) query.getSingleResult(); + } ); assertFalse( Hibernate.isInitialized( company.employees ) ); - assertFalse( Hibernate.isInitialized( company.location ) ); // should be initialized if 'company.location' fetch profile takes effect + assertFalse( Hibernate.isInitialized( + company.location ) ); // should be initialized if 'company.location' fetch profile takes effect assertTrue( Hibernate.isInitialized( company.markets ) ); // With "fetchgraph", non-specified attributes effect 'lazy' mode. So, here, // @ElementCollection(fetch = FetchType.EAGER) should not be initialized. assertFalse( Hibernate.isInitialized( company.phoneNumbers ) ); - entityManager = getOrCreateEntityManager(); - entityManager.getTransaction().begin(); - - Subgraph subgraph = entityGraph.addSubgraph( "employees" ); - subgraph.addAttributeNodes( "managers" ); - subgraph.addAttributeNodes( "friends" ); - Subgraph subSubgraph = subgraph.addSubgraph( "managers", Manager.class ); - subSubgraph.addAttributeNodes( "managers" ); - subSubgraph.addAttributeNodes( "friends" ); - - query = entityManager.createQuery( "from " + CompanyFetchProfile.class.getName() ); - query.setHint( HINT_JAVAEE_FETCH_GRAPH, entityGraph ); - company = (CompanyFetchProfile) query.getSingleResult(); - - entityManager.getTransaction().commit(); - entityManager.close(); + company = scope.fromTransaction( entityManager -> { + Subgraph subgraph = entityGraph.addSubgraph( "employees" ); + subgraph.addAttributeNodes( "managers" ); + subgraph.addAttributeNodes( "friends" ); + Subgraph subSubgraph = subgraph.addSubgraph( "managers", Manager.class ); + subSubgraph.addAttributeNodes( "managers" ); + subSubgraph.addAttributeNodes( "friends" ); + + Query query = entityManager.createQuery( "from " + CompanyFetchProfile.class.getName() ); + query.setHint( HINT_JAVAEE_FETCH_GRAPH, entityGraph ); + return (CompanyFetchProfile) query.getSingleResult(); + } ); assertTrue( Hibernate.isInitialized( company.employees ) ); - assertFalse( Hibernate.isInitialized( company.location ) ); // should be initialized if 'company.location' fetch profile takes effect + assertFalse( Hibernate.isInitialized( + company.location ) ); // should be initialized if 'company.location' fetch profile takes effect assertTrue( Hibernate.isInitialized( company.markets ) ); // With "fetchgraph", non-specified attributes effect 'lazy' mode. So, here, // @ElementCollection(fetch = FetchType.EAGER) should not be initialized. assertFalse( Hibernate.isInitialized( company.phoneNumbers ) ); boolean foundManager = false; - Iterator employeeItr = company.employees.iterator(); - while (employeeItr.hasNext()) { - Employee employee = employeeItr.next(); + for ( Employee employee : company.employees ) { assertTrue( Hibernate.isInitialized( employee.managers ) ); assertTrue( Hibernate.isInitialized( employee.friends ) ); // test 1 more level - Iterator managerItr = employee.managers.iterator(); - while (managerItr.hasNext()) { + for ( Manager manager : employee.managers ) { foundManager = true; - Manager manager = managerItr.next(); assertTrue( Hibernate.isInitialized( manager.managers ) ); assertTrue( Hibernate.isInitialized( manager.friends ) ); } } - assertTrue(foundManager); + assertTrue( foundManager ); } @Test @JiraKey( value = "HHH-9457") - public void testLoadGraphOrderByWithImplicitJoin() { - EntityManager entityManager = getOrCreateEntityManager(); - entityManager.getTransaction().begin(); - - // create a new Company at a different location in a different zip code - Location location = new Location(); - location.address = "123 somewhere"; - location.zip = 11234; - entityManager.persist( location ); - Company companyNew = new Company(); - companyNew.location = location; - entityManager.persist( companyNew ); - - entityManager.getTransaction().commit(); - entityManager.close(); - - entityManager = getOrCreateEntityManager(); - entityManager.getTransaction().begin(); - - EntityGraph entityGraph = entityManager.createEntityGraph( Company.class ); - //entityGraph.addAttributeNodes( "location" ); - entityGraph.addAttributeNodes( "markets" ); - Query query = entityManager.createQuery( "from " + Company.class.getName() + " c order by c.location.zip, c.id" ); - query.setHint( HINT_SPEC_LOAD_GRAPH, entityGraph ); - List results = query.getResultList(); - - // - 1st will be the Company with location.zip == 11234 with an empty markets collection - // - 2nd should be the Company with location.zip == 12345 - assertEquals( 2, results.size() ); - - Company companyResult = (Company) results.get( 0 ); - assertFalse( Hibernate.isInitialized( companyResult.employees ) ); - assertFalse( Hibernate.isInitialized( companyResult.location ) ); - // initialize and check zip - // TODO: must have getters to access lazy entity after being initialized (why?) - //assertEquals( 11234, companyResult.location.zip ); - assertEquals( 11234, companyResult.getLocation().getZip() ); - assertTrue( Hibernate.isInitialized( companyResult.markets ) ); - assertEquals( 0, companyResult.markets.size() ); - // With "loadgraph", non-specified attributes use the fetch modes defined in the mappings. So, here, - // @ElementCollection(fetch = FetchType.EAGER) should cause the follow-on selects to happen. - assertTrue( Hibernate.isInitialized( companyResult.phoneNumbers ) ); - assertEquals( 0, companyResult.phoneNumbers.size() ); - - companyResult = (Company) results.get( 1 ); - assertFalse( Hibernate.isInitialized( companyResult.employees ) ); - assertFalse( Hibernate.isInitialized( companyResult.location ) ); - // initialize and check zip - // TODO: must have getters to access lazy entity after being initialized (why?) - //assertEquals( 12345, companyResult.location.zip ); - assertEquals( 12345, companyResult.getLocation().getZip() ); - assertTrue( Hibernate.isInitialized( companyResult.markets ) ); - assertEquals( 2, companyResult.markets.size() ); - // With "loadgraph", non-specified attributes use the fetch modes defined in the mappings. So, here, - // @ElementCollection(fetch = FetchType.EAGER) should cause the follow-on selects to happen. - assertTrue( Hibernate.isInitialized( companyResult.phoneNumbers ) ); - assertEquals( 2, companyResult.phoneNumbers.size() ); + public void testLoadGraphOrderByWithImplicitJoin(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { + // create a new Company at a different location in a different zip code + Location location = new Location(); + location.address = "123 somewhere"; + location.zip = 11234; + entityManager.persist( location ); + Company companyNew = new Company(); + companyNew.location = location; + entityManager.persist( companyNew ); + } ); - entityManager.getTransaction().commit(); - entityManager.close(); + scope.inTransaction( entityManager -> { + EntityGraph entityGraph = entityManager.createEntityGraph( Company.class ); + //entityGraph.addAttributeNodes( "location" ); + entityGraph.addAttributeNodes( "markets" ); + Query query = entityManager.createQuery( + "from " + Company.class.getName() + " c order by c.location.zip, c.id" ); + query.setHint( HINT_SPEC_LOAD_GRAPH, entityGraph ); + List results = query.getResultList(); + + // - 1st will be the Company with location.zip == 11234 with an empty markets collection + // - 2nd should be the Company with location.zip == 12345 + assertEquals( 2, results.size() ); + + Company companyResult = (Company) results.get( 0 ); + assertFalse( Hibernate.isInitialized( companyResult.employees ) ); + assertFalse( Hibernate.isInitialized( companyResult.location ) ); + // initialize and check zip + // TODO: must have getters to access lazy entity after being initialized (why?) + //assertEquals( 11234, companyResult.location.zip ); + assertEquals( 11234, companyResult.getLocation().getZip() ); + assertTrue( Hibernate.isInitialized( companyResult.markets ) ); + assertEquals( 0, companyResult.markets.size() ); + // With "loadgraph", non-specified attributes use the fetch modes defined in the mappings. So, here, + // @ElementCollection(fetch = FetchType.EAGER) should cause the follow-on selects to happen. + assertTrue( Hibernate.isInitialized( companyResult.phoneNumbers ) ); + assertEquals( 0, companyResult.phoneNumbers.size() ); + + companyResult = (Company) results.get( 1 ); + assertFalse( Hibernate.isInitialized( companyResult.employees ) ); + assertFalse( Hibernate.isInitialized( companyResult.location ) ); + // initialize and check zip + // TODO: must have getters to access lazy entity after being initialized (why?) + //assertEquals( 12345, companyResult.location.zip ); + assertEquals( 12345, companyResult.getLocation().getZip() ); + assertTrue( Hibernate.isInitialized( companyResult.markets ) ); + assertEquals( 2, companyResult.markets.size() ); + // With "loadgraph", non-specified attributes use the fetch modes defined in the mappings. So, here, + // @ElementCollection(fetch = FetchType.EAGER) should cause the follow-on selects to happen. + assertTrue( Hibernate.isInitialized( companyResult.phoneNumbers ) ); + assertEquals( 2, companyResult.phoneNumbers.size() ); + } ); } @Test @JiraKey( value = "HHH-9448") - public void testLoadGraphWithRestriction() { - EntityManager entityManager = getOrCreateEntityManager(); - entityManager.getTransaction().begin(); - - EntityGraph entityGraph = entityManager.createEntityGraph( Company.class ); - entityGraph.addAttributeNodes( "location" ); - entityGraph.addAttributeNodes( "markets" ); - Query query = entityManager.createQuery( "from " + Company.class.getName() + " where location.zip = :zip") - .setParameter( "zip", 12345 ); - query.setHint( HINT_SPEC_LOAD_GRAPH, entityGraph ); - Company company = (Company) query.getSingleResult(); + public void testLoadGraphWithRestriction(EntityManagerFactoryScope scope) { + EntityGraph entityGraph = scope.fromTransaction( entityManager -> { + EntityGraph _entityGraph = entityManager.createEntityGraph( Company.class ); + _entityGraph.addAttributeNodes( "location" ); + _entityGraph.addAttributeNodes( "markets" ); + return _entityGraph; - entityManager.getTransaction().commit(); - entityManager.close(); + } ); + Company company = scope.fromTransaction( entityManager -> { + Query query = entityManager.createQuery( "from " + Company.class.getName() + " where location.zip = :zip" ) + .setParameter( "zip", 12345 ); + query.setHint( HINT_SPEC_LOAD_GRAPH, entityGraph ); + return (Company) query.getSingleResult(); + } ); assertFalse( Hibernate.isInitialized( company.employees ) ); assertTrue( Hibernate.isInitialized( company.location ) ); @@ -360,23 +345,19 @@ public void testLoadGraphWithRestriction() { // @ElementCollection(fetch = FetchType.EAGER) should cause the follow-on selects to happen. assertTrue( Hibernate.isInitialized( company.phoneNumbers ) ); - entityManager = getOrCreateEntityManager(); - entityManager.getTransaction().begin(); - - Subgraph subgraph = entityGraph.addSubgraph( "employees" ); - subgraph.addAttributeNodes( "managers" ); - subgraph.addAttributeNodes( "friends" ); - Subgraph subSubgraph = subgraph.addSubgraph( "managers", Manager.class ); - subSubgraph.addAttributeNodes( "managers" ); - subSubgraph.addAttributeNodes( "friends" ); - - query = entityManager.createQuery( "from " + Company.class.getName() + " where location.zip = :zip" ) - .setParameter( "zip", 12345 ); - query.setHint( HINT_SPEC_LOAD_GRAPH, entityGraph ); - company = (Company) query.getSingleResult(); - - entityManager.getTransaction().commit(); - entityManager.close(); + company = scope.fromTransaction( entityManager -> { + Subgraph subgraph = entityGraph.addSubgraph( "employees" ); + subgraph.addAttributeNodes( "managers" ); + subgraph.addAttributeNodes( "friends" ); + Subgraph subSubgraph = subgraph.addSubgraph( "managers", Manager.class ); + subSubgraph.addAttributeNodes( "managers" ); + subSubgraph.addAttributeNodes( "friends" ); + + Query query = entityManager.createQuery( "from " + Company.class.getName() + " where location.zip = :zip" ) + .setParameter( "zip", 12345 ); + query.setHint( HINT_SPEC_LOAD_GRAPH, entityGraph ); + return (Company) query.getSingleResult(); + } ); assertTrue( Hibernate.isInitialized( company.employees ) ); assertTrue( Hibernate.isInitialized( company.location ) ); @@ -386,40 +367,32 @@ public void testLoadGraphWithRestriction() { assertTrue( Hibernate.isInitialized( company.phoneNumbers ) ); boolean foundManager = false; - Iterator employeeItr = company.employees.iterator(); - while (employeeItr.hasNext()) { - Employee employee = employeeItr.next(); + for ( Employee employee : company.employees ) { assertTrue( Hibernate.isInitialized( employee.managers ) ); assertTrue( Hibernate.isInitialized( employee.friends ) ); // test 1 more level - Iterator managerItr = employee.managers.iterator(); - while (managerItr.hasNext()) { + for ( Manager manager : employee.managers ) { foundManager = true; - Manager manager = managerItr.next(); assertTrue( Hibernate.isInitialized( manager.managers ) ); assertTrue( Hibernate.isInitialized( manager.friends ) ); } } - assertTrue(foundManager); + assertTrue( foundManager ); } @Test - public void testEntityGraphWithExplicitFetch() { - EntityManager entityManager = getOrCreateEntityManager(); - entityManager.getTransaction().begin(); - - EntityGraph entityGraph = entityManager.createEntityGraph( Company.class ); - entityGraph.addAttributeNodes( "location" ); - entityGraph.addAttributeNodes( "markets" ); - entityGraph.addAttributeNodes( "employees" ); - // Ensure the EntityGraph and explicit fetches do not conflict. - Query query = entityManager.createQuery( "from " + Company.class.getName() - + " as c left join fetch c.location left join fetch c.employees" ); - query.setHint( HINT_SPEC_LOAD_GRAPH, entityGraph ); - Company company = (Company) query.getSingleResult(); - - entityManager.getTransaction().commit(); - entityManager.close(); + public void testEntityGraphWithExplicitFetch(EntityManagerFactoryScope scope ) { + Company company = scope.fromTransaction( entityManager -> { + EntityGraph entityGraph = entityManager.createEntityGraph( Company.class ); + entityGraph.addAttributeNodes( "location" ); + entityGraph.addAttributeNodes( "markets" ); + entityGraph.addAttributeNodes( "employees" ); + // Ensure the EntityGraph and explicit fetches do not conflict. + Query query = entityManager.createQuery( "from " + Company.class.getName() + + " as c left join fetch c.location left join fetch c.employees" ); + query.setHint( HINT_SPEC_LOAD_GRAPH, entityGraph ); + return (Company) query.getSingleResult(); + } ); assertTrue( Hibernate.isInitialized( company.employees ) ); assertTrue( Hibernate.isInitialized( company.location ) ); @@ -431,23 +404,19 @@ public void testEntityGraphWithExplicitFetch() { @Test @JiraKey( value = "HHH-9448") - public void testEntityGraphWithExplicitFetchAndRestriction() { - EntityManager entityManager = getOrCreateEntityManager(); - entityManager.getTransaction().begin(); - - EntityGraph entityGraph = entityManager.createEntityGraph( Company.class ); - entityGraph.addAttributeNodes( "location" ); - entityGraph.addAttributeNodes( "markets" ); - entityGraph.addAttributeNodes( "employees" ); - // Ensure the EntityGraph and explicit fetches do not conflict. - Query query = entityManager.createQuery( "from " + Company.class.getName() - + " as c left join fetch c.location left join fetch c.employees where c.location.zip = :zip") - .setParameter("zip", 12345); - query.setHint( HINT_SPEC_LOAD_GRAPH, entityGraph ); - Company company = (Company) query.getSingleResult(); - - entityManager.getTransaction().commit(); - entityManager.close(); + public void testEntityGraphWithExplicitFetchAndRestriction(EntityManagerFactoryScope scope) { + Company company = scope.fromTransaction( entityManager -> { + EntityGraph entityGraph = entityManager.createEntityGraph( Company.class ); + entityGraph.addAttributeNodes( "location" ); + entityGraph.addAttributeNodes( "markets" ); + entityGraph.addAttributeNodes( "employees" ); + // Ensure the EntityGraph and explicit fetches do not conflict. + Query query = entityManager.createQuery( "from " + Company.class.getName() + + " as c left join fetch c.location left join fetch c.employees where c.location.zip = :zip" ) + .setParameter( "zip", 12345 ); + query.setHint( HINT_SPEC_LOAD_GRAPH, entityGraph ); + return (Company) query.getSingleResult(); + } ); assertTrue( Hibernate.isInitialized( company.employees ) ); assertTrue( Hibernate.isInitialized( company.location ) ); @@ -459,24 +428,21 @@ public void testEntityGraphWithExplicitFetchAndRestriction() { @Test @JiraKey(value = "HHH-9374") - public void testEntityGraphWithCollectionSubquery(){ - EntityManager entityManager = getOrCreateEntityManager(); - entityManager.getTransaction().begin(); - - EntityGraph entityGraph = entityManager.createEntityGraph(Company.class); - entityGraph.addAttributeNodes("location"); - Query query = entityManager.createQuery("select c from " + Company.class.getName() + " c where c.employees IS EMPTY"); - query.setHint(HINT_SPEC_LOAD_GRAPH, entityGraph); - query.getResultList(); - - entityManager.getTransaction().commit(); - entityManager.close(); + public void testEntityGraphWithCollectionSubquery(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { + EntityGraph entityGraph = entityManager.createEntityGraph( Company.class ); + entityGraph.addAttributeNodes( "location" ); + Query query = entityManager.createQuery( + "select c from " + Company.class.getName() + " c where c.employees IS EMPTY" ); + query.setHint( HINT_SPEC_LOAD_GRAPH, entityGraph ); + query.getResultList(); + } ); } @Test @JiraKey(value = "HHH-11569") - public void testCollectionSizeLoadedWithGraph() { - doInJPA( this::entityManagerFactory, entityManager -> { + public void testCollectionSizeLoadedWithGraph(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { Student student1 = new Student(); student1.setId( 1 ); @@ -490,12 +456,12 @@ public void testCollectionSizeLoadedWithGraph() { Course course2 = new Course(); course2.setName( "Part Time" ); - Set std1Courses = new HashSet(); + Set std1Courses = new HashSet<>(); std1Courses.add( course1 ); std1Courses.add( course2 ); student1.setCourses( std1Courses ); - Set std2Courses = new HashSet(); + Set std2Courses = new HashSet<>(); std2Courses.add( course2 ); student2.setCourses( std2Courses ); @@ -504,7 +470,7 @@ public void testCollectionSizeLoadedWithGraph() { }); - doInJPA( this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { EntityGraph graph = entityManager.getEntityGraph( "Student.Full" ); List students = entityManager.createNamedQuery( "LIST_OF_STD", Student.class ) @@ -515,61 +481,53 @@ public void testCollectionSizeLoadedWithGraph() { }); } - @Before - public void createData() { - EntityManager entityManager = getOrCreateEntityManager(); - entityManager.getTransaction().begin(); - - Manager manager1 = new Manager(); - entityManager.persist( manager1 ); - - Manager manager2 = new Manager(); - manager2.managers.add( manager1 ); - entityManager.persist( manager2 ); - - Employee employee = new Employee(); - employee.managers.add( manager1 ); - entityManager.persist( employee ); - - Location location = new Location(); - location.address = "123 somewhere"; - location.zip = 12345; - entityManager.persist( location ); - - Company company = new Company(); - company.employees.add( employee ); - company.employees.add( manager1 ); - company.employees.add( manager2 ); - company.location = location; - company.markets.add( Market.SERVICES ); - company.markets.add( Market.TECHNOLOGY ); - company.phoneNumbers.add( "012-345-6789" ); - company.phoneNumbers.add( "987-654-3210" ); - entityManager.persist( company ); - - CompanyFetchProfile companyFetchProfile = new CompanyFetchProfile(); - companyFetchProfile.employees.add( employee ); - companyFetchProfile.employees.add( manager1 ); - companyFetchProfile.employees.add( manager2 ); - companyFetchProfile.location = location; - companyFetchProfile.markets.add( Market.SERVICES ); - companyFetchProfile.markets.add( Market.TECHNOLOGY ); - companyFetchProfile.phoneNumbers.add( "012-345-6789" ); - companyFetchProfile.phoneNumbers.add( "987-654-3210" ); - entityManager.persist( companyFetchProfile ); - - entityManager.getTransaction().commit(); - entityManager.close(); - } + @BeforeEach + public void createData(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { + + Manager manager1 = new Manager(); + entityManager.persist( manager1 ); + + Manager manager2 = new Manager(); + manager2.managers.add( manager1 ); + entityManager.persist( manager2 ); + + Employee employee = new Employee(); + employee.managers.add( manager1 ); + entityManager.persist( employee ); + + Location location = new Location(); + location.address = "123 somewhere"; + location.zip = 12345; + entityManager.persist( location ); + + Company company = new Company(); + company.employees.add( employee ); + company.employees.add( manager1 ); + company.employees.add( manager2 ); + company.location = location; + company.markets.add( Market.SERVICES ); + company.markets.add( Market.TECHNOLOGY ); + company.phoneNumbers.add( "012-345-6789" ); + company.phoneNumbers.add( "987-654-3210" ); + entityManager.persist( company ); + + CompanyFetchProfile companyFetchProfile = new CompanyFetchProfile(); + companyFetchProfile.employees.add( employee ); + companyFetchProfile.employees.add( manager1 ); + companyFetchProfile.employees.add( manager2 ); + companyFetchProfile.location = location; + companyFetchProfile.markets.add( Market.SERVICES ); + companyFetchProfile.markets.add( Market.TECHNOLOGY ); + companyFetchProfile.phoneNumbers.add( "012-345-6789" ); + companyFetchProfile.phoneNumbers.add( "987-654-3210" ); + entityManager.persist( companyFetchProfile ); - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { Company.class, CompanyFetchProfile.class, Employee.class, Manager.class, Location.class, Course.class, Student.class }; + } ); } - @Override - protected void addConfigOptions(Map options) { - super.addConfigOptions( options ); - options.put( DEFAULT_LIST_SEMANTICS, CollectionClassification.BAG ); + @AfterEach + public void cleanup(EntityManagerFactoryScope scope) { + scope.getEntityManagerFactory().getSchemaManager().truncate(); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/jointable/ManyToOneJoinTableTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/jointable/ManyToOneJoinTableTest.java index b8da8cc47e6d..0f70ebd24c8f 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/jointable/ManyToOneJoinTableTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/jointable/ManyToOneJoinTableTest.java @@ -4,25 +4,22 @@ */ package org.hibernate.orm.test.jpa.jointable; -import java.util.LinkedList; +import java.util.List; -import org.hibernate.boot.SessionFactoryBuilder; -import org.hibernate.boot.spi.MetadataImplementor; import org.hibernate.cfg.AvailableSettings; -import org.hibernate.engine.spi.SessionFactoryImplementor; -import org.hibernate.testing.jdbc.SQLStatementInterceptor; +import org.hibernate.testing.jdbc.SQLStatementInspector; import org.hibernate.testing.orm.junit.DomainModel; import org.hibernate.testing.orm.junit.ServiceRegistry; import org.hibernate.testing.orm.junit.SessionFactory; -import org.hibernate.testing.orm.junit.SessionFactoryProducer; import org.hibernate.testing.orm.junit.SessionFactoryScope; import org.hibernate.testing.orm.junit.Setting; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertThat; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertFalse; /** * @author Christian Beikov @@ -38,15 +35,14 @@ @Setting(name = AvailableSettings.JAKARTA_HBM2DDL_DATABASE_ACTION, value = "create-drop") } ) -@SessionFactory -public class ManyToOneJoinTableTest implements SessionFactoryProducer { - private SQLStatementInterceptor sqlStatementInterceptor; +@SessionFactory(useCollectingStatementInspector = true) +public class ManyToOneJoinTableTest { + private SQLStatementInspector sqlStatementInspector; - @Override - public SessionFactoryImplementor produceSessionFactory(MetadataImplementor model) { - final SessionFactoryBuilder sessionFactoryBuilder = model.getSessionFactoryBuilder(); - sqlStatementInterceptor = new SQLStatementInterceptor( sessionFactoryBuilder ); - return (SessionFactoryImplementor) sessionFactoryBuilder.build(); + @BeforeEach + public void setup(SessionFactoryScope scope) { + sqlStatementInspector = scope.getCollectingStatementInspector(); + sqlStatementInspector.clear(); } @Test @@ -54,16 +50,16 @@ public void testAvoidJoin(SessionFactoryScope scope) { final String queryString = "SELECT e.id FROM Person e"; scope.inTransaction( session -> { - final LinkedList sqlQueries = sqlStatementInterceptor.getSqlQueries(); + final List sqlQueries = sqlStatementInspector.getSqlQueries(); sqlQueries.clear(); session.createQuery( queryString ).list(); assertThat( sqlQueries.size(), is( 1 ) ); // Ideally, we could detect that *ToOne join tables aren't used, but that requires tracking the uses of properties // Since *ToOne join tables are treated like secondary or subclass/superclass tables, the proper fix will allow many more optimizations - String generatedSQl = sqlQueries.getFirst(); + String generatedSQl = sqlQueries.get( 0 ); assertFalse( - "The generated sql contains a useless join: " + generatedSQl, - generatedSQl.contains( "join" ) + generatedSQl.contains( "join" ), + "The generated sql contains a useless join: " + generatedSQl ); } ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/metamodel/AbstractJpaMetamodelPopulationTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/metamodel/AbstractJpaMetamodelPopulationTest.java index 36bf17d57ef7..1c767966ce2e 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/metamodel/AbstractJpaMetamodelPopulationTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/metamodel/AbstractJpaMetamodelPopulationTest.java @@ -5,35 +5,32 @@ package org.hibernate.orm.test.jpa.metamodel; import java.io.Serializable; -import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import jakarta.persistence.Embeddable; import jakarta.persistence.EmbeddedId; import jakarta.persistence.Entity; -import jakarta.persistence.EntityManager; import jakarta.persistence.GeneratedValue; import jakarta.persistence.Id; import jakarta.persistence.metamodel.EmbeddableType; import jakarta.persistence.metamodel.EntityType; import jakarta.persistence.metamodel.Metamodel; -import org.hibernate.cfg.AvailableSettings; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; -import org.junit.Test; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.junit.jupiter.api.Test; import org.hibernate.testing.orm.junit.JiraKey; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Chris Cranford */ @JiraKey(value = "HHH-12871") -public abstract class AbstractJpaMetamodelPopulationTest extends BaseEntityManagerFunctionalTestCase { +public abstract class AbstractJpaMetamodelPopulationTest { @Entity(name = "SimpleAnnotatedEntity") public static class SimpleAnnotatedEntity { @Id @@ -55,37 +52,16 @@ public static class CompositeIdId implements Serializable { private Integer id2; } - @Override - protected String[] getMappings() { - return new String[] { - "org/hibernate/jpa/test/metamodel/SimpleEntity.xml", - "org/hibernate/jpa/test/metamodel/CompositeIdEntity.hbm.xml", - "org/hibernate/jpa/test/metamodel/CompositeId2Entity.hbm.xml" - }; - } - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { SimpleAnnotatedEntity.class, CompositeIdAnnotatedEntity.class }; - } - protected abstract String getJpaMetamodelPopulationValue(); - @Override - protected void addConfigOptions(Map options) { - super.addConfigOptions( options ); - options.put( AvailableSettings.JPA_METAMODEL_POPULATION, getJpaMetamodelPopulationValue() ); - } - @Test - public void testMetamodel() { - EntityManager entityManager = getOrCreateEntityManager(); - try { + public void testMetamodel(EntityManagerFactoryScope scope) { + scope.inEntityManager( entityManager -> { final Metamodel metamodel = entityManager.getMetamodel(); if ( getJpaMetamodelPopulationValue().equalsIgnoreCase( "disabled" ) ) { // In 5.1, metamodel returned null. - // In 5.2+, metamodel erturned as a non-null instance. + // In 5.2+, metamodel returned as a non-null instance. assertNotNull( metamodel ); assertEquals( 0, metamodel.getManagedTypes().size() ); assertEquals( 0, metamodel.getEntities().size() ); @@ -98,10 +74,7 @@ public void testMetamodel() { assertManagedTypes( metamodel ); assertEntityTypes( metamodel ); assertEmbeddableTypes( metamodel ); - } - finally { - entityManager.close(); - } + } ); } private void assertManagedTypes(Metamodel metamodel) { @@ -153,7 +126,7 @@ private void assertEntityTypes(Metamodel metamodel) { // SimpleAnnotatedEntity // SimpleEntity <-- this should not exist since its entity-type is filtered // CompositeIdEntity <-- this should not exist since its entity-type is filtered - // CompsoiteId2Entity <-- this should not exist since its entity-type is filtered + // CompositeId2Entity <-- this should not exist since its entity-type is filtered // // In 5.2, this returns 5 elements too. // In 5.3, this returns 5 elements too. diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/metamodel/JpaMetamodelDisabledPopulationTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/metamodel/JpaMetamodelDisabledPopulationTest.java index 7c43aa4e4021..b0b7eec99a35 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/metamodel/JpaMetamodelDisabledPopulationTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/metamodel/JpaMetamodelDisabledPopulationTest.java @@ -4,12 +4,24 @@ */ package org.hibernate.orm.test.jpa.metamodel; +import org.hibernate.cfg.AvailableSettings; import org.hibernate.testing.orm.junit.JiraKey; +import org.hibernate.testing.orm.junit.Jpa; +import org.hibernate.testing.orm.junit.Setting; /** * @author Chris Cranford */ @JiraKey(value = "HHH-12871") +@Jpa( + annotatedClasses = {AbstractJpaMetamodelPopulationTest.SimpleAnnotatedEntity.class, AbstractJpaMetamodelPopulationTest.CompositeIdAnnotatedEntity.class}, + xmlMappings = { + "org/hibernate/jpa/test/metamodel/SimpleEntity.xml", + "org/hibernate/jpa/test/metamodel/CompositeIdEntity.hbm.xml", + "org/hibernate/jpa/test/metamodel/CompositeId2Entity.hbm.xml" + }, + integrationSettings = {@Setting(name = AvailableSettings.JPA_METAMODEL_POPULATION, value = "disabled")} +) public class JpaMetamodelDisabledPopulationTest extends AbstractJpaMetamodelPopulationTest { @Override protected String getJpaMetamodelPopulationValue() { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/metamodel/JpaMetamodelEnabledPopulationTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/metamodel/JpaMetamodelEnabledPopulationTest.java index 9907ff6114e2..0ba2db187c80 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/metamodel/JpaMetamodelEnabledPopulationTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/metamodel/JpaMetamodelEnabledPopulationTest.java @@ -4,12 +4,24 @@ */ package org.hibernate.orm.test.jpa.metamodel; +import org.hibernate.cfg.AvailableSettings; import org.hibernate.testing.orm.junit.JiraKey; +import org.hibernate.testing.orm.junit.Jpa; +import org.hibernate.testing.orm.junit.Setting; /** * @author Chris Cranford */ @JiraKey(value = "HHH-12871") +@Jpa( + annotatedClasses = {AbstractJpaMetamodelPopulationTest.SimpleAnnotatedEntity.class, AbstractJpaMetamodelPopulationTest.CompositeIdAnnotatedEntity.class}, + xmlMappings = { + "org/hibernate/jpa/test/metamodel/SimpleEntity.xml", + "org/hibernate/jpa/test/metamodel/CompositeIdEntity.hbm.xml", + "org/hibernate/jpa/test/metamodel/CompositeId2Entity.hbm.xml" + }, + integrationSettings = {@Setting(name = AvailableSettings.JPA_METAMODEL_POPULATION, value = "enabled")} +) public class JpaMetamodelEnabledPopulationTest extends AbstractJpaMetamodelPopulationTest { @Override protected String getJpaMetamodelPopulationValue() { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/metamodel/JpaMetamodelIgnoreUnsupportedPopulationTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/metamodel/JpaMetamodelIgnoreUnsupportedPopulationTest.java index 896bed9bfa3d..cf4ccb186110 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/metamodel/JpaMetamodelIgnoreUnsupportedPopulationTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/metamodel/JpaMetamodelIgnoreUnsupportedPopulationTest.java @@ -4,12 +4,24 @@ */ package org.hibernate.orm.test.jpa.metamodel; +import org.hibernate.cfg.AvailableSettings; import org.hibernate.testing.orm.junit.JiraKey; +import org.hibernate.testing.orm.junit.Jpa; +import org.hibernate.testing.orm.junit.Setting; /** * @author Chris Cranford */ @JiraKey(value = "HHH-12871") +@Jpa( + annotatedClasses = {AbstractJpaMetamodelPopulationTest.SimpleAnnotatedEntity.class, AbstractJpaMetamodelPopulationTest.CompositeIdAnnotatedEntity.class}, + xmlMappings = { + "org/hibernate/jpa/test/metamodel/SimpleEntity.xml", + "org/hibernate/jpa/test/metamodel/CompositeIdEntity.hbm.xml", + "org/hibernate/jpa/test/metamodel/CompositeId2Entity.hbm.xml" + }, + integrationSettings = {@Setting(name = AvailableSettings.JPA_METAMODEL_POPULATION, value = "ignoreUnsupported")} +) public class JpaMetamodelIgnoreUnsupportedPopulationTest extends AbstractJpaMetamodelPopulationTest { @Override protected String getJpaMetamodelPopulationValue() { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/ops/GetLoadTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/ops/GetLoadTest.java index 16080960f6de..a2325db9f854 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/ops/GetLoadTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/ops/GetLoadTest.java @@ -121,7 +121,7 @@ public void testLoad(EntityManagerFactoryScope scope) { emp.getId(); assertFalse( Hibernate.isInitialized( emp ) ); Node node = s.getReference( Node.class, nodeName ); - assertEquals( node.getName(), nodeName ); + assertEquals( nodeName, node.getName() ); assertFalse( Hibernate.isInitialized( node ) ); } ); @@ -133,7 +133,7 @@ public void testLoad(EntityManagerFactoryScope scope) { emp.getId(); assertFalse( Hibernate.isInitialized( emp ) ); Node node = ( Node ) s.getReference( Node.class.getName(), nodeName ); - assertEquals( node.getName(), nodeName ); + assertEquals( nodeName, node.getName() ); assertFalse( Hibernate.isInitialized( node ) ); } ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/ops/MergeJpaComplianceTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/ops/MergeJpaComplianceTest.java index 16ee2ce784f7..17fb20d78a28 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/ops/MergeJpaComplianceTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/ops/MergeJpaComplianceTest.java @@ -7,7 +7,6 @@ import java.io.Serializable; import java.util.ArrayList; import java.util.List; -import java.util.Map; import jakarta.persistence.CascadeType; import jakarta.persistence.Embeddable; import jakarta.persistence.EmbeddedId; @@ -17,33 +16,27 @@ import jakarta.persistence.ManyToOne; import jakarta.persistence.OneToMany; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; - +import org.hibernate.cfg.AvailableSettings; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; import org.hibernate.testing.orm.junit.JiraKey; -import org.junit.Test; - -import static org.hibernate.testing.transaction.TransactionUtil2.fromTransaction; -import static org.hibernate.testing.transaction.TransactionUtil2.inTransaction; +import org.hibernate.testing.orm.junit.Jpa; +import org.hibernate.testing.orm.junit.Setting; +import org.junit.jupiter.api.Test; @JiraKey( value = "HHH-14608") -public class MergeJpaComplianceTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Person.class, Occupation.class, PersonOccupation.class - }; - } - - @Override - protected void addConfigOptions(Map config) { - config.put( org.hibernate.cfg.AvailableSettings.JPA_PROXY_COMPLIANCE, true ); - } +@Jpa( + annotatedClasses = { + MergeJpaComplianceTest.Person.class, + MergeJpaComplianceTest.Occupation.class, + MergeJpaComplianceTest.PersonOccupation.class + }, + integrationSettings = {@Setting(name = AvailableSettings.JPA_PROXY_COMPLIANCE, value = "true")} +) +public class MergeJpaComplianceTest { @Test - public void testMerge() { - Person person = fromTransaction( - entityManagerFactory(), + public void testMerge(EntityManagerFactoryScope scope) { + Person person = scope.fromTransaction( entityManager -> { Person p; p = new Person( "1", "Fab" ); @@ -60,8 +53,7 @@ public void testMerge() { } ); - inTransaction( - entityManagerFactory(), + scope.inTransaction( entityManager -> { person.setName( "Fabiana" ); entityManager.merge( person ); @@ -100,7 +92,7 @@ public List getOccupations() { return occupations; } - protected void addOccupationPeoplet(PersonOccupation personOccupation) { + protected void addOccupationPeople(PersonOccupation personOccupation) { if ( this.occupations == null ) { occupations = new ArrayList<>(); } @@ -173,7 +165,7 @@ protected PersonOccupation() { } public PersonOccupation(Person person, Occupation occupation) { - person.addOccupationPeoplet( this ); + person.addOccupationPeople( this ); occupation.addPersonOccupation( this ); } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/orphan/onetoone/multilevelcascade/DeleteMultiLevelOrphansTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/orphan/onetoone/multilevelcascade/DeleteMultiLevelOrphansTest.java index 83765cd37359..1cf0800b3798 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/orphan/onetoone/multilevelcascade/DeleteMultiLevelOrphansTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/orphan/onetoone/multilevelcascade/DeleteMultiLevelOrphansTest.java @@ -8,116 +8,112 @@ import jakarta.persistence.EntityManager; -import org.junit.Test; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.AfterEach; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; import org.hibernate.testing.orm.junit.JiraKey; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; /** * @author Steve Ebersole * @author Gail Badner */ -public class DeleteMultiLevelOrphansTest extends BaseEntityManagerFunctionalTestCase { - - private void createData() { - Preisregelung preisregelung = new Preisregelung(); - - Tranchenmodell tranchenmodell = new Tranchenmodell(); - - X x = new X(); - - Tranche tranche1 = new Tranche(); - - Y y = new Y(); - - Tranche tranche2 = new Tranche(); - - preisregelung.setTranchenmodell( tranchenmodell ); - tranchenmodell.setPreisregelung( preisregelung ); - - tranchenmodell.setX( x ); - x.setTranchenmodell( tranchenmodell ); - - tranchenmodell.getTranchen().add( tranche1 ); - tranche1.setTranchenmodell( tranchenmodell ); - tranchenmodell.getTranchen().add( tranche2 ); - tranche2.setTranchenmodell( tranchenmodell ); - - tranche1.setY( y ); - y.setTranche( tranche1 ); - - EntityManager em = getOrCreateEntityManager(); - em.getTransaction().begin(); - em.persist( preisregelung ); - em.getTransaction().commit(); - em.close(); +@Jpa( + annotatedClasses = { + Preisregelung.class, + Tranche.class, + Tranchenmodell.class, + X.class, + Y.class + } +) +public class DeleteMultiLevelOrphansTest { + + @BeforeEach + public void createData(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { + Preisregelung preisregelung = new Preisregelung(); + Tranchenmodell tranchenmodell = new Tranchenmodell(); + X x = new X(); + Tranche tranche1 = new Tranche(); + Y y = new Y(); + Tranche tranche2 = new Tranche(); + + preisregelung.setTranchenmodell( tranchenmodell ); + tranchenmodell.setPreisregelung( preisregelung ); + + tranchenmodell.setX( x ); + x.setTranchenmodell( tranchenmodell ); + + tranchenmodell.getTranchen().add( tranche1 ); + tranche1.setTranchenmodell( tranchenmodell ); + tranchenmodell.getTranchen().add( tranche2 ); + tranche2.setTranchenmodell( tranchenmodell ); + + tranche1.setY( y ); + y.setTranche( tranche1 ); + + entityManager.persist( preisregelung ); + } ); } - private void cleanupData() { - EntityManager em = getOrCreateEntityManager(); - em.getTransaction().begin(); - em.createQuery( "delete Tranche" ).executeUpdate(); - em.createQuery( "delete Tranchenmodell" ).executeUpdate(); - em.createQuery( "delete Preisregelung" ).executeUpdate(); - em.getTransaction().commit(); - em.close(); + @AfterEach + public void cleanupData(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> scope.getEntityManagerFactory().getSchemaManager().truncate() ); } @Test @JiraKey( value = "HHH-9091") - public void testDirectAssociationOrphanedWhileManaged() { - createData(); - - EntityManager em = getOrCreateEntityManager(); - em.getTransaction().begin(); - List results = em.createQuery( "from Tranchenmodell" ).getResultList(); - assertEquals( 1, results.size() ); - results = em.createQuery( "from Preisregelung" ).getResultList(); - assertEquals( 1, results.size() ); - Preisregelung preisregelung = (Preisregelung) results.get( 0 ); - Tranchenmodell tranchenmodell = preisregelung.getTranchenmodell(); - assertNotNull( tranchenmodell ); - assertNotNull( tranchenmodell.getX() ); - assertEquals( 2, tranchenmodell.getTranchen().size() ); - assertNotNull( tranchenmodell.getTranchen().get( 0 ).getY() ); - preisregelung.setTranchenmodell( null ); - em.getTransaction().commit(); - em.close(); - - em = getOrCreateEntityManager(); - em.getTransaction().begin(); - - preisregelung = (Preisregelung) em.find( Preisregelung.class, preisregelung.getId() ); - assertNull( preisregelung.getTranchenmodell() ); - results = em.createQuery( "from Tranchenmodell" ).getResultList(); - assertEquals( 0, results.size() ); - results = em.createQuery( "from Tranche" ).getResultList(); - assertEquals( 0, results.size() ); - results = em.createQuery( "from X" ).getResultList(); - assertEquals( 0, results.size() ); - results = em.createQuery( "from Y" ).getResultList(); - assertEquals( 0, results.size() ); - - results = em.createQuery( "from Preisregelung" ).getResultList(); - assertEquals( 1, results.size() ); - - em.getTransaction().commit(); - em.close(); - - cleanupData(); + public void testDirectAssociationOrphanedWhileManaged(EntityManagerFactoryScope scope) { + Long id = scope.fromTransaction( + em -> { + List results = em.createQuery( "from Tranchenmodell" ).getResultList(); + assertEquals( 1, results.size() ); + results = em.createQuery( "from Preisregelung" ).getResultList(); + assertEquals( 1, results.size() ); + Preisregelung preisregelung = (Preisregelung) results.get( 0 ); + Tranchenmodell tranchenmodell = preisregelung.getTranchenmodell(); + assertNotNull( tranchenmodell ); + assertNotNull( tranchenmodell.getX() ); + assertEquals( 2, tranchenmodell.getTranchen().size() ); + assertNotNull( tranchenmodell.getTranchen().get( 0 ).getY() ); + preisregelung.setTranchenmodell( null ); + + return preisregelung.getId(); + } + ); + + scope.inTransaction( + em -> { + Preisregelung preisregelung = em.find( Preisregelung.class, id ); + assertNull( preisregelung.getTranchenmodell() ); + List results = em.createQuery( "from Tranchenmodell" ).getResultList(); + assertEquals( 0, results.size() ); + results = em.createQuery( "from Tranche" ).getResultList(); + assertEquals( 0, results.size() ); + results = em.createQuery( "from X" ).getResultList(); + assertEquals( 0, results.size() ); + results = em.createQuery( "from Y" ).getResultList(); + assertEquals( 0, results.size() ); + + results = em.createQuery( "from Preisregelung" ).getResultList(); + assertEquals( 1, results.size() ); + } + ); } @Test @JiraKey( value = "HHH-9091") - public void testReplacedDirectAssociationWhileManaged() { - createData(); - - EntityManager em = getOrCreateEntityManager(); + public void testReplacedDirectAssociationWhileManaged(EntityManagerFactoryScope scope) { + EntityManager em = scope.getEntityManagerFactory().createEntityManager(); em.getTransaction().begin(); + List results = em.createQuery( "from Tranchenmodell" ).getResultList(); assertEquals( 1, results.size() ); results = em.createQuery( "from Preisregelung" ).getResultList(); @@ -148,7 +144,7 @@ public void testReplacedDirectAssociationWhileManaged() { em.getTransaction().commit(); em.close(); - em = getOrCreateEntityManager(); + em = scope.getEntityManagerFactory().createEntityManager(); em.getTransaction().begin(); results = em.createQuery( "from Tranche" ).getResultList(); @@ -175,11 +171,13 @@ public void testReplacedDirectAssociationWhileManaged() { tranchenmodellNew = new Tranchenmodell(); preisregelung.setTranchenmodell(tranchenmodellNew ); tranchenmodellNew.setPreisregelung( preisregelung ); + em.getTransaction().commit(); em.close(); - em = getOrCreateEntityManager(); + em = scope.getEntityManagerFactory().createEntityManager(); em.getTransaction().begin(); + results = em.createQuery( "from Tranchenmodell" ).getResultList(); assertEquals( 1, results.size() ); tranchenmodell = (Tranchenmodell) results.get( 0 ); @@ -194,67 +192,50 @@ public void testReplacedDirectAssociationWhileManaged() { assertEquals( 0, results.size() ); results = em.createQuery( "from Y" ).getResultList(); assertEquals( 0, results.size() ); + em.getTransaction().commit(); em.close(); - - cleanupData(); } @Test @JiraKey( value = "HHH-9091") - public void testDirectAndNestedAssociationsOrphanedWhileManaged() { - createData(); - - EntityManager em = getOrCreateEntityManager(); - em.getTransaction().begin(); - List results = em.createQuery( "from Tranchenmodell" ).getResultList(); - assertEquals( 1, results.size() ); - results = em.createQuery( "from Preisregelung" ).getResultList(); - assertEquals( 1, results.size() ); - Preisregelung preisregelung = (Preisregelung) results.get( 0 ); - Tranchenmodell tranchenmodell = preisregelung.getTranchenmodell(); - assertNotNull( tranchenmodell ); - assertNotNull( tranchenmodell.getX() ); - assertEquals( 2, tranchenmodell.getTranchen().size() ); - assertNotNull( tranchenmodell.getTranchen().get( 0 ).getY() ); - preisregelung.setTranchenmodell( null ); - tranchenmodell.setX( null ); - tranchenmodell.getTranchen().get( 0 ).setY( null ); - em.getTransaction().commit(); - em.close(); - - em = getOrCreateEntityManager(); - em.getTransaction().begin(); - - preisregelung = (Preisregelung) em.find( Preisregelung.class, preisregelung.getId() ); - assertNull( preisregelung.getTranchenmodell() ); - results = em.createQuery( "from Tranchenmodell" ).getResultList(); - assertEquals( 0, results.size() ); - results = em.createQuery( "from Tranche" ).getResultList(); - assertEquals( 0, results.size() ); - results = em.createQuery( "from X" ).getResultList(); - assertEquals( 0, results.size() ); - results = em.createQuery( "from Y" ).getResultList(); - assertEquals( 0, results.size() ); - - results = em.createQuery( "from Preisregelung" ).getResultList(); - assertEquals( 1, results.size() ); - - em.getTransaction().commit(); - em.close(); - - cleanupData(); - } - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[]{ - Preisregelung.class, - Tranche.class, - Tranchenmodell.class, - X.class, - Y.class - }; + public void testDirectAndNestedAssociationsOrphanedWhileManaged(EntityManagerFactoryScope scope) { + Long id = scope.fromTransaction( + em -> { + List results = em.createQuery( "from Tranchenmodell" ).getResultList(); + assertEquals( 1, results.size() ); + results = em.createQuery( "from Preisregelung" ).getResultList(); + assertEquals( 1, results.size() ); + Preisregelung preisregelung = (Preisregelung) results.get( 0 ); + Tranchenmodell tranchenmodell = preisregelung.getTranchenmodell(); + assertNotNull( tranchenmodell ); + assertNotNull( tranchenmodell.getX() ); + assertEquals( 2, tranchenmodell.getTranchen().size() ); + assertNotNull( tranchenmodell.getTranchen().get( 0 ).getY() ); + preisregelung.setTranchenmodell( null ); + tranchenmodell.setX( null ); + tranchenmodell.getTranchen().get( 0 ).setY( null ); + + return preisregelung.getId(); + } + ); + scope.inTransaction( + em -> { + Preisregelung preisregelung = em.find( Preisregelung.class, id ); + assertNull( preisregelung.getTranchenmodell() ); + List results = em.createQuery( "from Tranchenmodell" ).getResultList(); + assertEquals( 0, results.size() ); + results = em.createQuery( "from Tranche" ).getResultList(); + assertEquals( 0, results.size() ); + results = em.createQuery( "from X" ).getResultList(); + assertEquals( 0, results.size() ); + results = em.createQuery( "from Y" ).getResultList(); + assertEquals( 0, results.size() ); + + results = em.createQuery( "from Preisregelung" ).getResultList(); + assertEquals( 1, results.size() ); + } + ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/persistenceunit/DuplicatePersistenceUnitNameTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/persistenceunit/DuplicatePersistenceUnitNameTest.java index 7c3566a66fc0..e09059867ddf 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/persistenceunit/DuplicatePersistenceUnitNameTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/persistenceunit/DuplicatePersistenceUnitNameTest.java @@ -5,50 +5,39 @@ package org.hibernate.orm.test.jpa.persistenceunit; import java.util.List; -import java.util.Set; import org.hibernate.jpa.boot.spi.PersistenceXmlParser; +import org.hibernate.jpa.internal.JpaLogger; import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseUnitTestCase; -import org.hibernate.testing.logger.LoggerInspectionRule; -import org.hibernate.testing.logger.Triggerable; -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; - +import org.hibernate.testing.orm.junit.LoggingInspections; +import org.hibernate.testing.orm.junit.LoggingInspectionsScope; +import org.junit.jupiter.api.Test; import static org.hibernate.internal.util.ConfigHelper.findAsResource; -import static org.hibernate.jpa.internal.JpaLogger.JPA_LOGGER; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Andrea Boriero */ @JiraKey(value = "HHH-11845") -public class DuplicatePersistenceUnitNameTest extends BaseUnitTestCase { - private Triggerable triggerable; - - @Rule - public LoggerInspectionRule logInspection = new LoggerInspectionRule( JPA_LOGGER ); - - @Before - public void setUp() { - triggerable = logInspection.watchForLogMessages( Set.of( "HHH008518" ) ); - } - - @After - public void tearDown() { - triggerable.reset(); - } +@LoggingInspections( + messages = { + @LoggingInspections.Message( + messageKey = "HHH008518", + loggers = @org.hibernate.testing.orm.junit.Logger(loggerName = JpaLogger.NAME) + ) + } +) +public class DuplicatePersistenceUnitNameTest { @Test - public void testDuplicatePersistenceUnitNameLogAWarnMessage() { + public void testDuplicatePersistenceUnitNameLogAWarnMessage(LoggingInspectionsScope scope) { PersistenceXmlParser.create().parse( List.of( findAsResource( "org/hibernate/jpa/test/persistenceunit/META-INF/persistence.xml" ), findAsResource( "org/hibernate/jpa/test/persistenceunit/META-INF/persistenceUnitForNameDuplicationTest.xml" ) ) ); - assertTrue( "The warn HHH015018 has not been logged ", triggerable.wasTriggered() ); + assertTrue( scope.getWatcher( "HHH008518", JpaLogger.NAME ).wasTriggered(), + "The warning HHH015018 was not logged" ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/persistenceunit/ExcludeUnlistedClassesTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/persistenceunit/ExcludeUnlistedClassesTest.java index b5c3144797c2..15ad90c5d37a 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/persistenceunit/ExcludeUnlistedClassesTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/persistenceunit/ExcludeUnlistedClassesTest.java @@ -5,8 +5,8 @@ package org.hibernate.orm.test.jpa.persistenceunit; import static org.hibernate.internal.util.ConfigHelper.findAsResource; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; import java.util.Collection; import java.util.List; @@ -14,12 +14,11 @@ import org.hibernate.jpa.boot.spi.PersistenceUnitDescriptor; import org.hibernate.jpa.boot.spi.PersistenceXmlParser; import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseUnitTestCase; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * HHH-8364 discusses the use of within Java SE environments. It was intended for Java EE - * only, but was probably supported in Java SE/Hibernate for user friendliness. If we are going to supports its use + * only, but was probably supported in Java SE/Hibernate for user-friendliness. If we are going to supports its use * like that, the following should happen: * * Omitted == do scan @@ -35,7 +34,7 @@ * @author Brett Meyer */ @JiraKey(value = "HHH-8364") -public class ExcludeUnlistedClassesTest extends BaseUnitTestCase { +public class ExcludeUnlistedClassesTest { @Test public void testExcludeUnlistedClasses() { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/persistenceunit/PersistenceXmlParserTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/persistenceunit/PersistenceXmlParserTest.java index 2a628e759d7c..41756f79f49e 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/persistenceunit/PersistenceXmlParserTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/persistenceunit/PersistenceXmlParserTest.java @@ -13,9 +13,7 @@ import org.hibernate.testing.orm.junit.JiraKey; import org.junit.jupiter.api.Test; -import java.io.IOException; import java.net.URL; -import java.util.Arrays; import java.util.Collections; import java.util.Enumeration; import java.util.List; @@ -30,7 +28,7 @@ public class PersistenceXmlParserTest { @Test public void create_classLoaders() { var parser = PersistenceXmlParser.create( - Map.of( AvailableSettings.CLASSLOADERS, Arrays.asList( new TestClassLoader( "pu1" ) ) ), + Map.of( AvailableSettings.CLASSLOADERS, List.of( new TestClassLoader( "pu1" ) ) ), new TestClassLoader( "pu2" ), null ); @@ -45,7 +43,7 @@ public void create_classLoaderService() { var myClassLoaderService = new ClassLoaderServiceImpl( new TestClassLoader( "pu3" ) ); var parser = PersistenceXmlParser.create( // Should be ignored - Map.of( AvailableSettings.CLASSLOADERS, Arrays.asList( new TestClassLoader( "pu1" ) ) ), + Map.of( AvailableSettings.CLASSLOADERS, List.of( new TestClassLoader( "pu1" ) ) ), // Should be ignored new TestClassLoader( "pu2" ), myClassLoaderService @@ -111,7 +109,7 @@ public TestClassLoader(String resourceName) { } @Override - protected Enumeration findResources(String name) throws IOException { + protected Enumeration findResources(String name) { return name.equals( "META-INF/persistence.xml" ) ? Collections.enumeration( List.of( url ) ) : Collections.emptyEnumeration(); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/persistenceunit/TwoPersistenceUnits2LCDisabledEnabled.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/persistenceunit/TwoPersistenceUnits2LCDisabledEnabled.java deleted file mode 100644 index 3a610400a7e7..000000000000 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/persistenceunit/TwoPersistenceUnits2LCDisabledEnabled.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * SPDX-License-Identifier: Apache-2.0 - * Copyright Red Hat Inc. and Hibernate Authors - */ -package org.hibernate.orm.test.jpa.persistenceunit; - -import java.util.Collections; -import java.util.Map; -import jakarta.persistence.Cacheable; -import jakarta.persistence.Entity; -import jakarta.persistence.Id; -import jakarta.persistence.SharedCacheMode; - -import org.hibernate.cfg.AvailableSettings; -import org.hibernate.cfg.Environment; -import org.hibernate.engine.spi.SessionFactoryImplementor; -import org.hibernate.jpa.boot.spi.Bootstrap; -import org.hibernate.jpa.boot.spi.EntityManagerFactoryBuilder; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; -import org.hibernate.persister.entity.EntityPersister; - -import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.util.ServiceRegistryUtil; -import org.junit.Test; - -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; - -/** - * @author Gail Badner - */ -public class TwoPersistenceUnits2LCDisabledEnabled { - - @Test - @JiraKey( value = "HHH-11516" ) - public void testDisabledEnabled() { - final Map config = Environment.getProperties(); - config.put( AvailableSettings.LOADED_CLASSES, Collections.singletonList( AnEntity.class ) ); - config.put( "javax.persistence.sharedCache.mode", SharedCacheMode.ENABLE_SELECTIVE ); - config.put( AvailableSettings.USE_SECOND_LEVEL_CACHE, "false" ); - ServiceRegistryUtil.applySettings( config ); - - testIt( config ); - - config.put( AvailableSettings.USE_SECOND_LEVEL_CACHE, "true" ); - - testIt( config ); - } - - private void testIt(Map config) { - EntityManagerFactoryBuilder entityManagerFactoryBuilder = Bootstrap.getEntityManagerFactoryBuilder( - new BaseEntityManagerFunctionalTestCase.TestingPersistenceUnitDescriptorImpl( getClass().getSimpleName() ), - config - ); - SessionFactoryImplementor sf = entityManagerFactoryBuilder.build().unwrap( SessionFactoryImplementor.class ); - final EntityPersister persister = sf.getMappingMetamodel().getEntityDescriptor( AnEntity.class.getName() ); - - try { - if ( config.get( AvailableSettings.USE_SECOND_LEVEL_CACHE ).equals( "true" ) ) { - assertNotNull( persister.getCacheAccessStrategy() ); - } - else { - assertNull( persister.getCacheAccessStrategy() ); - } - } - finally { - sf.close(); - } - } - - - @Cacheable - @Entity( name = "AnEntity" ) - public static class AnEntity { - @Id - private Long id; - } -} diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/persistenceunit/TwoPersistenceUnits2LCDisabledEnabledTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/persistenceunit/TwoPersistenceUnits2LCDisabledEnabledTest.java new file mode 100644 index 000000000000..8a25c40fb795 --- /dev/null +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/persistenceunit/TwoPersistenceUnits2LCDisabledEnabledTest.java @@ -0,0 +1,89 @@ +/* + * SPDX-License-Identifier: Apache-2.0 + * Copyright Red Hat Inc. and Hibernate Authors + */ +package org.hibernate.orm.test.jpa.persistenceunit; + +import java.util.List; +import jakarta.persistence.Cacheable; +import jakarta.persistence.Entity; +import jakarta.persistence.Id; + +import org.hibernate.cfg.AvailableSettings; +import org.hibernate.cfg.CacheSettings; +import org.hibernate.engine.spi.SessionFactoryImplementor; +import org.hibernate.persister.entity.EntityPersister; + +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.JiraKey; +import org.hibernate.testing.orm.junit.Jpa; +import org.hibernate.testing.orm.junit.Setting; +import org.hibernate.testing.orm.junit.SettingProvider; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; + +/** + * @author Gail Badner + */ +public class TwoPersistenceUnits2LCDisabledEnabledTest { + + @Test + @JiraKey( value = "HHH-11516" ) + @Jpa( + annotatedClasses = {TwoPersistenceUnits2LCDisabledEnabledTest.AnEntity.class}, + integrationSettings = { + @Setting(name = CacheSettings.JAKARTA_SHARED_CACHE_MODE, value = "ENABLE_SELECTIVE"), + @Setting(name = AvailableSettings.USE_SECOND_LEVEL_CACHE, value = "true") + }, + settingProviders = { + @SettingProvider( + settingName = AvailableSettings.LOADED_CLASSES, + provider = LoadedClassesSettingProvider.class + ) + } + ) + public void testEnabled(EntityManagerFactoryScope scope) { + final EntityPersister persister = + scope.getEntityManagerFactory().unwrap( SessionFactoryImplementor.class ) + .getMappingMetamodel().getEntityDescriptor( AnEntity.class ); + assertNotNull( persister.getCacheAccessStrategy() ); + } + + @Test + @JiraKey( value = "HHH-11516" ) + @Jpa( + annotatedClasses = {TwoPersistenceUnits2LCDisabledEnabledTest.AnEntity.class}, + integrationSettings = { + @Setting(name = CacheSettings.JAKARTA_SHARED_CACHE_MODE, value = "ENABLE_SELECTIVE"), + @Setting(name = AvailableSettings.USE_SECOND_LEVEL_CACHE, value = "false") + }, + settingProviders = { + @SettingProvider( + settingName = AvailableSettings.LOADED_CLASSES, + provider = LoadedClassesSettingProvider.class + ) + } + ) + public void testDisabled(EntityManagerFactoryScope scope) { + final EntityPersister persister = + scope.getEntityManagerFactory().unwrap( SessionFactoryImplementor.class ) + .getMappingMetamodel().getEntityDescriptor( AnEntity.class ); + assertNull( persister.getCacheAccessStrategy() ); + } + + public static class LoadedClassesSettingProvider implements SettingProvider.Provider>> { + @Override + public List> getSetting() { + return List.of(AnEntity.class); + } + } + + @Cacheable + @Entity( name = "AnEntity" ) + public static class AnEntity { + @Id + private Long id; + } +} diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/procedure/AbstractStoredProcedureTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/procedure/AbstractStoredProcedureTest.java index 31f892238c42..63f4324faac3 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/procedure/AbstractStoredProcedureTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/procedure/AbstractStoredProcedureTest.java @@ -8,82 +8,80 @@ import org.hibernate.engine.spi.SessionFactoryImplementor; import org.hibernate.engine.spi.SharedSessionContractImplementor; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; import org.hibernate.procedure.internal.NamedCallableQueryMementoImpl; import org.hibernate.procedure.spi.NamedCallableQueryMemento; import org.hibernate.procedure.spi.ParameterStrategy; import org.hibernate.procedure.spi.ProcedureParameterImplementor; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; import org.hibernate.type.BasicType; import org.hibernate.type.descriptor.java.IntegerJavaType; import org.hibernate.type.descriptor.java.LongJavaType; import org.hibernate.type.descriptor.java.StringJavaType; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import jakarta.persistence.EntityManager; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; /** * @author Strong Liu */ -public abstract class AbstractStoredProcedureTest extends BaseEntityManagerFunctionalTestCase { +public abstract class AbstractStoredProcedureTest { @Test - public void testNamedStoredProcedureBinding() { - EntityManager em = getOrCreateEntityManager(); - SessionFactoryImplementor sf = em.getEntityManagerFactory().unwrap( SessionFactoryImplementor.class ); - final NamedCallableQueryMementoImpl m1 = (NamedCallableQueryMementoImpl) sf.getQueryEngine() - .getNamedObjectRepository() - .getCallableQueryMemento( "s1" ); - assertNotNull( m1 ); - assertEquals( "p1", m1.getCallableName() ); - assertEquals( ParameterStrategy.NAMED, m1.getParameterStrategy() ); - List list = m1.getParameterMementos(); - assertEquals( 2, list.size() ); - NamedCallableQueryMemento.ParameterMemento memento = list.get( 0 ); - ProcedureParameterImplementor parameterImplementor = memento.resolve( (SharedSessionContractImplementor) em ); - assertEquals( "p11", parameterImplementor.getName() ); - assertEquals( jakarta.persistence.ParameterMode.IN, parameterImplementor.getMode() ); - BasicType hibernateType = (BasicType) parameterImplementor.getHibernateType(); - assertEquals( IntegerJavaType.INSTANCE, hibernateType.getJavaTypeDescriptor() ); - assertEquals( Integer.class, parameterImplementor.getParameterType() ); - - memento = list.get( 1 ); - parameterImplementor = memento.resolve( (SharedSessionContractImplementor) em ); - assertEquals( "p12", parameterImplementor.getName() ); - assertEquals( jakarta.persistence.ParameterMode.IN, parameterImplementor.getMode() ); - hibernateType = (BasicType) parameterImplementor.getHibernateType(); - assertEquals( IntegerJavaType.INSTANCE, hibernateType.getJavaTypeDescriptor() ); - assertEquals( Integer.class, parameterImplementor.getParameterType() ); + public void testNamedStoredProcedureBinding(EntityManagerFactoryScope scope) { + scope.inEntityManager( em -> { + SessionFactoryImplementor sf = em.getEntityManagerFactory().unwrap( SessionFactoryImplementor.class ); + final NamedCallableQueryMementoImpl m1 = (NamedCallableQueryMementoImpl) sf.getQueryEngine() + .getNamedObjectRepository() + .getCallableQueryMemento( "s1" ); + assertNotNull( m1 ); + assertEquals( "p1", m1.getCallableName() ); + assertEquals( ParameterStrategy.NAMED, m1.getParameterStrategy() ); + List list = m1.getParameterMementos(); + assertEquals( 2, list.size() ); + NamedCallableQueryMemento.ParameterMemento memento = list.get( 0 ); + ProcedureParameterImplementor parameterImplementor = memento.resolve( (SharedSessionContractImplementor) em ); + assertEquals( "p11", parameterImplementor.getName() ); + assertEquals( jakarta.persistence.ParameterMode.IN, parameterImplementor.getMode() ); + BasicType hibernateType = (BasicType) parameterImplementor.getHibernateType(); + assertEquals( IntegerJavaType.INSTANCE, hibernateType.getJavaTypeDescriptor() ); + assertEquals( Integer.class, parameterImplementor.getParameterType() ); + memento = list.get( 1 ); + parameterImplementor = memento.resolve( (SharedSessionContractImplementor) em ); + assertEquals( "p12", parameterImplementor.getName() ); + assertEquals( jakarta.persistence.ParameterMode.IN, parameterImplementor.getMode() ); + hibernateType = (BasicType) parameterImplementor.getHibernateType(); + assertEquals( IntegerJavaType.INSTANCE, hibernateType.getJavaTypeDescriptor() ); + assertEquals( Integer.class, parameterImplementor.getParameterType() ); - final NamedCallableQueryMementoImpl m2 = (NamedCallableQueryMementoImpl) sf.getQueryEngine() - .getNamedObjectRepository() - .getCallableQueryMemento( "s2" ); - assertNotNull( m2 ); - assertEquals( "p2", m2.getCallableName() ); - assertEquals( ParameterStrategy.POSITIONAL, m2.getParameterStrategy() ); - list = m2.getParameterMementos(); + final NamedCallableQueryMementoImpl m2 = (NamedCallableQueryMementoImpl) sf.getQueryEngine() + .getNamedObjectRepository() + .getCallableQueryMemento( "s2" ); + assertNotNull( m2 ); + assertEquals( "p2", m2.getCallableName() ); + assertEquals( ParameterStrategy.POSITIONAL, m2.getParameterStrategy() ); + list = m2.getParameterMementos(); - memento = list.get( 0 ); - parameterImplementor = memento.resolve( (SharedSessionContractImplementor) em ); - assertEquals( Integer.valueOf( 1 ), parameterImplementor.getPosition() ); - assertEquals( jakarta.persistence.ParameterMode.INOUT, parameterImplementor.getMode() ); - hibernateType = (BasicType) parameterImplementor.getHibernateType(); + memento = list.get( 0 ); + parameterImplementor = memento.resolve( (SharedSessionContractImplementor) em ); + assertEquals( Integer.valueOf( 1 ), parameterImplementor.getPosition() ); + assertEquals( jakarta.persistence.ParameterMode.INOUT, parameterImplementor.getMode() ); + hibernateType = (BasicType) parameterImplementor.getHibernateType(); - assertEquals( StringJavaType.INSTANCE, hibernateType.getJavaTypeDescriptor() ); - assertEquals( String.class, parameterImplementor.getParameterType() ); + assertEquals( StringJavaType.INSTANCE, hibernateType.getJavaTypeDescriptor() ); + assertEquals( String.class, parameterImplementor.getParameterType() ); - memento = list.get( 1 ); - parameterImplementor = memento.resolve( (SharedSessionContractImplementor) em ); + memento = list.get( 1 ); + parameterImplementor = memento.resolve( (SharedSessionContractImplementor) em ); - assertEquals( Integer.valueOf( 2 ), parameterImplementor.getPosition() ); - assertEquals( jakarta.persistence.ParameterMode.INOUT, parameterImplementor.getMode() ); - hibernateType = (BasicType) parameterImplementor.getHibernateType(); + assertEquals( Integer.valueOf( 2 ), parameterImplementor.getPosition() ); + assertEquals( jakarta.persistence.ParameterMode.INOUT, parameterImplementor.getMode() ); + hibernateType = (BasicType) parameterImplementor.getHibernateType(); - assertEquals( LongJavaType.INSTANCE, hibernateType.getJavaTypeDescriptor() ); - assertEquals( Long.class, parameterImplementor.getParameterType() ); + assertEquals( LongJavaType.INSTANCE, hibernateType.getJavaTypeDescriptor() ); + assertEquals( Long.class, parameterImplementor.getParameterType() ); + } ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/procedure/AnnotationTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/procedure/AnnotationTest.java index 3e59c0eb2084..7c56158675b6 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/procedure/AnnotationTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/procedure/AnnotationTest.java @@ -5,12 +5,11 @@ package org.hibernate.orm.test.jpa.procedure; +import org.hibernate.testing.orm.junit.Jpa; + /** * @author Strong Liu */ +@Jpa(annotatedClasses = {User.class}) public class AnnotationTest extends AbstractStoredProcedureTest { - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { User.class }; - } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/procedure/H2StoreProcedureTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/procedure/H2StoreProcedureTest.java index 8a8a8cf54d1d..33c585121b9e 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/procedure/H2StoreProcedureTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/procedure/H2StoreProcedureTest.java @@ -29,8 +29,8 @@ import static org.hamcrest.core.Is.is; import static org.hamcrest.core.IsNot.not; import static org.hamcrest.core.IsNull.nullValue; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Andrea Boriero @@ -71,7 +71,7 @@ public static ResultSet getAllEntities(Connection conn) throws SQLException { } public static ResultSet entityById(Connection conn, long id) throws SQLException { - return conn.createStatement().executeQuery( "select * from MY_ENTITY where id = " + Long.toString( id ) ); + return conn.createStatement().executeQuery( "select * from MY_ENTITY where id = " + id ); } @Test diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/procedure/HSQLStoreProcedureTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/procedure/HSQLStoreProcedureTest.java index b974ec02b09e..46414414b3b0 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/procedure/HSQLStoreProcedureTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/procedure/HSQLStoreProcedureTest.java @@ -5,7 +5,6 @@ package org.hibernate.orm.test.jpa.procedure; import jakarta.persistence.Entity; -import jakarta.persistence.EntityManager; import jakarta.persistence.EntityManagerFactory; import jakarta.persistence.GeneratedValue; import jakarta.persistence.Id; @@ -25,150 +24,117 @@ import org.hibernate.engine.jdbc.connections.spi.JdbcConnectionAccess; import org.hibernate.engine.jdbc.spi.JdbcServices; import org.hibernate.engine.spi.SessionFactoryImplementor; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import org.hibernate.testing.RequiresDialect; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.RequiresDialect; import org.hibernate.testing.orm.junit.JiraKey; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; import static org.hamcrest.core.IsNot.not; import static org.hamcrest.core.IsNull.nullValue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Andrea Boriero */ @RequiresDialect(value = HSQLDialect.class) -public class HSQLStoreProcedureTest extends BaseEntityManagerFunctionalTestCase { - EntityManagerFactory entityManagerFactory; +@Jpa(annotatedClasses = {HSQLStoreProcedureTest.User.class}) +public class HSQLStoreProcedureTest { - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] {User.class}; + @BeforeEach + public void startUp(EntityManagerFactoryScope scope) { + createProcedures( scope.getEntityManagerFactory() ); } - @Before - public void startUp() { - entityManagerFactory = getOrCreateEntityManager().getEntityManagerFactory(); - - createProcedures( entityManagerFactory ); - } - - @After - public void tearDown() { - dropProcedures( entityManagerFactory ); + @AfterEach + public void tearDown(EntityManagerFactoryScope scope) { + dropProcedures( scope.getEntityManagerFactory() ); } @Test @JiraKey(value = "HHH-10515") - public void testNamedStoredProcedureExecution() { - EntityManager em = entityManagerFactory.createEntityManager(); - try { - StoredProcedureQuery query = em.createNamedStoredProcedureQuery( "User.inoutproc" ); + public void testNamedStoredProcedureExecution(EntityManagerFactoryScope scope) { + scope.inEntityManager( em -> { + final StoredProcedureQuery query = em.createNamedStoredProcedureQuery( "User.inoutproc" ); query.setParameter( "arg1", 1 ); query.execute(); - } - finally { - em.close(); - } + } ); } @Test @JiraKey(value = "HHH-10915") - public void testGetNamedParameters() { - EntityManager em = entityManagerFactory.createEntityManager(); - try { - StoredProcedureQuery query = em.createNamedStoredProcedureQuery( "User.inoutproc" ); + public void testGetNamedParameters(EntityManagerFactoryScope scope) { + scope.inEntityManager( em -> { + final StoredProcedureQuery query = em.createNamedStoredProcedureQuery( "User.inoutproc" ); final Set> parameters = query.getParameters(); assertThat( parameters.size(), is( 2 ) ); assertThat( query.getParameter( "arg1" ), not( nullValue() ) ); assertThat( query.getParameter( "res" ), not( nullValue() ) ); assertThat( query.getParameter( "arg1", Integer.class ), not( nullValue() ) ); - try { - query.getParameter( "arg1", String.class ); - fail( "An IllegalArgumentException is expected, A parameter with name arg1 and type String does not exist" ); - } - catch (IllegalArgumentException iae) { - //expected - } - try { - query.getParameter( "arg2" ); - fail( "An IllegalArgumentException is expected, A parameter with name arg2 does not exist" ); - } - catch (IllegalArgumentException iae) { - //expected - } - } - finally { - em.close(); - } + assertThrows( + IllegalArgumentException.class, + () -> query.getParameter( "arg1", String.class ), + "An IllegalArgumentException is expected, A parameter with name arg1 and type String does not exist" + ); + + assertThrows( + IllegalArgumentException.class, + () -> query.getParameter( "arg2" ), + "An IllegalArgumentException is expected, A parameter with name arg2 does not exist" + ); + } ); } @Test @JiraKey(value = "HHH-10915") - public void testGetPositionalParameters() { - EntityManager em = entityManagerFactory.createEntityManager(); - try { - StoredProcedureQuery query = em.createNamedStoredProcedureQuery( "User.inoutproc" ); + public void testGetPositionalParameters(EntityManagerFactoryScope scope) { + scope.inEntityManager( em -> { + final StoredProcedureQuery query = em.createNamedStoredProcedureQuery( "User.inoutproc" ); final Set> parameters = query.getParameters(); assertThat( parameters.size(), is( 2 ) ); - try { - query.getParameter( 1 ); - fail( "An IllegalArgumentException is expected, The stored procedure has named parameters not positional" ); - } - catch (IllegalArgumentException iae) { - //expected - } - try { - query.getParameter( 1, String.class ); - fail( "An IllegalArgumentException is expected, The stored procedure has named parameters not positional" ); - } - catch (IllegalArgumentException iae) { - //expected - } - } - finally { - em.close(); - } + assertThrows( + IllegalArgumentException.class, + () -> query.getParameter( 1 ), + "An IllegalArgumentException is expected, The stored procedure has named parameters not positional" + ); + + assertThrows( + IllegalArgumentException.class, + () -> query.getParameter( 1, String.class ), + "An IllegalArgumentException is expected, The stored procedure has named parameters not positional" + ); + } ); } @Test @JiraKey(value = "HHH-10915") - public void testGetPositionalParameters2() { - EntityManager em = entityManagerFactory.createEntityManager(); - try { + public void testGetPositionalParameters2(EntityManagerFactoryScope scope) { + scope.inEntityManager( em -> { StoredProcedureQuery query = em.createNamedStoredProcedureQuery( "User.inoutprocpositional" ); final Set> parameters = query.getParameters(); assertThat( parameters.size(), is( 2 ) ); assertThat( query.getParameter( 1 ), not( nullValue() ) ); assertThat( query.getParameter( 2 ), not( nullValue() ) ); assertThat( query.getParameter( 1, Integer.class ), not( nullValue() ) ); - try { - query.getParameter( 3 ); - fail( "An IllegalArgumentException is expected, A parameter at position 3 does not exist" ); - } - catch (IllegalArgumentException iae) { - //expected - } - - try { - query.getParameter( 1, String.class ); - fail( "An IllegalArgumentException is expected, The parameter at position 1 is of type Integer not String" ); - } - catch (IllegalArgumentException iae) { - //expected - } - - } - finally { - em.close(); - } + assertThrows( + IllegalArgumentException.class, + () -> query.getParameter( 3 ), + "An IllegalArgumentException is expected, A parameter at position 3 does not exist" + ); + + assertThrows( + IllegalArgumentException.class, + () -> query.getParameter( 1, String.class ), + "An IllegalArgumentException is expected, The parameter at position 1 is of type Integer not String" + ); + } ); } private void createProcedures(EntityManagerFactory emf) { @@ -238,8 +204,7 @@ public void executeStatement(EntityManagerFactory emf, String toExecute) { } ) @Table(name = "USERS") - public class User { - + public static class User { @Id @GeneratedValue private Integer id; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/procedure/OrmTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/procedure/OrmTest.java index c64c565e4b3f..677d01b8b268 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/procedure/OrmTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/procedure/OrmTest.java @@ -4,12 +4,11 @@ */ package org.hibernate.orm.test.jpa.procedure; +import org.hibernate.testing.orm.junit.Jpa; + /** * @author Strong Liu */ +@Jpa(xmlMappings = {"org/hibernate/jpa/test/procedure/orm.xml"}) public class OrmTest extends AbstractStoredProcedureTest{ - @Override - public String[] getEjb3DD() { - return new String[]{"org/hibernate/jpa/test/procedure/orm.xml"}; - } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/procedure/StoreProcedureOutParameterByNameTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/procedure/StoreProcedureOutParameterByNameTest.java index ab2b7f7c0205..c27b4e1f079b 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/procedure/StoreProcedureOutParameterByNameTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/procedure/StoreProcedureOutParameterByNameTest.java @@ -9,7 +9,6 @@ import java.sql.Statement; import jakarta.persistence.Column; import jakarta.persistence.Entity; -import jakarta.persistence.EntityManager; import jakarta.persistence.EntityManagerFactory; import jakarta.persistence.Id; import jakarta.persistence.NamedStoredProcedureQueries; @@ -19,20 +18,21 @@ import jakarta.persistence.StoredProcedureQuery; import jakarta.persistence.Table; -import org.junit.Before; -import org.junit.Test; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.RequiresDialect; +import org.hibernate.testing.orm.junit.JiraKey; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.hibernate.dialect.OracleDialect; import org.hibernate.engine.jdbc.connections.spi.JdbcConnectionAccess; import org.hibernate.engine.jdbc.spi.JdbcServices; import org.hibernate.engine.spi.SessionFactoryImplementor; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; - -import org.hibernate.testing.RequiresDialect; -import org.hibernate.testing.orm.junit.JiraKey; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Andrea Boriero @@ -40,67 +40,60 @@ */ @JiraKey(value = "HHH-10756") @RequiresDialect(OracleDialect.class) -public class StoreProcedureOutParameterByNameTest extends BaseEntityManagerFunctionalTestCase { - EntityManagerFactory entityManagerFactory; +@Jpa( annotatedClasses = StoreProcedureOutParameterByNameTest.User.class) +public class StoreProcedureOutParameterByNameTest { - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] {User.class}; + @BeforeEach + public void startUp(EntityManagerFactoryScope scope) { + createProcedures( scope.getEntityManagerFactory() ); } - @Before - public void startUp() { - entityManagerFactory = getOrCreateEntityManager().getEntityManagerFactory(); - - createProcedures( entityManagerFactory ); + @AfterEach + public void cleanup(EntityManagerFactoryScope scope) { + scope.inTransaction( em -> { + em.createQuery( "delete from User" ).executeUpdate(); + } + ); } @Test - public void testOneBasicOutParameter() { - EntityManager em = entityManagerFactory.createEntityManager(); - em.getTransaction().begin(); - User user = new User(); - user.id = 1; - user.name = "aName"; - em.persist( user ); - em.getTransaction().commit(); + public void testOneBasicOutParameter(EntityManagerFactoryScope scope) { + scope.inEntityManager( em -> { + em.getTransaction().begin(); + User user = new User(); + user.id = 1; + user.name = "aName"; + em.persist( user ); + em.getTransaction().commit(); - em.clear(); + em.clear(); - try { StoredProcedureQuery query = em.createNamedStoredProcedureQuery( "User.findNameById" ); query.setParameter( "ID_PARAM", 1 ); assertEquals( "aName", query.getOutputParameterValue( "NAME_PARAM" ) ); - } - finally { - em.close(); - } + } ); } @Test - public void testTwoBasicOutParameters() { - EntityManager em = entityManagerFactory.createEntityManager(); - em.getTransaction().begin(); - User user = new User(); - user.id = 1; - user.name = "aName"; - user.age = 29; - em.persist( user ); - em.getTransaction().commit(); - - em.clear(); + public void testTwoBasicOutParameters(EntityManagerFactoryScope scope) { + scope.inEntityManager( em -> { + em.getTransaction().begin(); + User user = new User(); + user.id = 1; + user.name = "aName"; + user.age = 29; + em.persist( user ); + em.getTransaction().commit(); + + em.clear(); - try { StoredProcedureQuery query = em.createNamedStoredProcedureQuery( "User.findNameAndAgeById" ); query.setParameter( "ID_PARAM", 1 ); assertEquals( "aName", query.getOutputParameterValue( "NAME_PARAM" ) ); assertEquals( 29, query.getOutputParameterValue( "AGE_PARAM" ) ); - } - finally { - em.close(); - } + } ); } private void createProcedures(EntityManagerFactory emf) { @@ -190,7 +183,7 @@ private void createProcedure(EntityManagerFactory emf, String storedProc) { ) } ) - @Entity(name = "Message") + @Entity(name = "User") @Table(name = "USERS") public static class User { @Id diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/procedure/StoreProcedureOutParameterByPositionTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/procedure/StoreProcedureOutParameterByPositionTest.java index 4778bcf5a865..b4ba7197b394 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/procedure/StoreProcedureOutParameterByPositionTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/procedure/StoreProcedureOutParameterByPositionTest.java @@ -9,7 +9,6 @@ import java.sql.Statement; import jakarta.persistence.Column; import jakarta.persistence.Entity; -import jakarta.persistence.EntityManager; import jakarta.persistence.EntityManagerFactory; import jakarta.persistence.Id; import jakarta.persistence.NamedStoredProcedureQueries; @@ -19,20 +18,21 @@ import jakarta.persistence.StoredProcedureQuery; import jakarta.persistence.Table; -import org.junit.Before; -import org.junit.Test; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.RequiresDialect; +import org.hibernate.testing.orm.junit.JiraKey; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.hibernate.dialect.OracleDialect; import org.hibernate.engine.jdbc.connections.spi.JdbcConnectionAccess; import org.hibernate.engine.jdbc.spi.JdbcServices; import org.hibernate.engine.spi.SessionFactoryImplementor; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; - -import org.hibernate.testing.RequiresDialect; -import org.hibernate.testing.orm.junit.JiraKey; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Andrea Boriero @@ -40,67 +40,60 @@ */ @JiraKey(value = "HHH-10756") @RequiresDialect(OracleDialect.class) -public class StoreProcedureOutParameterByPositionTest extends BaseEntityManagerFunctionalTestCase { - EntityManagerFactory entityManagerFactory; +@Jpa( annotatedClasses = StoreProcedureOutParameterByPositionTest.User.class) +public class StoreProcedureOutParameterByPositionTest { - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] {User.class}; + @BeforeEach + public void startUp(EntityManagerFactoryScope scope) { + createProcedures( scope.getEntityManagerFactory() ); } - @Before - public void startUp() { - entityManagerFactory = getOrCreateEntityManager().getEntityManagerFactory(); - - createProcedures( entityManagerFactory ); + @AfterEach + public void cleanup(EntityManagerFactoryScope scope) { + scope.inTransaction( em -> { + em.createQuery( "delete from User" ).executeUpdate(); + } + ); } @Test - public void testOneBasicOutParameter() { - EntityManager em = entityManagerFactory.createEntityManager(); - em.getTransaction().begin(); - User user = new User(); - user.id = 1; - user.name = "aName"; - em.persist( user ); - em.getTransaction().commit(); + public void testOneBasicOutParameter(EntityManagerFactoryScope scope) { + scope.inEntityManager( em -> { + em.getTransaction().begin(); + User user = new User(); + user.id = 1; + user.name = "aName"; + em.persist( user ); + em.getTransaction().commit(); - em.clear(); + em.clear(); - try { StoredProcedureQuery query = em.createNamedStoredProcedureQuery( "User.findNameById" ); query.setParameter( 1, 1 ); assertEquals( "aName", query.getOutputParameterValue( 2 ) ); - } - finally { - em.close(); - } + } ); } @Test - public void testTwoBasicOutParameters() { - EntityManager em = entityManagerFactory.createEntityManager(); - em.getTransaction().begin(); - User user = new User(); - user.id = 1; - user.name = "aName"; - user.age = 29; - em.persist( user ); - em.getTransaction().commit(); - - em.clear(); + public void testTwoBasicOutParameters(EntityManagerFactoryScope scope) { + scope.inEntityManager( em -> { + em.getTransaction().begin(); + User user = new User(); + user.id = 1; + user.name = "aName"; + user.age = 29; + em.persist( user ); + em.getTransaction().commit(); + + em.clear(); - try { StoredProcedureQuery query = em.createNamedStoredProcedureQuery( "User.findNameAndAgeById" ); query.setParameter( 1, 1 ); assertEquals( "aName", query.getOutputParameterValue( 2 ) ); assertEquals( 29, query.getOutputParameterValue( 3 ) ); - } - finally { - em.close(); - } + } ); } private void createProcedures(EntityManagerFactory emf) { @@ -191,7 +184,7 @@ private void createProcedure(EntityManagerFactory emf, String storedProc) { ) } ) - @Entity(name = "Message") + @Entity(name = "User") @Table(name = "USERS") public static class User { @Id diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/procedure/StoreProcedureRefCursorOutParameterByNameTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/procedure/StoreProcedureRefCursorOutParameterByNameTest.java index c664d82bdd89..07f47e43eeb1 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/procedure/StoreProcedureRefCursorOutParameterByNameTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/procedure/StoreProcedureRefCursorOutParameterByNameTest.java @@ -9,7 +9,6 @@ import java.sql.Statement; import jakarta.persistence.Column; import jakarta.persistence.Entity; -import jakarta.persistence.EntityManager; import jakarta.persistence.EntityManagerFactory; import jakarta.persistence.Id; import jakarta.persistence.NamedStoredProcedureQuery; @@ -22,47 +21,46 @@ import org.hibernate.engine.jdbc.connections.spi.JdbcConnectionAccess; import org.hibernate.engine.jdbc.spi.JdbcServices; import org.hibernate.engine.spi.SessionFactoryImplementor; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; -import org.hibernate.testing.RequiresDialect; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.RequiresDialect; import org.hibernate.testing.orm.junit.JiraKey; -import org.junit.Before; -import org.junit.Test; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Andrea Boriero */ @JiraKey(value = "HHH-9286") @RequiresDialect(OracleDialect.class) -public class StoreProcedureRefCursorOutParameterByNameTest extends BaseEntityManagerFunctionalTestCase { - EntityManagerFactory entityManagerFactory; +@Jpa( annotatedClasses = StoreProcedureRefCursorOutParameterByNameTest.User.class) +public class StoreProcedureRefCursorOutParameterByNameTest { - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] {User.class}; + @BeforeEach + public void startUp(EntityManagerFactoryScope scope) { + createProcedures( scope.getEntityManagerFactory() ); } - @Before - public void startUp() { - entityManagerFactory = getOrCreateEntityManager().getEntityManagerFactory(); - - createProcedures( entityManagerFactory ); + @AfterEach + public void cleanup(EntityManagerFactoryScope scope) { + scope.inTransaction( em -> { + em.createQuery( "delete from User" ).executeUpdate(); + } + ); } @Test - public void testNamedStoredProcedureExecution() { - EntityManager em = entityManagerFactory.createEntityManager(); - try { + public void testNamedStoredProcedureExecution(EntityManagerFactoryScope scope) { + scope.inEntityManager( em -> { StoredProcedureQuery query = em.createNamedStoredProcedureQuery( "User.findByName" ); query.setParameter( "USER_NAME_PARAM", "my_name" ); query.getResultList(); - } - finally { - em.close(); - } + } ); } private void createProcedures(EntityManagerFactory emf) { @@ -126,7 +124,7 @@ private void createProcedures(EntityManagerFactory emf) { @StoredProcedureParameter(mode = ParameterMode.REF_CURSOR, name = "CURSOR_PARAM", type = Class.class) } ) - @Entity(name = "Message") + @Entity(name = "User") @Table(name = "USERS") public static class User { @Id diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/procedure/StoreProcedureRefCursorOutParameterByPositionTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/procedure/StoreProcedureRefCursorOutParameterByPositionTest.java index d9b0238d748e..96a53b58f799 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/procedure/StoreProcedureRefCursorOutParameterByPositionTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/procedure/StoreProcedureRefCursorOutParameterByPositionTest.java @@ -9,7 +9,6 @@ import java.sql.Statement; import jakarta.persistence.Column; import jakarta.persistence.Entity; -import jakarta.persistence.EntityManager; import jakarta.persistence.EntityManagerFactory; import jakarta.persistence.Id; import jakarta.persistence.NamedStoredProcedureQuery; @@ -22,47 +21,46 @@ import org.hibernate.engine.jdbc.connections.spi.JdbcConnectionAccess; import org.hibernate.engine.jdbc.spi.JdbcServices; import org.hibernate.engine.spi.SessionFactoryImplementor; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; -import org.hibernate.testing.RequiresDialect; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.RequiresDialect; import org.hibernate.testing.orm.junit.JiraKey; -import org.junit.Before; -import org.junit.Test; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Andrea Boriero */ @JiraKey(value = "HHH-9286") @RequiresDialect(OracleDialect.class) -public class StoreProcedureRefCursorOutParameterByPositionTest extends BaseEntityManagerFunctionalTestCase { - EntityManagerFactory entityManagerFactory; +@Jpa( annotatedClasses = StoreProcedureRefCursorOutParameterByPositionTest.User.class) +public class StoreProcedureRefCursorOutParameterByPositionTest { - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] {User.class}; + @BeforeEach + public void startUp(EntityManagerFactoryScope scope) { + createProcedures( scope.getEntityManagerFactory() ); } - @Before - public void startUp() { - entityManagerFactory = getOrCreateEntityManager().getEntityManagerFactory(); - - createProcedures( entityManagerFactory ); + @AfterEach + public void cleanup(EntityManagerFactoryScope scope) { + scope.inTransaction( em -> { + em.createQuery( "delete from User" ).executeUpdate(); + } + ); } @Test - public void testNamedStoredProcedureExecution() { - EntityManager em = entityManagerFactory.createEntityManager(); - try { + public void testNamedStoredProcedureExecution(EntityManagerFactoryScope scope) { + scope.inEntityManager( em -> { StoredProcedureQuery query = em.createNamedStoredProcedureQuery( "User.findByName" ); query.setParameter( 1, "my_name" ); query.getResultList(); - } - finally { - em.close(); - } + } ); } private void createProcedures(EntityManagerFactory emf) { @@ -127,7 +125,7 @@ private void createProcedures(EntityManagerFactory emf) { @StoredProcedureParameter(mode = ParameterMode.REF_CURSOR, type = Class.class) } ) - @Entity(name = "Message") + @Entity(name = "User") @Table(name = "USERS") public static class User { @Id diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/procedure/StoredProcedureResultSetMappingTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/procedure/StoredProcedureResultSetMappingTest.java index f9a8288c6b6f..7cc2fac5ed15 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/procedure/StoredProcedureResultSetMappingTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/procedure/StoredProcedureResultSetMappingTest.java @@ -7,35 +7,35 @@ import jakarta.persistence.ColumnResult; import jakarta.persistence.ConstructorResult; import jakarta.persistence.Entity; -import jakarta.persistence.EntityManager; import jakarta.persistence.Id; import jakarta.persistence.SqlResultSetMapping; import jakarta.persistence.StoredProcedureQuery; import jakarta.persistence.Table; import jakarta.persistence.Temporal; import jakarta.persistence.TemporalType; -import java.sql.Connection; -import java.sql.SQLException; import java.util.Date; import java.util.List; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.dialect.H2Dialect; -import org.hibernate.jdbc.Work; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; -import org.junit.Test; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import org.hibernate.testing.RequiresDialect; +import org.hibernate.testing.orm.junit.RequiresDialect; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Steve Ebersole */ @RequiresDialect( H2Dialect.class ) -public class StoredProcedureResultSetMappingTest extends BaseEntityManagerFunctionalTestCase { +@Jpa(annotatedClasses = {StoredProcedureResultSetMappingTest.Employee.class}) +public class StoredProcedureResultSetMappingTest { @Entity( name = "Employee" ) @Table( name = "EMP" ) // ignore the questionable-ness of constructing a partial entity @@ -71,67 +71,45 @@ public Employee(Integer id, String firstName, String lastName) { } } - @Override - protected void afterEntityManagerFactoryBuilt() { - super.afterEntityManagerFactoryBuilt(); - - Session s = entityManagerFactory().unwrap( SessionFactory.class ).openSession(); + @BeforeEach + protected void setup(EntityManagerFactoryScope scope) { + Session s = scope.getEntityManagerFactory().unwrap( SessionFactory.class ).openSession(); s.doWork( - new Work() { - @Override - public void execute(Connection connection) throws SQLException { - connection.createStatement().execute( - "CREATE ALIAS allEmployeeNames AS $$\n" + - "import org.h2.tools.SimpleResultSet;\n" + - "import java.sql.*;\n" + - "@CODE\n" + - "ResultSet allEmployeeNames() {\n" + - " SimpleResultSet rs = new SimpleResultSet();\n" + - " rs.addColumn(\"ID\", Types.INTEGER, 10, 0);\n" + - " rs.addColumn(\"FIRSTNAME\", Types.VARCHAR, 255, 0);\n" + - " rs.addColumn(\"LASTNAME\", Types.VARCHAR, 255, 0);\n" + - " rs.addRow(1, \"Steve\", \"Ebersole\");\n" + - " rs.addRow(1, \"Jane\", \"Doe\");\n" + - " rs.addRow(1, \"John\", \"Doe\");\n" + - " return rs;\n" + - "}\n" + - "$$" - ); - } - } + connection -> connection.createStatement().execute( + """ + CREATE ALIAS allEmployeeNames AS $$ + import org.h2.tools.SimpleResultSet; + import java.sql.*; + @CODE + ResultSet allEmployeeNames() { + SimpleResultSet rs = new SimpleResultSet(); + rs.addColumn("ID", Types.INTEGER, 10, 0); + rs.addColumn("FIRSTNAME", Types.VARCHAR, 255, 0); + rs.addColumn("LASTNAME", Types.VARCHAR, 255, 0); + rs.addRow(1, "Steve", "Ebersole"); + rs.addRow(1, "Jane", "Doe"); + rs.addRow(1, "John", "Doe"); + return rs; + } + $$""" + ) ); - s.close(); } - @Override - public void releaseResources() { - Session s = entityManagerFactory().unwrap( SessionFactory.class ).openSession(); + @AfterEach + public void cleanup(EntityManagerFactoryScope scope) { + Session s = scope.getEntityManagerFactory().unwrap( SessionFactory.class ).openSession(); s.doWork( - new Work() { - @Override - public void execute(Connection connection) throws SQLException { - connection.createStatement().execute( "DROP ALIAS allEmployeeNames IF EXISTS" ); - } - } + connection -> connection.createStatement().execute( "DROP ALIAS allEmployeeNames IF EXISTS" ) ); - s.close(); - - super.releaseResources(); - } - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { Employee.class }; } @Test - public void testPartialResults() { - EntityManager em = getOrCreateEntityManager(); - em.getTransaction().begin(); - StoredProcedureQuery query = em.createStoredProcedureQuery( "allEmployeeNames", "id-fname-lname" ); - List results = query.getResultList(); - assertEquals( 3, results.size() ); - em.getTransaction().commit(); - em.close(); + public void testPartialResults(EntityManagerFactoryScope scope) { + scope.inTransaction( em -> { + StoredProcedureQuery query = em.createStoredProcedureQuery( "allEmployeeNames", "id-fname-lname" ); + List results = query.getResultList(); + assertEquals( 3, results.size() ); + } ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/proxy/JPAProxyTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/proxy/JPAProxyTest.java index 6e8377d79157..0787e79faea2 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/proxy/JPAProxyTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/proxy/JPAProxyTest.java @@ -9,14 +9,12 @@ import org.hibernate.orm.test.jpa.model.AbstractJPATest; import org.hibernate.orm.test.jpa.model.Item; import org.junit.jupiter.api.Test; -import junit.framework.AssertionFailedError; import jakarta.persistence.EntityNotFoundException; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.fail; - +import static org.junit.jupiter.api.Assertions.assertThrows; /** * Test relation between proxies and get()/load() processing @@ -30,34 +28,24 @@ public class JPAProxyTest extends AbstractJPATest { public void testEjb3ProxyUsage() { inTransaction( s -> { - Item item = s.getReference( Item.class, new Long( -1 ) ); + Item item = s.getReference( Item.class, -1L ); assertFalse( Hibernate.isInitialized( item ) ); - try { - Hibernate.initialize( item ); - fail( "proxy access did not fail on non-existent proxy" ); - } - catch (EntityNotFoundException e) { - // expected behavior - } - catch (Throwable t) { - fail( "unexpected exception type on non-existent proxy access : " + t ); - } + assertThrows( + EntityNotFoundException.class, + () -> Hibernate.initialize(item), + "proxy access did not fail on non-existent proxy" + ); s.clear(); - Item item2 = s.getReference( Item.class, new Long( -1 ) ); + Item item2 = s.getReference( Item.class, -1L ); assertFalse( Hibernate.isInitialized( item2 ) ); assertFalse( item == item2 ); - try { - item2.getName(); - fail( "proxy access did not fail on non-existent proxy" ); - } - catch (EntityNotFoundException e) { - // expected behavior - } - catch (Throwable t) { - fail( "unexpected exception type on non-existent proxy access : " + t ); - } + assertThrows( + EntityNotFoundException.class, + item2::getName, + "proxy access did not fail on non-existent proxy" + ); } ); } @@ -67,7 +55,7 @@ public void testEjb3ProxyUsage() { */ @Test public void testGetSemantics() { - Long nonExistentId = new Long( -1 ); + Long nonExistentId = -1L; inTransaction( session -> { Item item = session.get( Item.class, nonExistentId ); @@ -81,19 +69,11 @@ public void testGetSemantics() { Item item = s.getReference( Item.class, nonExistentId ); assertFalse( Hibernate.isInitialized( item ) ); // then try to get() it to make sure we get an exception - try { - s.get( Item.class, nonExistentId ); - fail( "force load did not fail on non-existent entity" ); - } - catch (EntityNotFoundException e) { - // expected behavior - } - catch (AssertionFailedError e) { - throw e; - } - catch (Throwable t) { - fail( "unexpected exception type on non-existent entity force load : " + t ); - } + assertThrows( + EntityNotFoundException.class, + () -> s.get( Item.class, nonExistentId ), + "force load did not fail on non-existent entity" + ); } ); } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/ql/NamedNativeQueryTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/ql/NamedNativeQueryTest.java index 01ade79af427..21cded380ad3 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/ql/NamedNativeQueryTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/ql/NamedNativeQueryTest.java @@ -9,175 +9,158 @@ import java.util.List; import org.hibernate.query.Query; -import org.hibernate.Session; import org.hibernate.dialect.MySQLDialect; import org.hibernate.dialect.SQLServerDialect; -import org.hibernate.testing.SkipForDialect; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; -import org.junit.After; -import org.junit.Test; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.hibernate.testing.orm.junit.SkipForDialect; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Janario Oliveira */ -public class NamedNativeQueryTest extends BaseCoreFunctionalTestCase { +@DomainModel(annotatedClasses = { FromEntity.class, DestinationEntity.class }) +@SessionFactory +public class NamedNativeQueryTest { - private FromEntity createFrom(String name, String lastName) { - Session session = openSession(); - session.getTransaction().begin(); + private FromEntity createFrom(SessionFactoryScope scope, String name, String lastName) { FromEntity fromEntity = new FromEntity( name, lastName ); - session.persist( fromEntity ); - session.getTransaction().commit(); - session.close(); + + scope.inTransaction( session -> session.persist( fromEntity ) ); + return fromEntity; } - private DestinationEntity createDestination(FromEntity fromEntity, String fullName) { + private DestinationEntity createDestination(SessionFactoryScope scope, FromEntity fromEntity, String fullName) { final DestinationEntity destinationEntity = new DestinationEntity( fromEntity, fullName ); - Session session = openSession(); - session.getTransaction().begin(); - session.persist( destinationEntity ); - session.getTransaction().commit(); - session.close(); + scope.inTransaction( session -> session.persist( destinationEntity ) ); + return destinationEntity; } - @SuppressWarnings("unchecked") - private List findDestinationByIds(List ids) { - Session session = openSession(); - List list = session - .createQuery( "from DestinationEntity de where de.id in (:ids) order by id" ) - .setParameterList( "ids", ids ).list(); - session.close(); - return list; + private List findDestinationByIds(SessionFactoryScope scope, List ids) { + return scope.fromSession( + session -> session + .createQuery( "from DestinationEntity de where de.id in (:ids) order by id", DestinationEntity.class ) + .setParameterList( "ids", ids ).list() ); } - @After - public void cleanup() { - Session session = openSession(); - session.getTransaction().begin(); - session.createQuery( "delete DestinationEntity" ).executeUpdate(); - session.createQuery( "delete FromEntity" ).executeUpdate(); - session.getTransaction().commit(); - session.close(); + @AfterEach + public void cleanup(SessionFactoryScope scope) { + scope.inTransaction( session -> scope.dropData() ); } @Test - public void testSingleSelect() { + public void testSingleSelect(SessionFactoryScope scope) { final String name = "Name"; final String lastName = "LastName"; final String fullName = name + " " + lastName; - final DestinationEntity destination = createDestination( createFrom( name, lastName ), fullName ); - - Session session = openSession(); - Query select = session.getNamedQuery( "DestinationEntity.selectIds" ); - select.setParameterList( "ids", Collections.singletonList( destination.id ) ); - Object[] unique = (Object[]) select.uniqueResult(); - session.close(); - - // Compare the Strings, not the actual IDs. Can come back as, for ex, - // a BigDecimal in Oracle. - assertEquals( destination.id + "", unique[0] + "" ); - assertEquals( destination.from.id + "", unique[1] + "" ); - assertEquals( destination.fullNameFrom, unique[2] ); + final DestinationEntity destination = createDestination( scope, createFrom( scope, name, lastName ), fullName ); + + scope.inSession( session -> { + Query select = session.getNamedQuery( "DestinationEntity.selectIds" ); + select.setParameterList( "ids", Collections.singletonList( destination.id ) ); + Object[] unique = (Object[]) select.uniqueResult(); + // Compare the Strings, not the actual IDs. Can come back as, for ex, + // a BigDecimal in Oracle. + assertEquals( destination.id + "", unique[0] + "" ); + assertEquals( destination.from.id + "", unique[1] + "" ); + assertEquals( destination.fullNameFrom, unique[2] ); + } ); } @Test - public void testMultipleSelect() { + public void testMultipleSelect(SessionFactoryScope scope) { final String name = "Name"; final String lastName = "LastName"; - final List ids = new ArrayList(); + final List ids = new ArrayList<>(); final int quantity = 10; - final List destinations = new ArrayList(); + final List destinations = new ArrayList<>(); for ( int i = 0; i < quantity; i++ ) { - DestinationEntity createDestination = createDestination( createFrom( name + i, lastName + i ), name + i + DestinationEntity createDestination = createDestination( scope, createFrom( scope, name + i, lastName + i ), name + i + lastName + i ); ids.add( createDestination.id ); destinations.add( createDestination ); } - Session session = openSession(); - Query select = session.getNamedQuery( "DestinationEntity.selectIds" ); - select.setParameterList( "ids", ids ); - List list = select.list(); - session.close(); - - assertEquals( quantity, list.size() ); - for ( int i = 0; i < list.size(); i++ ) { - Object[] object = (Object[]) list.get( i ); - DestinationEntity destination = destinations.get( i ); - // Compare the Strings, not the actual IDs. Can come back as, for ex, - // a BigDecimal in Oracle. - assertEquals( destination.id + "", object[0] + "" ); - assertEquals( destination.from.id + "", object[1] + "" ); - assertEquals( destination.fullNameFrom, object[2] ); - } + scope.inSession( session -> { + Query select = session.getNamedQuery( "DestinationEntity.selectIds" ); + select.setParameterList( "ids", ids ); + List list = select.list(); + + assertEquals( quantity, list.size() ); + for ( int i = 0; i < list.size(); i++ ) { + Object[] object = (Object[]) list.get( i ); + DestinationEntity destination = destinations.get( i ); + // Compare the Strings, not the actual IDs. Can come back as, for ex, + // a BigDecimal in Oracle. + assertEquals( destination.id + "", object[0] + "" ); + assertEquals( destination.from.id + "", object[1] + "" ); + assertEquals( destination.fullNameFrom, object[2] ); + } + } ); } @Test - public void testInsertSingleValue() { + public void testInsertSingleValue(SessionFactoryScope scope) { final String name = "Name"; final String lastName = "LastName"; final String fullName = name + " " + lastName; - final FromEntity fromEntity = createFrom( name, lastName ); + final FromEntity fromEntity = createFrom( scope, name, lastName ); final int id = 10000;// id fake - Session session = openSession(); - session.getTransaction().begin(); - Query insert = session.getNamedQuery( "DestinationEntity.insert" ); - insert.setParameter( "generatedId", id ); - insert.setParameter( "fromId", fromEntity.id ); - insert.setParameter( "fullName", fullName ); - int executeUpdate = insert.executeUpdate(); - assertEquals( 1, executeUpdate ); - session.getTransaction().commit(); - session.close(); - - session = openSession(); - DestinationEntity get = (DestinationEntity) session.get( DestinationEntity.class, id ); - session.close(); - - assertEquals( fromEntity, get.from ); - assertEquals( fullName, get.fullNameFrom ); + scope.inTransaction( session -> { + Query insert = session.getNamedQuery( "DestinationEntity.insert" ); + insert.setParameter( "generatedId", id ); + insert.setParameter( "fromId", fromEntity.id ); + insert.setParameter( "fullName", fullName ); + int executeUpdate = insert.executeUpdate(); + assertEquals( 1, executeUpdate ); + } ); + + scope.inSession( session -> { + DestinationEntity de = session.find( DestinationEntity.class, id ); + assertEquals( fromEntity, de.from ); + assertEquals( fullName, de.fullNameFrom ); + } ); } @Test - @SkipForDialect( value = MySQLDialect.class, comment = "MySQL appears to have trouble with fe.id selected twice in one statement") - @SkipForDialect( value = SQLServerDialect.class, comment = "SQL Server does not support the || operator.") + @SkipForDialect( dialectClass = MySQLDialect.class, matchSubTypes = true, reason = "MySQL appears to have trouble with fe.id selected twice in one statement") + @SkipForDialect( dialectClass = SQLServerDialect.class, reason = "SQL Server does not support the || operator.") // TODO: Re-form DestinationEntity.insertSelect to something more supported? - public void testInsertMultipleValues() { + public void testInsertMultipleValues(SessionFactoryScope scope) { final String name = "Name"; final String lastName = "LastName"; - final List ids = new ArrayList(); + final List ids = new ArrayList<>(); final int quantity = 10; - final List froms = new ArrayList(); + final List froms = new ArrayList<>(); for ( int i = 0; i < quantity; i++ ) { - FromEntity fe = createFrom( name + i, lastName + i ); + FromEntity fe = createFrom( scope, name + i, lastName + i ); froms.add( fe ); ids.add( fe.id ); } - Session session = openSession(); - session.getTransaction().begin(); - Query insertSelect = session.getNamedQuery( "DestinationEntity.insertSelect" ); - insertSelect.setParameterList( "ids", ids ); - int executeUpdate = insertSelect.executeUpdate(); - assertEquals( quantity, executeUpdate ); - - session.getTransaction().commit(); - session.close(); + scope.inTransaction( session -> { + Query insertSelect = session.getNamedQuery( "DestinationEntity.insertSelect" ); + insertSelect.setParameterList( "ids", ids ); + int executeUpdate = insertSelect.executeUpdate(); + assertEquals( quantity, executeUpdate ); + } ); - List list = findDestinationByIds( ids ); + List list = findDestinationByIds( scope, ids ); assertEquals( quantity, list.size() ); for ( int i = 0; i < quantity; i++ ) { - DestinationEntity de = (DestinationEntity) list.get( i ); + DestinationEntity de = list.get( i ); FromEntity from = froms.get( i ); assertEquals( from, de.from ); assertEquals( from.name + from.lastName, de.fullNameFrom ); @@ -185,75 +168,65 @@ public void testInsertMultipleValues() { } @Test - public void testUpdateSingleValue() { + public void testUpdateSingleValue(SessionFactoryScope scope) { final String name = "Name"; final String lastName = "LastName"; final String fullName = name + " " + lastName; - final FromEntity fromEntity = createFrom( name, lastName ); - final DestinationEntity destinationEntity = createDestination( fromEntity, fullName ); + final FromEntity fromEntity = createFrom( scope, name, lastName ); + final DestinationEntity destinationEntity = createDestination( scope, fromEntity, fullName ); final String inverseFullName = lastName + " " + name; - final FromEntity anotherFrom = createFrom( lastName, name ); + final FromEntity anotherFrom = createFrom( scope, lastName, name ); - Session session = openSession(); - session.getTransaction().begin(); - Query update = session.getNamedQuery( "DestinationEntity.update" ); - update.setParameter( "idFrom", anotherFrom.id ); - update.setParameter( "fullName", inverseFullName ); - update.setParameterList( "ids", Collections.singletonList( destinationEntity.id ) ); + scope.inTransaction( session -> { + Query update = session.getNamedQuery( "DestinationEntity.update" ); + update.setParameter( "idFrom", anotherFrom.id ); + update.setParameter( "fullName", inverseFullName ); + update.setParameterList( "ids", Collections.singletonList( destinationEntity.id ) ); - int executeUpdate = update.executeUpdate(); - assertEquals( 1, executeUpdate ); + int executeUpdate = update.executeUpdate(); + assertEquals( 1, executeUpdate ); + } ); - session.getTransaction().commit(); - session.close(); + scope.inTransaction( session -> { + DestinationEntity de = session.find( DestinationEntity.class, destinationEntity.id ); - session = openSession(); - session.beginTransaction(); - DestinationEntity get = (DestinationEntity) session.get( DestinationEntity.class, destinationEntity.id ); - - assertEquals( anotherFrom, get.from ); - assertEquals( inverseFullName, get.fullNameFrom ); - session.getTransaction().commit(); - session.close(); + assertEquals( anotherFrom, de.from ); + assertEquals( inverseFullName, de.fullNameFrom ); + } ); } @Test - public void testUpdateMultipleValues() { + public void testUpdateMultipleValues(SessionFactoryScope scope) { final String name = "Name"; final String lastName = "LastName"; - final List ids = new ArrayList(); + final List ids = new ArrayList<>(); final int quantity = 10; - final List destinations = new ArrayList(); for ( int i = 0; i < quantity; i++ ) { - FromEntity fe = createFrom( name + i, lastName + i ); - DestinationEntity destination = createDestination( fe, fe.name + fe.lastName ); - destinations.add( destination ); + FromEntity fe = createFrom( scope, name + i, lastName + i ); + DestinationEntity destination = createDestination( scope, fe, fe.name + fe.lastName ); ids.add( destination.id ); } final String inverseFullName = lastName + " " + name; - final FromEntity anotherFrom = createFrom( lastName, name ); - - Session session = openSession(); - session.getTransaction().begin(); - Query update = session.getNamedQuery( "DestinationEntity.update" ); - update.setParameter( "idFrom", anotherFrom.id ); - update.setParameter( "fullName", inverseFullName ); - update.setParameterList( "ids", ids ); + final FromEntity anotherFrom = createFrom( scope, lastName, name ); - int executeUpdate = update.executeUpdate(); - assertEquals( quantity, executeUpdate ); + scope.inTransaction( session -> { + Query update = session.getNamedQuery( "DestinationEntity.update" ); + update.setParameter( "idFrom", anotherFrom.id ); + update.setParameter( "fullName", inverseFullName ); + update.setParameterList( "ids", ids ); - session.getTransaction().commit(); - session.close(); + int executeUpdate = update.executeUpdate(); + assertEquals( quantity, executeUpdate ); + } ); - List list = findDestinationByIds( ids ); + List list = findDestinationByIds( scope, ids ); assertEquals( quantity, list.size() ); for ( int i = 0; i < quantity; i++ ) { - DestinationEntity updated = (DestinationEntity) list.get( i ); + DestinationEntity updated = list.get( i ); assertEquals( anotherFrom, updated.from ); assertEquals( inverseFullName, updated.fullNameFrom ); @@ -261,63 +234,50 @@ public void testUpdateMultipleValues() { } @Test - public void testDeleteSingleValue() { + public void testDeleteSingleValue(SessionFactoryScope scope) { final String name = "Name"; final String lastName = "LastName"; final String fullName = name + " " + lastName; - final FromEntity fromEntity = createFrom( name, lastName ); - final DestinationEntity destinationEntity = createDestination( fromEntity, fullName ); + final FromEntity fromEntity = createFrom( scope, name, lastName ); + final DestinationEntity destinationEntity = createDestination( scope, fromEntity, fullName ); - Session session = openSession(); - session.getTransaction().begin(); - Query delete = session.getNamedQuery( "DestinationEntity.delete" ); - delete.setParameterList( "ids", Collections.singletonList( destinationEntity.id ) ); + scope.inTransaction( session -> { + Query delete = session.getNamedQuery( "DestinationEntity.delete" ); + delete.setParameterList( "ids", Collections.singletonList( destinationEntity.id ) ); - int executeUpdate = delete.executeUpdate(); - assertEquals( 1, executeUpdate ); + int executeUpdate = delete.executeUpdate(); + assertEquals( 1, executeUpdate ); + } ); - session.getTransaction().commit(); - session.close(); - - session = openSession(); - DestinationEntity get = (DestinationEntity) session.get( DestinationEntity.class, destinationEntity.id ); - session.close(); - - assertNull( get ); + scope.inSession( session -> { + DestinationEntity get = session.find( DestinationEntity.class, destinationEntity.id ); + assertNull( get ); + } ); } @Test - public void testDeleteMultipleValues() { + public void testDeleteMultipleValues(SessionFactoryScope scope) { final String name = "Name"; final String lastName = "LastName"; - final List ids = new ArrayList(); + final List ids = new ArrayList<>(); final int quantity = 10; - final List destinations = new ArrayList(); for ( int i = 0; i < quantity; i++ ) { - FromEntity fe = createFrom( name + i, lastName + i ); - DestinationEntity destination = createDestination( fe, fe.name + fe.lastName ); - destinations.add( destination ); + FromEntity fe = createFrom( scope, name + i, lastName + i ); + DestinationEntity destination = createDestination( scope, fe, fe.name + fe.lastName ); ids.add( destination.id ); } - Session session = openSession(); - session.getTransaction().begin(); - Query delete = session.getNamedQuery( "DestinationEntity.delete" ); - delete.setParameterList( "ids", ids ); + scope.inTransaction( session -> { + Query delete = session.getNamedQuery( "DestinationEntity.delete" ); + delete.setParameterList( "ids", ids ); - int executeUpdate = delete.executeUpdate(); - assertEquals( quantity, executeUpdate ); + int executeUpdate = delete.executeUpdate(); + assertEquals( quantity, executeUpdate ); + } ); - session.getTransaction().commit(); - session.close(); - - List list = findDestinationByIds( ids ); + List list = findDestinationByIds( scope, ids ); assertTrue( list.isEmpty() ); } - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { FromEntity.class, DestinationEntity.class }; - } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/ql/TreatKeywordTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/ql/TreatKeywordTest.java index c22f3cc00a25..bc7f1e39b61c 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/ql/TreatKeywordTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/ql/TreatKeywordTest.java @@ -16,182 +16,145 @@ import jakarta.persistence.ManyToOne; import jakarta.persistence.OneToMany; import jakarta.persistence.Table; -import java.util.Arrays; import java.util.List; import java.util.Set; -import org.hibernate.Session; - -import org.junit.Test; - import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Steve Ebersole */ -public class TreatKeywordTest extends BaseCoreFunctionalTestCase { - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - JoinedEntity.class, JoinedEntitySubclass.class, JoinedEntitySubSubclass.class, - JoinedEntitySubclass2.class, JoinedEntitySubSubclass2.class, - DiscriminatorEntity.class, DiscriminatorEntitySubclass.class, DiscriminatorEntitySubSubclass.class, - Animal.class, Dog.class, Dachshund.class, Greyhound.class - }; +@DomainModel(annotatedClasses = { + TreatKeywordTest.JoinedEntity.class, TreatKeywordTest.JoinedEntitySubclass.class, TreatKeywordTest.JoinedEntitySubSubclass.class, + TreatKeywordTest.JoinedEntitySubclass2.class, TreatKeywordTest.JoinedEntitySubSubclass2.class, + TreatKeywordTest.DiscriminatorEntity.class, TreatKeywordTest.DiscriminatorEntitySubclass.class, TreatKeywordTest.DiscriminatorEntitySubSubclass.class, + TreatKeywordTest.Animal.class, TreatKeywordTest.Dog.class, TreatKeywordTest.Dachshund.class, TreatKeywordTest.Greyhound.class +}) +@SessionFactory +public class TreatKeywordTest { + + @AfterEach + public void cleanup(SessionFactoryScope scope) { + scope.dropData(); } @Test - public void testBasicUsageInJoin() { + public void testBasicUsageInJoin(SessionFactoryScope scope) { // todo : assert invalid naming of non-subclasses in TREAT statement - Session s = openSession(); - - s.createQuery( "from DiscriminatorEntity e join treat(e.other as DiscriminatorEntitySubclass) o", Object[].class ).list(); - s.createQuery( "from DiscriminatorEntity e join treat(e.other as DiscriminatorEntitySubSubclass) o", Object[].class ).list(); - s.createQuery( "from DiscriminatorEntitySubclass e join treat(e.other as DiscriminatorEntitySubSubclass) o", Object[].class ).list(); - - s.createQuery( "from JoinedEntity e join treat(e.other as JoinedEntitySubclass) o", Object[].class ).list(); - s.createQuery( "from JoinedEntity e join treat(e.other as JoinedEntitySubSubclass) o", Object[].class ).list(); - s.createQuery( "from JoinedEntitySubclass e join treat(e.other as JoinedEntitySubSubclass) o", Object[].class ).list(); - - s.close(); + scope.inSession( s -> { + s.createQuery( "from DiscriminatorEntity e join treat(e.other as DiscriminatorEntitySubclass) o", Object[].class ).list(); + s.createQuery( "from DiscriminatorEntity e join treat(e.other as DiscriminatorEntitySubSubclass) o", Object[].class ).list(); + s.createQuery( "from DiscriminatorEntitySubclass e join treat(e.other as DiscriminatorEntitySubSubclass) o", Object[].class ).list(); + + s.createQuery( "from JoinedEntity e join treat(e.other as JoinedEntitySubclass) o", Object[].class ).list(); + s.createQuery( "from JoinedEntity e join treat(e.other as JoinedEntitySubSubclass) o", Object[].class ).list(); + s.createQuery( "from JoinedEntitySubclass e join treat(e.other as JoinedEntitySubSubclass) o", Object[].class ).list(); + } ); } @Test @JiraKey( value = "HHH-8637" ) - public void testFilteringDiscriminatorSubclasses() { - Session s = openSession(); - s.beginTransaction(); - DiscriminatorEntity root = new DiscriminatorEntity( 1, "root" ); - s.persist( root ); - DiscriminatorEntitySubclass child = new DiscriminatorEntitySubclass( 2, "child", root ); - s.persist( child ); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - - // in select clause - List result = s.createQuery( "select e from DiscriminatorEntity e", Object[].class ).list(); - assertEquals( 2, result.size() ); - result = s.createQuery( "select treat (e as DiscriminatorEntitySubclass) from DiscriminatorEntity e", Object[].class ).list(); - assertEquals( 1, result.size() ); - result = s.createQuery( "select treat (e as DiscriminatorEntitySubSubclass) from DiscriminatorEntity e", Object[].class ).list(); - assertEquals( 0, result.size() ); - - // in join - result = s.createQuery( "from DiscriminatorEntity e inner join e.other", DiscriminatorEntity.class ).list(); - assertEquals( 1, result.size() ); - result = s.createQuery( "from DiscriminatorEntity e inner join treat (e.other as DiscriminatorEntitySubclass)", DiscriminatorEntity.class ).list(); - assertEquals( 0, result.size() ); - result = s.createQuery( "from DiscriminatorEntity e inner join treat (e.other as DiscriminatorEntitySubSubclass)", DiscriminatorEntity.class ).list(); - assertEquals( 0, result.size() ); - - s.close(); - - s = openSession(); - s.beginTransaction(); - s.remove( root ); - s.remove( child ); - s.getTransaction().commit(); - s.close(); + public void testFilteringDiscriminatorSubclasses(SessionFactoryScope scope) { + scope.inTransaction( s -> { + DiscriminatorEntity root = new DiscriminatorEntity( 1, "root" ); + s.persist( root ); + DiscriminatorEntitySubclass child = new DiscriminatorEntitySubclass( 2, "child", root ); + s.persist( child ); + } ); + + scope.inSession( s -> { + // in select clause + List result = s.createQuery( "select e from DiscriminatorEntity e", Object[].class ).list(); + assertEquals( 2, result.size() ); + result = s.createQuery( "select treat (e as DiscriminatorEntitySubclass) from DiscriminatorEntity e", Object[].class ).list(); + assertEquals( 1, result.size() ); + result = s.createQuery( "select treat (e as DiscriminatorEntitySubSubclass) from DiscriminatorEntity e", Object[].class ).list(); + assertEquals( 0, result.size() ); + + // in join + List result2 = s.createQuery( "from DiscriminatorEntity e inner join e.other", DiscriminatorEntity.class ).list(); + assertEquals( 1, result2.size() ); + result2 = s.createQuery( "from DiscriminatorEntity e inner join treat (e.other as DiscriminatorEntitySubclass)", DiscriminatorEntity.class ).list(); + assertEquals( 0, result2.size() ); + result2 = s.createQuery( "from DiscriminatorEntity e inner join treat (e.other as DiscriminatorEntitySubSubclass)", DiscriminatorEntity.class ).list(); + assertEquals( 0, result2.size() ); + } ); } @Test @JiraKey( value = "HHH-8637" ) - public void testFilteringJoinedSubclasses() { - Session s = openSession(); - s.beginTransaction(); - JoinedEntity root = new JoinedEntity( 1, "root" ); - s.persist( root ); - JoinedEntitySubclass child = new JoinedEntitySubclass( 2, "child", root ); - s.persist( child ); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - - // in the select clause which causes an implicit inclusion of subclass joins, the test here makes sure that - // the TREAT-AS effects the join-type used. - List result = s.createQuery( "select e from JoinedEntity e" ).list(); - assertEquals( 2, result.size() ); - result = s.createQuery( "select treat (e as JoinedEntitySubclass) from JoinedEntity e" ).list(); - assertEquals( 1, result.size() ); - result = s.createQuery( "select e from JoinedEntity e where treat (e as JoinedEntitySubclass) is not null" ).list(); - assertEquals( 1, result.size() ); - result = s.createQuery( "select treat (e as JoinedEntitySubSubclass) from JoinedEntity e" ).list(); - assertEquals( 0, result.size() ); - - // in join - result = s.createQuery( "from JoinedEntity e inner join e.other", JoinedEntity.class ).list(); - assertEquals( 1, result.size() ); - result = s.createQuery( "from JoinedEntity e inner join treat (e.other as JoinedEntitySubclass)", JoinedEntity.class ).list(); - assertEquals( 0, result.size() ); - result = s.createQuery( "from JoinedEntity e inner join treat (e.other as JoinedEntitySubSubclass)", JoinedEntity.class ).list(); - assertEquals( 0, result.size() ); - - s.close(); - - s = openSession(); - s.beginTransaction(); - s.remove( child ); - s.remove( root ); - s.getTransaction().commit(); - s.close(); + public void testFilteringJoinedSubclasses(SessionFactoryScope scope) { + scope.inTransaction( s -> { + JoinedEntity root = new JoinedEntity( 1, "root" ); + s.persist( root ); + JoinedEntitySubclass child = new JoinedEntitySubclass( 2, "child", root ); + s.persist( child ); + } ); + + scope.inSession( s -> { + // in the select clause which causes an implicit inclusion of subclass joins, the test here makes sure that + // the TREAT-AS effects the join-type used. + List result = s.createQuery( "select e from JoinedEntity e" ).list(); + assertEquals( 2, result.size() ); + result = s.createQuery( "select treat (e as JoinedEntitySubclass) from JoinedEntity e" ).list(); + assertEquals( 1, result.size() ); + result = s.createQuery( "select e from JoinedEntity e where treat (e as JoinedEntitySubclass) is not null" ).list(); + assertEquals( 1, result.size() ); + result = s.createQuery( "select treat (e as JoinedEntitySubSubclass) from JoinedEntity e" ).list(); + assertEquals( 0, result.size() ); + + // in join + result = s.createQuery( "from JoinedEntity e inner join e.other", JoinedEntity.class ).list(); + assertEquals( 1, result.size() ); + result = s.createQuery( "from JoinedEntity e inner join treat (e.other as JoinedEntitySubclass)", JoinedEntity.class ).list(); + assertEquals( 0, result.size() ); + result = s.createQuery( "from JoinedEntity e inner join treat (e.other as JoinedEntitySubSubclass)", JoinedEntity.class ).list(); + assertEquals( 0, result.size() ); + } ); } @Test @JiraKey( value = "HHH-9862" ) - public void testRestrictionsOnJoinedSubclasses() { - Session s = openSession(); - s.beginTransaction(); - JoinedEntity root = new JoinedEntity( 1, "root" ); - s.persist( root ); - JoinedEntitySubclass child1 = new JoinedEntitySubclass( 2, "child1", root ); - s.persist( child1 ); - JoinedEntitySubclass2 child2 = new JoinedEntitySubclass2( 3, "child2", root ); - s.persist( child2 ); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - - List result = s.createQuery( "select e from JoinedEntity e where treat (e as JoinedEntitySubclass ).name = 'child1'" ).list(); - assertEquals( 1, result.size() ); - assertTrue( JoinedEntitySubclass.class.isInstance( result.get( 0 ) ) ); - - result = s.createQuery( "select e from JoinedEntity e where treat (e as JoinedEntitySubclass2 ).name = 'child1'" ).list(); - assertEquals( 0, result.size() ); - - result = s.createQuery( "select e from JoinedEntity e where treat (e as JoinedEntitySubclass2 ).name = 'child2'" ).list(); - assertEquals( 1, result.size() ); - assertTrue( JoinedEntitySubclass2.class.isInstance( result.get( 0 ) ) ); - - result = s.createQuery( "select e from JoinedEntity e where treat (e as JoinedEntitySubclass ).name = 'child1' or treat (e as JoinedEntitySubclass2 ).name = 'child2'" ).list(); - assertEquals( 2, result.size() ); - - s.close(); - - s = openSession(); - s.beginTransaction(); - s.remove( child1 ); - s.remove( child2 ); - s.remove( root ); - s.getTransaction().commit(); - s.close(); + public void testRestrictionsOnJoinedSubclasses(SessionFactoryScope scope) { + scope.inTransaction( s -> { + JoinedEntity root = new JoinedEntity( 1, "root" ); + s.persist( root ); + JoinedEntitySubclass child1 = new JoinedEntitySubclass( 2, "child1", root ); + s.persist( child1 ); + JoinedEntitySubclass2 child2 = new JoinedEntitySubclass2( 3, "child2", root ); + s.persist( child2 ); + } ); + + scope.inSession( s -> { + List result = s.createQuery( "select e from JoinedEntity e where treat (e as JoinedEntitySubclass ).name = 'child1'" ).list(); + assertEquals( 1, result.size() ); + assertTrue( JoinedEntitySubclass.class.isInstance( result.get( 0 ) ) ); + + result = s.createQuery( "select e from JoinedEntity e where treat (e as JoinedEntitySubclass2 ).name = 'child1'" ).list(); + assertEquals( 0, result.size() ); + + result = s.createQuery( "select e from JoinedEntity e where treat (e as JoinedEntitySubclass2 ).name = 'child2'" ).list(); + assertEquals( 1, result.size() ); + assertTrue( JoinedEntitySubclass2.class.isInstance( result.get( 0 ) ) ); + + result = s.createQuery( "select e from JoinedEntity e where treat (e as JoinedEntitySubclass ).name = 'child1' or treat (e as JoinedEntitySubclass2 ).name = 'child2'" ).list(); + assertEquals( 2, result.size() ); + } ); } @Test @JiraKey(value = "HHH-9411") - public void testTreatWithRestrictionOnAbstractClass() { - inTransaction( + public void testTreatWithRestrictionOnAbstractClass(SessionFactoryScope scope) { + scope.inTransaction( s -> { Greyhound greyhound = new Greyhound(); Dachshund dachshund = new Dachshund(); @@ -200,7 +163,7 @@ public void testTreatWithRestrictionOnAbstractClass() { List results = s.createQuery( "select treat (a as Dog) from Animal a where a.fast = TRUE" ).list(); - assertEquals( Arrays.asList( greyhound ), results ); + assertEquals( List.of( greyhound ), results ); s.remove( greyhound ); s.remove( dachshund ); } @@ -209,8 +172,8 @@ public void testTreatWithRestrictionOnAbstractClass() { @Test @JiraKey(value = "HHH-16657") - public void testTypeFilterInSubquery() { - inTransaction( + public void testTypeFilterInSubquery(SessionFactoryScope scope) { + scope.inTransaction( s -> { JoinedEntitySubclass2 child1 = new JoinedEntitySubclass2(3, "child1"); JoinedEntitySubSubclass2 child2 = new JoinedEntitySubSubclass2(4, "child2"); @@ -222,7 +185,7 @@ public void testTypeFilterInSubquery() { s.persist( root2 ); } ); - inSession( + scope.inSession( s -> { List results = s.createSelectionQuery( "select (select o.name from j.other o where type(j) = JoinedEntitySubSubclass) from JoinedEntitySubclass j order by j.id", @@ -234,18 +197,12 @@ public void testTypeFilterInSubquery() { assertEquals( "child2", results.get( 1 ) ); } ); - inTransaction( - s -> { - s.createMutationQuery( "update JoinedEntity j set j.other = null" ).executeUpdate(); - s.createMutationQuery( "delete from JoinedEntity" ).executeUpdate(); - } - ); } @Test @JiraKey(value = "HHH-16658") - public void testPropagateEntityNameUsesFromDisjunction() { - inSession( + public void testPropagateEntityNameUsesFromDisjunction(SessionFactoryScope scope) { + scope.inSession( s -> { s.createSelectionQuery( "select 1 from Animal a where (type(a) <> Dachshund or treat(a as Dachshund).fast) and (type(a) <> Greyhound or treat(a as Greyhound).fast)", @@ -257,8 +214,8 @@ public void testPropagateEntityNameUsesFromDisjunction() { @Test @JiraKey(value = "HHH-16658") - public void testPropagateEntityNameUsesFromDisjunction2() { - inSession( + public void testPropagateEntityNameUsesFromDisjunction2(SessionFactoryScope scope) { + scope.inSession( s -> { s.createSelectionQuery( "select 1 from JoinedEntity j where type(j) <> JoinedEntitySubclass or length(coalesce(treat(j as JoinedEntitySubclass).name,'')) > 1", @@ -270,8 +227,8 @@ public void testPropagateEntityNameUsesFromDisjunction2() { @Test @JiraKey(value = "HHH-16657") - public void testTreatInSelect() { - inTransaction( + public void testTreatInSelect(SessionFactoryScope scope) { + scope.inTransaction( s -> { JoinedEntitySubclass root1 = new JoinedEntitySubclass(1, "root1"); JoinedEntitySubSubclass root2 = new JoinedEntitySubSubclass(2, "root2"); @@ -279,7 +236,7 @@ public void testTreatInSelect() { s.persist( root2 ); } ); - inSession( + scope.inSession( s -> { List results = s.createSelectionQuery( "select treat(j as JoinedEntitySubSubclass).name from JoinedEntitySubclass j order by j.id", @@ -291,21 +248,16 @@ public void testTreatInSelect() { assertEquals( "root2", results.get( 1 ) ); } ); - inTransaction( - s -> { - s.createMutationQuery( "delete from JoinedEntity" ).executeUpdate(); - } - ); } @Test @JiraKey(value = "HHH-16571") // Sort of related to that issue - public void testJoinSubclassOneToMany() { + public void testJoinSubclassOneToMany(SessionFactoryScope scope) { // Originally, the FK for "others" used the primary key of the root table JoinedEntity // Since we didn't register an entity use, we wrongly pruned that table before. // This was fixed by letting the FK descriptor point to the primary key of JoinedEntitySubclass2, // i.e. the plural attribute declaring type, which has the nice benefit of saving us a join - inSession( + scope.inSession( s -> { s.createSelectionQuery( "select 1 from JoinedEntitySubclass2 s left join s.others o", diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/removed/RemovedEntityTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/removed/RemovedEntityTest.java index f25bfcfbf08e..6861a7737514 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/removed/RemovedEntityTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/removed/RemovedEntityTest.java @@ -57,8 +57,8 @@ public void testRemoveThenGet() { Item item = fromTransaction( session -> { - session.remove( session.get( Item.class, id ) ); - return session.get( Item.class, id ); + session.remove( session.find( Item.class, id ) ); + return session.find( Item.class, id ); } ); @@ -79,26 +79,26 @@ public void testRemoveThenSave() { inTransaction( session -> { - Item item = session.get( Item.class, id ); + Item item = session.find( Item.class, id ); String sessionAsString = session.toString(); session.remove( item ); - Item item2 = session.get( Item.class, id ); + Item item2 = session.find( Item.class, id ); assertNull( item2, "expecting removed entity to be returned as null from get()" ); session.persist( item ); assertEquals( sessionAsString, session.toString(), "expecting session to be as it was before" ); item.setName( "Rescued" ); - item = session.get( Item.class, id ); + item = session.find( Item.class, id ); assertNotNull( item, "expecting rescued entity to be returned from get()" ); } ); Item item = fromTransaction( session -> - session.get( Item.class, id ) + session.find( Item.class, id ) ); assertNotNull( item, "expecting removed entity to be returned as null from get()" ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/schemagen/JpaSchemaGeneratorTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/schemagen/JpaSchemaGeneratorTest.java index f2eff8b3a700..ba31a26b1a47 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/schemagen/JpaSchemaGeneratorTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/schemagen/JpaSchemaGeneratorTest.java @@ -18,7 +18,6 @@ import org.hibernate.testing.orm.junit.JiraKey; import org.hibernate.testing.orm.junit.EntityManagerFactoryBasedFunctionalTest; import org.hibernate.testing.orm.junit.RequiresDialect; -import org.junit.Assert; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; @@ -158,7 +157,7 @@ private void doTest(Map settings) { EntityManager em = emf.createEntityManager(); try { Assertions.assertNotNull( em.find( Item.class, encodedName() ) ); - Assert.assertNotNull( em.find( Item.class, "multi-file-test" ) ); + Assertions.assertNotNull( em.find( Item.class, "multi-file-test" ) ); } finally { em.close(); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/schemagen/SchemaDatabaseFileGenerationFailureTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/schemagen/SchemaDatabaseFileGenerationFailureTest.java index c911dd50d72c..c87c46bce0be 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/schemagen/SchemaDatabaseFileGenerationFailureTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/schemagen/SchemaDatabaseFileGenerationFailureTest.java @@ -4,19 +4,10 @@ */ package org.hibernate.orm.test.jpa.schemagen; -import java.io.IOException; -import java.sql.Connection; -import java.sql.SQLException; -import java.sql.Statement; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Map; -import java.util.regex.Pattern; import jakarta.persistence.Entity; import jakarta.persistence.Id; import jakarta.persistence.PersistenceException; import jakarta.persistence.Table; - import org.hibernate.cfg.AvailableSettings; import org.hibernate.cfg.Environment; import org.hibernate.community.dialect.GaussDBDialect; @@ -25,19 +16,26 @@ import org.hibernate.jpa.boot.spi.Bootstrap; import org.hibernate.jpa.boot.spi.EntityManagerFactoryBuilder; import org.hibernate.jpa.boot.spi.PersistenceUnitDescriptor; +import org.hibernate.testing.orm.junit.EntityManagerFactoryBasedFunctionalTest; +import org.hibernate.testing.orm.junit.JiraKey; import org.hibernate.testing.orm.junit.SkipForDialect; +import org.hibernate.testing.util.ServiceRegistryUtil; import org.hibernate.tool.schema.spi.CommandAcceptanceException; import org.hibernate.tool.schema.spi.SchemaManagementException; -import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.orm.junit.EntityManagerFactoryBasedFunctionalTest; -import org.hibernate.testing.util.ServiceRegistryUtil; - import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; - import org.mockito.Mockito; +import java.io.IOException; +import java.sql.Connection; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Map; +import java.util.regex.Pattern; + import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/schemagen/SchemaScriptFileGenerationFailureTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/schemagen/SchemaScriptFileGenerationFailureTest.java index 0cc6a892d3e4..98e850c52eea 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/schemagen/SchemaScriptFileGenerationFailureTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/schemagen/SchemaScriptFileGenerationFailureTest.java @@ -4,17 +4,10 @@ */ package org.hibernate.orm.test.jpa.schemagen; -import java.io.IOException; -import java.io.Writer; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Map; -import java.util.regex.Pattern; import jakarta.persistence.Entity; import jakarta.persistence.Id; import jakarta.persistence.PersistenceException; import jakarta.persistence.Table; - import org.hibernate.cfg.AvailableSettings; import org.hibernate.cfg.Environment; import org.hibernate.community.dialect.GaussDBDialect; @@ -23,17 +16,23 @@ import org.hibernate.jpa.boot.spi.Bootstrap; import org.hibernate.jpa.boot.spi.EntityManagerFactoryBuilder; import org.hibernate.jpa.boot.spi.PersistenceUnitDescriptor; +import org.hibernate.testing.orm.junit.EntityManagerFactoryBasedFunctionalTest; +import org.hibernate.testing.orm.junit.JiraKey; import org.hibernate.testing.orm.junit.SkipForDialect; +import org.hibernate.testing.util.ServiceRegistryUtil; import org.hibernate.tool.schema.spi.CommandAcceptanceException; import org.hibernate.tool.schema.spi.SchemaManagementException; -import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.orm.junit.EntityManagerFactoryBasedFunctionalTest; -import org.hibernate.testing.util.ServiceRegistryUtil; - import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import java.io.IOException; +import java.io.Writer; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Map; +import java.util.regex.Pattern; + import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/schemagen/iso8859/JpaFileSchemaGeneratorWithHbm2DdlCharsetNameTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/schemagen/iso8859/JpaFileSchemaGeneratorWithHbm2DdlCharsetNameTest.java index 5b92c7c2b2a9..56297f0cdc88 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/schemagen/iso8859/JpaFileSchemaGeneratorWithHbm2DdlCharsetNameTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/schemagen/iso8859/JpaFileSchemaGeneratorWithHbm2DdlCharsetNameTest.java @@ -10,7 +10,7 @@ import org.hibernate.dialect.H2Dialect; import org.hibernate.orm.test.jpa.schemagen.JpaSchemaGeneratorTest; -import org.hibernate.testing.RequiresDialect; +import org.hibernate.testing.orm.junit.RequiresDialect; import org.hibernate.testing.orm.junit.JiraKey; /** diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/schemagen/iso8859/JpaSchemaGeneratorWithHbm2DdlCharsetNameTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/schemagen/iso8859/JpaSchemaGeneratorWithHbm2DdlCharsetNameTest.java index 08c1e642b41f..a77b175f59c5 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/schemagen/iso8859/JpaSchemaGeneratorWithHbm2DdlCharsetNameTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/schemagen/iso8859/JpaSchemaGeneratorWithHbm2DdlCharsetNameTest.java @@ -10,7 +10,7 @@ import org.hibernate.dialect.H2Dialect; import org.hibernate.orm.test.jpa.schemagen.JpaSchemaGeneratorTest; -import org.hibernate.testing.RequiresDialect; +import org.hibernate.testing.orm.junit.RequiresDialect; /** * @author Vlad Mihalcea diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/schemagen/iso8859/JpaSchemaGeneratorWithoutHbm2DdlCharsetNameTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/schemagen/iso8859/JpaSchemaGeneratorWithoutHbm2DdlCharsetNameTest.java index 71911aff193c..894514fabd4f 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/schemagen/iso8859/JpaSchemaGeneratorWithoutHbm2DdlCharsetNameTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/jpa/schemagen/iso8859/JpaSchemaGeneratorWithoutHbm2DdlCharsetNameTest.java @@ -7,7 +7,7 @@ import org.hibernate.dialect.H2Dialect; import org.hibernate.orm.test.jpa.schemagen.JpaSchemaGeneratorTest; -import org.hibernate.testing.RequiresDialect; +import org.hibernate.testing.orm.junit.RequiresDialect; /** * @author Vlad Mihalcea @@ -22,6 +22,6 @@ public String getScriptFolderPath() { } protected String encodedName() { - return "sch" + String.valueOf( '\uFFFD' ) +"magen-test"; + return "sch" + '\uFFFD' +"magen-test"; } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/AliasTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/AliasTest.java index 6c138d2d1f2f..dcb7c552e201 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/AliasTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/AliasTest.java @@ -85,7 +85,7 @@ public final void testUnderscoreInColumnName(SessionFactoryScope scope) { session.clear(); session.getTransaction().begin(); - user = session.get( UserEntity.class, user.getId() ); + user = session.find( UserEntity.class, user.getId() ); try { session.flush(); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/SecondaryTableTests.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/SecondaryTableTests.java index 771cefe0fc56..3316e8d23b19 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/SecondaryTableTests.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/SecondaryTableTests.java @@ -45,7 +45,7 @@ public void updateOnSecondaryTableColumn(SessionFactoryScope scope) { session.flush(); session.clear(); session.createQuery( "update SimpleEntityWithSecondaryTables e set e.data = 'test'" ).executeUpdate(); - SimpleEntityWithSecondaryTables entity = session.get( SimpleEntityWithSecondaryTables.class, 1 ); + SimpleEntityWithSecondaryTables entity = session.find( SimpleEntityWithSecondaryTables.class, 1 ); Assertions.assertEquals( "test", entity.data ); } ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/ValueVisitorTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/ValueVisitorTest.java index b8b421fc44f2..7911b5ace7aa 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/ValueVisitorTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/ValueVisitorTest.java @@ -29,27 +29,26 @@ import org.hibernate.mapping.ValueVisitor; import org.hibernate.testing.boot.MetadataBuildingContextTestingImpl; -import org.hibernate.testing.junit4.BaseUnitTestCase; import org.hibernate.testing.util.ServiceRegistryUtil; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * @author max */ -public class ValueVisitorTest extends BaseUnitTestCase { +public class ValueVisitorTest { private StandardServiceRegistry serviceRegistry; private MetadataBuildingContext metadataBuildingContext; - @Before + @BeforeEach public void prepare() { serviceRegistry = ServiceRegistryUtil.serviceRegistry(); metadataBuildingContext = new MetadataBuildingContextTestingImpl( serviceRegistry ); } - @After + @AfterEach public void release() { StandardServiceRegistryBuilder.destroy( serviceRegistry ); } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/access/ElementCollectionAccessTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/access/ElementCollectionAccessTest.java index d3cfbfa8435d..e2781332dda5 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/access/ElementCollectionAccessTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/access/ElementCollectionAccessTest.java @@ -15,27 +15,19 @@ import jakarta.persistence.Id; import jakarta.persistence.JoinColumn; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; - -import org.junit.Test; - -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.Test; /** * @author Vlad Mihalcea */ -public class ElementCollectionAccessTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Book.class - }; - } +@Jpa(annotatedClasses = {ElementCollectionAccessTest.Book.class}) +public class ElementCollectionAccessTest { @Test - public void test() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test(EntityManagerFactoryScope scope) { + scope.inTransaction(entityManager -> { Book book = new Book(); book.setId(1L); book.setTitle("High-Performance Java Persistence"); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/access/EmbeddableAccessTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/access/EmbeddableAccessTest.java index e1dae521b4df..747c40420ed1 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/access/EmbeddableAccessTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/access/EmbeddableAccessTest.java @@ -11,27 +11,19 @@ import jakarta.persistence.Entity; import jakarta.persistence.Id; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; - -import org.junit.Test; - -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.Test; /** * @author Vlad Mihalcea */ -public class EmbeddableAccessTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Book.class - }; - } +@Jpa(annotatedClasses = {EmbeddableAccessTest.Book.class}) +public class EmbeddableAccessTest { @Test - public void test() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test(EntityManagerFactoryScope scope) { + scope.inTransaction(entityManager -> { Book book = new Book(); book.setId(1L); book.setTitle("High-Performance Java Persistence"); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/access/FieldAccessTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/access/FieldAccessTest.java index e181ddd340d5..9e69db228757 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/access/FieldAccessTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/access/FieldAccessTest.java @@ -7,27 +7,19 @@ import jakarta.persistence.Entity; import jakarta.persistence.Id; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; - -import org.junit.Test; - -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.Test; /** * @author Vlad Mihalcea */ -public class FieldAccessTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Book.class - }; - } +@Jpa(annotatedClasses = {FieldAccessTest.Book.class}) +public class FieldAccessTest { @Test - public void test() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test(EntityManagerFactoryScope scope) { + scope.inTransaction(entityManager -> { Book book = new Book(); book.setId(1L); book.setTitle("High-Performance Java Persistence"); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/access/PropertyAccessOverrideTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/access/PropertyAccessOverrideTest.java index bb28b8d2e948..59443b8aaa94 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/access/PropertyAccessOverrideTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/access/PropertyAccessOverrideTest.java @@ -10,27 +10,19 @@ import jakarta.persistence.Id; import jakarta.persistence.Version; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; - -import org.junit.Test; - -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.Test; /** * @author Vlad Mihalcea */ -public class PropertyAccessOverrideTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Book.class - }; - } +@Jpa(annotatedClasses = {PropertyAccessOverrideTest.Book.class}) +public class PropertyAccessOverrideTest { @Test - public void test() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test(EntityManagerFactoryScope scope) { + scope.inTransaction(entityManager -> { Book book = new Book(); book.setId(1L); book.setTitle("High-Performance Java Persistence"); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/access/PropertyAccessTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/access/PropertyAccessTest.java index dc1af49d544b..0d5d08cf4faa 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/access/PropertyAccessTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/access/PropertyAccessTest.java @@ -7,27 +7,19 @@ import jakarta.persistence.Entity; import jakarta.persistence.Id; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; - -import org.junit.Test; - -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.Test; /** * @author Vlad Mihalcea */ -public class PropertyAccessTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Book.class - }; - } +@Jpa(annotatedClasses = {PropertyAccessTest.Book.class}) +public class PropertyAccessTest { @Test - public void test() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test(EntityManagerFactoryScope scope) { + scope.inTransaction(entityManager -> { Book book = new Book(); book.setId(1L); book.setTitle("High-Performance Java Persistence"); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/AutoQuotingTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/AutoQuotingTest.java index e5445be2a8e7..cf52c0aee145 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/AutoQuotingTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/AutoQuotingTest.java @@ -4,39 +4,28 @@ */ package org.hibernate.orm.test.mapping.basic; -import java.util.Map; import jakarta.persistence.Entity; import jakarta.persistence.Id; import org.hibernate.cfg.AvailableSettings; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; -import org.junit.Test; - -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.hibernate.testing.orm.junit.Setting; +import org.junit.jupiter.api.Test; /** * @author Vlad Mihalcea */ -public class AutoQuotingTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Product.class - }; - } - - @Override - protected Map buildSettings() { - Map settings = super.buildSettings(); - settings.put(AvailableSettings.GLOBALLY_QUOTED_IDENTIFIERS, true); - return settings; - } +@Jpa( + annotatedClasses = {AutoQuotingTest.Product.class}, + integrationSettings = {@Setting(name = AvailableSettings.GLOBALLY_QUOTED_IDENTIFIERS, value = "true")} +) +public class AutoQuotingTest { @Test - public void test() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { //tag::basic-auto-quoting-persistence-example[] Product product = new Product(); product.setId(1L); 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 d057f7b7b7a8..988893f5728f 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 @@ -8,28 +8,21 @@ import jakarta.persistence.Id; import jakarta.persistence.Lob; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.Test; -import org.junit.Test; - -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; -import static org.junit.Assert.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; /** * @author Vlad Mihalcea */ -public class BlobByteArrayTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Product.class - }; - } +@Jpa( annotatedClasses = {BlobByteArrayTest.Product.class} ) +public class BlobByteArrayTest { @Test - public void test() { - Integer productId = doInJPA(this::entityManagerFactory, entityManager -> { + public void test(EntityManagerFactoryScope scope) { + Integer productId = scope.fromTransaction( entityManager -> { final Product product = new Product(); product.setId(1); product.setName("Mobile phone"); @@ -38,7 +31,7 @@ public void test() { entityManager.persist(product); return product.getId(); }); - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { Product product = entityManager.find(Product.class, productId); assertArrayEquals(new byte[] {1, 2, 3}, product.getImage()); 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 613123745fa6..e0be7c3aec79 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 @@ -13,32 +13,24 @@ import jakarta.persistence.Id; import jakarta.persistence.Lob; -import org.hibernate.Session; import org.hibernate.engine.jdbc.proxy.BlobProxy; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; -import org.junit.Test; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.Test; -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Vlad Mihalcea */ -public class BlobTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Product.class - }; - } +@Jpa( annotatedClasses = {BlobTest.Product.class} ) +public class BlobTest { @Test - public void test() { - Integer productId = doInJPA(this::entityManagerFactory, entityManager -> { - Session session = entityManager.unwrap(Session.class); + public void test(EntityManagerFactoryScope scope) { + Integer productId = scope.fromTransaction( entityManager -> { //tag::basic-blob-persist-example[] byte[] image = new byte[] {1, 2, 3}; @@ -54,7 +46,7 @@ public void test() { return product.getId(); }); - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { try { //tag::basic-blob-find-example[] diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/CalendarWithTemporalTimestampTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/CalendarWithTemporalTimestampTest.java index 2456f00dcd27..6a994bf51805 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/CalendarWithTemporalTimestampTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/CalendarWithTemporalTimestampTest.java @@ -13,31 +13,23 @@ import jakarta.persistence.Temporal; import jakarta.persistence.TemporalType; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; - -import org.junit.Test; - -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.Test; /** * @author Vlad Mihalcea */ -public class CalendarWithTemporalTimestampTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - DateEvent.class - }; - } +@Jpa( annotatedClasses = {CalendarWithTemporalTimestampTest.DateEvent.class} ) +public class CalendarWithTemporalTimestampTest { @Test - public void testLifecycle() { + public void testLifecycle(EntityManagerFactoryScope scope) { final Calendar calendar = new GregorianCalendar(); - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { entityManager.persist(new DateEvent(calendar)); }); - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { DateEvent dateEvent = entityManager.createQuery("from DateEvent", DateEvent.class).getSingleResult(); //Assert.assertEquals(calendar, dateEvent.getTimestamp()); }); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/ClobCharArrayTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/ClobCharArrayTest.java index e62d1e07610b..e69c4091360c 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/ClobCharArrayTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/ClobCharArrayTest.java @@ -13,7 +13,7 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; /** * @author Vlad Mihalcea diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/ClobStringTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/ClobStringTest.java index 43b134622fc7..dd5c03fcc91a 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/ClobStringTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/ClobStringTest.java @@ -8,28 +8,21 @@ import jakarta.persistence.Id; import jakarta.persistence.Lob; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.Test; -import org.junit.Test; - -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Vlad Mihalcea */ -public class ClobStringTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Product.class - }; - } +@Jpa( annotatedClasses = {ClobStringTest.Product.class} ) +public class ClobStringTest { @Test - public void test() { - Integer productId = doInJPA(this::entityManagerFactory, entityManager -> { + public void test(EntityManagerFactoryScope scope) { + Integer productId = scope.fromTransaction( entityManager -> { final Product product = new Product(); product.setId(1); product.setName("Mobile phone"); @@ -38,7 +31,7 @@ public void test() { entityManager.persist(product); return product.getId(); }); - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { Product product = entityManager.find(Product.class, productId); assertEquals("My product warranty", product.getWarranty()); }); 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 7cfa91dba354..11a5d0db8ae3 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 @@ -15,29 +15,23 @@ import org.hibernate.Session; import org.hibernate.engine.jdbc.proxy.ClobProxy; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; -import org.junit.Test; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.Test; -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Vlad Mihalcea */ -public class ClobTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Product.class - }; - } +@Jpa( annotatedClasses = {ClobTest.Product.class} ) +public class ClobTest { @Test - public void test() { - Integer productId = doInJPA(this::entityManagerFactory, entityManager -> { + public void test(EntityManagerFactoryScope scope) { + Integer productId = scope.fromTransaction( entityManager -> { Session session = entityManager.unwrap(Session.class); //tag::basic-clob-persist-example[] @@ -54,7 +48,7 @@ public void test() { return product.getId(); }); - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { try { //tag::basic-clob-find-example[] diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/ColumnTransformerTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/ColumnTransformerTest.java index 421554d6713b..6ba6b903e505 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/ColumnTransformerTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/ColumnTransformerTest.java @@ -11,10 +11,11 @@ import org.hibernate.annotations.ColumnTransformer; import org.hibernate.annotations.CompositeType; import org.hibernate.dialect.H2Dialect; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; -import org.hibernate.testing.RequiresDialect; -import org.junit.Test; +import org.hibernate.testing.orm.junit.RequiresDialect; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.Test; import jakarta.persistence.AttributeOverride; import jakarta.persistence.AttributeOverrides; @@ -22,26 +23,19 @@ import jakarta.persistence.Entity; import jakarta.persistence.Id; -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Vlad Mihalcea */ @RequiresDialect(H2Dialect.class) -public class ColumnTransformerTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Savings.class - }; - } +@Jpa( annotatedClasses = {ColumnTransformerTest.Savings.class} ) +public class ColumnTransformerTest { @Test - public void testLifecycle() { + public void testLifecycle(EntityManagerFactoryScope scope) { //tag::mapping-column-read-and-write-composite-type-persistence-example[] - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { //tag::basic-datetime-temporal-date-persist-example[] Savings savings = new Savings(); savings.setId(1L); @@ -49,7 +43,7 @@ public void testLifecycle() { entityManager.persist(savings); }); - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { Savings savings = entityManager.find(Savings.class, 1L); assertEquals(10, savings.getWallet().getAmount().intValue()); assertEquals(Currency.getInstance(Locale.US), savings.getWallet().getCurrency()); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/DateWithTemporalDateTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/DateWithTemporalDateTest.java index 1c019dfa28ca..a74b02e6bda5 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/DateWithTemporalDateTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/DateWithTemporalDateTest.java @@ -12,27 +12,19 @@ import jakarta.persistence.Temporal; import jakarta.persistence.TemporalType; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; - -import org.junit.Test; - -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.Test; /** * @author Vlad Mihalcea */ -public class DateWithTemporalDateTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - DateEvent.class - }; - } +@Jpa( annotatedClasses = {DateWithTemporalDateTest.DateEvent.class} ) +public class DateWithTemporalDateTest { @Test - public void testLifecycle() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void testLifecycle(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { //tag::basic-datetime-temporal-date-persist-example[] DateEvent dateEvent = new DateEvent(new Date()); entityManager.persist(dateEvent); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/DateWithTemporalTimeTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/DateWithTemporalTimeTest.java index 6fcb710d584f..6f1ba6acf5a0 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/DateWithTemporalTimeTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/DateWithTemporalTimeTest.java @@ -13,29 +13,22 @@ import jakarta.persistence.TemporalType; import org.hibernate.dialect.SybaseDialect; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; -import org.hibernate.testing.SkipForDialect; -import org.junit.Test; - -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; +import org.hibernate.testing.orm.junit.SkipForDialect; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.Test; /** * @author Vlad Mihalcea */ -public class DateWithTemporalTimeTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - DateEvent.class - }; - } +@Jpa( annotatedClasses = {DateWithTemporalTimeTest.DateEvent.class} ) +public class DateWithTemporalTimeTest { @Test - @SkipForDialect(value = SybaseDialect.class, comment = "The jTDS driver doesn't allow setting a timestamp through setTime") - public void testLifecycle() { - doInJPA(this::entityManagerFactory, entityManager -> { + @SkipForDialect(dialectClass = SybaseDialect.class, reason = "The jTDS driver doesn't allow setting a timestamp through setTime") + public void testLifecycle(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { DateEvent dateEvent = new DateEvent(new Date()); entityManager.persist(dateEvent); }); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/DateWithTemporalTimestampTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/DateWithTemporalTimestampTest.java index 42d047ae50ca..91e56ac6414f 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/DateWithTemporalTimestampTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/DateWithTemporalTimestampTest.java @@ -12,27 +12,19 @@ import jakarta.persistence.Temporal; import jakarta.persistence.TemporalType; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; - -import org.junit.Test; - -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.Test; /** * @author Vlad Mihalcea */ -public class DateWithTemporalTimestampTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - DateEvent.class - }; - } +@Jpa( annotatedClasses = {DateWithTemporalTimestampTest.DateEvent.class} ) +public class DateWithTemporalTimestampTest { @Test - public void testLifecycle() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void testLifecycle(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { DateEvent dateEvent = new DateEvent(new Date()); entityManager.persist(dateEvent); }); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/EnumerationConverterTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/EnumerationConverterTest.java index 95cb317063d9..4234388da2c4 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/EnumerationConverterTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/EnumerationConverterTest.java @@ -10,27 +10,19 @@ import jakarta.persistence.Entity; import jakarta.persistence.Id; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; - -import org.junit.Test; - -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.Test; /** * @author Vlad Mihalcea */ -public class EnumerationConverterTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Person.class - }; - } +@Jpa( annotatedClasses = {EnumerationConverterTest.Person.class} ) +public class EnumerationConverterTest { @Test - public void test() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { Person person = new Person(); person.setId(1L); person.setName("John Doe"); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/EnumerationCustomTypeTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/EnumerationCustomTypeTest.java index edd612efeef9..13dd5ff24385 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/EnumerationCustomTypeTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/EnumerationCustomTypeTest.java @@ -5,31 +5,24 @@ package org.hibernate.orm.test.mapping.basic; import org.hibernate.annotations.Type; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; -import org.junit.Test; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.Test; import jakarta.persistence.Column; import jakarta.persistence.Entity; import jakarta.persistence.Id; -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; - /** * @author Vlad Mihalcea */ -public class EnumerationCustomTypeTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Person.class - }; - } +@Jpa( annotatedClasses = {EnumerationCustomTypeTest.Person.class} ) +public class EnumerationCustomTypeTest { @Test - public void test() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { Person person = new Person(); person.setId(1L); person.setName("John Doe"); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/ExplicitBasicTypeTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/ExplicitBasicTypeTest.java index 020af2a6dd6c..7c2b6b228c23 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/ExplicitBasicTypeTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/ExplicitBasicTypeTest.java @@ -8,27 +8,19 @@ import jakarta.persistence.Entity; import jakarta.persistence.Id; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; - -import org.junit.Test; - -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.Test; /** * @author Vlad Mihalcea */ -public class ExplicitBasicTypeTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Product.class - }; - } +@Jpa( annotatedClasses = {ExplicitBasicTypeTest.Product.class} ) +public class ExplicitBasicTypeTest { @Test - public void test() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { Product product = new Product(); product.id = 1; entityManager.persist(product); @@ -37,7 +29,7 @@ public void test() { //tag::basic-annotation-explicit-example[] @Entity(name = "Product") - public class Product { + public static class Product { @Id @Basic diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/ExplicitColumnNamingTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/ExplicitColumnNamingTest.java index 967efefbfc58..9e89eb70aacd 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/ExplicitColumnNamingTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/ExplicitColumnNamingTest.java @@ -8,27 +8,19 @@ import jakarta.persistence.Entity; import jakarta.persistence.Id; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; - -import org.junit.Test; - -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.Test; /** * @author Vlad Mihalcea */ -public class ExplicitColumnNamingTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Product.class - }; - } +@Jpa( annotatedClasses = {ExplicitColumnNamingTest.Product.class} ) +public class ExplicitColumnNamingTest { @Test - public void test() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { Product product = new Product(); product.id = 1; entityManager.persist(product); @@ -37,7 +29,7 @@ public void test() { //tag::basic-annotation-explicit-column-example[] @Entity(name = "Product") - public class Product { + public static class Product { @Id private Integer id; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/ExplicitTypeTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/ExplicitTypeTest.java index 293f70387135..5a4b72a4fef1 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/ExplicitTypeTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/ExplicitTypeTest.java @@ -9,35 +9,29 @@ import org.hibernate.annotations.Type; import org.hibernate.annotations.Parameter; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; import org.hibernate.usertype.UserTypeLegacyBridge; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; /** * @author Vlad Mihalcea */ -public class ExplicitTypeTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Product.class - }; - } +@Jpa( annotatedClasses = {ExplicitTypeTest.Product.class} ) +public class ExplicitTypeTest { @Test - public void test() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { }); } //tag::basic-type-annotation-example[] @Entity(name = "Product") - public class Product { + public static class Product { @Id private Integer id; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/FormulaTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/FormulaTest.java index 4b0182f6003a..cbe470b95445 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/FormulaTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/FormulaTest.java @@ -8,29 +8,23 @@ import jakarta.persistence.Id; import org.hibernate.annotations.Formula; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; -import org.junit.Test; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.Test; -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Vlad Mihalcea */ -public class FormulaTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Account.class - }; - } +@Jpa( annotatedClasses = {FormulaTest.Account.class} ) +public class FormulaTest { @Test - public void testLifecycle() { + public void testLifecycle(EntityManagerFactoryScope scope) { //tag::mapping-column-formula-persistence-example[] - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { //tag::basic-datetime-temporal-date-persist-example[] Account account = new Account(); account.setId(1L); @@ -39,7 +33,7 @@ public void testLifecycle() { entityManager.persist(account); }); - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { Account account = entityManager.find(Account.class, 1L); assertEquals(Double.valueOf(62.5d), account.getInterest()); }); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/ImplicitBasicTypeTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/ImplicitBasicTypeTest.java index e67ad1bbfe5b..4ba520a38fcc 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/ImplicitBasicTypeTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/ImplicitBasicTypeTest.java @@ -7,27 +7,19 @@ import jakarta.persistence.Entity; import jakarta.persistence.Id; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; - -import org.junit.Test; - -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.Test; /** * @author Vlad Mihalcea */ -public class ImplicitBasicTypeTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Product.class - }; - } +@Jpa( annotatedClasses = {ImplicitBasicTypeTest.Product.class} ) +public class ImplicitBasicTypeTest { @Test - public void test() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { Product product = new Product(); product.id = 1; entityManager.persist(product); @@ -36,7 +28,7 @@ public void test() { //tag::basic-annotation-implicit-example[] @Entity(name = "Product") - public class Product { + public static class Product { @Id private Integer id; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/JpaQuotingTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/JpaQuotingTest.java index 51fcd9333d8b..a83a599f72bd 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/JpaQuotingTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/JpaQuotingTest.java @@ -8,27 +8,19 @@ import jakarta.persistence.Entity; import jakarta.persistence.Id; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; - -import org.junit.Test; - -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.Test; /** * @author Vlad Mihalcea */ -public class JpaQuotingTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Product.class - }; - } +@Jpa( annotatedClasses = {JpaQuotingTest.Product.class} ) +public class JpaQuotingTest { @Test - public void test() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { //tag::basic-jpa-quoting-persistence-example[] Product product = new Product(); product.setId(1L); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/LocalDateTimeWithTemporalTimeTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/LocalDateTimeWithTemporalTimeTest.java index c36f3f220eac..3fb36f1aab29 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/LocalDateTimeWithTemporalTimeTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/LocalDateTimeWithTemporalTimeTest.java @@ -9,33 +9,26 @@ import jakarta.persistence.Entity; import jakarta.persistence.Id; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.Test; -import org.junit.Test; - -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNotNull; /** * @author Vlad Mihalcea */ -public class LocalDateTimeWithTemporalTimeTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - DateEvent.class - }; - } +@Jpa( annotatedClasses = {LocalDateTimeWithTemporalTimeTest.DateEvent.class} ) +public class LocalDateTimeWithTemporalTimeTest { @Test - public void testLifecycle() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void testLifecycle(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { DateEvent dateEvent = new DateEvent(LocalDateTime.now()); dateEvent.id = 1L; entityManager.persist(dateEvent); }); - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { DateEvent dateEvent = entityManager.find(DateEvent.class, 1L); assertNotNull(dateEvent.getTimestamp()); }); 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 c0146e81fbe9..afebca3e3199 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 @@ -9,28 +9,22 @@ import jakarta.persistence.Lob; import org.hibernate.annotations.Nationalized; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; -import org.junit.Test; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.Test; -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; -import static org.junit.Assert.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; /** * @author Vlad Mihalcea */ -public class NClobCharArrayTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Product.class - }; - } +@Jpa( annotatedClasses = {NClobCharArrayTest.Product.class} ) +public class NClobCharArrayTest { @Test - public void test() { - Integer productId = doInJPA(this::entityManagerFactory, entityManager -> { + public void test(EntityManagerFactoryScope scope) { + Integer productId = scope.fromTransaction( entityManager -> { final Product product = new Product(); product.setId(1); product.setName("Mobile phone"); @@ -39,7 +33,7 @@ public void test() { entityManager.persist(product); return product.getId(); }); - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { Product product = entityManager.find(Product.class, productId); assertArrayEquals("My product warranty".toCharArray(), product.getWarranty()); 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 9e546108eb57..bc6d129a0b67 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 @@ -10,30 +10,24 @@ import org.hibernate.annotations.Nationalized; import org.hibernate.dialect.SybaseASEDialect; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; import org.hibernate.testing.orm.junit.SkipForDialect; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Vlad Mihalcea */ @SkipForDialect(dialectClass = SybaseASEDialect.class) -public class NClobStringTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Product.class - }; - } +@Jpa( annotatedClasses = {NClobStringTest.Product.class} ) +public class NClobStringTest { @Test - public void test() { - Integer productId = doInJPA(this::entityManagerFactory, entityManager -> { + public void test(EntityManagerFactoryScope scope) { + Integer productId = scope.fromTransaction( entityManager -> { final Product product = new Product(); product.setId(1); product.setName("Mobile phone"); @@ -42,7 +36,7 @@ public void test() { entityManager.persist(product); return product.getId(); }); - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { Product product = entityManager.find(Product.class, productId); assertEquals("My product®™ warranty 😍", product.getWarranty()); 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 018f3a2fb7e2..5df0832a9153 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 @@ -20,8 +20,8 @@ import org.hibernate.testing.orm.junit.SkipForDialect; import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Vlad Mihalcea 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 11e6350a9cf5..0e1831075299 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 @@ -15,7 +15,7 @@ import org.hibernate.testing.orm.junit.RequiresDialectFeature; import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Vlad Mihalcea diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/ParentTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/ParentTest.java index d0ec528e972a..e5104a2ebcd0 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/ParentTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/ParentTest.java @@ -12,29 +12,23 @@ import org.hibernate.annotations.Parent; import org.hibernate.annotations.TargetEmbeddable; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; -import org.junit.Test; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.Test; -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; -import static org.junit.Assert.assertSame; +import static org.junit.jupiter.api.Assertions.assertSame; /** * @author Vlad Mihalcea */ -public class ParentTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - City.class, - }; - } +@Jpa( annotatedClasses = {ParentTest.City.class} ) +public class ParentTest { @Test - public void testLifecycle() { + public void testLifecycle(EntityManagerFactoryScope scope) { //tag::mapping-Parent-persist-example[] - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { City cluj = new City(); cluj.setName("Cluj"); @@ -46,7 +40,7 @@ public void testLifecycle() { //tag::mapping-Parent-fetching-example[] - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { City cluj = entityManager.find(City.class, 1L); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/PhoneTypeEnumeratedOrdinalTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/PhoneTypeEnumeratedOrdinalTest.java index 120cd4936063..67e302ab515f 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/PhoneTypeEnumeratedOrdinalTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/PhoneTypeEnumeratedOrdinalTest.java @@ -10,28 +10,21 @@ import jakarta.persistence.Enumerated; import jakarta.persistence.Id; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; import org.hibernate.testing.orm.domain.userguide.PhoneType; -import org.junit.Test; - -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.Test; /** * @author Vlad Mihalcea */ -public class PhoneTypeEnumeratedOrdinalTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Phone.class - }; - } +@Jpa( annotatedClasses = {PhoneTypeEnumeratedOrdinalTest.Phone.class} ) +public class PhoneTypeEnumeratedOrdinalTest { @Test - public void test() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { //tag::basic-enums-Enumerated-ordinal-persistence-example[] Phone phone = new Phone(); phone.setId(1L); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/PhoneTypeEnumeratedStringTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/PhoneTypeEnumeratedStringTest.java index be656af42094..363061624819 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/PhoneTypeEnumeratedStringTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/PhoneTypeEnumeratedStringTest.java @@ -10,28 +10,21 @@ import jakarta.persistence.Enumerated; import jakarta.persistence.Id; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; import org.hibernate.testing.orm.domain.userguide.PhoneType; -import org.junit.Test; - -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.Test; /** * @author Vlad Mihalcea */ -public class PhoneTypeEnumeratedStringTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Phone.class - }; - } +@Jpa( annotatedClasses = {PhoneTypeEnumeratedStringTest.Phone.class} ) +public class PhoneTypeEnumeratedStringTest { @Test - public void test() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { Phone phone = new Phone(); phone.setId(1L); phone.setNumber("123-456-78990"); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/QuotingTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/QuotingTest.java index f9c2c13986c9..44568fd59568 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/QuotingTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/QuotingTest.java @@ -8,27 +8,19 @@ import jakarta.persistence.Entity; import jakarta.persistence.Id; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; - -import org.junit.Test; - -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.Test; /** * @author Vlad Mihalcea */ -public class QuotingTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Product.class - }; - } +@Jpa( annotatedClasses = {QuotingTest.Product.class} ) +public class QuotingTest { @Test - public void test() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { //tag::basic-quoting-persistence-example[] Product product = new Product(); product.setId(1L); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/StringNationalizedMappingTests.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/StringNationalizedMappingTests.java index 1ac215923930..6c426dcacac4 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/StringNationalizedMappingTests.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/StringNationalizedMappingTests.java @@ -17,12 +17,12 @@ import org.hibernate.metamodel.mapping.internal.BasicAttributeMapping; import org.hibernate.metamodel.spi.MappingMetamodelImplementor; import org.hibernate.persister.entity.EntityPersister; -import org.hibernate.testing.orm.junit.SkipForDialect; import org.hibernate.type.descriptor.jdbc.spi.JdbcTypeRegistry; import org.hibernate.testing.orm.junit.DomainModel; import org.hibernate.testing.orm.junit.SessionFactory; import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.hibernate.testing.orm.junit.SkipForDialect; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/SubselectTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/SubselectTest.java index 8bf59f89388e..e5b5092dc4e7 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/SubselectTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/SubselectTest.java @@ -24,7 +24,7 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Vlad Mihalcea diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/TypeCategoryTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/TypeCategoryTest.java index e8b6cc67f82f..b0c04091eed9 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/TypeCategoryTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/TypeCategoryTest.java @@ -9,27 +9,19 @@ import jakarta.persistence.Entity; import jakarta.persistence.Id; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; - -import org.junit.Test; - -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.Test; /** * @author Vlad Mihalcea */ -public class TypeCategoryTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Contact.class - }; - } +@Jpa( annotatedClasses = {TypeCategoryTest.Contact.class} ) +public class TypeCategoryTest { @Test - public void test() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { Contact contact = new Contact(); contact.id = 1; entityManager.persist(contact); @@ -55,7 +47,7 @@ public static class Contact { } @Embeddable - public class Name { + public static class Name { private String firstName; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/bitset/BitSetRegisteredUserTypeTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/bitset/BitSetRegisteredUserTypeTest.java index b276cdb1a5b0..e3b9a8e73a8a 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/bitset/BitSetRegisteredUserTypeTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/bitset/BitSetRegisteredUserTypeTest.java @@ -12,54 +12,56 @@ import jakarta.persistence.NamedNativeQuery; import jakarta.persistence.SqlResultSetMapping; import org.hibernate.annotations.TypeRegistration; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; -import org.junit.Test; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; import java.util.BitSet; -import static org.hibernate.testing.transaction.TransactionUtil.doInHibernate; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -public class BitSetRegisteredUserTypeTest extends BaseCoreFunctionalTestCase { +@DomainModel(annotatedClasses = {BitSetRegisteredUserTypeTest.Product.class}) +@SessionFactory +public class BitSetRegisteredUserTypeTest { - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Product.class - }; + @AfterEach + public void cleanup(SessionFactoryScope scope) { + scope.getSessionFactory().getSchemaManager().truncateMappedObjects(); } @Test - public void test() { + public void test(SessionFactoryScope scope) { BitSet bitSet = BitSet.valueOf(new long[] {1, 2, 3}); - doInHibernate(this::sessionFactory, session -> { + scope.inTransaction( session -> { Product product = new Product(); product.setId(1); product.setBitSet(bitSet); session.persist(product); }); - doInHibernate(this::sessionFactory, session -> { - Product product = session.get(Product.class, 1); + scope.inTransaction( session -> { + Product product = session.find(Product.class, 1); assertEquals(bitSet, product.getBitSet()); }); } @Test - public void testNativeQuery() { + public void testNativeQuery(SessionFactoryScope scope) { BitSet bitSet = BitSet.valueOf(new long[] {1, 2, 3}); - doInHibernate(this::sessionFactory, session -> { + scope.inTransaction( session -> { Product product = new Product(); product.setId(1); product.setBitSet(bitSet); session.persist(product); }); - doInHibernate(this::sessionFactory, session -> { - Product product = (Product) session.createNamedQuery( + scope.inTransaction( session -> { + Product product = session.createNamedQuery( "find_person_by_bitset", Product.class) .setParameter("id", 1L) .getSingleResult(); @@ -68,11 +70,6 @@ public void testNativeQuery() { }); } - @Override - protected boolean isCleanupTestDataRequired() { - return true; - } - @NamedNativeQuery( name = "find_person_by_bitset", query = diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/bitset/BitSetTypeContributor.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/bitset/BitSetTypeContributor.java new file mode 100644 index 000000000000..0729443f4d3f --- /dev/null +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/bitset/BitSetTypeContributor.java @@ -0,0 +1,18 @@ +/* + * SPDX-License-Identifier: Apache-2.0 + * Copyright Red Hat Inc. and Hibernate Authors + */ +package org.hibernate.orm.test.mapping.basic.bitset; + +import org.hibernate.boot.model.TypeContributions; +import org.hibernate.boot.model.TypeContributor; +import org.hibernate.service.ServiceRegistry; + +//tag::basic-custom-type-register-BasicType-example[] +public class BitSetTypeContributor implements TypeContributor { + @Override + public void contribute(TypeContributions typeContributions, ServiceRegistry serviceRegistry) { + typeContributions.contributeType( BitSetType.INSTANCE ); + } +} +//end::basic-custom-type-register-BasicType-example[] diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/bitset/BitSetTypeTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/bitset/BitSetTypeTest.java index fdc490820c47..6d3521b53ed0 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/bitset/BitSetTypeTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/bitset/BitSetTypeTest.java @@ -10,52 +10,48 @@ import org.hibernate.annotations.Parameter; import org.hibernate.annotations.Type; -import org.hibernate.cfg.Configuration; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.ServiceRegistry; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; import org.hibernate.usertype.UserTypeLegacyBridge; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; -import static org.hibernate.testing.transaction.TransactionUtil.doInHibernate; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Vlad Mihalcea */ -public class BitSetTypeTest extends BaseCoreFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Product.class - }; - } - - @Override - protected void configure(Configuration configuration) { - super.configure( configuration ); - //tag::basic-custom-type-register-BasicType-example[] - configuration.registerTypeContributor( (typeContributions, serviceRegistry) -> { - typeContributions.contributeType( BitSetType.INSTANCE ); - } ); - //end::basic-custom-type-register-BasicType-example[] +@DomainModel( + annotatedClasses = {BitSetTypeTest.Product.class}, + typeContributors = {BitSetTypeContributor.class} +) +@SessionFactory +@ServiceRegistry() +public class BitSetTypeTest { + + @AfterEach + public void cleanup(SessionFactoryScope scope) { + scope.getSessionFactory().getSchemaManager().truncateMappedObjects(); } @Test - public void test() { + public void test(SessionFactoryScope scope) { //tag::basic-custom-type-BitSetType-persistence-example[] BitSet bitSet = BitSet.valueOf( new long[] {1, 2, 3} ); - doInHibernate( this::sessionFactory, session -> { + scope.inTransaction( session -> { Product product = new Product( ); product.setId( 1 ); product.setBitSet( bitSet ); session.persist( product ); } ); - doInHibernate( this::sessionFactory, session -> { - Product product = session.get( Product.class, 1 ); + scope.inTransaction( session -> { + Product product = session.find( Product.class, 1 ); assertEquals(bitSet, product.getBitSet()); } ); //end::basic-custom-type-BitSetType-persistence-example[] diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/bitset/BitSetUserTypeTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/bitset/BitSetUserTypeTest.java index 5febbc8a838b..d99b913d10ed 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/bitset/BitSetUserTypeTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/bitset/BitSetUserTypeTest.java @@ -8,8 +8,11 @@ import org.hibernate.annotations.Type; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; -import org.junit.Test; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; import jakarta.persistence.Column; import jakarta.persistence.ColumnResult; @@ -19,20 +22,14 @@ import jakarta.persistence.NamedNativeQuery; import jakarta.persistence.SqlResultSetMapping; -import static org.hibernate.testing.transaction.TransactionUtil.doInHibernate; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Vlad Mihalcea */ -public class BitSetUserTypeTest extends BaseCoreFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Product.class - }; - } +@DomainModel(annotatedClasses = {BitSetUserTypeTest.Product.class}) +@SessionFactory +public class BitSetUserTypeTest { // Note that the following is just for legacy documentation purposes /* @@ -47,37 +44,42 @@ protected void configure(Configuration configuration) { } */ + @AfterEach + public void cleanup(SessionFactoryScope scope) { + scope.getSessionFactory().getSchemaManager().truncateMappedObjects(); + } + @Test - public void test() { + public void test(SessionFactoryScope scope) { BitSet bitSet = BitSet.valueOf(new long[] {1, 2, 3}); - doInHibernate(this::sessionFactory, session -> { + scope.inTransaction( session -> { Product product = new Product(); product.setId(1); product.setBitSet(bitSet); session.persist(product); }); - doInHibernate(this::sessionFactory, session -> { - Product product = session.get(Product.class, 1); + scope.inTransaction( session -> { + Product product = session.find(Product.class, 1); assertEquals(bitSet, product.getBitSet()); }); } @Test - public void testNativeQuery() { + public void testNativeQuery(SessionFactoryScope scope) { BitSet bitSet = BitSet.valueOf(new long[] {1, 2, 3}); - doInHibernate(this::sessionFactory, session -> { + scope.inTransaction( session -> { Product product = new Product(); product.setId(1); product.setBitSet(bitSet); session.persist(product); }); - doInHibernate(this::sessionFactory, session -> { - Product product = (Product) session.createNamedQuery( + scope.inTransaction( session -> { + Product product = session.createNamedQuery( "find_person_by_bitset", Product.class) .setParameter("id", 1L) .getSingleResult(); @@ -86,11 +88,6 @@ public void testNativeQuery() { }); } - @Override - protected boolean isCleanupTestDataRequired() { - return true; - } - @NamedNativeQuery( name = "find_person_by_bitset", query = diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/ArrayTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/ArrayTest.java index 15f5cbe196a9..564e78a9e05b 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/ArrayTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/ArrayTest.java @@ -7,27 +7,19 @@ import jakarta.persistence.Entity; import jakarta.persistence.Id; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; - -import org.junit.Test; - -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.Test; /** * @author Vlad Mihalcea */ -public class ArrayTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Person.class - }; - } +@Jpa( annotatedClasses = {ArrayTest.Person.class} ) +public class ArrayTest { @Test - public void testLifecycle() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void testLifecycle(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { Person person = new Person(1L); String[] phones = new String[2]; phones[0] = "028-234-9876"; @@ -35,7 +27,7 @@ public void testLifecycle() { person.setPhones(phones); entityManager.persist(person); }); - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { Person person = entityManager.find(Person.class, 1L); String[] phones = new String[1]; phones[0] = "072-122-9876"; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/BasicTypeElementCollectionTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/BasicTypeElementCollectionTest.java index 04ba2199bdee..bc23f554d47f 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/BasicTypeElementCollectionTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/BasicTypeElementCollectionTest.java @@ -11,28 +11,22 @@ import jakarta.persistence.Id; import jakarta.persistence.OrderColumn; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; - -import org.junit.Test; - -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * @author Vlad Mihalcea */ -public class BasicTypeElementCollectionTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Person.class - }; - } +@Jpa( annotatedClasses = {BasicTypeElementCollectionTest.Person.class} ) +public class BasicTypeElementCollectionTest { - @Override - public void buildEntityManagerFactory() { - super.buildEntityManagerFactory(); - doInJPA(this::entityManagerFactory, entityManager -> { + @BeforeEach + public void setup(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { Person person = new Person(); person.id = 1L; person.phones.add("027-123-4567"); @@ -41,36 +35,39 @@ public void buildEntityManagerFactory() { }); } + @AfterEach + public void tearDown(EntityManagerFactoryScope scope) { + scope.getEntityManagerFactory().getSchemaManager().truncate(); + } + @Test - public void testProxies() { - doInJPA(this::entityManagerFactory, entityManager -> { - try { - //tag::collections-collection-proxy-usage-example[] - Person person = entityManager.find(Person.class, 1L); - //Throws java.lang.ClassCastException: org.hibernate.collection.internal.PersistentBag cannot be cast to java.util.ArrayList - ArrayList phones = (ArrayList) person.getPhones(); - //end::collections-collection-proxy-usage-example[] - } - catch (Exception expected) { - log.error("Failure", expected); - } + public void testProxies(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { + Assertions.assertThrows( + ClassCastException.class, + () -> { + //tag::collections-collection-proxy-usage-example[] + Person person = entityManager.find(Person.class, 1L); + //Throws java.lang.ClassCastException: org.hibernate.collection.internal.PersistentBag cannot be cast to java.util.ArrayList + ArrayList phones = (ArrayList) person.getPhones(); + //end::collections-collection-proxy-usage-example[] + } + ); }); } @Test - public void testLifecycle() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void testLifecycle(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { Person person = entityManager.find(Person.class, 1L); - log.info("Clear element collection and add element"); //tag::ex-collection-elemental-lifecycle[] person.getPhones().clear(); person.getPhones().add("123-456-7890"); person.getPhones().add("456-000-1234"); //end::ex-collection-elemental-lifecycle[] }); - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { Person person = entityManager.find(Person.class, 1L); - log.info("Remove one element"); //tag::collections-value-type-collection-remove-example[] person.getPhones().remove(0); //end::collections-value-type-collection-remove-example[] diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/BasicTypeOrderColumnElementCollectionTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/BasicTypeOrderColumnElementCollectionTest.java index 19d03eaf831d..2a8ff4b9c4fa 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/BasicTypeOrderColumnElementCollectionTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/BasicTypeOrderColumnElementCollectionTest.java @@ -11,36 +11,27 @@ import jakarta.persistence.Id; import jakarta.persistence.OrderColumn; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; - -import org.junit.Test; - -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.Test; /** * @author Vlad Mihalcea */ -public class BasicTypeOrderColumnElementCollectionTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Person.class - }; - } +@Jpa( annotatedClasses = {BasicTypeOrderColumnElementCollectionTest.Person.class} ) +public class BasicTypeOrderColumnElementCollectionTest { @Test - public void testLifecycle() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void testLifecycle(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { Person person = new Person(); person.id = 1L; person.getPhones().add("123-456-7890"); person.getPhones().add("456-000-1234"); entityManager.persist(person); }); - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { Person person = entityManager.find(Person.class, 1L); - log.info("Remove one element"); //tag::collections-value-type-collection-order-column-remove-example[] person.getPhones().remove(0); //end::collections-value-type-collection-order-column-remove-example[] diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/BidirectionalBagOrphanRemovalTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/BidirectionalBagOrphanRemovalTest.java index c692d95be4f5..8fed58041700 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/BidirectionalBagOrphanRemovalTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/BidirectionalBagOrphanRemovalTest.java @@ -15,28 +15,20 @@ import jakarta.persistence.OneToMany; import org.hibernate.annotations.NaturalId; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; -import org.junit.Test; - -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.Test; /** * @author Vlad Mihalcea */ -public class BidirectionalBagOrphanRemovalTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Person.class, - Phone.class, - }; - } +@Jpa( annotatedClasses = {BidirectionalBagOrphanRemovalTest.Person.class, BidirectionalBagOrphanRemovalTest.Phone.class} ) +public class BidirectionalBagOrphanRemovalTest { @Test - public void testLifecycle() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void testLifecycle(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { Person person = new Person(1L); entityManager.persist(person); person.addPhone(new Phone(1L, "landline", "028-234-9876")); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/BidirectionalBagTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/BidirectionalBagTest.java index a8d56b4edb69..454dc1404ee2 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/BidirectionalBagTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/BidirectionalBagTest.java @@ -15,28 +15,20 @@ import jakarta.persistence.OneToMany; import org.hibernate.annotations.NaturalId; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; -import org.junit.Test; - -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.Test; /** * @author Vlad Mihalcea */ -public class BidirectionalBagTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Person.class, - Phone.class, - }; - } +@Jpa( annotatedClasses = {BidirectionalBagTest.Person.class, BidirectionalBagTest.Phone.class} ) +public class BidirectionalBagTest { @Test - public void testLifecycle() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void testLifecycle(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { Person person = new Person(1L); entityManager.persist(person); //tag::collections-bidirectional-bag-lifecycle-example[] diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/BidirectionalComparatorSortedSetTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/BidirectionalComparatorSortedSetTest.java index 97583be2215a..358a20f9b716 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/BidirectionalComparatorSortedSetTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/BidirectionalComparatorSortedSetTest.java @@ -18,46 +18,38 @@ import org.hibernate.annotations.NaturalId; import org.hibernate.annotations.SortComparator; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; -import org.junit.Assert; -import org.junit.Test; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.Test; -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Vlad Mihalcea */ -public class BidirectionalComparatorSortedSetTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Person.class, - Phone.class, - }; - } +@Jpa( annotatedClasses = {BidirectionalComparatorSortedSetTest.Person.class, BidirectionalComparatorSortedSetTest.Phone.class} ) +public class BidirectionalComparatorSortedSetTest { @Test - public void testLifecycle() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void testLifecycle(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { Person person = new Person(1L); entityManager.persist(person); person.addPhone(new Phone(1L, "landline", "028-234-9876")); person.addPhone(new Phone(2L, "mobile", "072-122-9876")); }); - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { Person person = entityManager.find(Person.class, 1L); Set phones = person.getPhones(); - Assert.assertEquals(2, phones.size()); - phones.stream().forEach(phone -> log.infov("Phone number %s", phone.getNumber())); + assertEquals(2, phones.size()); person.removePhone(phones.iterator().next()); - Assert.assertEquals(1, phones.size()); + assertEquals(1, phones.size()); }); - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { Person person = entityManager.find(Person.class, 1L); Set phones = person.getPhones(); - Assert.assertEquals(1, phones.size()); + assertEquals(1, phones.size()); }); } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/BidirectionalMapTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/BidirectionalMapTest.java index de22ed247b04..11399173576b 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/BidirectionalMapTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/BidirectionalMapTest.java @@ -19,39 +19,30 @@ import jakarta.persistence.MapKeyEnumerated; import jakarta.persistence.OneToMany; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; - -import org.junit.Assert; -import org.junit.Test; - -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Assertions; /** * @author Vlad Mihalcea */ -public class BidirectionalMapTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Person.class, - Phone.class, - }; - } +@Jpa( annotatedClasses = {BidirectionalMapTest.Person.class, BidirectionalMapTest.Phone.class} ) +public class BidirectionalMapTest { @Test - public void testLifecycle() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void testLifecycle(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { Person person = new Person(1L); LocalDateTime now = LocalDateTime.now(); person.addPhone(new Phone(PhoneType.LAND_LINE, "028-234-9876", Timestamp.valueOf(now))); person.addPhone(new Phone(PhoneType.MOBILE, "072-122-9876", Timestamp.valueOf(now.minusDays(1)))); entityManager.persist(person); }); - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { Person person = entityManager.find(Person.class, 1L); Map phones = person.getPhoneRegister(); - Assert.assertEquals(2, phones.size()); + Assertions.assertEquals(2, phones.size()); }); } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/BidirectionalOrderByListTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/BidirectionalOrderByListTest.java index af2d14d97e4f..74c07de0b24c 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/BidirectionalOrderByListTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/BidirectionalOrderByListTest.java @@ -16,28 +16,20 @@ import jakarta.persistence.OrderBy; import org.hibernate.annotations.NaturalId; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; -import org.junit.Test; - -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.Test; /** * @author Vlad Mihalcea */ -public class BidirectionalOrderByListTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Person.class, - Phone.class, - }; - } +@Jpa( annotatedClasses = {BidirectionalOrderByListTest.Person.class, BidirectionalOrderByListTest.Phone.class} ) +public class BidirectionalOrderByListTest { @Test - public void testLifecycle() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void testLifecycle(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { Person person = new Person(1L); entityManager.persist(person); person.addPhone(new Phone(1L, "landline", "028-234-9876")); @@ -45,7 +37,7 @@ public void testLifecycle() { entityManager.flush(); person.removePhone(person.getPhones().get(0)); }); - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { entityManager.find(Person.class, 1L).getPhones().size(); }); } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/BidirectionalOrderColumnListTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/BidirectionalOrderColumnListTest.java index 21cf3323c47e..bee45e448f78 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/BidirectionalOrderColumnListTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/BidirectionalOrderColumnListTest.java @@ -16,28 +16,20 @@ import jakarta.persistence.OrderColumn; import org.hibernate.annotations.NaturalId; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; -import org.junit.Test; - -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.Test; /** * @author Vlad Mihalcea */ -public class BidirectionalOrderColumnListTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Person.class, - Phone.class, - }; - } +@Jpa( annotatedClasses = {BidirectionalOrderColumnListTest.Person.class, BidirectionalOrderColumnListTest.Phone.class} ) +public class BidirectionalOrderColumnListTest { @Test - public void testLifecycle() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void testLifecycle(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { Person person = new Person(1L); entityManager.persist(person); person.addPhone(new Phone(1L, "landline", "028-234-9876")); @@ -45,9 +37,7 @@ public void testLifecycle() { entityManager.flush(); person.removePhone(person.getPhones().get(0)); }); - doInJPA(this::entityManagerFactory, entityManager -> { - entityManager.find(Person.class, 1L).getPhones().size(); - }); + scope.inTransaction( entityManager -> entityManager.find(Person.class, 1L).getPhones().size() ); } @Entity(name = "Person") diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/BidirectionalSetTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/BidirectionalSetTest.java index c8e4c1325229..253653d4f18f 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/BidirectionalSetTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/BidirectionalSetTest.java @@ -15,45 +15,38 @@ import jakarta.persistence.OneToMany; import org.hibernate.annotations.NaturalId; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; -import org.junit.Assert; -import org.junit.Test; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.Test; -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Vlad Mihalcea */ -public class BidirectionalSetTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Person.class, - Phone.class, - }; - } +@Jpa( annotatedClasses = {BidirectionalSetTest.Person.class, BidirectionalSetTest.Phone.class} ) +public class BidirectionalSetTest { @Test - public void testLifecycle() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void testLifecycle(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { Person person = new Person(1L); entityManager.persist(person); person.addPhone(new Phone(1L, "landline", "028-234-9876")); person.addPhone(new Phone(2L, "mobile", "072-122-9876")); }); - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { Person person = entityManager.find(Person.class, 1L); Set phones = person.getPhones(); - Assert.assertEquals(2, phones.size()); + assertEquals(2, phones.size()); person.removePhone(phones.iterator().next()); - Assert.assertEquals(1, phones.size()); + assertEquals(1, phones.size()); }); - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { Person person = entityManager.find(Person.class, 1L); Set phones = person.getPhones(); - Assert.assertEquals(1, phones.size()); + assertEquals(1, phones.size()); }); } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/BidirectionalSortedSetTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/BidirectionalSortedSetTest.java index a0bb47c50a17..86d1926fc3ac 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/BidirectionalSortedSetTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/BidirectionalSortedSetTest.java @@ -17,46 +17,38 @@ import org.hibernate.annotations.NaturalId; import org.hibernate.annotations.SortNatural; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; -import org.junit.Assert; -import org.junit.Test; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.Test; -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Vlad Mihalcea */ -public class BidirectionalSortedSetTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Person.class, - Phone.class, - }; - } +@Jpa( annotatedClasses = {BidirectionalSortedSetTest.Person.class, BidirectionalSortedSetTest.Phone.class} ) +public class BidirectionalSortedSetTest { @Test - public void testLifecycle() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void testLifecycle(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { Person person = new Person(1L); entityManager.persist(person); person.addPhone(new Phone(1L, "landline", "028-234-9876")); person.addPhone(new Phone(2L, "mobile", "072-122-9876")); }); - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { Person person = entityManager.find(Person.class, 1L); Set phones = person.getPhones(); - Assert.assertEquals(2, phones.size()); - phones.stream().forEach(phone -> log.infov("Phone number %s", phone.getNumber())); + assertEquals(2, phones.size()); person.removePhone(phones.iterator().next()); - Assert.assertEquals(1, phones.size()); + assertEquals(1, phones.size()); }); - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { Person person = entityManager.find(Person.class, 1L); Set phones = person.getPhones(); - Assert.assertEquals(1, phones.size()); + assertEquals(1, phones.size()); }); } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/ElementCollectionMapTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/ElementCollectionMapTest.java index 617d9ee4838e..6e9d94cd1b76 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/ElementCollectionMapTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/ElementCollectionMapTest.java @@ -16,29 +16,20 @@ import jakarta.persistence.Temporal; import jakarta.persistence.TemporalType; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; - -import org.junit.Assert; -import org.junit.Test; - -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; /** * @author Vlad Mihalcea */ -public class ElementCollectionMapTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Person.class, - Phone.class, - }; - } +@Jpa( annotatedClasses = {ElementCollectionMapTest.Person.class, ElementCollectionMapTest.Phone.class} ) +public class ElementCollectionMapTest { @Test - public void testLifecycle() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void testLifecycle(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { Person person = new Person(1L); //tag::collections-map-value-type-entity-key-add-example[] person.getPhoneRegister().put( @@ -50,10 +41,10 @@ public void testLifecycle() { //end::collections-map-value-type-entity-key-add-example[] entityManager.persist(person); }); - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { Person person = entityManager.find(Person.class, 1L); Map phones = person.getPhoneRegister(); - Assert.assertEquals(2, phones.size()); + Assertions.assertEquals(2, phones.size()); }); } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/EmbeddableTypeElementCollectionTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/EmbeddableTypeElementCollectionTest.java index 044f5a2a131e..fee790c8cf86 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/EmbeddableTypeElementCollectionTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/EmbeddableTypeElementCollectionTest.java @@ -13,27 +13,19 @@ import jakarta.persistence.Id; import jakarta.persistence.Table; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; - -import org.junit.Test; - -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.Test; /** * @author Vlad Mihalcea */ -public class EmbeddableTypeElementCollectionTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Person.class - }; - } +@Jpa( annotatedClasses = {EmbeddableTypeElementCollectionTest.Person.class} ) +public class EmbeddableTypeElementCollectionTest { @Test - public void testLifecycle() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void testLifecycle(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { Person person = new Person(); person.id = 1L; //tag::collections-embeddable-type-collection-lifecycle-example[] diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/MapKeyClassTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/MapKeyClassTest.java index 29fc2cf96f46..b07d5961e6ad 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/MapKeyClassTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/MapKeyClassTest.java @@ -18,29 +18,22 @@ import jakarta.persistence.MapKeyColumn; import jakarta.persistence.Table; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.Test; -import org.junit.Test; - -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Vlad Mihalcea */ -public class MapKeyClassTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Person.class, - }; - } +@Jpa( annotatedClasses = {MapKeyClassTest.Person.class} ) +public class MapKeyClassTest { @Test - public void testLifecycle() { + public void testLifecycle(EntityManagerFactoryScope scope) { - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { //tag::collections-map-key-class-persist-example[] Person person = new Person(); person.setId(1L); @@ -51,7 +44,7 @@ public void testLifecycle() { //end::collections-map-key-class-persist-example[] }); - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { //tag::collections-map-key-class-fetch-example[] Person person = entityManager.find(Person.class, 1L); assertEquals(2, person.getCallRegister().size()); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/MapKeyTypeTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/MapKeyTypeTest.java index bfacff81664e..7492310e1015 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/MapKeyTypeTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/MapKeyTypeTest.java @@ -17,10 +17,10 @@ import org.hibernate.cfg.AvailableSettings; import org.hibernate.engine.spi.SessionFactoryImplementor; import org.hibernate.jpa.boot.spi.Bootstrap; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; +import org.hibernate.testing.orm.junit.EntityManagerFactoryBasedFunctionalTest; import org.hibernate.type.descriptor.java.JdbcTimestampJavaType; -import org.junit.Test; +import org.junit.jupiter.api.Test; import jakarta.persistence.CollectionTable; import jakarta.persistence.Column; @@ -33,12 +33,12 @@ import jakarta.persistence.Table; import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Vlad Mihalcea */ -public class MapKeyTypeTest extends BaseEntityManagerFunctionalTestCase { +public class MapKeyTypeTest extends EntityManagerFactoryBasedFunctionalTest { @Override protected Class[] getAnnotatedClasses() { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/OrderColumnListIndexBaseTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/OrderColumnListIndexBaseTest.java index 20d9f7746c31..2e2d626bc8ed 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/OrderColumnListIndexBaseTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/OrderColumnListIndexBaseTest.java @@ -5,7 +5,7 @@ package org.hibernate.orm.test.mapping.collections; import java.sql.ResultSet; -import java.sql.SQLException; +import java.sql.Statement; import java.util.ArrayList; import java.util.List; import java.util.Objects; @@ -17,32 +17,25 @@ import jakarta.persistence.OneToMany; import jakarta.persistence.OrderColumn; +import org.hibernate.SessionFactory; import org.hibernate.annotations.ListIndexBase; import org.hibernate.annotations.NaturalId; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; -import org.junit.Test; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.Test; -import static org.hibernate.testing.transaction.TransactionUtil.doInAutoCommit; -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Vlad Mihalcea */ -public class OrderColumnListIndexBaseTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Person.class, - Phone.class, - }; - } +@Jpa( annotatedClasses = {OrderColumnListIndexBaseTest.Person.class, OrderColumnListIndexBaseTest.Phone.class} ) +public class OrderColumnListIndexBaseTest { @Test - public void testLifecycle() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void testLifecycle(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { //tag::collections-customizing-ordered-list-ordinal-persist-example[] Person person = new Person(1L); entityManager.persist(person); @@ -50,47 +43,55 @@ public void testLifecycle() { person.addPhone(new Phone(2L, "mobile", "072-122-9876")); //end::collections-customizing-ordered-list-ordinal-persist-example[] }); - doInAutoCommit( st -> { - try (ResultSet rs = st.executeQuery( "select id, order_id from Phone" )) { - while ( rs.next() ) { - final long id = rs.getLong( 1 ); - if ( id == 1 ) { - assertEquals( 100, rs.getInt( 2 ) ); - } - else if ( id == 2 ) { - assertEquals( 101, rs.getInt( 2 ) ); + scope.getEntityManagerFactory().unwrap( SessionFactory.class ).inSession( + session -> { + session.doWork( conn -> { + try (Statement st = conn.createStatement()) { + st.execute( "select id, order_id from Phone" ); + ResultSet rs = st.getResultSet(); + while ( rs.next() ) { + final long id = rs.getLong( 1 ); + if ( id == 1 ) { + assertEquals( 100, rs.getInt( 2 ) ); + } + else if ( id == 2 ) { + assertEquals( 101, rs.getInt( 2 ) ); + } + } } - } - } - catch (SQLException e) { - throw new RuntimeException( e ); - } - } ); - doInJPA(this::entityManagerFactory, entityManager -> { + } ); + } ); + + scope.inTransaction( entityManager -> { Person person = entityManager.find( Person.class, 1L); person.addPhone(new Phone(3L, "fax", "099-234-9876")); entityManager.persist(person); }); - doInAutoCommit( st -> { - try (ResultSet rs = st.executeQuery( "select id, order_id from Phone" )) { - while ( rs.next() ) { - final long id = rs.getLong( 1 ); - if ( id == 1 ) { - assertEquals( 100, rs.getInt( 2 ) ); - } - else if ( id == 2 ) { - assertEquals( 101, rs.getInt( 2 ) ); - } - else if ( id == 3 ) { - assertEquals( 102, rs.getInt( 2 ) ); - } - } - } - catch (SQLException e) { - throw new RuntimeException( e ); - } - } ); - doInJPA(this::entityManagerFactory, entityManager -> { + + scope.getEntityManagerFactory().unwrap( SessionFactory.class ).inSession( + session -> { + session.doWork( conn -> { + try (Statement st = conn.createStatement()) { + st.execute( "select id, order_id from Phone" ); + try (ResultSet rs = st.getResultSet()) { + while ( rs.next() ) { + final long id = rs.getLong( 1 ); + if ( id == 1 ) { + assertEquals( 100, rs.getInt( 2 ) ); + } + else if ( id == 2 ) { + assertEquals( 101, rs.getInt( 2 ) ); + } + else if ( id == 3 ) { + assertEquals( 102, rs.getInt( 2 ) ); + } + } + } + } + } ); + } ); + + scope.inTransaction( entityManager -> { Person person = entityManager.find( Person.class, 1L); final List phones = person.getPhones(); assertEquals( Long.valueOf( 1L ), phones.get( 0 ).getId() ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/OrderColumnListIndexHHH18771ListInitializerTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/OrderColumnListIndexHHH18771ListInitializerTest.java index bfadaf20077f..31b533bce90b 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/OrderColumnListIndexHHH18771ListInitializerTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/OrderColumnListIndexHHH18771ListInitializerTest.java @@ -10,9 +10,10 @@ import org.hibernate.annotations.Cache; import org.hibernate.annotations.CacheConcurrencyStrategy; import org.hibernate.annotations.ListIndexBase; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; -import org.junit.Test; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.Test; import jakarta.persistence.CascadeType; import jakarta.persistence.Entity; @@ -25,33 +26,27 @@ import jakarta.persistence.OneToMany; import jakarta.persistence.OrderColumn; -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; /** * @author Selaron */ -public class OrderColumnListIndexHHH18771ListInitializerTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Person.class, - Phone.class, - }; - } +@Jpa( annotatedClasses = { + OrderColumnListIndexHHH18771ListInitializerTest.Person.class, OrderColumnListIndexHHH18771ListInitializerTest.Phone.class +} ) +public class OrderColumnListIndexHHH18771ListInitializerTest { @Test - public void testLifecycle() { - doInJPA( this::entityManagerFactory, entityManager -> { + public void testLifecycle(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { Person person = new Person( 1L ); entityManager.persist( person ); person.addPhone( new Phone( 1L ) ); person.getChildren().add( new Person( 2L ) ); person.getChildren().get( 0 ).setMother( person ); } ); - doInJPA( this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { Person person = entityManager.find( Person.class, 1L ); assertNotNull( person ); assertEquals( 1, person.getPhones().size() ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/OrderedBySQLTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/OrderedBySQLTest.java index dc4315b28855..3a5e300238bf 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/OrderedBySQLTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/OrderedBySQLTest.java @@ -6,7 +6,6 @@ import java.util.ArrayList; import java.util.List; -import java.util.Map; import jakarta.persistence.CascadeType; import jakarta.persistence.Entity; @@ -18,39 +17,29 @@ import org.hibernate.annotations.SQLOrder; import org.hibernate.dialect.H2Dialect; -import org.hibernate.metamodel.CollectionClassification; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; -import org.hibernate.testing.RequiresDialect; -import org.junit.Test; +import org.hibernate.testing.orm.junit.RequiresDialect; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.hibernate.testing.orm.junit.Setting; +import org.junit.jupiter.api.Test; import static org.hibernate.cfg.AvailableSettings.DEFAULT_LIST_SEMANTICS; -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Vlad Mihalcea */ @RequiresDialect(H2Dialect.class) -public class OrderedBySQLTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Person.class, - Article.class, - }; - } - - @Override - protected void addConfigOptions(Map options) { - super.addConfigOptions( options ); - options.put( DEFAULT_LIST_SEMANTICS, CollectionClassification.BAG.name() ); - } +@Jpa( + annotatedClasses = {OrderedBySQLTest.Person.class, OrderedBySQLTest.Article.class}, + integrationSettings = {@Setting(name = DEFAULT_LIST_SEMANTICS, value = "BAG")} +) +public class OrderedBySQLTest { @Test - public void testLifecycle() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void testLifecycle(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { Person person = new Person(); person.setId(1L); person.setName("Vlad Mihalcea"); @@ -69,7 +58,7 @@ public void testLifecycle() { ); entityManager.persist(person); }); - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { //tag::collections-customizing-ordered-by-sql-clause-fetching-example[] Person person = entityManager.find(Person.class, 1L); assertEquals( diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/QueueTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/QueueTest.java index b1367c3848bc..66de66e182d7 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/QueueTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/QueueTest.java @@ -16,37 +16,30 @@ import org.hibernate.annotations.CollectionType; import org.hibernate.annotations.NaturalId; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; import org.hibernate.orm.test.mapping.collections.type.QueueType; -import org.junit.Test; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.Test; -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertSame; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; /** * @author Vlad Mihalcea */ -public class QueueTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Person.class, - Phone.class, - }; - } +@Jpa( annotatedClasses = {QueueTest.Person.class, QueueTest.Phone.class} ) +public class QueueTest { @Test - public void test() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { Person person = new Person(1L); person.getPhones().add(new Phone(1L, "landline", "028-234-9876")); person.getPhones().add(new Phone(2L, "mobile", "072-122-9876")); entityManager.persist(person); }); - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { //tag::collections-custom-collection-example[] Person person = entityManager.find(Person.class, 1L); Queue phones = person.getPhones(); @@ -55,7 +48,7 @@ public void test() { assertEquals(1, phones.size()); //end::collections-custom-collection-example[] }); - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { Person person = entityManager.find(Person.class, 1L); person.getPhones().clear(); }); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/UnidirectionalBagTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/UnidirectionalBagTest.java index 586660b9888c..9ab3a861638d 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/UnidirectionalBagTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/UnidirectionalBagTest.java @@ -12,28 +12,19 @@ import jakarta.persistence.Id; import jakarta.persistence.OneToMany; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; - -import org.junit.Test; - -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.Test; /** * @author Vlad Mihalcea */ -public class UnidirectionalBagTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Person.class, - Phone.class, - }; - } +@Jpa( annotatedClasses = {UnidirectionalBagTest.Person.class, UnidirectionalBagTest.Phone.class} ) +public class UnidirectionalBagTest { @Test - public void testLifecycle() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void testLifecycle(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { //tag::collections-unidirectional-bag-lifecycle-example[] Person person = new Person(1L); person.getPhones().add(new Phone(1L, "landline", "028-234-9876")); @@ -41,7 +32,7 @@ public void testLifecycle() { entityManager.persist(person); //end::collections-unidirectional-bag-lifecycle-example[] }); - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { Person person = entityManager.find(Person.class, 1L); person.getPhones().remove(0); }); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/UnidirectionalComparatorSortedSetTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/UnidirectionalComparatorSortedSetTest.java index 3e01f8cb6da7..4bf4f939dc23 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/UnidirectionalComparatorSortedSetTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/UnidirectionalComparatorSortedSetTest.java @@ -17,46 +17,38 @@ import org.hibernate.annotations.NaturalId; import org.hibernate.annotations.SortComparator; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; -import org.junit.Assert; -import org.junit.Test; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.Test; -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Vlad Mihalcea */ -public class UnidirectionalComparatorSortedSetTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Person.class, - Phone.class, - }; - } +@Jpa( annotatedClasses = {UnidirectionalComparatorSortedSetTest.Person.class, UnidirectionalComparatorSortedSetTest.Phone.class} ) +public class UnidirectionalComparatorSortedSetTest { @Test - public void testLifecycle() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void testLifecycle(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { Person person = new Person(1L); person.getPhones().add(new Phone(1L, "landline", "028-234-9876")); person.getPhones().add(new Phone(2L, "mobile", "072-122-9876")); entityManager.persist(person); }); - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { Person person = entityManager.find(Person.class, 1L); Set phones = person.getPhones(); - Assert.assertEquals(2, phones.size()); - phones.stream().forEach(phone -> log.infov("Phone number %s", phone.getNumber())); + assertEquals(2, phones.size()); phones.remove(phones.iterator().next()); - Assert.assertEquals(1, phones.size()); + assertEquals(1, phones.size()); }); - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { Person person = entityManager.find(Person.class, 1L); Set phones = person.getPhones(); - Assert.assertEquals(1, phones.size()); + assertEquals(1, phones.size()); }); } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/UnidirectionalMapTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/UnidirectionalMapTest.java index c19b158fdc00..ea4ef2dbecf0 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/UnidirectionalMapTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/UnidirectionalMapTest.java @@ -21,29 +21,20 @@ import jakarta.persistence.OneToMany; import jakarta.persistence.TemporalType; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; - -import org.junit.Assert; -import org.junit.Test; - -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Assertions; /** * @author Vlad Mihalcea */ -public class UnidirectionalMapTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Person.class, - Phone.class, - }; - } +@Jpa( annotatedClasses = {UnidirectionalMapTest.Person.class, UnidirectionalMapTest.Phone.class} ) +public class UnidirectionalMapTest { @Test - public void testLifecycle() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void testLifecycle(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { Person person = new Person(1L); LocalDateTime now = LocalDateTime.now(); person.addPhone( @@ -54,10 +45,10 @@ public void testLifecycle() { ); entityManager.persist(person); }); - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { Person person = entityManager.find(Person.class, 1L); Map phones = person.getPhoneRegister(); - Assert.assertEquals(2, phones.size()); + Assertions.assertEquals(2, phones.size()); }); } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/UnidirectionalOrderColumnListTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/UnidirectionalOrderColumnListTest.java index 50788d7a22af..5a8593382432 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/UnidirectionalOrderColumnListTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/UnidirectionalOrderColumnListTest.java @@ -13,34 +13,25 @@ import jakarta.persistence.OneToMany; import jakarta.persistence.OrderColumn; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; - -import org.junit.Test; - -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.Test; /** * @author Vlad Mihalcea */ -public class UnidirectionalOrderColumnListTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Person.class, - Phone.class, - }; - } +@Jpa( annotatedClasses = {UnidirectionalOrderColumnListTest.Person.class, UnidirectionalOrderColumnListTest.Phone.class} ) +public class UnidirectionalOrderColumnListTest { @Test - public void testLifecycle() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void testLifecycle(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { Person person = new Person(1L); person.getPhones().add(new Phone(1L, "landline", "028-234-9876")); person.getPhones().add(new Phone(2L, "mobile", "072-122-9876")); entityManager.persist(person); }); - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { Person person = entityManager.find(Person.class, 1L); person.getPhones().remove(0); }); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/UnidirectionalOrderedByListTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/UnidirectionalOrderedByListTest.java index dbba8ade419d..6f3ee2cb6ec9 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/UnidirectionalOrderedByListTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/UnidirectionalOrderedByListTest.java @@ -13,34 +13,25 @@ import jakarta.persistence.OneToMany; import jakarta.persistence.OrderBy; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; - -import org.junit.Test; - -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.Test; /** * @author Vlad Mihalcea */ -public class UnidirectionalOrderedByListTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Person.class, - Phone.class, - }; - } +@Jpa( annotatedClasses = {UnidirectionalOrderedByListTest.Person.class, UnidirectionalOrderedByListTest.Phone.class} ) +public class UnidirectionalOrderedByListTest { @Test - public void testLifecycle() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void testLifecycle(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { Person person = new Person(1L); person.getPhones().add(new Phone(1L, "landline", "028-234-9876")); person.getPhones().add(new Phone(2L, "mobile", "072-122-9876")); entityManager.persist(person); }); - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { Person person = entityManager.find(Person.class, 1L); person.getPhones().remove(0); }); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/UnidirectionalSetTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/UnidirectionalSetTest.java index f97765a5b985..54e306b6eaad 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/UnidirectionalSetTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/UnidirectionalSetTest.java @@ -14,45 +14,38 @@ import jakarta.persistence.OneToMany; import org.hibernate.annotations.NaturalId; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; -import org.junit.Assert; -import org.junit.Test; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.Test; -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Vlad Mihalcea */ -public class UnidirectionalSetTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Person.class, - Phone.class, - }; - } +@Jpa( annotatedClasses = {UnidirectionalSetTest.Person.class, UnidirectionalSetTest.Phone.class} ) +public class UnidirectionalSetTest { @Test - public void testLifecycle() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void testLifecycle(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { Person person = new Person(1L); person.getPhones().add(new Phone(1L, "landline", "028-234-9876")); person.getPhones().add(new Phone(2L, "mobile", "072-122-9876")); entityManager.persist(person); }); - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { Person person = entityManager.find(Person.class, 1L); Set phones = person.getPhones(); - Assert.assertEquals(2, phones.size()); + assertEquals(2, phones.size()); phones.remove(phones.iterator().next()); - Assert.assertEquals(1, phones.size()); + assertEquals(1, phones.size()); }); - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { Person person = entityManager.find(Person.class, 1L); Set phones = person.getPhones(); - Assert.assertEquals(1, phones.size()); + assertEquals(1, phones.size()); }); } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/UnidirectionalSortedSetTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/UnidirectionalSortedSetTest.java index 6e69139add93..6f6006d6289a 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/UnidirectionalSortedSetTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/UnidirectionalSortedSetTest.java @@ -16,46 +16,38 @@ import org.hibernate.annotations.NaturalId; import org.hibernate.annotations.SortNatural; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; -import org.junit.Assert; -import org.junit.Test; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.Test; -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Vlad Mihalcea */ -public class UnidirectionalSortedSetTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Person.class, - Phone.class, - }; - } +@Jpa( annotatedClasses = {UnidirectionalSortedSetTest.Person.class, UnidirectionalSortedSetTest.Phone.class} ) +public class UnidirectionalSortedSetTest { @Test - public void testLifecycle() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void testLifecycle(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { Person person = new Person(1L); person.getPhones().add(new Phone(1L, "landline", "028-234-9876")); person.getPhones().add(new Phone(2L, "mobile", "072-122-9876")); entityManager.persist(person); }); - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { Person person = entityManager.find(Person.class, 1L); Set phones = person.getPhones(); - Assert.assertEquals(2, phones.size()); - phones.stream().forEach(phone -> log.infov("Phone number %s", phone.getNumber())); + assertEquals(2, phones.size()); phones.remove(phones.iterator().next()); - Assert.assertEquals(1, phones.size()); + assertEquals(1, phones.size()); }); - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { Person person = entityManager.find(Person.class, 1L); Set phones = person.getPhones(); - Assert.assertEquals(1, phones.size()); + assertEquals(1, phones.size()); }); } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/custom/basic/UserCollectionTypeAnnotationsVariantTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/custom/basic/UserCollectionTypeAnnotationsVariantTest.java index 8c16dedccc90..31a443769679 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/custom/basic/UserCollectionTypeAnnotationsVariantTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/custom/basic/UserCollectionTypeAnnotationsVariantTest.java @@ -5,20 +5,22 @@ package org.hibernate.orm.test.mapping.collections.custom.basic; import org.hibernate.Hibernate; +import org.hibernate.testing.orm.junit.DomainModel; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Steve Ebersole */ +@DomainModel( + annotatedClasses = {User.class, Email.class}, + concurrencyStrategy = "nonstrict-read-write" +) public class UserCollectionTypeAnnotationsVariantTest extends UserCollectionTypeTest { - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { User.class, Email.class }; - } @Override protected void checkEmailAddressInitialization(User user) { assertTrue( Hibernate.isInitialized( user.getEmailAddresses() ) ); } + } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/custom/basic/UserCollectionTypeHbmVariantTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/custom/basic/UserCollectionTypeHbmVariantTest.java index d25179d3730f..b6b32b57d508 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/custom/basic/UserCollectionTypeHbmVariantTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/custom/basic/UserCollectionTypeHbmVariantTest.java @@ -5,25 +5,22 @@ package org.hibernate.orm.test.mapping.collections.custom.basic; import org.hibernate.Hibernate; +import org.hibernate.testing.orm.junit.DomainModel; -import static org.junit.Assert.assertFalse; +import static org.junit.jupiter.api.Assertions.assertFalse; /** * @author Steve Ebersole */ +@DomainModel( + xmlMappings = { "/org/hibernate/orm/test/mapping/collections/custom/basic/UserPermissions.hbm.xml" }, + concurrencyStrategy = "nonstrict-read-write" +) public class UserCollectionTypeHbmVariantTest extends UserCollectionTypeTest { - @Override - protected String getBaseForMappings() { - return ""; - } - - @Override - public String[] getMappings() { - return new String[] { "/org/hibernate/orm/test/mapping/collections/custom/basic/UserPermissions.hbm.xml" }; - } @Override protected void checkEmailAddressInitialization(User user) { assertFalse( Hibernate.isInitialized( user.getEmailAddresses() ) ); } + } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/custom/basic/UserCollectionTypeTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/custom/basic/UserCollectionTypeTest.java index 2cf2dcd43444..89a00f5f30f9 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/custom/basic/UserCollectionTypeTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/custom/basic/UserCollectionTypeTest.java @@ -8,25 +8,22 @@ import jakarta.persistence.criteria.CriteriaQuery; -import org.hibernate.testing.junit4.BaseNonConfigCoreFunctionalTestCase; -import org.junit.Test; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Max Rydahl Andersen */ -public abstract class UserCollectionTypeTest extends BaseNonConfigCoreFunctionalTestCase { - - @Override - protected String getCacheConcurrencyStrategy() { - return "nonstrict-read-write"; - } +@SessionFactory +public abstract class UserCollectionTypeTest { @Test - public void testBasicOperation() { + public void testBasicOperation(SessionFactoryScope scope) { User u = new User( 1, "max" ); - inTransaction( + scope.inTransaction( s -> { u.getEmailAddresses().add( new Email("max@hibernate.org") ); u.getEmailAddresses().add( new Email("max.andersen@jboss.com") ); @@ -34,29 +31,26 @@ public void testBasicOperation() { } ); - inTransaction( + scope.inTransaction( s -> { CriteriaBuilder criteriaBuilder = s.getCriteriaBuilder(); CriteriaQuery criteria = criteriaBuilder.createQuery( User.class ); criteria.from( User.class ); User u2 = s.createQuery( criteria ).uniqueResult(); -// User u2 = (User) s.createCriteria(User.class).uniqueResult(); checkEmailAddressInitialization( u2 ); - assertEquals( u2.getEmailAddresses().size(), 2 ); + assertEquals( 2, u2.getEmailAddresses().size() ); } ); - inTransaction( + scope.inTransaction( s -> { - User u2 = s.get( User.class, u.getId() ); - u2.getEmailAddresses().size(); - assertEquals( 2, MyListType.lastInstantiationRequest ); - + User u2 = s.find( User.class, u.getId() ); + assertEquals( u2.getEmailAddresses().size(), MyListType.lastInstantiationRequest ); } ); - inTransaction( + scope.inTransaction( s -> s.remove( u ) ); } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/custom/declaredtype/UserCollectionTypeAnnotationsVariantTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/custom/declaredtype/UserCollectionTypeAnnotationsVariantTest.java index a2a855f9215e..6c6ddb37a240 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/custom/declaredtype/UserCollectionTypeAnnotationsVariantTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/custom/declaredtype/UserCollectionTypeAnnotationsVariantTest.java @@ -5,20 +5,22 @@ package org.hibernate.orm.test.mapping.collections.custom.declaredtype; import org.hibernate.Hibernate; +import org.hibernate.testing.orm.junit.DomainModel; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Steve Ebersole */ +@DomainModel( + annotatedClasses = {User.class, Email.class}, + concurrencyStrategy = "nonstrict-read-write" +) public class UserCollectionTypeAnnotationsVariantTest extends UserCollectionTypeTest { - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { User.class, Email.class }; - } @Override protected void checkEmailAddressInitialization(User user) { assertTrue( Hibernate.isInitialized( user.getEmailAddresses() ) ); } + } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/custom/declaredtype/UserCollectionTypeHbmVariantTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/custom/declaredtype/UserCollectionTypeHbmVariantTest.java index 48c01a08a5fe..96f29d842b70 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/custom/declaredtype/UserCollectionTypeHbmVariantTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/custom/declaredtype/UserCollectionTypeHbmVariantTest.java @@ -5,20 +5,22 @@ package org.hibernate.orm.test.mapping.collections.custom.declaredtype; import org.hibernate.Hibernate; +import org.hibernate.testing.orm.junit.DomainModel; -import static org.junit.Assert.assertFalse; +import static org.junit.jupiter.api.Assertions.assertFalse; /** * @author Steve Ebersole */ +@DomainModel( + xmlMappings = { "/org/hibernate/orm/test/mapping/collections/custom/declaredtype/UserPermissions.hbm.xml" }, + concurrencyStrategy = "nonstrict-read-write" +) public class UserCollectionTypeHbmVariantTest extends UserCollectionTypeTest { - @Override - public String[] getMappings() { - return new String[] { "mapping/collections/custom/declaredtype/UserPermissions.hbm.xml" }; - } @Override protected void checkEmailAddressInitialization(User user) { assertFalse( Hibernate.isInitialized( user.getEmailAddresses() ) ); } + } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/custom/declaredtype/UserCollectionTypeTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/custom/declaredtype/UserCollectionTypeTest.java index 8ef8104dd656..a88156b7023d 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/custom/declaredtype/UserCollectionTypeTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/custom/declaredtype/UserCollectionTypeTest.java @@ -7,27 +7,23 @@ import jakarta.persistence.criteria.CriteriaBuilder; import jakarta.persistence.criteria.CriteriaQuery; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.junit.jupiter.api.Test; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; /** * @author Max Rydahl Andersen * @author David Weinberg */ -public abstract class UserCollectionTypeTest extends BaseCoreFunctionalTestCase { - - @Override - protected String getCacheConcurrencyStrategy() { - return "nonstrict-read-write"; - } +@SessionFactory +public abstract class UserCollectionTypeTest { @Test - public void testBasicOperation() { - inTransaction( + public void testBasicOperation(SessionFactoryScope scope) { + scope.inTransaction( s -> { User u = new User( 1, "max" ); u.getEmailAddresses().add( new Email("max@hibernate.org") ); @@ -36,15 +32,14 @@ public void testBasicOperation() { } ); - inTransaction( + scope.inTransaction( s -> { CriteriaBuilder criteriaBuilder = s.getCriteriaBuilder(); CriteriaQuery criteria = criteriaBuilder.createQuery( User.class ); criteria.from( User.class ); User u2 = s.createQuery( criteria ).uniqueResult(); -// User u2 = (User) s.createCriteria(User.class).uniqueResult(); checkEmailAddressInitialization(u2); - assertEquals( u2.getEmailAddresses().size(), 2 ); + assertEquals( 2, u2.getEmailAddresses().size() ); assertNotNull( u2.getEmailAddresses().head()); } ); @@ -52,5 +47,4 @@ public void testBasicOperation() { protected abstract void checkEmailAddressInitialization(User user); - } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/custom/declaredtype/UserWithUnimplementedCollectionTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/custom/declaredtype/UserWithUnimplementedCollectionTest.java index 28e487878b0c..661198d7b17a 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/custom/declaredtype/UserWithUnimplementedCollectionTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/custom/declaredtype/UserWithUnimplementedCollectionTest.java @@ -14,7 +14,7 @@ import jakarta.persistence.OneToMany; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.fail; /** * Test that we get an exception when an attribute whose type is not a Collection diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/custom/parameterized/ParameterizedUserCollectionTypeAnnotationsVariantTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/custom/parameterized/ParameterizedUserCollectionTypeAnnotationsVariantTest.java index 9dbf5a3bdaf0..db5b0b17e9a4 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/custom/parameterized/ParameterizedUserCollectionTypeAnnotationsVariantTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/custom/parameterized/ParameterizedUserCollectionTypeAnnotationsVariantTest.java @@ -4,12 +4,13 @@ */ package org.hibernate.orm.test.mapping.collections.custom.parameterized; +import org.hibernate.testing.orm.junit.DomainModel; + /** * @author Steve Ebersole */ +@DomainModel( + annotatedClasses = {Entity.class} +) public class ParameterizedUserCollectionTypeAnnotationsVariantTest extends ParameterizedUserCollectionTypeTest { - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { Entity.class }; - } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/custom/parameterized/ParameterizedUserCollectionTypeHbmVariantTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/custom/parameterized/ParameterizedUserCollectionTypeHbmVariantTest.java index 378f56e7bc68..eeade21ba044 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/custom/parameterized/ParameterizedUserCollectionTypeHbmVariantTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/custom/parameterized/ParameterizedUserCollectionTypeHbmVariantTest.java @@ -4,11 +4,13 @@ */ package org.hibernate.orm.test.mapping.collections.custom.parameterized; +import org.hibernate.testing.orm.junit.DomainModel; + /** * @author Steve Ebersole */ +@DomainModel( + xmlMappings = { "/org/hibernate/orm/test/mapping/collections/custom/parameterized/Mapping.hbm.xml" } +) public class ParameterizedUserCollectionTypeHbmVariantTest extends ParameterizedUserCollectionTypeTest { - public String[] getMappings() { - return new String[] { "mapping/collections/custom/parameterized/Mapping.hbm.xml" }; - } } 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 4b575db45594..23bdb84db418 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 @@ -5,14 +5,13 @@ package org.hibernate.orm.test.mapping.collections.custom.parameterized; import org.hibernate.Hibernate; -import org.hibernate.Session; -import org.hibernate.Transaction; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; -import org.junit.Test; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * Tes for parameterized user collection types. @@ -20,26 +19,24 @@ * @author Holger Brands * @author Steve Ebersole */ -public abstract class ParameterizedUserCollectionTypeTest extends BaseCoreFunctionalTestCase { +@SessionFactory +public abstract class ParameterizedUserCollectionTypeTest { @SuppressWarnings( {"unchecked"}) @Test - public void testBasicOperation() { - Session s = openSession(); - Transaction t = s.beginTransaction(); - Entity entity = new Entity( "tester" ); - entity.getValues().add( "value-1" ); - s.persist( entity ); - t.commit(); - s.close(); + public void testBasicOperation(SessionFactoryScope scope) { + scope.inTransaction( session -> { + Entity entity = new Entity( "tester" ); + entity.getValues().add( "value-1" ); + session.persist( entity ); + } ); - s = openSession(); - t = s.beginTransaction(); - entity = s.get( Entity.class, "tester" ); - assertTrue( Hibernate.isInitialized( entity.getValues() ) ); - assertEquals( 1, entity.getValues().size() ); - assertEquals( "Hello", ( ( DefaultableList ) entity.getValues() ).getDefaultValue() ); - s.remove( entity ); - t.commit(); - s.close(); + scope.inTransaction( session -> { + Entity entity = session.find( Entity.class, "tester" ); + assertTrue( Hibernate.isInitialized( entity.getValues() ) ); + assertEquals( 1, entity.getValues().size() ); + assertEquals( "Hello", ( ( DefaultableList ) entity.getValues() ).getDefaultValue() ); + session.remove( entity ); + } ); } + } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/AndLobTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/AndLobTest.java index 9b5c502bf12b..65e17a434029 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/AndLobTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/AndLobTest.java @@ -24,8 +24,8 @@ import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; -import static org.hibernate.testing.junit4.ExtraAssertions.assertTyping; -import static org.junit.Assert.assertThat; +import static org.hibernate.testing.orm.junit.ExtraAssertions.assertTyping; +import static org.hamcrest.MatcherAssert.assertThat; /** * Test mapping a model with an attribute combining {@code @Lob} with an AttributeConverter. diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/AndNationalizedTests.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/AndNationalizedTests.java index 237df2d79e76..853969d1de8e 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/AndNationalizedTests.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/AndNationalizedTests.java @@ -20,19 +20,17 @@ import org.hibernate.mapping.PersistentClass; import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseUnitTestCase; import org.hibernate.testing.util.ServiceRegistryUtil; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * Test the combination of @Nationalized and @Convert * * @author Steve Ebersole */ -//@SkipForDialect(value = DB2Dialect.class, comment = "DB2 jdbc driver doesn't support setNString") -public class AndNationalizedTests extends BaseUnitTestCase { +public class AndNationalizedTests { @Test @JiraKey( value = "HHH-9599") public void basicTest() { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/AttributeConverterTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/AttributeConverterTest.java index 84e852c079a7..85e1e5be68b5 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/AttributeConverterTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/AttributeConverterTest.java @@ -40,10 +40,9 @@ import org.hibernate.testing.orm.junit.JiraKey; import org.hibernate.testing.boot.MetadataBuildingContextTestingImpl; -import org.hibernate.testing.junit4.BaseUnitTestCase; import org.hibernate.testing.util.ExceptionUtil; import org.hibernate.testing.util.ServiceRegistryUtil; -import org.junit.Test; +import org.junit.jupiter.api.Test; import jakarta.persistence.AttributeConverter; import jakarta.persistence.Column; @@ -58,18 +57,18 @@ import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.is; -import static org.hibernate.testing.junit4.ExtraAssertions.assertTyping; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.fail; +import static org.hibernate.testing.orm.junit.ExtraAssertions.assertTyping; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.fail; /** * Tests the principle of adding "AttributeConverter" to the mix of {@link Type} resolution * * @author Steve Ebersole */ -public class AttributeConverterTest extends BaseUnitTestCase { +public class AttributeConverterTest { @Test public void testErrorInstantiatingConverterClass() { Configuration cfg = new Configuration(); @@ -313,21 +312,21 @@ public void testBasicUsage() { sf.getStatistics().clear(); session = sf.openSession(); session.beginTransaction(); - session.get( Tester4.class, 1L ); + session.find( Tester4.class, 1L ); session.getTransaction().commit(); session.close(); assertEquals( 0, sf.getStatistics().getEntityUpdateCount() ); session = sf.openSession(); session.beginTransaction(); - Tester4 t4 = (Tester4) session.get( Tester4.class, 1L ); + Tester4 t4 = session.find( Tester4.class, 1L ); t4.code = 300; session.getTransaction().commit(); session.close(); session = sf.openSession(); session.beginTransaction(); - t4 = session.get( Tester4.class, 1L ); + t4 = session.find( Tester4.class, 1L ); assertEquals( 300, t4.code.longValue() ); session.remove( t4 ); session.getTransaction().commit(); @@ -386,7 +385,7 @@ public void testBasicTimestampUsage() { sf.getStatistics().clear(); session = sf.openSession(); session.beginTransaction(); - IrrelevantInstantEntity e = (IrrelevantInstantEntity) session.get( IrrelevantInstantEntity.class, 1L ); + IrrelevantInstantEntity e = session.find( IrrelevantInstantEntity.class, 1L ); session.getTransaction().commit(); session.close(); assertEquals( 0, sf.getStatistics().getEntityUpdateCount() ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/BasicCustomTimeConversionTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/BasicCustomTimeConversionTest.java index 07a39aa24b9b..f1b848b59b35 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/BasicCustomTimeConversionTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/BasicCustomTimeConversionTest.java @@ -4,32 +4,34 @@ */ package org.hibernate.orm.test.mapping.converted.converter; -import java.net.MalformedURLException; import java.time.LocalDate; import jakarta.persistence.AttributeConverter; import jakarta.persistence.Convert; import jakarta.persistence.Entity; import jakarta.persistence.Id; -import org.hibernate.Session; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; import org.hibernate.type.descriptor.converter.spi.JpaAttributeConverter; import org.hibernate.persister.entity.EntityPersister; import org.hibernate.type.Type; import org.hibernate.type.internal.ConvertedBasicTypeImpl; import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseNonConfigCoreFunctionalTestCase; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.hibernate.testing.junit4.ExtraAssertions.assertTyping; -import static org.junit.Assert.assertTrue; +import static org.hibernate.testing.orm.junit.ExtraAssertions.assertTyping; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Steve Ebersole */ @JiraKey( value = "HHH-8842" ) -public class BasicCustomTimeConversionTest extends BaseNonConfigCoreFunctionalTestCase { +@DomainModel(annotatedClasses = {BasicCustomTimeConversionTest.TheEntity.class}) +@SessionFactory +public class BasicCustomTimeConversionTest { static boolean convertToDatabaseColumnCalled = false; static boolean convertToEntityAttributeCalled = false; @@ -68,14 +70,9 @@ public TheEntity(Integer id, CustomLocalDate theDate) { } } - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { TheEntity.class }; - } - @Test - public void testSimpleConvertUsage() throws MalformedURLException { - final EntityPersister ep = sessionFactory().getMappingMetamodel().getEntityDescriptor(TheEntity.class.getName()); + public void testSimpleConvertUsage(SessionFactoryScope scope) { + final EntityPersister ep = scope.getSessionFactory().getMappingMetamodel().getEntityDescriptor(TheEntity.class.getName()); final Type theDatePropertyType = ep.getPropertyType( "theDate" ); final ConvertedBasicTypeImpl type = assertTyping( ConvertedBasicTypeImpl.class, theDatePropertyType ); final JpaAttributeConverter converter = (JpaAttributeConverter) type.getValueConverter(); @@ -83,28 +80,16 @@ public void testSimpleConvertUsage() throws MalformedURLException { resetFlags(); - Session session = openSession(); - session.getTransaction().begin(); - session.persist( new TheEntity( 1, new CustomLocalDate( 2025, 9, 26 ) ) ); - session.getTransaction().commit(); - session.close(); + scope.inTransaction( session -> session.persist( new TheEntity( 1, new CustomLocalDate( 2025, 9, 26 ) ) ) ); assertTrue( convertToDatabaseColumnCalled ); resetFlags(); - session = openSession(); - session.getTransaction().begin(); - session.get( TheEntity.class, 1 ); - session.getTransaction().commit(); - session.close(); + scope.inTransaction( session -> session.find( TheEntity.class, 1 ) ); assertTrue( convertToEntityAttributeCalled ); resetFlags(); - session = openSession(); - session.getTransaction().begin(); - session.createQuery( "delete TheEntity" ).executeUpdate(); - session.getTransaction().commit(); - session.close(); + scope.dropData(); } } 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 ac8840fdabae..74576e313eb1 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 @@ -10,120 +10,92 @@ import jakarta.persistence.Entity; import jakarta.persistence.Id; -import org.hibernate.Session; - import org.hibernate.metamodel.mapping.AttributeMapping; import org.hibernate.persister.entity.EntityPersister; -import org.hibernate.testing.junit4.BaseNonConfigCoreFunctionalTestCase; -import org.junit.Test; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Steve Ebersole */ -public class DirtyCheckingTest extends BaseNonConfigCoreFunctionalTestCase { +@DomainModel(annotatedClasses = {DirtyCheckingTest.SomeEntity.class}) +@SessionFactory +public class DirtyCheckingTest { @Test - public void dirtyCheckAgainstNewNameInstance() { + public void dirtyCheckAgainstNewNameInstance(SessionFactoryScope scope) { SomeEntity simpleEntity = new SomeEntity(); simpleEntity.setId( 1L ); simpleEntity.setName( new Name( "Steven" ) ); - Session session = openSession(); - session.getTransaction().begin(); - session.persist( simpleEntity ); - session.getTransaction().commit(); - session.close(); - - session = openSession(); - session.getTransaction().begin(); - SomeEntity loaded = session.byId( SomeEntity.class ).load( 1L ); - loaded.setName( new Name( "Steve" ) ); - session.getTransaction().commit(); - session.close(); - - session = openSession(); - session.getTransaction().begin(); - loaded = session.byId( SomeEntity.class ).load( 1L ); - assertEquals( "Steve", loaded.getName().getText() ); - session.remove( loaded ); - session.getTransaction().commit(); - session.close(); + scope.inTransaction( session -> session.persist( simpleEntity ) ); + + scope.inTransaction( session -> { + SomeEntity loaded = session.find( SomeEntity.class, 1L ); + loaded.setName( new Name( "Steve" ) ); + } ); + + scope.inTransaction( session -> { + SomeEntity loaded = session.find( SomeEntity.class, 1L ); + assertEquals( "Steve", loaded.getName().getText() ); + session.remove( loaded ); + } ); } @Test - public void dirtyCheckAgainstMutatedNameInstance() { + public void dirtyCheckAgainstMutatedNameInstance(SessionFactoryScope scope) { SomeEntity simpleEntity = new SomeEntity(); simpleEntity.setId( 1L ); simpleEntity.setName( new Name( "Steven" ) ); - Session session = openSession(); - session.getTransaction().begin(); - session.persist( simpleEntity ); - session.getTransaction().commit(); - session.close(); - - session = openSession(); - session.getTransaction().begin(); - SomeEntity loaded = session.byId( SomeEntity.class ).load( 1L ); - loaded.getName().setText( "Steve" ); - session.getTransaction().commit(); - session.close(); - - session = openSession(); - session.getTransaction().begin(); - loaded = session.byId( SomeEntity.class ).load( 1L ); - assertEquals( "Steve", loaded.getName().getText() ); - session.remove( loaded ); - session.getTransaction().commit(); - session.close(); + scope.inTransaction( session -> session.persist( simpleEntity ) ); + + scope.inTransaction( session -> { + SomeEntity loaded = session.find( SomeEntity.class, 1L ); + loaded.getName().setText( "Steve" ); + } ); + + scope.inTransaction( session -> { + SomeEntity loaded = session.find( SomeEntity.class, 1L ); + assertEquals( "Steve", loaded.getName().getText() ); + session.remove( loaded ); + } ); } @Test - public void dirtyCheckAgainstNewNumberInstance() { + public void dirtyCheckAgainstNewNumberInstance(SessionFactoryScope scope) { // numbers (and most other java types) are actually immutable... SomeEntity simpleEntity = new SomeEntity(); simpleEntity.setId( 1L ); simpleEntity.setNumber( 1 ); - Session session = openSession(); - session.getTransaction().begin(); - session.persist( simpleEntity ); - session.getTransaction().commit(); - session.close(); - - session = openSession(); - session.getTransaction().begin(); - SomeEntity loaded = session.byId( SomeEntity.class ).load( 1L ); - loaded.setNumber( 2 ); - session.getTransaction().commit(); - session.close(); - - session = openSession(); - session.getTransaction().begin(); - loaded = session.byId( SomeEntity.class ).load( 1L ); - assertEquals( 2, loaded.getNumber().intValue() ); - session.remove( loaded ); - session.getTransaction().commit(); - session.close(); + scope.inTransaction( session -> session.persist( simpleEntity ) ); + + scope.inTransaction( session -> { + SomeEntity loaded = session.find( SomeEntity.class, 1L ); + loaded.setNumber( 2 ); + } ); + + scope.inTransaction( session -> { + SomeEntity loaded = session.find( SomeEntity.class, 1L ); + assertEquals( 2, loaded.getNumber().intValue() ); + session.remove( loaded ); + } ); } @Test - public void checkConverterMutabilityPlans() { - final EntityPersister persister = sessionFactory().getMappingMetamodel().getEntityDescriptor(SomeEntity.class.getName()); + public void checkConverterMutabilityPlans(SessionFactoryScope scope) { + final EntityPersister persister = scope.getSessionFactory().getMappingMetamodel().getEntityDescriptor(SomeEntity.class.getName()); final AttributeMapping numberMapping = persister.findAttributeMapping( "number" ); final AttributeMapping nameMapping = persister.findAttributeMapping( "name" ); - - assertFalse( persister.getPropertyType( "number" ).isMutable() ); - assertTrue( persister.getPropertyType( "name" ).isMutable() ); - } - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] {SomeEntity.class}; + assertFalse( numberMapping.getExposedMutabilityPlan().isMutable() ); + assertTrue( nameMapping.getExposedMutabilityPlan().isMutable() ); } public static class 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 84356c308372..d7f1d9237f86 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 @@ -4,31 +4,33 @@ */ package org.hibernate.orm.test.mapping.converted.converter; -import java.net.MalformedURLException; import java.util.Date; import jakarta.persistence.AttributeConverter; import jakarta.persistence.Convert; import jakarta.persistence.Entity; import jakarta.persistence.Id; -import org.hibernate.Session; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; import org.hibernate.type.descriptor.converter.spi.JpaAttributeConverter; import org.hibernate.persister.entity.EntityPersister; import org.hibernate.type.Type; import org.hibernate.type.internal.ConvertedBasicTypeImpl; import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseNonConfigCoreFunctionalTestCase; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.hibernate.testing.junit4.ExtraAssertions.assertTyping; -import static org.junit.Assert.assertTrue; +import static org.hibernate.testing.orm.junit.ExtraAssertions.assertTyping; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Steve Ebersole */ @JiraKey( value = "HHH-8807" ) -public class ExplicitDateConvertersTest extends BaseNonConfigCoreFunctionalTestCase { +@DomainModel(annotatedClasses = {ExplicitDateConvertersTest.Entity1.class}) +@SessionFactory +public class ExplicitDateConvertersTest { // NOTE : initially unable to reproduce the reported problem @@ -72,14 +74,9 @@ public Entity1(Integer id, String name, Date theDate) { } } - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { Entity1.class }; - } - @Test - public void testSimpleConvertUsage() throws MalformedURLException { - final EntityPersister ep = sessionFactory().getMappingMetamodel().getEntityDescriptor(Entity1.class.getName()); + public void testSimpleConvertUsage(SessionFactoryScope scope) { + final EntityPersister ep = scope.getSessionFactory().getMappingMetamodel().getEntityDescriptor(Entity1.class.getName()); final Type theDatePropertyType = ep.getPropertyType( "theDate" ); final ConvertedBasicTypeImpl type = assertTyping( ConvertedBasicTypeImpl.class, @@ -90,27 +87,14 @@ public void testSimpleConvertUsage() throws MalformedURLException { resetFlags(); - Session session = openSession(); - session.getTransaction().begin(); - session.persist( new Entity1( 1, "1", new Date() ) ); - session.getTransaction().commit(); - session.close(); - + scope.inTransaction( session -> session.persist(new Entity1(1, "1", new Date())) ); assertTrue( convertToDatabaseColumnCalled ); - resetFlags(); - session = openSession(); - session.getTransaction().begin(); - session.get( Entity1.class, 1 ); - session.getTransaction().commit(); - session.close(); + resetFlags(); + scope.inTransaction( session -> session.find( Entity1.class, 1 ) ); assertTrue( convertToEntityAttributeCalled ); - session = openSession(); - session.getTransaction().begin(); - session.createQuery( "delete Entity1" ).executeUpdate(); - session.getTransaction().commit(); - session.close(); + scope.dropData(); } } 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 7a5bde851526..c98fe0057d46 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 @@ -4,30 +4,32 @@ */ package org.hibernate.orm.test.mapping.converted.converter; -import java.net.MalformedURLException; import jakarta.persistence.AttributeConverter; import jakarta.persistence.Convert; import jakarta.persistence.Entity; import jakarta.persistence.Id; -import org.hibernate.Session; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; import org.hibernate.type.descriptor.converter.spi.JpaAttributeConverter; import org.hibernate.persister.entity.EntityPersister; import org.hibernate.type.Type; import org.hibernate.type.internal.ConvertedBasicTypeImpl; import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseNonConfigCoreFunctionalTestCase; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.hibernate.testing.junit4.ExtraAssertions.assertTyping; -import static org.junit.Assert.assertTrue; +import static org.hibernate.testing.orm.junit.ExtraAssertions.assertTyping; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Steve Ebersole */ @JiraKey( value = "HHH-8809" ) -public class ExplicitEnumConvertersTest extends BaseNonConfigCoreFunctionalTestCase { +@DomainModel(annotatedClasses = {ExplicitEnumConvertersTest.Entity1.class}) +@SessionFactory +public class ExplicitEnumConvertersTest { // NOTE : initially unable to reproduce the reported problem @@ -39,12 +41,6 @@ public static enum MediaType { VIDEO_STREAM } - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { Entity1.class }; - } - - static boolean convertToDatabaseColumnCalled = false; static boolean convertToEntityAttributeCalled = false; @@ -86,8 +82,8 @@ public Entity1(Integer id, String name, MediaType mediaType) { } @Test - public void testSimpleConvertUsage() throws MalformedURLException { - final EntityPersister ep = sessionFactory().getMappingMetamodel().getEntityDescriptor(Entity1.class.getName()); + public void testSimpleConvertUsage(SessionFactoryScope scope) { + final EntityPersister ep = scope.getSessionFactory().getMappingMetamodel().getEntityDescriptor(Entity1.class.getName()); final Type theDatePropertyType = ep.getPropertyType( "mediaType" ); final ConvertedBasicTypeImpl type = assertTyping( ConvertedBasicTypeImpl.class, @@ -97,28 +93,16 @@ public void testSimpleConvertUsage() throws MalformedURLException { assertTrue( MediaTypeConverter.class.isAssignableFrom( converter.getConverterJavaType().getJavaTypeClass() ) ); resetFlags(); - - Session session = openSession(); - session.getTransaction().begin(); - session.persist( new Entity1( 1, "300", MediaType.VIDEO ) ); - session.getTransaction().commit(); - session.close(); + scope.inTransaction( session -> session.persist( new Entity1( 1, "300", MediaType.VIDEO ) ) ); assertTrue( convertToDatabaseColumnCalled ); resetFlags(); - session = openSession(); - session.getTransaction().begin(); - session.get( Entity1.class, 1 ); - session.getTransaction().commit(); - session.close(); + scope.inTransaction( session -> session.find( Entity1.class, 1 ) ); assertTrue( convertToEntityAttributeCalled ); - session = openSession(); - session.getTransaction().begin(); - session.createQuery( "delete Entity1" ).executeUpdate(); - session.getTransaction().commit(); - session.close(); + scope.dropData(); } + } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/ExplicitJavaTypeDescriptorTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/ExplicitJavaTypeDescriptorTest.java index dfda9ddd1afe..7a7d59b99821 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/ExplicitJavaTypeDescriptorTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/ExplicitJavaTypeDescriptorTest.java @@ -16,11 +16,14 @@ import jakarta.persistence.Table; import org.hibernate.annotations.Immutable; -import org.hibernate.boot.MetadataBuilder; -import org.hibernate.boot.MetadataSources; import org.hibernate.boot.model.TypeContributions; -import org.hibernate.boot.registry.StandardServiceRegistryBuilder; +import org.hibernate.boot.model.TypeContributor; import org.hibernate.cfg.AvailableSettings; +import org.hibernate.service.ServiceRegistry; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.hibernate.testing.orm.junit.Setting; import org.hibernate.type.descriptor.WrapperOptions; import org.hibernate.type.descriptor.java.ImmutableMutabilityPlan; import org.hibernate.type.descriptor.java.JavaType; @@ -29,10 +32,9 @@ import org.hibernate.type.descriptor.jdbc.JdbcTypeIndicators; import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseNonConfigCoreFunctionalTestCase; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; @@ -40,7 +42,16 @@ /** * @author Steve Ebersole */ -public class ExplicitJavaTypeDescriptorTest extends BaseNonConfigCoreFunctionalTestCase { +@DomainModel( + annotatedClasses = {ExplicitJavaTypeDescriptorTest.TheEntity.class}, + typeContributors = {ExplicitJavaTypeDescriptorTest.PseudoMutableStateJavaTypeContributor.class} +) +@SessionFactory(generateStatistics = true) +@org.hibernate.testing.orm.junit.ServiceRegistry( + // to make sure we get the deepCopy calls + settings = @Setting(name = AvailableSettings.USE_SECOND_LEVEL_CACHE, value = "true") +) +public class ExplicitJavaTypeDescriptorTest { private static int mutableToDatabaseCallCount; private static int mutableToDomainCallCount; @@ -53,11 +64,9 @@ public class ExplicitJavaTypeDescriptorTest extends BaseNonConfigCoreFunctionalT @Test @JiraKey( value = "HHH-11098" ) - public void testIt() { + public void testIt(SessionFactoryScope scope) { // create data and check assertions - inTransaction( - (session) -> session.persist( new TheEntity( 1 ) ) - ); + scope.inTransaction( session -> session.persist(new TheEntity(1)) ); // assertions based on the persist call assertThat( mutableToDomainCallCount, is(1 ) ); // 1 instead of 0 because of the deep copy call @@ -70,10 +79,10 @@ public void testIt() { assertThat( pseudoMutableToDatabaseCallCount, is(1 ) ); // was 2 (like mutable) before the JavaTypeDescriptor registration } - @Before - public void clearCounts() { + @BeforeEach + public void clearCounts(SessionFactoryScope scope) { // in case we add additional tests - sessionFactory().getStatistics().clear(); + scope.getSessionFactory().getStatistics().clear(); mutableToDatabaseCallCount = 0; mutableToDomainCallCount = 0; @@ -85,34 +94,18 @@ public void clearCounts() { pseudoMutableToDomainCallCount = 0; } - @After - public void dropTestData() { - inTransaction( - session -> session.createQuery( "delete TheEntity" ).executeUpdate() - ); - } - - @Override - protected void configureMetadataBuilder(MetadataBuilder metadataBuilder) { - ( (TypeContributions) metadataBuilder ).contributeJavaType( PseudoMutableStateJavaType.INSTANCE ); - } - - @Override - protected void configureStandardServiceRegistryBuilder(StandardServiceRegistryBuilder ssrb) { - super.configureStandardServiceRegistryBuilder( ssrb ); - - // to make sure we get the deepCopy calls - ssrb.applySetting( AvailableSettings.USE_SECOND_LEVEL_CACHE, "true" ); - ssrb.applySetting( AvailableSettings.GENERATE_STATISTICS, "true" ); + @AfterEach + public void dropTestData(SessionFactoryScope scope) { + scope.dropData(); } - @Override - protected void applyMetadataSources(MetadataSources sources) { - super.applyMetadataSources( sources ); - sources.addAnnotatedClass( TheEntity.class ); + public static class PseudoMutableStateJavaTypeContributor implements TypeContributor { + @Override + public void contribute(TypeContributions typeContributions, ServiceRegistry serviceRegistry) { + typeContributions.contributeJavaType( PseudoMutableStateJavaType.INSTANCE ); + } } - @Entity( name = "TheEntity") @Table( name = "T_ENTITY" ) @Cacheable diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/ExplicitlyNamedConverterClassesTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/ExplicitlyNamedConverterClassesTest.java index 20e592687176..003eac09678c 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/ExplicitlyNamedConverterClassesTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/ExplicitlyNamedConverterClassesTest.java @@ -9,17 +9,21 @@ import jakarta.persistence.Entity; import jakarta.persistence.Id; -import org.hibernate.Session; - -import org.hibernate.testing.junit4.BaseNonConfigCoreFunctionalTestCase; -import org.junit.Test; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.junit.jupiter.api.Test; /** * Tests for asserting correct behavior of applying AttributeConverters explicitly listed in persistence.xml. * * @author Steve Ebersole */ -public class ExplicitlyNamedConverterClassesTest extends BaseNonConfigCoreFunctionalTestCase { +@DomainModel( + annotatedClasses = {ExplicitlyNamedConverterClassesTest.Entity1.class, ExplicitlyNamedConverterClassesTest.NotAutoAppliedConverter.class} +) +@SessionFactory() +public class ExplicitlyNamedConverterClassesTest { // test handling of explicitly named, but non-auto-applied converter ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -51,23 +55,10 @@ public Entity1(Integer id, String name) { } } - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { Entity1.class, NotAutoAppliedConverter.class }; - } - @Test - public void testNonAutoAppliedConvertIsNotApplied() { - Session session = openSession(); - session.getTransaction().begin(); - session.persist( new Entity1( 1, "1" ) ); - session.getTransaction().commit(); - session.close(); + public void testNonAutoAppliedConvertIsNotApplied(SessionFactoryScope scope) { + scope.inTransaction( session -> session.persist(new Entity1(1, "1")) ); - session = openSession(); - session.getTransaction().begin(); - session.createQuery( "delete Entity1" ).executeUpdate(); - session.getTransaction().commit(); - session.close(); + scope.dropData(); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/IgnoreAutoAppliedConverterForIdAndVersionTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/IgnoreAutoAppliedConverterForIdAndVersionTest.java index 63a2d8c0e659..d5ad7b8a8381 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/IgnoreAutoAppliedConverterForIdAndVersionTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/IgnoreAutoAppliedConverterForIdAndVersionTest.java @@ -16,7 +16,7 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; @JiraKey( value = "HHH-19286" ) @DomainModel( annotatedClasses = { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/LongToDateConversionTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/LongToDateConversionTest.java index 49591cd6a2f2..9d330d27eb80 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/LongToDateConversionTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/LongToDateConversionTest.java @@ -27,7 +27,7 @@ import jakarta.persistence.Table; import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; +import static org.hamcrest.MatcherAssert.assertThat; /** * @author Andrea Boriero diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/NullHandlingTests.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/NullHandlingTests.java index 29d352417522..6f949a578c98 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/NullHandlingTests.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/NullHandlingTests.java @@ -4,9 +4,8 @@ */ package org.hibernate.orm.test.mapping.converted.converter; -import java.sql.Connection; import java.sql.ResultSet; -import java.sql.SQLException; +import java.sql.Statement; import java.util.Locale; import jakarta.persistence.AttributeConverter; import jakarta.persistence.Convert; @@ -14,104 +13,70 @@ import jakarta.persistence.Id; import jakarta.persistence.Table; -import org.hibernate.Session; -import org.hibernate.jdbc.Work; - +import org.hibernate.testing.orm.junit.DomainModel; import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; -import org.junit.Test; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Steve Ebersole */ -public class NullHandlingTests extends BaseCoreFunctionalTestCase { - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { TheEntity.class }; - } +@DomainModel(annotatedClasses = {NullHandlingTests.TheEntity.class}) +@SessionFactory +public class NullHandlingTests { @Test @JiraKey( value = "HHH-8697" ) - public void testNullReplacementOnBinding() { + public void testNullReplacementOnBinding(SessionFactoryScope scope) { TheEntity theEntity = new TheEntity( 1 ); - Session session = openSession(); - session.beginTransaction(); // at this point TheEntity.sex is null // lets make sure that the converter is given a chance to adjust that to UNKNOWN... - session.persist( theEntity ); - session.getTransaction().commit(); - session.close(); - - session = openSession(); - session.beginTransaction(); - session.doWork( - new Work() { - @Override - public void execute(Connection connection) throws SQLException { - ResultSet rs = connection.createStatement().executeQuery( "select sex from the_entity where id=1" ); - try { - if ( !rs.next() ) { - throw new RuntimeException( "Could not locate inserted row" ); + scope.inTransaction( session -> session.persist( theEntity ) ); + + scope.inTransaction( session -> { + session.doWork( + conn -> { + try (Statement st = conn.createStatement()) { + st.execute( "select sex from the_entity where id = 1" ); + ResultSet rs = st.getResultSet(); + if ( !rs.next() ) { + throw new RuntimeException( "Could not locate inserted row" ); + } + + String sexDbValue = rs.getString( 1 ); + + if ( rs.next() ) { + throw new RuntimeException( "Found more than one row" ); + } + + assertEquals( Sex.UNKNOWN.name().toLowerCase( Locale.ENGLISH ), sexDbValue ); + } } + ); + } ); - String sexDbValue = rs.getString( 1 ); - - if ( rs.next() ) { - throw new RuntimeException( "Found more than one row" ); - } - - assertEquals( Sex.UNKNOWN.name().toLowerCase( Locale.ENGLISH ), sexDbValue ); - } - finally { - rs.close(); - } - } - } - ); - session.getTransaction().commit(); - session.close(); - - session = openSession(); - session.beginTransaction(); - session.remove( theEntity ); - session.getTransaction().commit(); - session.close(); + scope.inTransaction( session -> session.remove( theEntity ) ); } @Test @JiraKey( value = "HHH-9320" ) - public void testNullReplacementOnExtraction() { - Session session = openSession(); - session.beginTransaction(); - session.doWork( - new Work() { - @Override - public void execute(Connection connection) throws SQLException { - connection.createStatement().execute( "insert into the_entity(id, sex) values (1, null)" ); - } - } - ); - session.getTransaction().commit(); - session.close(); - - session = openSession(); - session.beginTransaction(); + public void testNullReplacementOnExtraction(SessionFactoryScope scope) { + scope.inTransaction( session -> { + session.doWork( + connection -> connection.createStatement().execute( "insert into the_entity(id, sex) values (1, null)" ) + ); + } ); + // at this point TheEntity.sex is null in the database // lets load it and make sure that the converter is given a chance to adjust that to UNKNOWN... - TheEntity theEntity = (TheEntity) session.get( TheEntity.class, 1 ); - session.getTransaction().commit(); - session.close(); - + TheEntity theEntity = scope.fromTransaction( session -> session.find( TheEntity.class, 1 ) ); assertEquals( Sex.UNKNOWN, theEntity.sex ); - session = openSession(); - session.beginTransaction(); - session.remove( theEntity ); - session.getTransaction().commit(); - session.close(); + scope.inTransaction( session -> session.remove( theEntity ) ); } @Entity( name = "TheEntity" ) diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/PackagePrivateAttributeConverterEntityManagerFactoryTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/PackagePrivateAttributeConverterEntityManagerFactoryTest.java index fe2f3f13f1a8..2f3112a8e3f4 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/PackagePrivateAttributeConverterEntityManagerFactoryTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/PackagePrivateAttributeConverterEntityManagerFactoryTest.java @@ -19,7 +19,7 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Vlad Mihalcea diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/PackagePrivateAttributeConverterSessionFactoryTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/PackagePrivateAttributeConverterSessionFactoryTest.java index 363b6f7eb819..64da0806d2dc 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/PackagePrivateAttributeConverterSessionFactoryTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/PackagePrivateAttributeConverterSessionFactoryTest.java @@ -17,7 +17,7 @@ import org.hibernate.testing.orm.junit.SessionFactoryScope; import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Vlad Mihalcea diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/QueryConvertedAttributeTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/QueryConvertedAttributeTest.java index 8acae4fdba03..7147c3bf6708 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/QueryConvertedAttributeTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/QueryConvertedAttributeTest.java @@ -7,11 +7,13 @@ import java.time.Year; import java.util.List; +import org.hibernate.testing.orm.junit.DomainModel; import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseNonConfigCoreFunctionalTestCase; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import jakarta.persistence.AttributeConverter; import jakarta.persistence.Column; @@ -27,18 +29,13 @@ * @author Marco Belladelli */ @JiraKey( value = "HHH-15742") -public class QueryConvertedAttributeTest extends BaseNonConfigCoreFunctionalTestCase { +@DomainModel(annotatedClasses = {QueryConvertedAttributeTest.EntityA.class}) +@SessionFactory +public class QueryConvertedAttributeTest { - @Override - public Class[] getAnnotatedClasses() { - return new Class[] { - EntityA.class, - }; - } - - @Before - public void prepare() { - inTransaction( s -> { + @BeforeEach + public void prepare(SessionFactoryScope scope) { + scope.inTransaction( s -> { EntityA entityA1 = new EntityA( 1, Year.parse("2022") ); EntityA entityA2 = new EntityA( 2, Year.parse("2021") ); EntityA entityA3 = new EntityA( 3, null ); @@ -48,22 +45,20 @@ public void prepare() { } ); } - @After - public void tearDown() { - inTransaction( s -> { - s.createMutationQuery( "delete entitya" ).executeUpdate(); - } ); + @AfterEach + public void tearDown(SessionFactoryScope scope) { + scope.inTransaction( s -> s.createMutationQuery( "delete entitya" ).executeUpdate() ); } @Test - public void testQueryConvertedAttribute() { - inTransaction( s -> { + public void testQueryConvertedAttribute(SessionFactoryScope scope) { + scope.inTransaction( s -> { TypedQuery query = s.createQuery( "from entitya" , EntityA.class); List resultList = query.getResultList(); assertEquals(3, resultList.size()); } ); - inTransaction( s -> { + scope.inTransaction( s -> { TypedQuery query = s.createQuery( "from entitya a where :year is null or a.year = :year", EntityA.class diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/QueryTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/QueryTest.java index ab80290c81a3..82a1548aee97 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/QueryTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/QueryTest.java @@ -19,54 +19,53 @@ import jakarta.persistence.Table; import org.hibernate.HibernateException; -import org.hibernate.Session; import org.hibernate.query.NativeQuery; -import org.hibernate.testing.FailureExpected; -import org.hibernate.testing.junit4.BaseNonConfigCoreFunctionalTestCase; +import org.hibernate.testing.orm.junit.DomainModel; import org.hibernate.testing.orm.junit.JiraKey; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import static junit.framework.Assert.assertNotNull; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertNotNull; /** * Test AttributeConverter functioning in various Query scenarios. * * @author Steve Ebersole */ -public class QueryTest extends BaseNonConfigCoreFunctionalTestCase { +@DomainModel(annotatedClasses = {QueryTest.Employee.class, QueryTest.SalaryConverter.class}) +@SessionFactory +public class QueryTest { - public static final float SALARY = 267.89f; + private static final float SALARY = 267.89f; + private static final float EXPECTED_NON_CONVERTED = 26789f; @Test - public void testJpqlFloatLiteral() { - Session session = openSession(); - session.getTransaction().begin(); - Employee jDoe = (Employee) session.createQuery( "from Employee e where e.salary = " + SALARY + "f" ).uniqueResult(); - assertNotNull( jDoe ); - session.getTransaction().commit(); - session.close(); + public void testJpqlFloatLiteral(SessionFactoryScope scope) { + scope.inTransaction( session -> { + Employee jDoe = session.createQuery( "from Employee e where e.salary = " + SALARY + "f", Employee.class ).uniqueResult(); + assertNotNull( jDoe ); + } ); } @Test - public void testJpqlBooleanLiteral() { - Session session = openSession(); - session.getTransaction().begin(); - assertNotNull( session.createQuery( "from Employee e where e.active = true" ).uniqueResult() ); - assertNull( session.createQuery( "from Employee e where e.active = false" ).uniqueResult() ); - session.getTransaction().commit(); - session.close(); + public void testJpqlBooleanLiteral(SessionFactoryScope scope) { + scope.inTransaction( session -> { + assertNotNull( session.createQuery( "from Employee e where e.active = true", Employee.class ).uniqueResult() ); + assertNull( session.createQuery( "from Employee e where e.active = false", Employee.class ).uniqueResult() ); + } ); } @Test @JiraKey( "HHH-13082" ) - public void testNativeQueryResult() { - inTransaction( (session) -> { - final NativeQuery query = session.createNativeQuery( "select id, salary from EMP", "emp_id_salary" ); + public void testNativeQueryResult(SessionFactoryScope scope) { + scope.inTransaction( session -> { + final NativeQuery query = session.createNativeQuery( "select id, salary from EMP", "emp_id_salary", Object[].class ); final List results = query.list(); assertThat( results ).hasSize( 1 ); @@ -77,8 +76,9 @@ public void testNativeQueryResult() { } ); } - public void testNativeQueryResultWithResultClass() { - inTransaction( (session) -> { + @Test + public void testNativeQueryResultWithResultClass(SessionFactoryScope scope) { + scope.inTransaction( session -> { final NativeQuery query = session.createNativeQuery( "select id, salary from EMP", "emp_id_salary", Object[].class ); final List results = query.list(); @@ -91,42 +91,28 @@ public void testNativeQueryResultWithResultClass() { } @Test - @FailureExpected( jiraKey = "HHH-14975", message = "Not yet implemented" ) @JiraKey( "HHH-14975" ) - public void testAutoAppliedConverterAsNativeQueryResult() { - inTransaction( (session) -> { - final NativeQuery query = session.createNativeQuery( "select id, salary from EMP", "emp_id_salary2" ); + public void testAutoAppliedConverterAsNativeQueryResult(SessionFactoryScope scope) { + scope.inTransaction( (session) -> { + final NativeQuery query = session.createNativeQuery( "select id, salary from EMP", "emp_id_salary2", Object[].class ); final List results = query.list(); assertThat( results ).hasSize( 1 ); final Object[] values = results.get( 0 ); assertThat( values[0] ).isEqualTo( 1 ); - assertThat( values[1] ).isEqualTo( SALARY ); + assertThat( values[1] ).isEqualTo( EXPECTED_NON_CONVERTED ); } ); } - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { Employee.class, SalaryConverter.class }; - } - - @Before - public void setUpTestData() { - Session session = openSession(); - session.getTransaction().begin(); - session.persist( new Employee( 1, new Name( "John", "Q.", "Doe" ), SALARY ) ); - session.getTransaction().commit(); - session.close(); + @BeforeEach + public void setUpTestData(SessionFactoryScope scope) { + scope.inTransaction( session -> session.persist(new Employee(1, new Name("John", "Q.", "Doe" ), SALARY)) ); } - @After - public void cleanUpTestData() { - Session session = openSession(); - session.getTransaction().begin(); - session.createQuery( "delete Employee" ).executeUpdate(); - session.getTransaction().commit(); - session.close(); + @AfterEach + public void cleanUpTestData(SessionFactoryScope scope) { + scope.inTransaction( session -> scope.dropData() ); } @Entity( name = "Employee" ) @@ -191,7 +177,7 @@ public Long convertToDatabaseColumn(Float attribute) { return null; } - return new Long( (long)(attribute*100) ); + return Long.valueOf( (long)(attribute*100) ); } @Override @@ -201,7 +187,7 @@ public Float convertToEntityAttribute(Long dbData) { return null; } - return new Float( ( dbData.floatValue() ) / 100 ); + return Float.valueOf( (dbData.floatValue()) / 100); } } 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 9980b76ef49e..eedcfd9ba22e 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 @@ -5,6 +5,7 @@ package org.hibernate.orm.test.mapping.converted.converter; import java.net.MalformedURLException; +import java.net.URI; import java.net.URL; import jakarta.persistence.AttributeConverter; import jakarta.persistence.Convert; @@ -12,33 +13,31 @@ import jakarta.persistence.Entity; import jakarta.persistence.Id; -import org.hibernate.Session; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; import org.hibernate.type.descriptor.converter.spi.JpaAttributeConverter; import org.hibernate.persister.entity.EntityPersister; import org.hibernate.type.Type; import org.hibernate.type.internal.ConvertedBasicTypeImpl; -import org.hibernate.testing.junit4.BaseNonConfigCoreFunctionalTestCase; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.hibernate.testing.junit4.ExtraAssertions.assertTyping; -import static org.junit.Assert.assertTrue; +import static org.hibernate.testing.orm.junit.ExtraAssertions.assertTyping; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * test handling of an AttributeConverter explicitly named via a @Convert annotation * * @author Steve Ebersole */ -public class SimpleConvertAnnotationTest extends BaseNonConfigCoreFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { Entity1.class, UrlConverter.class, AutoUrlConverter.class }; - } +@DomainModel(annotatedClasses = {SimpleConvertAnnotationTest.Entity1.class, SimpleConvertAnnotationTest.UrlConverter.class, SimpleConvertAnnotationTest.AutoUrlConverter.class}) +@SessionFactory +public class SimpleConvertAnnotationTest { @Test - public void testSimpleConvertUsage() throws MalformedURLException { - final EntityPersister ep = sessionFactory().getMappingMetamodel().getEntityDescriptor(Entity1.class.getName()); + public void testSimpleConvertUsage(SessionFactoryScope scope) { + final EntityPersister ep = scope.getSessionFactory().getMappingMetamodel().getEntityDescriptor(Entity1.class.getName()); final Type websitePropertyType = ep.getPropertyType( "website" ); final ConvertedBasicTypeImpl type = assertTyping( ConvertedBasicTypeImpl.class, @@ -49,19 +48,18 @@ public void testSimpleConvertUsage() throws MalformedURLException { resetFlags(); - Session session = openSession(); - session.getTransaction().begin(); - session.persist( new Entity1( 1, "1", new URL( "http://hibernate.org" ) ) ); - session.getTransaction().commit(); - session.close(); + scope.inTransaction( session -> { + try { + session.persist( new Entity1(1, "1", URI.create("http://hibernate.org" ).toURL()) ); + } + catch (MalformedURLException e) { + // Ignore + } + } ); assertTrue( convertToDatabaseColumnCalled ); - session = openSession(); - session.getTransaction().begin(); - session.createQuery( "delete Entity1" ).executeUpdate(); - session.getTransaction().commit(); - session.close(); + scope.dropData(); } static boolean convertToDatabaseColumnCalled = false; 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 3ddcc6963239..55cd38400099 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 @@ -5,6 +5,7 @@ package org.hibernate.orm.test.mapping.converted.converter; import java.net.MalformedURLException; +import java.net.URI; import java.net.URL; import jakarta.persistence.AttributeConverter; import jakarta.persistence.Convert; @@ -13,33 +14,31 @@ import jakarta.persistence.Entity; import jakarta.persistence.Id; -import org.hibernate.Session; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; import org.hibernate.type.descriptor.converter.spi.JpaAttributeConverter; import org.hibernate.persister.entity.EntityPersister; import org.hibernate.type.Type; import org.hibernate.type.internal.ConvertedBasicTypeImpl; -import org.hibernate.testing.junit4.BaseNonConfigCoreFunctionalTestCase; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.hibernate.testing.junit4.ExtraAssertions.assertTyping; -import static org.junit.Assert.assertTrue; +import static org.hibernate.testing.orm.junit.ExtraAssertions.assertTyping; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * test handling of an AttributeConverter explicitly named via a @Converts annotation * * @author Steve Ebersole */ -public class SimpleConvertsAnnotationTest extends BaseNonConfigCoreFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { Entity1.class, UrlConverter.class, AutoUrlConverter.class }; - } +@DomainModel(annotatedClasses = {SimpleConvertsAnnotationTest.Entity1.class, SimpleConvertsAnnotationTest.UrlConverter.class, SimpleConvertsAnnotationTest.AutoUrlConverter.class }) +@SessionFactory +public class SimpleConvertsAnnotationTest { @Test - public void testSimpleConvertsUsage() throws MalformedURLException { - final EntityPersister ep = sessionFactory().getMappingMetamodel().getEntityDescriptor(Entity1.class.getName()); + public void testSimpleConvertsUsage(SessionFactoryScope scope) { + final EntityPersister ep = scope.getSessionFactory().getMappingMetamodel().getEntityDescriptor(Entity1.class.getName()); final Type websitePropertyType = ep.getPropertyType( "website" ); final ConvertedBasicTypeImpl type = assertTyping( ConvertedBasicTypeImpl.class, @@ -50,19 +49,18 @@ public void testSimpleConvertsUsage() throws MalformedURLException { resetFlags(); - Session session = openSession(); - session.getTransaction().begin(); - session.persist( new Entity1( 1, "1", new URL( "http://hibernate.org" ) ) ); - session.getTransaction().commit(); - session.close(); + scope.inTransaction( session -> { + try { + session.persist( new Entity1(1, "1", URI.create("http://hibernate.org" ).toURL()) ); + } + catch (MalformedURLException e) { + // Ignore + } + } ); assertTrue( convertToDatabaseColumnCalled ); - session = openSession(); - session.getTransaction().begin(); - session.createQuery( "delete Entity1" ).executeUpdate(); - session.getTransaction().commit(); - session.close(); + scope.dropData(); } static boolean convertToDatabaseColumnCalled = false; 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 2810203a1807..5aae5a130e25 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 @@ -13,40 +13,35 @@ import jakarta.persistence.Id; import org.hibernate.persister.entity.EntityPersister; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; import org.hibernate.type.BasicType; import org.hibernate.type.CompositeType; import org.hibernate.type.Type; import org.hibernate.type.descriptor.java.StringJavaType; import org.hibernate.type.descriptor.jdbc.spi.JdbcTypeRegistry; -import org.hibernate.testing.junit4.BaseNonConfigCoreFunctionalTestCase; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.hibernate.testing.junit4.ExtraAssertions.assertTyping; +import static org.hibernate.testing.orm.junit.ExtraAssertions.assertTyping; /** * Tests MappedSuperclass/Entity overriding of Convert definitions * * @author Steve Ebersole */ -public class SimpleEmbeddableOverriddenConverterTest extends BaseNonConfigCoreFunctionalTestCase { - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { Person.class }; - } - - @Override - protected boolean createSchema() { - return false; - } +@DomainModel(annotatedClasses = {SimpleEmbeddableOverriddenConverterTest.Person.class}) +@SessionFactory(exportSchema = false) +public class SimpleEmbeddableOverriddenConverterTest { /** * Test outcome of annotations exclusively. */ @Test - public void testSimpleConvertOverrides() { - final EntityPersister ep = sessionFactory().getMappingMetamodel().getEntityDescriptor(Person.class.getName()); - final JdbcTypeRegistry jdbcTypeRegistry = sessionFactory().getTypeConfiguration() + public void testSimpleConvertOverrides(SessionFactoryScope scope) { + final EntityPersister ep = scope.getSessionFactory().getMappingMetamodel().getEntityDescriptor(Person.class.getName()); + final JdbcTypeRegistry jdbcTypeRegistry = scope.getSessionFactory().getTypeConfiguration() .getJdbcTypeRegistry(); CompositeType homeAddressType = assertTyping( CompositeType.class, ep.getPropertyType( "homeAddress" ) ); BasicType homeAddressCityType = (BasicType) findCompositeAttributeType( homeAddressType, "city" ); 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 0434929aced1..d833921aae2d 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 @@ -12,38 +12,33 @@ import jakarta.persistence.MappedSuperclass; import org.hibernate.persister.entity.EntityPersister; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; import org.hibernate.type.BasicType; import org.hibernate.type.descriptor.java.StringJavaType; import org.hibernate.type.descriptor.jdbc.spi.JdbcTypeRegistry; -import org.hibernate.testing.junit4.BaseNonConfigCoreFunctionalTestCase; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.hibernate.testing.junit4.ExtraAssertions.assertTyping; +import static org.hibernate.testing.orm.junit.ExtraAssertions.assertTyping; /** * Tests MappedSuperclass/Entity overriding of Convert definitions * * @author Steve Ebersole */ -public class SimpleOverriddenConverterTest extends BaseNonConfigCoreFunctionalTestCase { - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { Super.class, Sub.class }; - } - - @Override - protected boolean createSchema() { - return false; - } +@DomainModel(annotatedClasses = {SimpleOverriddenConverterTest.Super.class, SimpleOverriddenConverterTest.Sub.class}) +@SessionFactory(exportSchema = false) +public class SimpleOverriddenConverterTest { /** * Test outcome of annotations exclusively. */ @Test - public void testSimpleConvertOverrides() { - final EntityPersister ep = sessionFactory().getMappingMetamodel().getEntityDescriptor(Sub.class.getName()); - final JdbcTypeRegistry jdbcTypeRegistry = sessionFactory().getTypeConfiguration().getJdbcTypeRegistry(); + public void testSimpleConvertOverrides(SessionFactoryScope scope) { + final EntityPersister ep = scope.getSessionFactory().getMappingMetamodel().getEntityDescriptor(Sub.class.getName()); + final JdbcTypeRegistry jdbcTypeRegistry = scope.getSessionFactory().getTypeConfiguration().getJdbcTypeRegistry(); BasicType type = (BasicType) ep.getPropertyType( "it" ); assertTyping( StringJavaType.class, type.getJavaTypeDescriptor() ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/SimpleXmlOverriddenTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/SimpleXmlOverriddenTest.java index 4a096dbe8326..f2461f5480f8 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/SimpleXmlOverriddenTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/SimpleXmlOverriddenTest.java @@ -12,9 +12,9 @@ import org.hibernate.boot.Metadata; import org.hibernate.boot.MetadataSources; -import org.hibernate.boot.registry.StandardServiceRegistry; -import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.mapping.PersistentClass; +import org.hibernate.testing.orm.junit.ServiceRegistry; +import org.hibernate.testing.orm.junit.ServiceRegistryScope; import org.hibernate.type.descriptor.converter.spi.JpaAttributeConverter; import org.hibernate.type.BasicType; import org.hibernate.type.Type; @@ -22,41 +22,25 @@ import org.hibernate.type.descriptor.jdbc.spi.JdbcTypeRegistry; import org.hibernate.type.internal.ConvertedBasicTypeImpl; -import org.hibernate.testing.junit4.BaseUnitTestCase; -import org.hibernate.testing.util.ServiceRegistryUtil; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.hibernate.testing.junit4.ExtraAssertions.assertTyping; -import static org.junit.Assert.assertTrue; +import static org.hibernate.testing.orm.junit.ExtraAssertions.assertTyping; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * Test simple application of Convert annotation via XML. * * @author Steve Ebersole */ -public class SimpleXmlOverriddenTest extends BaseUnitTestCase { - private StandardServiceRegistry ssr; - - @Before - public void before() { - ssr = ServiceRegistryUtil.serviceRegistry(); - } - - @After - public void after() { - if ( ssr != null ) { - StandardServiceRegistryBuilder.destroy( ssr ); - } - } +@ServiceRegistry +public class SimpleXmlOverriddenTest { /** * A baseline test, with an explicit @Convert annotation that should be in effect */ @Test - public void baseline() { - Metadata metadata = new MetadataSources( ssr ) + public void baseline(ServiceRegistryScope scope) { + Metadata metadata = new MetadataSources( scope.getRegistry() ) .addAnnotatedClass( TheEntity.class ) .buildMetadata(); @@ -71,9 +55,9 @@ public void baseline() { * Test outcome of applying overrides via orm.xml, specifically at the attribute level */ @Test - public void testDefinitionAtAttributeLevel() { + public void testDefinitionAtAttributeLevel(ServiceRegistryScope scope) { // NOTE : simple-override.xml applied disable-conversion="true" at the attribute-level - Metadata metadata = new MetadataSources( ssr ) + Metadata metadata = new MetadataSources( scope.getRegistry() ) .addAnnotatedClass( TheEntity.class ) .addResource( "org/hibernate/test/converter/simple-override.xml" ) .buildMetadata(); @@ -90,9 +74,9 @@ public void testDefinitionAtAttributeLevel() { * Test outcome of applying overrides via orm.xml, specifically at the entity level */ @Test - public void testDefinitionAtEntityLevel() { + public void testDefinitionAtEntityLevel(ServiceRegistryScope scope) { // NOTE : simple-override2.xml applied disable-conversion="true" at the entity-level - Metadata metadata = new MetadataSources( ssr ) + Metadata metadata = new MetadataSources( scope.getRegistry() ) .addAnnotatedClass( TheEntity2.class ) .addResource( "org/hibernate/test/converter/simple-override2.xml" ) .buildMetadata(); 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 18f3f5045970..e06e7c4aff73 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 @@ -13,18 +13,19 @@ import jakarta.persistence.PrePersist; import jakarta.persistence.PreUpdate; -import org.hibernate.Session; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; import org.hibernate.type.descriptor.converter.spi.JpaAttributeConverter; import org.hibernate.persister.entity.EntityPersister; import org.hibernate.type.Type; import org.hibernate.type.internal.ConvertedBasicTypeImpl; import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseNonConfigCoreFunctionalTestCase; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.hibernate.testing.junit4.ExtraAssertions.assertTyping; -import static org.junit.Assert.assertTrue; +import static org.hibernate.testing.orm.junit.ExtraAssertions.assertTyping; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * Jira HHH-8812 claims that explicit {@link jakarta.persistence.Convert} annotations are not processed when a orm.xml @@ -33,16 +34,12 @@ * @author Steve Ebersole */ @JiraKey( value = "HHH-8812" ) -public class XmlWithExplicitConvertAnnotationsTest extends BaseNonConfigCoreFunctionalTestCase { - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { Entity1.class }; - } - - @Override - protected String[] getXmlFiles() { - return new String[] { "org/hibernate/test/converter/mixed.xml" }; - } +@DomainModel( + annotatedClasses = {XmlWithExplicitConvertAnnotationsTest.Entity1.class}, + xmlMappings = {"org/hibernate/test/converter/mixed.xml"} +) +@SessionFactory +public class XmlWithExplicitConvertAnnotationsTest { // NOTE : essentially the same exact test as ExplicitDateConvertersTest, but here we will mix annotations and xml @@ -95,8 +92,8 @@ private void listen(Object entity) { } @Test - public void testSimpleConvertUsage() throws MalformedURLException { - final EntityPersister ep = sessionFactory().getMappingMetamodel().getEntityDescriptor(Entity1.class.getName()); + public void testSimpleConvertUsage(SessionFactoryScope scope) throws MalformedURLException { + final EntityPersister ep = scope.getSessionFactory().getMappingMetamodel().getEntityDescriptor(Entity1.class.getName()); final Type theDatePropertyType = ep.getPropertyType( "theDate" ); final ConvertedBasicTypeImpl type = assertTyping( ConvertedBasicTypeImpl.class, @@ -107,28 +104,15 @@ public void testSimpleConvertUsage() throws MalformedURLException { resetFlags(); - Session session = openSession(); - session.getTransaction().begin(); - session.persist( new Entity1( 1, "1", new Date() ) ); - session.getTransaction().commit(); - session.close(); - + scope.inTransaction( session -> session.persist(new Entity1(1, "1", new Date())) ); assertTrue( convertToDatabaseColumnCalled ); - resetFlags(); - session = openSession(); - session.getTransaction().begin(); - session.get( Entity1.class, 1 ); - session.getTransaction().commit(); - session.close(); + resetFlags(); + scope.inTransaction( session -> session.find( Entity1.class, 1 ) ); assertTrue( convertToEntityAttributeCalled ); - session = openSession(); - session.getTransaction().begin(); - session.createQuery( "delete Entity1" ).executeUpdate(); - session.getTransaction().commit(); - session.close(); + scope.dropData(); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/elementCollection/CollectionCompositeElementConversionTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/elementCollection/CollectionCompositeElementConversionTest.java index 1cd79a32311a..f0e34c7aa3a5 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/elementCollection/CollectionCompositeElementConversionTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/elementCollection/CollectionCompositeElementConversionTest.java @@ -24,7 +24,7 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Steve Ebersole @@ -49,9 +49,7 @@ public void testElementCollectionConversion(SessionFactoryScope scope) { ); scope.inTransaction( - (session) -> { - assertEquals( 1, session.get( Disguise.class, 1 ).traits.size() ); - } + session -> assertEquals( 1, session.find( Disguise.class, 1 ).traits.size() ) ); } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/elementCollection/CollectionCompositeElementExplicitConversionTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/elementCollection/CollectionCompositeElementExplicitConversionTest.java index 4802dfa1c082..ba5ee4d21f0e 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/elementCollection/CollectionCompositeElementExplicitConversionTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/elementCollection/CollectionCompositeElementExplicitConversionTest.java @@ -37,7 +37,7 @@ import org.hamcrest.CoreMatchers; -import static org.junit.Assert.assertThat; +import static org.hamcrest.MatcherAssert.assertThat; /** * Similar to {@link CollectionCompositeElementConversionTest} except here we have an diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/elementCollection/CollectionElementConversionTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/elementCollection/CollectionElementConversionTest.java index 46c6c8be067e..0ee11689d1b3 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/elementCollection/CollectionElementConversionTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/elementCollection/CollectionElementConversionTest.java @@ -25,7 +25,7 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Steve Ebersole @@ -56,7 +56,7 @@ public void testElementCollectionConversion(SessionFactoryScope scope) { scope.inTransaction( (session) -> { - final Customer customer = session.get( Customer.class, 1 ); + final Customer customer = session.find( Customer.class, 1 ); assertEquals( customer.set, customer.set ); assertEquals( customer.map, customer.map ); } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/elementCollection/CollectionElementExplicitConversionTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/elementCollection/CollectionElementExplicitConversionTest.java index 3044193ee930..cd82a4e59164 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/elementCollection/CollectionElementExplicitConversionTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/elementCollection/CollectionElementExplicitConversionTest.java @@ -27,7 +27,7 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Steve Ebersole @@ -53,9 +53,7 @@ public void testElementCollectionConversion(SessionFactoryScope scope) { ); scope.inTransaction( - (session) -> { - assertEquals( 1, session.get( Customer.class, 1 ).colors.size() ); - } + session -> assertEquals( 1, session.find( Customer.class, 1 ).colors.size() ) ); } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/elementCollection/ElementCollectionTests.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/elementCollection/ElementCollectionTests.java index a0a29d8ce015..bf26e260f1cc 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/elementCollection/ElementCollectionTests.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/elementCollection/ElementCollectionTests.java @@ -38,9 +38,9 @@ import jakarta.persistence.MapKeyColumn; import jakarta.persistence.Table; -import static org.hibernate.testing.junit4.ExtraAssertions.assertTyping; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.hibernate.testing.orm.junit.ExtraAssertions.assertTyping; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; /** * Test for {@link CollectionPropertyHolder}. diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/generics/ParameterizedAttributeConverterParameterTypeTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/generics/ParameterizedAttributeConverterParameterTypeTest.java index 31908fc9be3d..81a948601425 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/generics/ParameterizedAttributeConverterParameterTypeTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/generics/ParameterizedAttributeConverterParameterTypeTest.java @@ -28,9 +28,9 @@ import org.hibernate.testing.orm.junit.ServiceRegistryScope; import org.junit.jupiter.api.Test; -import static org.hibernate.testing.junit4.ExtraAssertions.assertTyping; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.hibernate.testing.orm.junit.ExtraAssertions.assertTyping; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * Test the ability to interpret and understand AttributeConverter impls which diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/literal/QueryLiteralTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/literal/QueryLiteralTest.java index 78d7a540613c..719029f85af8 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/literal/QueryLiteralTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/literal/QueryLiteralTest.java @@ -27,10 +27,10 @@ import org.junit.jupiter.api.Test; import static org.hamcrest.Matchers.instanceOf; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Janario Oliveira diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/map/MapElementConversionTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/map/MapElementConversionTest.java index 166a3330a9d1..575eb3a66045 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/map/MapElementConversionTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/map/MapElementConversionTest.java @@ -25,7 +25,7 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Steve Ebersole @@ -50,9 +50,7 @@ public void testElementCollectionConversion(SessionFactoryScope scope) { ); scope.inTransaction( - (session) -> { - assertEquals( 1, session.get( Customer.class, 1 ).colors.size() ); - } + session -> assertEquals( 1, session.find( Customer.class, 1 ).colors.size() ) ); } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/map/MapKeyAttributeConverterTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/map/MapKeyAttributeConverterTest.java index f29ba38f92ea..61a52e3eaf24 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/map/MapKeyAttributeConverterTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/map/MapKeyAttributeConverterTest.java @@ -13,6 +13,7 @@ import jakarta.persistence.Entity; import jakarta.persistence.EnumType; import jakarta.persistence.Enumerated; +import jakarta.persistence.FetchType; import jakarta.persistence.GeneratedValue; import jakarta.persistence.GenerationType; import jakarta.persistence.Id; @@ -22,215 +23,240 @@ import jakarta.persistence.OneToMany; import jakarta.persistence.Table; -import org.hibernate.Transaction; +import org.hibernate.Session; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.junit.jupiter.api.Test; -import org.hibernate.testing.junit4.BaseNonConfigCoreFunctionalTestCase; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Janario Oliveira */ -public class MapKeyAttributeConverterTest extends BaseNonConfigCoreFunctionalTestCase { - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - MapEntity.class, - MapValue.class, +@DomainModel( + annotatedClasses = { + MapKeyAttributeConverterTest.MapEntity.class, + MapKeyAttributeConverterTest.MapValue.class, ColorTypeConverter.class, - CustomColorTypeConverter.class, - ImplicitEnumMapKeyConverter.class, - ExplicitEnumMapKeyConverter.class, - ImplicitEnumMapKeyOverridedConverter.class - }; - } + MapKeyAttributeConverterTest.CustomColorTypeConverter.class, + MapKeyAttributeConverterTest.ImplicitEnumMapKeyConverter.class, + MapKeyAttributeConverterTest.ExplicitEnumMapKeyConverter.class, + MapKeyAttributeConverterTest.ImplicitEnumMapKeyOverriddenConverter.class + } +) +@SessionFactory +public class MapKeyAttributeConverterTest { @Test - public void testImplicitType() { - MapValue mapValue = create(); - mapValue.implicitType = ColorType.BLUE; - mapValue.mapEntity.implicitType.put( mapValue.implicitType, mapValue ); - - MapEntity found = persist( mapValue.mapEntity ); - - assertEquals( 1, found.implicitType.size() ); - MapValue foundValue = found.implicitType.get( ColorType.BLUE ); - assertEquals( ColorType.BLUE, foundValue.implicitType ); - - assertEquals( "blue", findDatabaseValue( foundValue, "implicitType" ) ); - getSession().close(); + public void testImplicitType(SessionFactoryScope scope) { + MapEntity found = scope.fromTransaction( session -> { + MapValue mapValue = create(); + mapValue.implicitType = ColorType.BLUE; + mapValue.mapEntity.implicitType.put( mapValue.implicitType, mapValue ); + + return persist( session, mapValue.mapEntity ); + } ); + + scope.inSession( session -> { + assertEquals( 1, found.implicitType.size() ); + MapValue foundValue = found.implicitType.get( ColorType.BLUE ); + assertEquals( ColorType.BLUE, foundValue.implicitType ); + + assertEquals( "blue", findDatabaseValue( session, foundValue.id, "implicitType", String.class ) ); + } ); } @Test - public void testExplicitType() { - MapValue mapValue = create(); - mapValue.explicitType = ColorType.RED; - mapValue.mapEntity.explicitType.put( mapValue.explicitType, mapValue ); + public void testExplicitType(SessionFactoryScope scope) { + MapEntity found = scope.fromTransaction( session -> { + MapValue mapValue = create(); + mapValue.explicitType = ColorType.RED; + mapValue.mapEntity.explicitType.put( mapValue.explicitType, mapValue ); + + return persist( session, mapValue.mapEntity ); + } ); - MapEntity found = persist( mapValue.mapEntity ); + scope.inSession( session -> { - assertEquals( 1, found.explicitType.size() ); - MapValue foundValue = found.explicitType.get( ColorType.RED ); - assertEquals( ColorType.RED, foundValue.explicitType ); + assertEquals( 1, found.explicitType.size() ); + MapValue foundValue = found.explicitType.get( ColorType.RED ); + assertEquals( ColorType.RED, foundValue.explicitType ); - assertEquals( "COLOR-red", findDatabaseValue( foundValue, "explicitType" ) ); - getSession().close(); + assertEquals( "COLOR-red", findDatabaseValue( session, foundValue.id, "explicitType", String.class ) ); + } ); } @Test - public void testEnumDefaultType() { - MapValue mapValue = create(); - mapValue.enumDefault = EnumMapKey.VALUE_1; - mapValue.mapEntity.enumDefaultType.put( mapValue.enumDefault, mapValue ); - - MapEntity found = persist( mapValue.mapEntity ); - - assertEquals( 1, found.enumDefaultType.size() ); - MapValue foundValue = found.enumDefaultType.get( EnumMapKey.VALUE_1 ); - assertEquals( EnumMapKey.VALUE_1, foundValue.enumDefault ); - - assertEquals( 0, ((Number) findDatabaseValue( foundValue, "enumDefault" )).intValue() ); - getSession().close(); + public void testEnumDefaultType(SessionFactoryScope scope) { + MapEntity found = scope.fromTransaction( session -> { + MapValue mapValue = create(); + mapValue.enumDefault = EnumMapKey.VALUE_1; + mapValue.mapEntity.enumDefaultType.put( mapValue.enumDefault, mapValue ); + + return persist( session, mapValue.mapEntity ); + } ); + + scope.inSession( session -> { + assertEquals( 1, found.enumDefaultType.size() ); + MapValue foundValue = found.enumDefaultType.get( EnumMapKey.VALUE_1 ); + assertEquals( EnumMapKey.VALUE_1, foundValue.enumDefault ); + + assertEquals( 0, findDatabaseValue( session, foundValue.id, "enumDefault", Integer.class ) ); + } ); } @Test - public void testEnumExplicitOrdinalType() { - MapValue mapValue = create(); - mapValue.enumExplicitOrdinal = EnumMapKey.VALUE_2; - mapValue.mapEntity.enumExplicitOrdinalType.put( mapValue.enumExplicitOrdinal, mapValue ); - - MapEntity found = persist( mapValue.mapEntity ); - - assertEquals( 1, found.enumExplicitOrdinalType.size() ); - MapValue foundValue = found.enumExplicitOrdinalType.get( EnumMapKey.VALUE_2 ); - assertEquals( EnumMapKey.VALUE_2, foundValue.enumExplicitOrdinal ); - - assertEquals( 1, ((Number) findDatabaseValue( foundValue, "enumExplicitOrdinal" )).intValue() ); - getSession().close(); + public void testEnumExplicitOrdinalType(SessionFactoryScope scope) { + MapEntity found = scope.fromTransaction( session -> { + MapValue mapValue = create(); + mapValue.enumExplicitOrdinal = EnumMapKey.VALUE_2; + mapValue.mapEntity.enumExplicitOrdinalType.put( mapValue.enumExplicitOrdinal, mapValue ); + + return persist( session, mapValue.mapEntity ); + } ); + + scope.inSession( session -> { + assertEquals( 1, found.enumExplicitOrdinalType.size() ); + MapValue foundValue = found.enumExplicitOrdinalType.get( EnumMapKey.VALUE_2 ); + assertEquals( EnumMapKey.VALUE_2, foundValue.enumExplicitOrdinal ); + + assertEquals( 1, findDatabaseValue( session, foundValue.id, "enumExplicitOrdinal", Integer.class ) ); + } ); } @Test - public void testEnumExplicitStringType() { - MapValue mapValue = create(); - mapValue.enumExplicitString = EnumMapKey.VALUE_1; - mapValue.mapEntity.enumExplicitStringType.put( mapValue.enumExplicitString, mapValue ); - - MapEntity found = persist( mapValue.mapEntity ); - - assertEquals( 1, found.enumExplicitStringType.size() ); - MapValue foundValue = found.enumExplicitStringType.get( EnumMapKey.VALUE_1 ); - assertEquals( EnumMapKey.VALUE_1, foundValue.enumExplicitString ); - - assertEquals( "VALUE_1", findDatabaseValue( foundValue, "enumExplicitString" ) ); - getSession().close(); + public void testEnumExplicitStringType(SessionFactoryScope scope) { + MapEntity found = scope.fromTransaction( session -> { + MapValue mapValue = create(); + mapValue.enumExplicitString = EnumMapKey.VALUE_1; + mapValue.mapEntity.enumExplicitStringType.put( mapValue.enumExplicitString, mapValue ); + + return persist( session, mapValue.mapEntity ); + } ); + + scope.inSession( session -> { + assertEquals( 1, found.enumExplicitStringType.size() ); + MapValue foundValue = found.enumExplicitStringType.get( EnumMapKey.VALUE_1 ); + assertEquals( EnumMapKey.VALUE_1, foundValue.enumExplicitString ); + + assertEquals( "VALUE_1", findDatabaseValue( session, foundValue.id, "enumExplicitString", String.class ) ); + } ); } @Test - public void testEnumExplicitType() { - MapValue mapValue = create(); - mapValue.enumExplicit = EnumMapKey.VALUE_2; - mapValue.mapEntity.enumExplicitType.put( mapValue.enumExplicit, mapValue ); - - MapEntity found = persist( mapValue.mapEntity ); - - assertEquals( 1, found.enumExplicitType.size() ); - MapValue foundValue = found.enumExplicitType.get( EnumMapKey.VALUE_2 ); - assertEquals( EnumMapKey.VALUE_2, foundValue.enumExplicit ); - - assertEquals( "2", findDatabaseValue( foundValue, "enumExplicit" ) ); - getSession().close(); + public void testEnumExplicitType(SessionFactoryScope scope) { + MapEntity found = scope.fromTransaction( session -> { + MapValue mapValue = create(); + mapValue.enumExplicit = EnumMapKey.VALUE_2; + mapValue.mapEntity.enumExplicitType.put( mapValue.enumExplicit, mapValue ); + + return persist( session, mapValue.mapEntity ); + } ); + + scope.inSession( session -> { + assertEquals( 1, found.enumExplicitType.size() ); + MapValue foundValue = found.enumExplicitType.get( EnumMapKey.VALUE_2 ); + assertEquals( EnumMapKey.VALUE_2, foundValue.enumExplicit ); + + assertEquals( "2", findDatabaseValue( session, foundValue.id, "enumExplicit", String.class ) ); + } ); } @Test - public void testEnumImplicitType() { - MapValue mapValue = create(); - mapValue.enumImplicit = ImplicitEnumMapKey.VALUE_2; - mapValue.mapEntity.enumImplicitType.put( mapValue.enumImplicit, mapValue ); - - MapEntity found = persist( mapValue.mapEntity ); - - assertEquals( 1, found.enumImplicitType.size() ); - MapValue foundValue = found.enumImplicitType.get( ImplicitEnumMapKey.VALUE_2 ); - assertEquals( ImplicitEnumMapKey.VALUE_2, foundValue.enumImplicit ); - - assertEquals( "I2", findDatabaseValue( foundValue, "enumImplicit" ) ); - getSession().close(); + public void testEnumImplicitType(SessionFactoryScope scope) { + MapEntity found = scope.fromTransaction( session -> { + MapValue mapValue = create(); + mapValue.enumImplicit = ImplicitEnumMapKey.VALUE_2; + mapValue.mapEntity.enumImplicitType.put( mapValue.enumImplicit, mapValue ); + + return persist( session, mapValue.mapEntity ); + } ); + + scope.inSession( session -> { + assertEquals( 1, found.enumImplicitType.size() ); + MapValue foundValue = found.enumImplicitType.get( ImplicitEnumMapKey.VALUE_2 ); + assertEquals( ImplicitEnumMapKey.VALUE_2, foundValue.enumImplicit ); + + assertEquals( "I2", findDatabaseValue( session, foundValue.id, "enumImplicit", String.class ) ); + } ); } @Test - public void testEnumImplicitOverrideOrdinalType() { - MapValue mapValue = create(); - mapValue.enumImplicitOverrideOrdinal = ImplicitEnumMapKey.VALUE_1; - mapValue.mapEntity.enumImplicitOverrideOrdinalType.put( mapValue.enumImplicitOverrideOrdinal, mapValue ); - - MapEntity found = persist( mapValue.mapEntity ); - - assertEquals( 1, found.enumImplicitOverrideOrdinalType.size() ); - MapValue foundValue = found.enumImplicitOverrideOrdinalType.get( ImplicitEnumMapKey.VALUE_1 ); - assertEquals( ImplicitEnumMapKey.VALUE_1, foundValue.enumImplicitOverrideOrdinal ); - - assertEquals( 0, ((Number) findDatabaseValue( foundValue, "enumImplicitOverrideOrdinal" )).intValue() ); - getSession().close(); + public void testEnumImplicitOverrideOrdinalType(SessionFactoryScope scope) { + MapEntity found = scope.fromTransaction( session -> { + MapValue mapValue = create(); + mapValue.enumImplicitOverrideOrdinal = ImplicitEnumMapKey.VALUE_1; + mapValue.mapEntity.enumImplicitOverrideOrdinalType.put( mapValue.enumImplicitOverrideOrdinal, mapValue ); + + return persist( session, mapValue.mapEntity ); + } ); + + scope.inSession( session -> { + assertEquals( 1, found.enumImplicitOverrideOrdinalType.size() ); + MapValue foundValue = found.enumImplicitOverrideOrdinalType.get( ImplicitEnumMapKey.VALUE_1 ); + assertEquals( ImplicitEnumMapKey.VALUE_1, foundValue.enumImplicitOverrideOrdinal ); + + assertEquals( 0, findDatabaseValue( session, foundValue.id, "enumImplicitOverrideOrdinal", Integer.class ) ); + } ); } @Test - public void testEnumImplicitOverrideStringType() { - MapValue mapValue = create(); - mapValue.enumImplicitOverrideString = ImplicitEnumMapKey.VALUE_2; - mapValue.mapEntity.enumImplicitOverrideStringType.put( mapValue.enumImplicitOverrideString, mapValue ); - - MapEntity found = persist( mapValue.mapEntity ); - - assertEquals( 1, found.enumImplicitOverrideStringType.size() ); - MapValue foundValue = found.enumImplicitOverrideStringType.get( ImplicitEnumMapKey.VALUE_2 ); - assertEquals( ImplicitEnumMapKey.VALUE_2, foundValue.enumImplicitOverrideString ); - - assertEquals( "VALUE_2", findDatabaseValue( foundValue, "enumImplicitOverrideString" ) ); - getSession().close(); + public void testEnumImplicitOverrideStringType(SessionFactoryScope scope) { + MapEntity found = scope.fromTransaction( session -> { + MapValue mapValue = create(); + mapValue.enumImplicitOverrideString = ImplicitEnumMapKey.VALUE_2; + mapValue.mapEntity.enumImplicitOverrideStringType.put( mapValue.enumImplicitOverrideString, mapValue ); + + return persist( session, mapValue.mapEntity ); + } ); + + scope.inSession( session -> { + assertEquals( 1, found.enumImplicitOverrideStringType.size() ); + MapValue foundValue = found.enumImplicitOverrideStringType.get( ImplicitEnumMapKey.VALUE_2 ); + assertEquals( ImplicitEnumMapKey.VALUE_2, foundValue.enumImplicitOverrideString ); + + assertEquals( "VALUE_2", findDatabaseValue( session, foundValue.id, "enumImplicitOverrideString", String.class ) ); + } ); } @Test - public void testEnumImplicitOverridedType() { - MapValue mapValue = create(); - mapValue.enumImplicitOverrided = ImplicitEnumMapKey.VALUE_1; - mapValue.mapEntity.enumImplicitOverridedType.put( mapValue.enumImplicitOverrided, mapValue ); - - MapEntity found = persist( mapValue.mapEntity ); - - assertEquals( 1, found.enumImplicitOverridedType.size() ); - MapValue foundValue = found.enumImplicitOverridedType.get( ImplicitEnumMapKey.VALUE_1 ); - assertEquals( ImplicitEnumMapKey.VALUE_1, foundValue.enumImplicitOverrided ); - - assertEquals( "O1", findDatabaseValue( foundValue, "enumImplicitOverrided" ) ); - getSession().close(); + public void testEnumImplicitOverriddenType(SessionFactoryScope scope) { + MapEntity found = scope.fromTransaction( session -> { + MapValue mapValue = create(); + mapValue.enumImplicitOverridden = ImplicitEnumMapKey.VALUE_1; + mapValue.mapEntity.enumImplicitOverriddenType.put( mapValue.enumImplicitOverridden, mapValue ); + + return persist( session, mapValue.mapEntity ); + } ); + + scope.inSession( session -> { + assertEquals( 1, found.enumImplicitOverriddenType.size() ); + MapValue foundValue = found.enumImplicitOverriddenType.get( ImplicitEnumMapKey.VALUE_1 ); + assertEquals( ImplicitEnumMapKey.VALUE_1, foundValue.enumImplicitOverridden ); + + assertEquals( "O1", findDatabaseValue( session, foundValue.id, "enumImplicitOverridden", String.class ) ); + } ); } - private MapValue create() { MapEntity mapEntity = new MapEntity(); return new MapValue( mapEntity ); } - private MapEntity persist(MapEntity mapEntity) { - Transaction tx = openSession().getTransaction(); - tx.begin(); - mapEntity = (MapEntity) getSession().merge( mapEntity ); + private MapEntity persist(Session session, final MapEntity mapEntity) { + session.persist(mapEntity); - tx.commit(); - getSession().close(); - - mapEntity = openSession().get( MapEntity.class, mapEntity.id ); - return mapEntity; + return session.find(MapEntity.class, mapEntity.id); } - private Object findDatabaseValue(MapValue mapValue, String column) { - return getSession() - .createNativeQuery( "select mv." + column + " from map_value mv where mv.id=:id" ) - .setParameter( "id", mapValue.id ) - .uniqueResult(); + private Object findDatabaseValue(Session session, Integer id, String columnName, Class expectedResultType) { + return session.createNativeQuery( + "select mv." + columnName + " from map_value mv where mv.id=:id", expectedResultType ) + .setParameter( "id", id ) + .uniqueResult(); } @Entity( name = "MapEntity" ) @@ -240,39 +266,39 @@ public static class MapEntity { @GeneratedValue(strategy = GenerationType.AUTO) private Integer id; - @OneToMany(mappedBy = "mapEntity", cascade = CascadeType.ALL) + @OneToMany(mappedBy = "mapEntity", cascade = CascadeType.ALL, fetch = FetchType.EAGER) @MapKey(name = "implicitType") - private Map implicitType = new HashMap(); + private Map implicitType = new HashMap<>(); @OneToMany(mappedBy = "mapEntity", cascade = CascadeType.ALL) @MapKey(name = "explicitType") - private Map explicitType = new HashMap(); + private Map explicitType = new HashMap<>(); @OneToMany(mappedBy = "mapEntity", cascade = CascadeType.ALL) @MapKey(name = "enumDefault") - private Map enumDefaultType = new HashMap(); + private Map enumDefaultType = new HashMap<>(); @OneToMany(mappedBy = "mapEntity", cascade = CascadeType.ALL) @MapKey(name = "enumExplicitOrdinal") - private Map enumExplicitOrdinalType = new HashMap(); + private Map enumExplicitOrdinalType = new HashMap<>(); @OneToMany(mappedBy = "mapEntity", cascade = CascadeType.ALL) @MapKey(name = "enumExplicitString") - private Map enumExplicitStringType = new HashMap(); + private Map enumExplicitStringType = new HashMap<>(); @OneToMany(mappedBy = "mapEntity", cascade = CascadeType.ALL) @MapKey(name = "enumExplicit") - private Map enumExplicitType = new HashMap(); + private Map enumExplicitType = new HashMap<>(); @OneToMany(mappedBy = "mapEntity", cascade = CascadeType.ALL) @MapKey(name = "enumImplicit") - private Map enumImplicitType = new HashMap(); + private Map enumImplicitType = new HashMap<>(); @OneToMany(mappedBy = "mapEntity", cascade = CascadeType.ALL) @MapKey(name = "enumImplicitOverrideOrdinal") - private Map enumImplicitOverrideOrdinalType = new HashMap(); + private Map enumImplicitOverrideOrdinalType = new HashMap<>(); @OneToMany(mappedBy = "mapEntity", cascade = CascadeType.ALL) @MapKey(name = "enumImplicitOverrideString") - private Map enumImplicitOverrideStringType = new HashMap(); + private Map enumImplicitOverrideStringType = new HashMap<>(); @OneToMany(mappedBy = "mapEntity", cascade = CascadeType.ALL) - @MapKey(name = "enumImplicitOverrided") - private Map enumImplicitOverridedType = new HashMap(); + @MapKey(name = "enumImplicitOverridden") + private Map enumImplicitOverriddenType = new HashMap<>(); } @Entity( name = "MapValue" ) @@ -305,8 +331,8 @@ public static class MapValue { @Convert(disableConversion = true) private ImplicitEnumMapKey enumImplicitOverrideString; - @Convert(converter = ImplicitEnumMapKeyOverridedConverter.class) - private ImplicitEnumMapKey enumImplicitOverrided; + @Convert(converter = ImplicitEnumMapKeyOverriddenConverter.class) + private ImplicitEnumMapKey enumImplicitOverridden; protected MapValue() { } @@ -368,7 +394,7 @@ public ImplicitEnumMapKey convertToEntityAttribute(String dbData) { @Converter - public static class ImplicitEnumMapKeyOverridedConverter implements AttributeConverter { + public static class ImplicitEnumMapKeyOverriddenConverter implements AttributeConverter { @Override public String convertToDatabaseColumn(ImplicitEnumMapKey attribute) { return attribute == null ? null : diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/map/MapKeyConversionTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/map/MapKeyConversionTest.java index 928d6629047a..f523296ba927 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/map/MapKeyConversionTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/map/MapKeyConversionTest.java @@ -14,46 +14,33 @@ import jakarta.persistence.JoinColumn; import jakarta.persistence.Table; -import org.hibernate.Session; - +import org.hibernate.testing.orm.junit.DomainModel; import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseNonConfigCoreFunctionalTestCase; -import org.junit.Test; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Steve Ebersole */ @JiraKey( value = "HHH-8529" ) -public class MapKeyConversionTest extends BaseNonConfigCoreFunctionalTestCase { - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { Customer.class, ColorTypeConverter.class }; - } +@DomainModel(annotatedClasses = {MapKeyConversionTest.Customer.class, ColorTypeConverter.class}) +@SessionFactory +public class MapKeyConversionTest { @Test - public void testElementCollectionConversion() { - Session session = openSession(); - session.getTransaction().begin(); - Customer customer = new Customer( 1 ); - customer.colors.put( ColorType.BLUE, "favorite" ); - session.persist( customer ); - session.getTransaction().commit(); - session.close(); + public void testElementCollectionConversion(SessionFactoryScope scope) { + scope.inTransaction( session -> { + Customer customer = new Customer( 1 ); + customer.colors.put( ColorType.BLUE, "favorite" ); + session.persist( customer ); + } ); - session = openSession(); - session.getTransaction().begin(); - assertEquals( 1, session.get( Customer.class, 1 ).colors.size() ); - session.getTransaction().commit(); - session.close(); + scope.inTransaction( session -> assertEquals( 1, session.find( Customer.class, 1 ).colors.size() ) ); - session = openSession(); - session.getTransaction().begin(); - customer = session.get( Customer.class, 1 ); - session.remove( customer ); - session.getTransaction().commit(); - session.close(); + scope.dropData(); } @Entity( name = "Customer" ) diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/enums/EnumExplicitTypeTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/enums/EnumExplicitTypeTest.java index 0c9eb7a3ac7c..f5eced426900 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/enums/EnumExplicitTypeTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/enums/EnumExplicitTypeTest.java @@ -11,7 +11,7 @@ import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Vlad Mihalcea diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/enums/EnumTypeTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/enums/EnumTypeTest.java index cce9dc18ca54..e992bbd20b48 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/enums/EnumTypeTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/enums/EnumTypeTest.java @@ -9,84 +9,68 @@ import jakarta.persistence.criteria.Root; import org.hibernate.Session; -import org.hibernate.cfg.Configuration; import org.hibernate.cfg.Environment; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.LoggingInspections; +import org.hibernate.testing.orm.junit.LoggingInspectionsScope; +import org.hibernate.testing.orm.junit.ServiceRegistry; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.hibernate.testing.orm.junit.Setting; import org.hibernate.type.descriptor.JdbcBindingLogging; import org.hibernate.type.descriptor.JdbcExtractingLogging; import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; -import org.hibernate.testing.logger.LoggerInspectionRule; -import org.hibernate.testing.logger.Triggerable; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import org.jboss.logging.Logger; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; - -import static org.hibernate.testing.transaction.TransactionUtil.doInHibernate; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Brett Meyer */ -public class EnumTypeTest extends BaseCoreFunctionalTestCase { - - @Rule - public LoggerInspectionRule binderLogInspection = - new LoggerInspectionRule( Logger.getLogger( JdbcBindingLogging.NAME ) ); - - @Rule - public LoggerInspectionRule extractorLogInspection = - new LoggerInspectionRule( Logger.getLogger( JdbcExtractingLogging.NAME ) ); +@DomainModel(xmlMappings = {"org/hibernate/orm/test/mapping/converted/enums/Person.hbm.xml" }) +@SessionFactory +@ServiceRegistry(settings = {@Setting(name = Environment.PREFER_NATIVE_ENUM_TYPES, value = "false")}) +@LoggingInspections( + messages = { + @LoggingInspections.Message( + messageKey = "binding parameter", + loggers = @org.hibernate.testing.orm.junit.Logger(loggerName = JdbcBindingLogging.NAME) + ), + @LoggingInspections.Message( + messageKey = "extracted value", + loggers = @org.hibernate.testing.orm.junit.Logger(loggerName = JdbcExtractingLogging.NAME) + ) + } +) +public class EnumTypeTest { private Person person; - private Triggerable binderTriggerable; - - private Triggerable extractorTriggerable; - - @Override - protected String getBaseForMappings() { - return ""; - } - - protected String[] getMappings() { - return new String[] { "org/hibernate/orm/test/mapping/converted/enums/Person.hbm.xml" }; - } - - @Override - protected void configure(Configuration configuration) { - super.configure( configuration ); - configuration.setProperty( Environment.PREFER_NATIVE_ENUM_TYPES, "false" ); - } - - @Override - protected void prepareTest() { - doInHibernate( this::sessionFactory, s -> { + @BeforeEach + protected void prepareTest(SessionFactoryScope scope) { + scope.inTransaction( s -> { this.person = Person.person( Gender.MALE, HairColor.BROWN ); s.persist( person ); s.persist( Person.person( Gender.MALE, HairColor.BLACK ) ); s.persist( Person.person( Gender.FEMALE, HairColor.BROWN ) ); s.persist( Person.person( Gender.FEMALE, HairColor.BLACK ) ); } ); - - binderTriggerable = binderLogInspection.watchForLogMessages( "binding parameter" ); - extractorTriggerable = extractorLogInspection.watchForLogMessages( "extracted value" ); } - @Override - protected boolean isCleanupTestDataRequired() { - return true; + @AfterEach + protected void cleanupTestData(SessionFactoryScope scope) { + scope.dropData(); } @Test @JiraKey(value = "HHH-8153") - public void hbmEnumTypeTest() { - doInHibernate( - this::sessionFactory, - s -> { + public void hbmEnumTypeTest(SessionFactoryScope scope) { + scope.inTransaction( s -> { assertEquals( 2, getNumberOfPersonByGender( s, Gender.MALE ) ); assertEquals( 1, getNumberOfPersonByGenderAndHairColor( s, Gender.MALE, HairColor.BROWN ) ); assertEquals( 2, getNumberOfPersonByGender( s, Gender.FEMALE ) ); @@ -116,22 +100,20 @@ private int getNumberOfPersonByGenderAndHairColor(Session session, Gender gender @Test @JiraKey(value = "HHH-12978") - public void testEnumAsBindParameterAndExtract() { - doInHibernate( this::sessionFactory, s -> { - binderTriggerable.reset(); - extractorTriggerable.reset(); + public void testEnumAsBindParameterAndExtract(LoggingInspectionsScope loggingScope, SessionFactoryScope scope) { + scope.inTransaction( s -> { + loggingScope.resetWatchers(); s.createQuery( "select p.id from Person p where p.id = :id", Long.class ) .setParameter( "id", person.getId() ) .getSingleResult(); - assertTrue( binderTriggerable.wasTriggered() ); - assertTrue( extractorTriggerable.wasTriggered() ); + assertTrue( loggingScope.getWatcher( "binding parameter", JdbcBindingLogging.NAME ).wasTriggered() ); + assertTrue( loggingScope.getWatcher( "extracted value", JdbcExtractingLogging.NAME ).wasTriggered() ); } ); - doInHibernate( this::sessionFactory, s -> { - binderTriggerable.reset(); - extractorTriggerable.reset(); + scope.inTransaction( s -> { + loggingScope.resetWatchers(); s.createQuery( "select p.gender from Person p where p.gender = :gender and p.hairColor = :hairColor", @@ -141,8 +123,8 @@ public void testEnumAsBindParameterAndExtract() { .setParameter( "hairColor", HairColor.BROWN ) .getSingleResult(); - assertTrue( binderTriggerable.wasTriggered() ); - assertTrue( extractorTriggerable.wasTriggered() ); + assertTrue( loggingScope.getWatcher( "binding parameter", JdbcBindingLogging.NAME ).wasTriggered() ); + assertTrue( loggingScope.getWatcher( "extracted value", JdbcExtractingLogging.NAME ).wasTriggered() ); } ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/enums/InvalidEnumeratedJavaTypeTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/enums/InvalidEnumeratedJavaTypeTest.java index d8a08a9d2762..3aa8d8e48ffd 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/enums/InvalidEnumeratedJavaTypeTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/enums/InvalidEnumeratedJavaTypeTest.java @@ -15,7 +15,7 @@ import org.hibernate.testing.orm.junit.ServiceRegistryScope; import org.junit.jupiter.api.Test; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Steve Ebersole diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/enums/UnspecifiedEnumTypeTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/enums/UnspecifiedEnumTypeTest.java index 4cec8b1e3753..2abd9f75957e 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/enums/UnspecifiedEnumTypeTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/enums/UnspecifiedEnumTypeTest.java @@ -4,51 +4,37 @@ */ package org.hibernate.orm.test.mapping.converted.enums; -import java.sql.Connection; -import java.sql.SQLException; - import org.hibernate.Session; -import org.hibernate.cfg.Configuration; import org.hibernate.cfg.Environment; import org.hibernate.dialect.H2Dialect; -import org.hibernate.jdbc.Work; -import org.hibernate.testing.RequiresDialect; +import org.hibernate.testing.orm.junit.RequiresDialect; +import org.hibernate.testing.orm.junit.DomainModel; import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.hibernate.testing.orm.junit.ServiceRegistry; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.hibernate.testing.orm.junit.Setting; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * @author Lukasz Antoniak */ @JiraKey( value = "HHH-7780" ) @RequiresDialect( value = H2Dialect.class ) -public class UnspecifiedEnumTypeTest extends BaseCoreFunctionalTestCase { - @Override - protected String getBaseForMappings() { - return ""; - } - - @Override - protected String[] getMappings() { - return new String[] { "org/hibernate/orm/test/mapping/converted/enums/mappings.hbm.xml" }; - } +@DomainModel(xmlMappings = {"org/hibernate/orm/test/mapping/converted/enums/mappings.hbm.xml"}) +@SessionFactory(exportSchema = false) +@ServiceRegistry(settings = {@Setting(name = Environment.PREFER_NATIVE_ENUM_TYPES, value = "false")}) +public class UnspecifiedEnumTypeTest { - @Override - protected void configure(Configuration configuration) { - super.configure( configuration ); - configuration.setProperty( Environment.HBM2DDL_AUTO, "" ); - configuration.setProperty( Environment.PREFER_NATIVE_ENUM_TYPES, "false" ); - } - - @Before - public void prepareTable() { - Session session = openSession(); - dropTable( session ); - createTable( session ); - session.close(); + @BeforeEach + public void prepareTable(SessionFactoryScope scope) { + scope.inSession( session -> { + dropTable( session ); + createTable( session ); + } ); } public void dropTable(Session session) { @@ -62,31 +48,21 @@ private void createTable(Session session) { ); } - @After - public void dropTable() { - Session session = openSession(); - dropTable( session ); - session.close(); + @AfterEach + public void dropTable(SessionFactoryScope scope) { + scope.inSession( this::dropTable ); } @Test - public void testEnumTypeDiscovery() { - Session session = openSession(); - session.beginTransaction(); - UnspecifiedEnumTypeEntity entity = new UnspecifiedEnumTypeEntity( UnspecifiedEnumTypeEntity.E1.X, UnspecifiedEnumTypeEntity.E2.A ); - session.persist( entity ); - session.getTransaction().commit(); - session.close(); + public void testEnumTypeDiscovery(SessionFactoryScope scope) { + scope.inTransaction( + session -> session.persist(new UnspecifiedEnumTypeEntity(UnspecifiedEnumTypeEntity.E1.X, UnspecifiedEnumTypeEntity.E2.A) ) + ); } private void executeUpdateSafety(Session session, String query) { session.doWork( - new Work() { - @Override - public void execute(Connection connection) throws SQLException { - connection.createStatement().execute( query ); - } - } + connection -> connection.createStatement().execute( query ) ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converter/MoneyConverterTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converter/MoneyConverterTest.java index 8c3ffa6b627a..8a1e2d9058db 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converter/MoneyConverterTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converter/MoneyConverterTest.java @@ -9,21 +9,20 @@ import jakarta.persistence.Entity; import jakarta.persistence.Id; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; - -import org.junit.Test; - -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.Test; /** * @author Vlad Mihalcea */ -public class MoneyConverterTest extends BaseEntityManagerFunctionalTestCase { +@Jpa(annotatedClasses = {MoneyConverterTest.Account.class}) +public class MoneyConverterTest { @Test - public void testConverterMutability() { + public void testConverterMutability(EntityManagerFactoryScope scope) { - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { Account account = new Account(); account.setId(1L); account.setOwner("John Doe"); @@ -32,7 +31,7 @@ public void testConverterMutability() { entityManager.persist(account); }); - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { //tag::basic-jpa-convert-money-converter-mutability-plan-example[] Account account = entityManager.find(Account.class, 1L); account.getBalance().setCents(150 * 100L); @@ -42,11 +41,6 @@ public void testConverterMutability() { } - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { Account.class }; - } - //tag::basic-jpa-convert-money-converter-mapping-example[] public static class Money { 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 ced0c4731549..5f9d9f782bf7 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 @@ -11,38 +11,31 @@ import jakarta.persistence.GeneratedValue; import jakarta.persistence.Id; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.Test; -import org.junit.Test; - -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Vlad Mihalcea */ -public class PeriodStringTest extends BaseEntityManagerFunctionalTestCase { +@Jpa(annotatedClasses = {PeriodStringTest.Event.class}) +public class PeriodStringTest { private Period period = Period.ofYears(1).plusMonths(2).plusDays(3); - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Event.class - }; - } - @Test - public void testLifecycle() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void testLifecycle(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { Event event = new Event(period); entityManager.persist(event); }); - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { Event event = entityManager.createQuery("from Event", Event.class).getSingleResult(); assertEquals(period, event.getSpan()); }); - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { //tag::basic-jpa-convert-period-string-converter-immutability-plan-example[] Event event = entityManager.createQuery("from Event", Event.class).getSingleResult(); event.setSpan(Period diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converter/hbm/MoneyConverterHbmTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converter/hbm/MoneyConverterHbmTest.java index 68849797ff17..f42bb9e274ce 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converter/hbm/MoneyConverterHbmTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converter/hbm/MoneyConverterHbmTest.java @@ -4,21 +4,20 @@ */ package org.hibernate.orm.test.mapping.converter.hbm; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; - -import org.junit.Test; - -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.Test; /** * @author Vlad Mihalcea */ -public class MoneyConverterHbmTest extends BaseEntityManagerFunctionalTestCase { +@Jpa(xmlMappings = {"org/hibernate/orm/test/mapping/converter/hbm/MoneyConverterHbmTest.hbm.xml"}) +public class MoneyConverterHbmTest { @Test - public void testConverterMutability() { + public void testConverterMutability(EntityManagerFactoryScope scope) { - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { Account account = new Account(); account.setId(1L); account.setOwner("John Doe"); @@ -27,7 +26,7 @@ public void testConverterMutability() { entityManager.persist(account); }); - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { //tag::basic-hbm-convert-money-converter-mutability-plan-example[] Account account = entityManager.find(Account.class, 1L); account.getBalance().setCents(150 * 100L); @@ -36,10 +35,4 @@ public void testConverterMutability() { }); } - @Override - protected String[] getMappings() { - return new String[] { - "org/hibernate/orm/test/mapping/converter/hbm/MoneyConverterHbmTest.hbm.xml" - }; - } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/dynamic/DynamicEntityTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/dynamic/DynamicEntityTest.java index 660436d3e9cf..f8ed98bb6433 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/dynamic/DynamicEntityTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/dynamic/DynamicEntityTest.java @@ -4,40 +4,37 @@ */ package org.hibernate.orm.test.mapping.dynamic; +import java.util.Collections; import java.util.HashMap; import java.util.Map; import org.hibernate.Session; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; -import org.junit.Test; - -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.hibernate.testing.orm.junit.Setting; +import org.junit.jupiter.api.Test; /** * @author Vlad Mihalcea */ -public class DynamicEntityTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected String[] getMappings() { - return new String[] { - "org/hibernate/orm/test/mapping/dynamic/Book.hbm.xml" - }; - } - - @Override - protected Map buildSettings() { - Map settings = super.buildSettings(); +@Jpa( + xmlMappings = {"org/hibernate/orm/test/mapping/dynamic/Book.hbm.xml"}, + integrationSettings = {@Setting( name = "hibernate.default_entity_mode", value = "dynamic-map")} +) +public class DynamicEntityTest { + + // Preserved because of the doc inclusions + protected void doesNothing() { + Map settings = Collections.EMPTY_MAP; //tag::mapping-model-dynamic-setting-example[] settings.put("hibernate.default_entity_mode", "dynamic-map"); //end::mapping-model-dynamic-setting-example[] - return settings; } @Test - public void test() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { //tag::mapping-model-dynamic-example[] Map book = new HashMap<>(); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/embeddable/EmbeddableImplicitOverrideTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/embeddable/EmbeddableImplicitOverrideTest.java index 47ad13bf26fe..26e89dc6c92c 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/embeddable/EmbeddableImplicitOverrideTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/embeddable/EmbeddableImplicitOverrideTest.java @@ -15,28 +15,39 @@ import org.hibernate.boot.MetadataBuilder; import org.hibernate.boot.model.naming.ImplicitNamingStrategyComponentPathImpl; -import org.hibernate.testing.junit4.BaseNonConfigCoreFunctionalTestCase; -import org.junit.Test; - -import static org.hibernate.testing.transaction.TransactionUtil.doInHibernate; +import org.hibernate.cfg.MappingSettings; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.ServiceRegistry; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.hibernate.testing.orm.junit.SettingProvider; +import org.junit.jupiter.api.Test; /** * @author Vlad Mihalcea */ -public class EmbeddableImplicitOverrideTest - extends BaseNonConfigCoreFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Book.class, - Country.class - }; +@DomainModel( + annotatedClasses = {EmbeddableImplicitOverrideTest.Book.class, EmbeddableImplicitOverrideTest.Country.class} +) +@SessionFactory +@ServiceRegistry( + settingProviders = { + @SettingProvider( + settingName = MappingSettings.IMPLICIT_NAMING_STRATEGY, + provider = EmbeddableImplicitOverrideTest.ImplicitNamingStrategySettingProvider.class) + } +) +public class EmbeddableImplicitOverrideTest { + + public static class ImplicitNamingStrategySettingProvider implements SettingProvider.Provider { + @Override + public ImplicitNamingStrategyComponentPathImpl getSetting() { + return ImplicitNamingStrategyComponentPathImpl.INSTANCE; + } } - @Override - protected void initialize(MetadataBuilder metadataBuilder) { - super.initialize(metadataBuilder); + // Preserved because of the doc inclusion + private void doesNothing(MetadataBuilder metadataBuilder) { //tag::embeddable-multiple-ImplicitNamingStrategyComponentPathImpl[] metadataBuilder.applyImplicitNamingStrategy( ImplicitNamingStrategyComponentPathImpl.INSTANCE @@ -45,8 +56,8 @@ protected void initialize(MetadataBuilder metadataBuilder) { } @Test - public void testLifecycle() { - doInHibernate(this::sessionFactory, session -> { + public void testLifecycle(SessionFactoryScope scope) { + scope.inTransaction( session -> { Country canada = new Country(); canada.setName("Canada"); session.persist(canada); @@ -56,7 +67,7 @@ public void testLifecycle() { session.persist(usa); }); - doInHibernate(this::sessionFactory, session -> { + scope.inTransaction( session -> { Country canada = session.byNaturalId(Country.class).using("name", "Canada").load(); Country usa = session.byNaturalId(Country.class).using("name", "USA").load(); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/embeddable/EmbeddableOverrideTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/embeddable/EmbeddableOverrideTest.java index 123d390410dd..c2afae083d78 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/embeddable/EmbeddableOverrideTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/embeddable/EmbeddableOverrideTest.java @@ -19,28 +19,23 @@ import org.hibernate.Session; import org.hibernate.annotations.NaturalId; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; -import org.junit.Test; - -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.Test; /** * @author Vlad Mihalcea */ -public class EmbeddableOverrideTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Book.class, - Country.class - }; - } +@Jpa(annotatedClasses = { + EmbeddableOverrideTest.Book.class, + EmbeddableOverrideTest.Country.class +}) +public class EmbeddableOverrideTest { @Test - public void testLifecycle() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void testLifecycle(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { Country canada = new Country(); canada.setName("Canada"); entityManager.persist(canada); @@ -50,7 +45,7 @@ public void testLifecycle() { entityManager.persist(usa); }); - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { Session session = entityManager.unwrap(Session.class); Country canada = session.byNaturalId(Country.class).using("name", "Canada").load(); Country usa = session.byNaturalId(Country.class).using("name", "USA").load(); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/embeddable/JsonEmbeddableArrayTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/embeddable/JsonEmbeddableArrayTest.java index c37a5a5dee67..1b596eb9f76f 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/embeddable/JsonEmbeddableArrayTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/embeddable/JsonEmbeddableArrayTest.java @@ -19,14 +19,15 @@ import java.util.UUID; import org.hibernate.annotations.JdbcTypeCode; +import org.hibernate.testing.orm.junit.DomainModel; import org.hibernate.testing.orm.junit.FailureExpected; -import org.hibernate.type.SqlTypes; - +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; import org.hibernate.testing.orm.domain.gambit.EntityOfBasics; import org.hibernate.testing.orm.domain.gambit.MutableValue; -import org.hibernate.testing.orm.junit.BaseSessionFactoryFunctionalTest; import org.hibernate.testing.orm.junit.DialectFeatureChecks; import org.hibernate.testing.orm.junit.RequiresDialectFeature; +import org.hibernate.type.SqlTypes; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -39,18 +40,13 @@ import static org.junit.jupiter.api.Assertions.assertNull; @RequiresDialectFeature(feature = DialectFeatureChecks.SupportsJsonAggregate.class) -public class JsonEmbeddableArrayTest extends BaseSessionFactoryFunctionalTest { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - JsonEmbeddableArrayTest.JsonArrayHolder.class - }; - } +@DomainModel(annotatedClasses = {JsonEmbeddableArrayTest.JsonArrayHolder.class}) +@SessionFactory +public class JsonEmbeddableArrayTest { @BeforeEach - public void setUp() { - inTransaction( + public void setUp(SessionFactoryScope scope) { + scope.inTransaction( session -> { session.persist( new JsonArrayHolder( 1L, EmbeddableAggregate.createAggregateArray1() )); session.persist( new JsonArrayHolder( 2L, EmbeddableAggregate.createAggregateArray2() )); @@ -59,30 +55,30 @@ public void setUp() { } @AfterEach - protected void cleanupTest() { - sessionFactoryScope().getSessionFactory().getSchemaManager().truncate(); + protected void cleanupTest(SessionFactoryScope scope) { + scope.dropData(); } @Test - public void testUpdate() { - sessionFactoryScope().inTransaction( - entityManager -> { - JsonArrayHolder jsonArrayHolder = entityManager.find( JsonArrayHolder.class, 1L ); + public void testUpdate(SessionFactoryScope scope) { + scope.inTransaction( + session -> { + JsonArrayHolder jsonArrayHolder = session.find( JsonArrayHolder.class, 1L ); jsonArrayHolder.setAggregateArray( EmbeddableAggregate.createAggregateArray2() ); - entityManager.flush(); - entityManager.clear(); + session.flush(); + session.clear(); EmbeddableAggregate.assertArraysEquals( EmbeddableAggregate.createAggregateArray2(), - entityManager.find( JsonArrayHolder.class, 1L ).getAggregateArray() ); + session.find( JsonArrayHolder.class, 1L ).getAggregateArray() ); } ); } @Test - public void testFetch() { - sessionFactoryScope().inSession( - entityManager -> { - List jsonArrayHolders = entityManager.createQuery( "from JsonArrayHolder b where b.id = 1", JsonArrayHolder.class ).getResultList(); + public void testFetch(SessionFactoryScope scope) { + scope.inSession( + session -> { + List jsonArrayHolders = session.createQuery( "from JsonArrayHolder b where b.id = 1", JsonArrayHolder.class ).getResultList(); assertEquals( 1, jsonArrayHolders.size() ); assertEquals( 1L, jsonArrayHolders.get( 0 ).getId() ); EmbeddableAggregate.assertArraysEquals( EmbeddableAggregate.createAggregateArray1(), jsonArrayHolders.get( 0 ).getAggregateArray() ); @@ -91,10 +87,10 @@ public void testFetch() { } @Test - public void testFetchNull() { - sessionFactoryScope().inSession( - entityManager -> { - List jsonArrayHolders = entityManager.createQuery( "from JsonArrayHolder b where b.id = 2", JsonArrayHolder.class ).getResultList(); + public void testFetchNull(SessionFactoryScope scope) { + scope.inSession( + session -> { + List jsonArrayHolders = session.createQuery( "from JsonArrayHolder b where b.id = 2", JsonArrayHolder.class ).getResultList(); assertEquals( 1, jsonArrayHolders.size() ); assertEquals( 2L, jsonArrayHolders.get( 0 ).getId() ); EmbeddableAggregate.assertEquals( EmbeddableAggregate.createAggregateArray2()[0], jsonArrayHolders.get( 0 ).getAggregateArray()[0] ); @@ -103,10 +99,10 @@ public void testFetchNull() { } @Test - public void testDomainResult() { - sessionFactoryScope().inSession( - entityManager -> { - List structs = entityManager.createQuery( "select b.aggregateArray from JsonArrayHolder b where b.id = 1", EmbeddableAggregate[].class ).getResultList(); + public void testDomainResult(SessionFactoryScope scope) { + scope.inSession( + session -> { + List structs = session.createQuery( "select b.aggregateArray from JsonArrayHolder b where b.id = 1", EmbeddableAggregate[].class ).getResultList(); assertEquals( 1, structs.size() ); EmbeddableAggregate.assertArraysEquals( EmbeddableAggregate.createAggregateArray1(), structs.get( 0 ) ); } @@ -115,10 +111,10 @@ public void testDomainResult() { @Test @FailureExpected(jiraKey = "HHH-18717", reason = "Requires array functions to work with JSON_ARRAY") - public void testSelectionItems() { - sessionFactoryScope().inSession( - entityManager -> { - List tuples = entityManager.createQuery( + public void testSelectionItems(SessionFactoryScope scope) { + scope.inSession( + session -> { + List tuples = session.createQuery( "select " + "b.aggregateArray[0].theInt," + "b.aggregateArray[0].theDouble," + @@ -182,60 +178,60 @@ public void testSelectionItems() { } @Test - public void testDeleteWhere() { - sessionFactoryScope().inTransaction( - entityManager -> { - entityManager.createMutationQuery( "delete JsonArrayHolder b where b.aggregateArray is not null" ).executeUpdate(); - assertNull( entityManager.find( JsonArrayHolder.class, 1L ) ); + public void testDeleteWhere(SessionFactoryScope scope) { + scope.inTransaction( + session -> { + session.createMutationQuery( "delete JsonArrayHolder b where b.aggregateArray is not null" ).executeUpdate(); + assertNull( session.find( JsonArrayHolder.class, 1L ) ); } ); } @Test - public void testUpdateAggregate() { - sessionFactoryScope().inTransaction( - entityManager -> { - entityManager.createMutationQuery( "update JsonArrayHolder b set b.aggregateArray = null" ).executeUpdate(); - assertNull( entityManager.find( JsonArrayHolder.class, 1L ).getAggregateArray() ); + public void testUpdateAggregate(SessionFactoryScope scope) { + scope.inTransaction( + session -> { + session.createMutationQuery( "update JsonArrayHolder b set b.aggregateArray = null" ).executeUpdate(); + assertNull( session.find( JsonArrayHolder.class, 1L ).getAggregateArray() ); } ); } @Test @FailureExpected(jiraKey = "HHH-18717", reason = "Requires array functions to work with JSON_ARRAY") - public void testUpdateAggregateMember() { - sessionFactoryScope().inTransaction( - entityManager -> { - entityManager.createMutationQuery( "update JsonArrayHolder b set b.aggregateArray[0].theString = null where b.id = 1" ).executeUpdate(); + public void testUpdateAggregateMember(SessionFactoryScope scope) { + scope.inTransaction( + session -> { + session.createMutationQuery( "update JsonArrayHolder b set b.aggregateArray[0].theString = null where b.id = 1" ).executeUpdate(); EmbeddableAggregate[] struct = EmbeddableAggregate.createAggregateArray1(); struct[0].setTheString( null ); - EmbeddableAggregate.assertArraysEquals( struct, entityManager.find( JsonArrayHolder.class, 1L ).getAggregateArray() ); + EmbeddableAggregate.assertArraysEquals( struct, session.find( JsonArrayHolder.class, 1L ).getAggregateArray() ); } ); } @Test @FailureExpected(jiraKey = "HHH-18717", reason = "Requires array functions to work with JSON_ARRAY") - public void testUpdateMultipleAggregateMembers() { - sessionFactoryScope().inTransaction( - entityManager -> { - entityManager.createMutationQuery( "update JsonArrayHolder b set b.aggregateArray.theString = null, b.aggregateArray[0].theUuid = null" ).executeUpdate(); + public void testUpdateMultipleAggregateMembers(SessionFactoryScope scope) { + scope.inTransaction( + session -> { + session.createMutationQuery( "update JsonArrayHolder b set b.aggregateArray.theString = null, b.aggregateArray[0].theUuid = null" ).executeUpdate(); EmbeddableAggregate[] struct = EmbeddableAggregate.createAggregateArray1(); struct[0].setTheString( null ); struct[0].setTheUuid( null ); - EmbeddableAggregate.assertArraysEquals( struct, entityManager.find( JsonArrayHolder.class, 1L ).getAggregateArray() ); + EmbeddableAggregate.assertArraysEquals( struct, session.find( JsonArrayHolder.class, 1L ).getAggregateArray() ); } ); } @Test @FailureExpected(jiraKey = "HHH-18717", reason = "Requires array functions to work with JSON_ARRAY") - public void testUpdateAllAggregateMembers() { - sessionFactoryScope().inTransaction( - entityManager -> { + public void testUpdateAllAggregateMembers(SessionFactoryScope scope) { + scope.inTransaction( + session -> { EmbeddableAggregate[] struct = EmbeddableAggregate.createAggregateArray1(); - entityManager.createMutationQuery( + session.createMutationQuery( "update JsonArrayHolder b set " + "b.aggregateArray[0].theInt = :theInt," + "b.aggregateArray[0].theDouble = :theDouble," + @@ -290,7 +286,7 @@ public void testUpdateAllAggregateMembers() { .setParameter( "theOffsetDateTime", struct[0].getTheOffsetDateTime() ) .setParameter( "mutableValue", struct[0].getMutableValue() ) .executeUpdate(); - EmbeddableAggregate.assertArraysEquals( EmbeddableAggregate.createAggregateArray1(), entityManager.find( JsonArrayHolder.class, 2L ).getAggregateArray() ); + EmbeddableAggregate.assertArraysEquals( EmbeddableAggregate.createAggregateArray1(), session.find( JsonArrayHolder.class, 2L ).getAggregateArray() ); } ); } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/embeddable/JsonEmbeddableTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/embeddable/JsonEmbeddableTest.java index dbf8318ff305..5373a60577e9 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/embeddable/JsonEmbeddableTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/embeddable/JsonEmbeddableTest.java @@ -19,14 +19,15 @@ import java.util.UUID; import org.hibernate.annotations.JdbcTypeCode; -import org.hibernate.type.SqlTypes; - +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; import org.hibernate.testing.orm.domain.gambit.EntityOfBasics; import org.hibernate.testing.orm.domain.gambit.MutableValue; -import org.hibernate.testing.orm.junit.BaseSessionFactoryFunctionalTest; import org.hibernate.testing.orm.junit.DialectFeatureChecks; import org.hibernate.testing.orm.junit.JiraKey; import org.hibernate.testing.orm.junit.RequiresDialectFeature; +import org.hibernate.type.SqlTypes; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -39,18 +40,13 @@ import static org.junit.jupiter.api.Assertions.assertNull; @RequiresDialectFeature(feature = DialectFeatureChecks.SupportsJsonAggregate.class) -public class JsonEmbeddableTest extends BaseSessionFactoryFunctionalTest { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - JsonHolder.class - }; - } +@DomainModel(annotatedClasses = {JsonEmbeddableTest.JsonHolder.class}) +@SessionFactory +public class JsonEmbeddableTest { @BeforeEach - public void setUp() { - inTransaction( + public void setUp(SessionFactoryScope scope) { + scope.inTransaction( session -> { session.persist( new JsonHolder( 1L, EmbeddableAggregate.createAggregate1() ) ); session.persist( new JsonHolder( 2L, EmbeddableAggregate.createAggregate2() ) ); @@ -59,42 +55,42 @@ public void setUp() { } @AfterEach - protected void cleanupTest() { - sessionFactoryScope().getSessionFactory().getSchemaManager().truncate(); + protected void cleanupTest(SessionFactoryScope scope) { + scope.dropData(); } @Test - public void testUpdate() { - sessionFactoryScope().inTransaction( - entityManager -> { - JsonHolder jsonHolder = entityManager.find( JsonHolder.class, 1L ); + public void testUpdate(SessionFactoryScope scope) { + scope.inTransaction( + session -> { + JsonHolder jsonHolder = session.find( JsonHolder.class, 1L ); jsonHolder.setAggregate( EmbeddableAggregate.createAggregate2() ); - entityManager.flush(); - entityManager.clear(); - EmbeddableAggregate.assertEquals( EmbeddableAggregate.createAggregate2(), entityManager.find( JsonHolder.class, 1L ).getAggregate() ); + session.flush(); + session.clear(); + EmbeddableAggregate.assertEquals( EmbeddableAggregate.createAggregate2(), session.find( JsonHolder.class, 1L ).getAggregate() ); } ); } @Test @JiraKey( "HHH-16682" ) - public void testDirtyChecking() { - sessionFactoryScope().inTransaction( - entityManager -> { - JsonHolder jsonHolder = entityManager.find( JsonHolder.class, 1L ); + public void testDirtyChecking(SessionFactoryScope scope) { + scope.inTransaction( + session -> { + JsonHolder jsonHolder = session.find( JsonHolder.class, 1L ); jsonHolder.getAggregate().setTheString( "MyString" ); - entityManager.flush(); - entityManager.clear(); - assertEquals( "MyString", entityManager.find( JsonHolder.class, 1L ).getAggregate().getTheString() ); + session.flush(); + session.clear(); + assertEquals( "MyString", session.find( JsonHolder.class, 1L ).getAggregate().getTheString() ); } ); } @Test - public void testFetch() { - sessionFactoryScope().inSession( - entityManager -> { - List jsonHolders = entityManager.createQuery( "from JsonHolder b where b.id = 1", JsonHolder.class ).getResultList(); + public void testFetch(SessionFactoryScope scope) { + scope.inSession( + session -> { + List jsonHolders = session.createQuery( "from JsonHolder b where b.id = 1", JsonHolder.class ).getResultList(); assertEquals( 1, jsonHolders.size() ); assertEquals( 1L, jsonHolders.get( 0 ).getId() ); EmbeddableAggregate.assertEquals( EmbeddableAggregate.createAggregate1(), jsonHolders.get( 0 ).getAggregate() ); @@ -103,10 +99,10 @@ public void testFetch() { } @Test - public void testFetchNull() { - sessionFactoryScope().inSession( - entityManager -> { - List jsonHolders = entityManager.createQuery( "from JsonHolder b where b.id = 2", JsonHolder.class ).getResultList(); + public void testFetchNull(SessionFactoryScope scope) { + scope.inSession( + session -> { + List jsonHolders = session.createQuery( "from JsonHolder b where b.id = 2", JsonHolder.class ).getResultList(); assertEquals( 1, jsonHolders.size() ); assertEquals( 2L, jsonHolders.get( 0 ).getId() ); EmbeddableAggregate.assertEquals( EmbeddableAggregate.createAggregate2(), jsonHolders.get( 0 ).getAggregate() ); @@ -115,10 +111,10 @@ public void testFetchNull() { } @Test - public void testDomainResult() { - sessionFactoryScope().inSession( - entityManager -> { - List structs = entityManager.createQuery( "select b.aggregate from JsonHolder b where b.id = 1", EmbeddableAggregate.class ).getResultList(); + public void testDomainResult(SessionFactoryScope scope) { + scope.inSession( + session -> { + List structs = session.createQuery( "select b.aggregate from JsonHolder b where b.id = 1", EmbeddableAggregate.class ).getResultList(); assertEquals( 1, structs.size() ); EmbeddableAggregate.assertEquals( EmbeddableAggregate.createAggregate1(), structs.get( 0 ) ); } @@ -126,10 +122,10 @@ public void testDomainResult() { } @Test - public void testSelectionItems() { - sessionFactoryScope().inSession( - entityManager -> { - List tuples = entityManager.createQuery( + public void testSelectionItems(SessionFactoryScope scope) { + scope.inSession( + session -> { + List tuples = session.createQuery( "select " + "b.aggregate.theInt," + "b.aggregate.theDouble," + @@ -193,60 +189,60 @@ public void testSelectionItems() { } @Test - public void testDeleteWhere() { - sessionFactoryScope().inTransaction( - entityManager -> { - entityManager.createMutationQuery( "delete JsonHolder b where b.aggregate is not null" ).executeUpdate(); - assertNull( entityManager.find( JsonHolder.class, 1L ) ); + public void testDeleteWhere(SessionFactoryScope scope) { + scope.inTransaction( + session -> { + session.createMutationQuery( "delete JsonHolder b where b.aggregate is not null" ).executeUpdate(); + assertNull( session.find( JsonHolder.class, 1L ) ); } ); } @Test - public void testUpdateAggregate() { - sessionFactoryScope().inTransaction( - entityManager -> { - entityManager.createMutationQuery( "update JsonHolder b set b.aggregate = null" ).executeUpdate(); - assertNull( entityManager.find( JsonHolder.class, 1L ).getAggregate() ); + public void testUpdateAggregate(SessionFactoryScope scope) { + scope.inTransaction( + session -> { + session.createMutationQuery( "update JsonHolder b set b.aggregate = null" ).executeUpdate(); + assertNull( session.find( JsonHolder.class, 1L ).getAggregate() ); } ); } @Test @RequiresDialectFeature(feature = DialectFeatureChecks.SupportsJsonComponentUpdate.class) - public void testUpdateAggregateMember() { - sessionFactoryScope().inTransaction( - entityManager -> { - entityManager.createMutationQuery( "update JsonHolder b set b.aggregate.theString = null" ).executeUpdate(); + public void testUpdateAggregateMember(SessionFactoryScope scope) { + scope.inTransaction( + session -> { + session.createMutationQuery( "update JsonHolder b set b.aggregate.theString = null" ).executeUpdate(); EmbeddableAggregate struct = EmbeddableAggregate.createAggregate1(); struct.setTheString( null ); - EmbeddableAggregate.assertEquals( struct, entityManager.find( JsonHolder.class, 1L ).getAggregate() ); + EmbeddableAggregate.assertEquals( struct, session.find( JsonHolder.class, 1L ).getAggregate() ); } ); } @Test @RequiresDialectFeature(feature = DialectFeatureChecks.SupportsJsonComponentUpdate.class) - public void testUpdateMultipleAggregateMembers() { - sessionFactoryScope().inTransaction( - entityManager -> { - entityManager.createMutationQuery( "update JsonHolder b set b.aggregate.theString = null, b.aggregate.theUuid = null" ).executeUpdate(); + public void testUpdateMultipleAggregateMembers(SessionFactoryScope scope) { + scope.inTransaction( + session -> { + session.createMutationQuery( "update JsonHolder b set b.aggregate.theString = null, b.aggregate.theUuid = null" ).executeUpdate(); EmbeddableAggregate struct = EmbeddableAggregate.createAggregate1(); struct.setTheString( null ); struct.setTheUuid( null ); - EmbeddableAggregate.assertEquals( struct, entityManager.find( JsonHolder.class, 1L ).getAggregate() ); + EmbeddableAggregate.assertEquals( struct, session.find( JsonHolder.class, 1L ).getAggregate() ); } ); } @Test @RequiresDialectFeature(feature = DialectFeatureChecks.SupportsJsonComponentUpdate.class) - public void testUpdateAllAggregateMembers() { - sessionFactoryScope().inTransaction( - entityManager -> { + public void testUpdateAllAggregateMembers(SessionFactoryScope scope) { + scope.inTransaction( + session -> { EmbeddableAggregate struct = EmbeddableAggregate.createAggregate1(); - entityManager.createMutationQuery( + session.createMutationQuery( "update JsonHolder b set " + "b.aggregate.theInt = :theInt," + "b.aggregate.theDouble = :theDouble," + @@ -301,7 +297,7 @@ public void testUpdateAllAggregateMembers() { .setParameter( "theOffsetDateTime", struct.getTheOffsetDateTime() ) .setParameter( "mutableValue", struct.getMutableValue() ) .executeUpdate(); - EmbeddableAggregate.assertEquals( EmbeddableAggregate.createAggregate1(), entityManager.find( JsonHolder.class, 2L ).getAggregate() ); + EmbeddableAggregate.assertEquals( EmbeddableAggregate.createAggregate1(), session.find( JsonHolder.class, 2L ).getAggregate() ); } ); } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/embeddable/JsonWithArrayEmbeddableTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/embeddable/JsonWithArrayEmbeddableTest.java index 65cc823db67c..6865cab05e34 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/embeddable/JsonWithArrayEmbeddableTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/embeddable/JsonWithArrayEmbeddableTest.java @@ -80,12 +80,12 @@ protected void cleanupTest(SessionFactoryScope scope) { @Test public void testUpdate(SessionFactoryScope scope) { scope.inTransaction( - entityManager -> { - JsonHolder jsonHolder = entityManager.find( JsonHolder.class, 1L ); + session -> { + JsonHolder jsonHolder = session.find( JsonHolder.class, 1L ); jsonHolder.setAggregate( EmbeddableWithArrayAggregate.createAggregate2() ); - entityManager.flush(); - entityManager.clear(); - EmbeddableWithArrayAggregate.assertEquals( EmbeddableWithArrayAggregate.createAggregate2(), entityManager.find( JsonHolder.class, 1L ).getAggregate() ); + session.flush(); + session.clear(); + EmbeddableWithArrayAggregate.assertEquals( EmbeddableWithArrayAggregate.createAggregate2(), session.find( JsonHolder.class, 1L ).getAggregate() ); } ); } @@ -93,8 +93,8 @@ public void testUpdate(SessionFactoryScope scope) { @Test public void testFetch(SessionFactoryScope scope) { scope.inSession( - entityManager -> { - List jsonHolders = entityManager.createQuery( "from JsonHolder b where b.id = 1", JsonHolder.class ).getResultList(); + session -> { + List jsonHolders = session.createQuery( "from JsonHolder b where b.id = 1", JsonHolder.class ).getResultList(); assertEquals( 1, jsonHolders.size() ); assertEquals( 1L, jsonHolders.get( 0 ).getId() ); EmbeddableWithArrayAggregate.assertEquals( EmbeddableWithArrayAggregate.createAggregate1(), jsonHolders.get( 0 ).getAggregate() ); @@ -105,8 +105,8 @@ public void testFetch(SessionFactoryScope scope) { @Test public void testFetchNull(SessionFactoryScope scope) { scope.inSession( - entityManager -> { - List jsonHolders = entityManager.createQuery( "from JsonHolder b where b.id = 2", JsonHolder.class ).getResultList(); + session -> { + List jsonHolders = session.createQuery( "from JsonHolder b where b.id = 2", JsonHolder.class ).getResultList(); assertEquals( 1, jsonHolders.size() ); assertEquals( 2L, jsonHolders.get( 0 ).getId() ); EmbeddableWithArrayAggregate.assertEquals( EmbeddableWithArrayAggregate.createAggregate2(), jsonHolders.get( 0 ).getAggregate() ); @@ -117,8 +117,8 @@ public void testFetchNull(SessionFactoryScope scope) { @Test public void testDomainResult(SessionFactoryScope scope) { scope.inSession( - entityManager -> { - List structs = entityManager.createQuery( "select b.aggregate from JsonHolder b where b.id = 1", EmbeddableWithArrayAggregate.class ).getResultList(); + session -> { + List structs = session.createQuery( "select b.aggregate from JsonHolder b where b.id = 1", EmbeddableWithArrayAggregate.class ).getResultList(); assertEquals( 1, structs.size() ); EmbeddableWithArrayAggregate.assertEquals( EmbeddableWithArrayAggregate.createAggregate1(), structs.get( 0 ) ); } @@ -128,8 +128,8 @@ public void testDomainResult(SessionFactoryScope scope) { @Test public void testSelectionItems(SessionFactoryScope scope) { scope.inSession( - entityManager -> { - List tuples = entityManager.createQuery( + session -> { + List tuples = session.createQuery( "select " + "b.aggregate.theInt," + "b.aggregate.theDouble," + @@ -195,9 +195,9 @@ public void testSelectionItems(SessionFactoryScope scope) { @Test public void testDeleteWhere(SessionFactoryScope scope) { scope.inTransaction( - entityManager -> { - entityManager.createMutationQuery( "delete JsonHolder b where b.aggregate is not null" ).executeUpdate(); - assertNull( entityManager.find( JsonHolder.class, 1L ) ); + session -> { + session.createMutationQuery( "delete JsonHolder b where b.aggregate is not null" ).executeUpdate(); + assertNull( session.find( JsonHolder.class, 1L ) ); } ); @@ -206,9 +206,9 @@ public void testDeleteWhere(SessionFactoryScope scope) { @Test public void testUpdateAggregate(SessionFactoryScope scope) { scope.inTransaction( - entityManager -> { - entityManager.createMutationQuery( "update JsonHolder b set b.aggregate = null" ).executeUpdate(); - assertNull( entityManager.find( JsonHolder.class, 1L ).getAggregate() ); + session -> { + session.createMutationQuery( "update JsonHolder b set b.aggregate = null" ).executeUpdate(); + assertNull( session.find( JsonHolder.class, 1L ).getAggregate() ); } ); } @@ -217,11 +217,11 @@ public void testUpdateAggregate(SessionFactoryScope scope) { @RequiresDialectFeature(feature = DialectFeatureChecks.SupportsJsonComponentUpdate.class) public void testUpdateAggregateMember(SessionFactoryScope scope) { scope.inTransaction( - entityManager -> { - entityManager.createMutationQuery( "update JsonHolder b set b.aggregate.theString = null" ).executeUpdate(); + session -> { + session.createMutationQuery( "update JsonHolder b set b.aggregate.theString = null" ).executeUpdate(); EmbeddableWithArrayAggregate struct = EmbeddableWithArrayAggregate.createAggregate1(); struct.setTheString( null ); - EmbeddableWithArrayAggregate.assertEquals( struct, entityManager.find( JsonHolder.class, 1L ).getAggregate() ); + EmbeddableWithArrayAggregate.assertEquals( struct, session.find( JsonHolder.class, 1L ).getAggregate() ); } ); } @@ -230,12 +230,12 @@ public void testUpdateAggregateMember(SessionFactoryScope scope) { @RequiresDialectFeature(feature = DialectFeatureChecks.SupportsJsonComponentUpdate.class) public void testUpdateMultipleAggregateMembers(SessionFactoryScope scope) { scope.inTransaction( - entityManager -> { - entityManager.createMutationQuery( "update JsonHolder b set b.aggregate.theString = null, b.aggregate.theUuid = null" ).executeUpdate(); + session -> { + session.createMutationQuery( "update JsonHolder b set b.aggregate.theString = null, b.aggregate.theUuid = null" ).executeUpdate(); EmbeddableWithArrayAggregate struct = EmbeddableWithArrayAggregate.createAggregate1(); struct.setTheString( null ); struct.setTheUuid( null ); - EmbeddableWithArrayAggregate.assertEquals( struct, entityManager.find( JsonHolder.class, 1L ).getAggregate() ); + EmbeddableWithArrayAggregate.assertEquals( struct, session.find( JsonHolder.class, 1L ).getAggregate() ); } ); } @@ -245,9 +245,9 @@ public void testUpdateMultipleAggregateMembers(SessionFactoryScope scope) { @SkipForDialect( dialectClass = OracleDialect.class, reason = "External driver fix required") public void testUpdateAllAggregateMembers(SessionFactoryScope scope) { scope.inTransaction( - entityManager -> { + session -> { EmbeddableWithArrayAggregate struct = EmbeddableWithArrayAggregate.createAggregate1(); - entityManager.createMutationQuery( + session.createMutationQuery( "update JsonHolder b set " + "b.aggregate.theInt = :theInt," + "b.aggregate.theDouble = :theDouble," + @@ -302,7 +302,7 @@ public void testUpdateAllAggregateMembers(SessionFactoryScope scope) { .setParameter( "theOffsetDateTime", struct.getTheOffsetDateTime() ) .setParameter( "mutableValue", struct.getMutableValue() ) .executeUpdate(); - EmbeddableWithArrayAggregate.assertEquals( EmbeddableWithArrayAggregate.createAggregate1(), entityManager.find( JsonHolder.class, 2L ).getAggregate() ); + EmbeddableWithArrayAggregate.assertEquals( EmbeddableWithArrayAggregate.createAggregate1(), session.find( JsonHolder.class, 2L ).getAggregate() ); } ); } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/embeddable/NestedEmbeddableTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/embeddable/NestedEmbeddableTest.java index 63f64cde191e..d828a2552180 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/embeddable/NestedEmbeddableTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/embeddable/NestedEmbeddableTest.java @@ -9,29 +9,20 @@ import jakarta.persistence.GeneratedValue; import jakarta.persistence.Id; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; - -import org.junit.Test; - -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.Test; /** * @author Vlad Mihalcea */ -public class NestedEmbeddableTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Book.class - }; - } +@Jpa(annotatedClasses = {NestedEmbeddableTest.Book.class}) +public class NestedEmbeddableTest { @Test - public void testLifecycle() { - - doInJPA(this::entityManagerFactory, entityManager -> { + public void testLifecycle(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { Book book = new Book(); book.setTitle("High-Performance Java Persistence"); book.setAuthor("Vlad Mihalcea"); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/embeddable/NestedJsonEmbeddableTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/embeddable/NestedJsonEmbeddableTest.java index 968f97528dcc..44a6071d663e 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/embeddable/NestedJsonEmbeddableTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/embeddable/NestedJsonEmbeddableTest.java @@ -20,14 +20,15 @@ import java.util.UUID; import org.hibernate.annotations.JdbcTypeCode; -import org.hibernate.type.SqlTypes; - +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; import org.hibernate.testing.orm.domain.gambit.EntityOfBasics; import org.hibernate.testing.orm.domain.gambit.MutableValue; -import org.hibernate.testing.orm.junit.BaseSessionFactoryFunctionalTest; import org.hibernate.testing.orm.junit.DialectFeatureChecks; import org.hibernate.testing.orm.junit.Jira; import org.hibernate.testing.orm.junit.RequiresDialectFeature; +import org.hibernate.type.SqlTypes; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -42,18 +43,13 @@ import static org.junit.jupiter.api.Assertions.assertNull; @RequiresDialectFeature(feature = DialectFeatureChecks.SupportsJsonAggregate.class) -public class NestedJsonEmbeddableTest extends BaseSessionFactoryFunctionalTest { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - JsonHolder.class - }; - } +@DomainModel(annotatedClasses = {NestedJsonEmbeddableTest.JsonHolder.class}) +@SessionFactory +public class NestedJsonEmbeddableTest { @BeforeEach - public void setUp() { - inTransaction( + public void setUp(SessionFactoryScope scope) { + scope.inTransaction( session -> { session.persist( new JsonHolder( 1L, "XYZ", 10, "String \"A&B\"", EmbeddableAggregate.createAggregate1() ) ); session.persist( new JsonHolder( 2L, null, 20, "String 'abc'", EmbeddableAggregate.createAggregate2() ) ); @@ -62,19 +58,19 @@ public void setUp() { } @AfterEach - protected void cleanupTest() { - sessionFactoryScope().getSessionFactory().getSchemaManager().truncate(); + protected void cleanupTest(SessionFactoryScope scope) { + scope.dropData(); } @Test - public void testUpdate() { - sessionFactoryScope().inTransaction( - entityManager -> { - JsonHolder jsonHolder = entityManager.find( JsonHolder.class, 1L ); + public void testUpdate(SessionFactoryScope scope) { + scope.inTransaction( + session -> { + JsonHolder jsonHolder = session.find( JsonHolder.class, 1L ); jsonHolder.setAggregate( EmbeddableAggregate.createAggregate2() ); - entityManager.flush(); - entityManager.clear(); - jsonHolder = entityManager.find( JsonHolder.class, 1L ); + session.flush(); + session.clear(); + jsonHolder = session.find( JsonHolder.class, 1L ); assertEquals( "XYZ", jsonHolder.theJson.stringField ); assertEquals( 10, jsonHolder.theJson.simpleEmbeddable.integerField ); assertStructEquals( EmbeddableAggregate.createAggregate2(), jsonHolder.getAggregate() ); @@ -83,10 +79,10 @@ public void testUpdate() { } @Test - public void testFetch() { - sessionFactoryScope().inSession( - entityManager -> { - List jsonHolders = entityManager.createQuery( "from JsonHolder b where b.id = 1", JsonHolder.class ).getResultList(); + public void testFetch(SessionFactoryScope scope) { + scope.inSession( + session -> { + List jsonHolders = session.createQuery( "from JsonHolder b where b.id = 1", JsonHolder.class ).getResultList(); assertEquals( 1, jsonHolders.size() ); JsonHolder jsonHolder = jsonHolders.get( 0 ); assertEquals( 1L, jsonHolder.getId() ); @@ -99,10 +95,10 @@ public void testFetch() { } @Test - public void testFetchNull() { - sessionFactoryScope().inSession( - entityManager -> { - List jsonHolders = entityManager.createQuery( "from JsonHolder b where b.id = 2", JsonHolder.class ).getResultList(); + public void testFetchNull(SessionFactoryScope scope) { + scope.inSession( + session -> { + List jsonHolders = session.createQuery( "from JsonHolder b where b.id = 2", JsonHolder.class ).getResultList(); assertEquals( 1, jsonHolders.size() ); JsonHolder jsonHolder = jsonHolders.get( 0 ); assertEquals( 2L, jsonHolder.getId() ); @@ -114,10 +110,10 @@ public void testFetchNull() { } @Test - public void testDomainResult() { - sessionFactoryScope().inSession( - entityManager -> { - List structs = entityManager.createQuery( "select b.theJson from JsonHolder b where b.id = 1", TheJson.class ).getResultList(); + public void testDomainResult(SessionFactoryScope scope) { + scope.inSession( + session -> { + List structs = session.createQuery( "select b.theJson from JsonHolder b where b.id = 1", TheJson.class ).getResultList(); assertEquals( 1, structs.size() ); TheJson theJson = structs.get( 0 ); assertEquals( "XYZ", theJson.stringField ); @@ -129,10 +125,10 @@ public void testDomainResult() { } @Test - public void testSelectionItems() { - sessionFactoryScope().inSession( - entityManager -> { - List tuples = entityManager.createQuery( + public void testSelectionItems(SessionFactoryScope scope) { + scope.inSession( + session -> { + List tuples = session.createQuery( "select " + "b.theJson.nested.theInt," + "b.theJson.nested.theDouble," + @@ -207,38 +203,38 @@ public void testSelectionItems() { } @Test - public void testDeleteWhere() { - sessionFactoryScope().inTransaction( - entityManager -> { - entityManager.createMutationQuery( "delete JsonHolder b where b.theJson is not null" ).executeUpdate(); - assertNull( entityManager.find( JsonHolder.class, 1L ) ); + public void testDeleteWhere(SessionFactoryScope scope) { + scope.inTransaction( + session -> { + session.createMutationQuery( "delete JsonHolder b where b.theJson is not null" ).executeUpdate(); + assertNull( session.find( JsonHolder.class, 1L ) ); } ); } @Test - public void testUpdateAggregate() { - sessionFactoryScope().inTransaction( - entityManager -> { - entityManager.createMutationQuery( "update JsonHolder b set b.theJson = null" ).executeUpdate(); - assertNull( entityManager.find( JsonHolder.class, 1L ).getAggregate() ); + public void testUpdateAggregate(SessionFactoryScope scope) { + scope.inTransaction( + session -> { + session.createMutationQuery( "update JsonHolder b set b.theJson = null" ).executeUpdate(); + assertNull( session.find( JsonHolder.class, 1L ).getAggregate() ); } ); } @Test @Jira( "https://hibernate.atlassian.net/browse/HHH-17695" ) - public void testNullNestedAggregate() { - sessionFactoryScope().inTransaction( - entityManager -> { + public void testNullNestedAggregate(SessionFactoryScope scope) { + scope.inTransaction( + session -> { JsonHolder jsonHolder = new JsonHolder(3L, "abc", 30, "String 'xyz'", null ); - entityManager.persist( jsonHolder ); + session.persist( jsonHolder ); } ); - sessionFactoryScope().inTransaction( - entityManager -> { - JsonHolder jsonHolder = entityManager.createQuery( "from JsonHolder b where b.id = 3", JsonHolder.class ).getSingleResult(); + scope.inTransaction( + session -> { + JsonHolder jsonHolder = session.createQuery( "from JsonHolder b where b.id = 3", JsonHolder.class ).getSingleResult(); assertEquals( "abc", jsonHolder.theJson.stringField ); assertEquals( 30, jsonHolder.theJson.simpleEmbeddable.integerField ); assertEquals( "String 'xyz'", jsonHolder.theJson.simpleEmbeddable.doubleNested.theNested.theLeaf.stringField ); @@ -249,18 +245,18 @@ public void testNullNestedAggregate() { @Test @Jira( "https://hibernate.atlassian.net/browse/HHH-17695" ) - public void testNullNestedEmbeddable() { - sessionFactoryScope().inTransaction( - entityManager -> { + public void testNullNestedEmbeddable(SessionFactoryScope scope) { + scope.inTransaction( + session -> { JsonHolder jsonHolder = new JsonHolder( ); jsonHolder.setId( 3L ); jsonHolder.setTheJson( new TheJson( "abc", null, EmbeddableAggregate.createAggregate1() ) ); - entityManager.persist( jsonHolder ); + session.persist( jsonHolder ); } ); - sessionFactoryScope().inTransaction( - entityManager -> { - JsonHolder jsonHolder = entityManager.createQuery( "from JsonHolder b where b.id = 3", JsonHolder.class ).getSingleResult(); + scope.inTransaction( + session -> { + JsonHolder jsonHolder = session.createQuery( "from JsonHolder b where b.id = 3", JsonHolder.class ).getSingleResult(); assertEquals( "abc", jsonHolder.theJson.stringField ); assertNull( jsonHolder.theJson.simpleEmbeddable ); assertStructEquals( EmbeddableAggregate.createAggregate1(), jsonHolder.getAggregate() ); @@ -270,18 +266,18 @@ public void testNullNestedEmbeddable() { @Test @Jira( "https://hibernate.atlassian.net/browse/HHH-17695" ) - public void testNullNestedEmbeddableAndAggregate() { - sessionFactoryScope().inTransaction( - entityManager -> { + public void testNullNestedEmbeddableAndAggregate(SessionFactoryScope scope) { + scope.inTransaction( + session -> { JsonHolder jsonHolder = new JsonHolder( ); jsonHolder.setId( 3L ); jsonHolder.setTheJson( new TheJson( "abc", null, null ) ); - entityManager.persist( jsonHolder ); + session.persist( jsonHolder ); } ); - sessionFactoryScope().inTransaction( - entityManager -> { - JsonHolder jsonHolder = entityManager.createQuery( "from JsonHolder b where b.id = 3", JsonHolder.class ).getSingleResult(); + scope.inTransaction( + session -> { + JsonHolder jsonHolder = session.createQuery( "from JsonHolder b where b.id = 3", JsonHolder.class ).getSingleResult(); assertEquals( "abc", jsonHolder.theJson.stringField ); assertNull( jsonHolder.theJson.simpleEmbeddable ); assertNull( jsonHolder.getAggregate() ); @@ -291,38 +287,38 @@ public void testNullNestedEmbeddableAndAggregate() { @Test @RequiresDialectFeature(feature = DialectFeatureChecks.SupportsJsonComponentUpdate.class) - public void testUpdateAggregateMember() { - sessionFactoryScope().inTransaction( - entityManager -> { - entityManager.createMutationQuery( "update JsonHolder b set b.theJson.nested.theString = null" ).executeUpdate(); + public void testUpdateAggregateMember(SessionFactoryScope scope) { + scope.inTransaction( + session -> { + session.createMutationQuery( "update JsonHolder b set b.theJson.nested.theString = null" ).executeUpdate(); EmbeddableAggregate struct = EmbeddableAggregate.createAggregate1(); struct.setTheString( null ); - assertStructEquals( struct, entityManager.find( JsonHolder.class, 1L ).getAggregate() ); + assertStructEquals( struct, session.find( JsonHolder.class, 1L ).getAggregate() ); } ); } @Test @RequiresDialectFeature(feature = DialectFeatureChecks.SupportsJsonComponentUpdate.class) - public void testUpdateMultipleAggregateMembers() { - sessionFactoryScope().inTransaction( - entityManager -> { - entityManager.createMutationQuery( "update JsonHolder b set b.theJson.nested.theString = null, b.theJson.nested.theUuid = null" ).executeUpdate(); + public void testUpdateMultipleAggregateMembers(SessionFactoryScope scope) { + scope.inTransaction( + session -> { + session.createMutationQuery( "update JsonHolder b set b.theJson.nested.theString = null, b.theJson.nested.theUuid = null" ).executeUpdate(); EmbeddableAggregate struct = EmbeddableAggregate.createAggregate1(); struct.setTheString( null ); struct.setTheUuid( null ); - assertStructEquals( struct, entityManager.find( JsonHolder.class, 1L ).getAggregate() ); + assertStructEquals( struct, session.find( JsonHolder.class, 1L ).getAggregate() ); } ); } @Test @RequiresDialectFeature(feature = DialectFeatureChecks.SupportsJsonComponentUpdate.class) - public void testUpdateAllAggregateMembers() { - sessionFactoryScope().inTransaction( - entityManager -> { + public void testUpdateAllAggregateMembers(SessionFactoryScope scope) { + scope.inTransaction( + session -> { EmbeddableAggregate struct = EmbeddableAggregate.createAggregate1(); - entityManager.createMutationQuery( + session.createMutationQuery( "update JsonHolder b set " + "b.theJson.nested.theInt = :theInt," + "b.theJson.nested.theDouble = :theDouble," + @@ -379,7 +375,7 @@ public void testUpdateAllAggregateMembers() { .setParameter( "mutableValue", struct.getMutableValue() ) .setParameter( "integerField", 5 ) .executeUpdate(); - JsonHolder jsonHolder = entityManager.find( JsonHolder.class, 2L ); + JsonHolder jsonHolder = session.find( JsonHolder.class, 2L ); assertEquals( 5, jsonHolder.theJson.simpleEmbeddable.integerField ); assertStructEquals( EmbeddableAggregate.createAggregate1(), jsonHolder.getAggregate() ); } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/embeddable/NestedStructEmbeddableTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/embeddable/NestedStructEmbeddableTest.java index 3d2e927d27b1..72b0c72279a8 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/embeddable/NestedStructEmbeddableTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/embeddable/NestedStructEmbeddableTest.java @@ -270,12 +270,12 @@ protected void cleanupTest(SessionFactoryScope scope) { @Test public void testUpdate(SessionFactoryScope scope) { scope.inTransaction( - entityManager -> { - StructHolder structHolder = entityManager.find( StructHolder.class, 1L ); + session -> { + StructHolder structHolder = session.find( StructHolder.class, 1L ); structHolder.setAggregate( EmbeddableAggregate.createAggregate2() ); - entityManager.flush(); - entityManager.clear(); - structHolder = entityManager.find( StructHolder.class, 1L ); + session.flush(); + session.clear(); + structHolder = session.find( StructHolder.class, 1L ); assertEquals( "XYZ", structHolder.struct.stringField ); assertEquals( 10, structHolder.struct.simpleEmbeddable.integerField ); assertStructEquals( EmbeddableAggregate.createAggregate2(), structHolder.getAggregate() ); @@ -286,8 +286,8 @@ public void testUpdate(SessionFactoryScope scope) { @Test public void testFetch(SessionFactoryScope scope) { scope.inSession( - entityManager -> { - List structHolders = entityManager.createQuery( "from StructHolder b where b.id = 1", StructHolder.class ).getResultList(); + session -> { + List structHolders = session.createQuery( "from StructHolder b where b.id = 1", StructHolder.class ).getResultList(); assertEquals( 1, structHolders.size() ); StructHolder structHolder = structHolders.get( 0 ); assertEquals( 1L, structHolder.getId() ); @@ -302,8 +302,8 @@ public void testFetch(SessionFactoryScope scope) { @Test public void testFetchNull(SessionFactoryScope scope) { scope.inSession( - entityManager -> { - List structHolders = entityManager.createQuery( "from StructHolder b where b.id = 2", StructHolder.class ).getResultList(); + session -> { + List structHolders = session.createQuery( "from StructHolder b where b.id = 2", StructHolder.class ).getResultList(); assertEquals( 1, structHolders.size() ); StructHolder structHolder = structHolders.get( 0 ); assertEquals( 2L, structHolder.getId() ); @@ -317,8 +317,8 @@ public void testFetchNull(SessionFactoryScope scope) { @Test public void testDomainResult(SessionFactoryScope scope) { scope.inSession( - entityManager -> { - List structs = entityManager.createQuery( "select b.struct from StructHolder b where b.id = 1", TheStruct.class ).getResultList(); + session -> { + List structs = session.createQuery( "select b.struct from StructHolder b where b.id = 1", TheStruct.class ).getResultList(); assertEquals( 1, structs.size() ); TheStruct theStruct = structs.get( 0 ); assertEquals( "XYZ", theStruct.stringField ); @@ -332,8 +332,8 @@ public void testDomainResult(SessionFactoryScope scope) { @Test public void testSelectionItems(SessionFactoryScope scope) { scope.inSession( - entityManager -> { - List tuples = entityManager.createQuery( + session -> { + List tuples = session.createQuery( "select " + "b.struct.nested.theInt," + "b.struct.nested.theDouble," + @@ -410,9 +410,9 @@ public void testSelectionItems(SessionFactoryScope scope) { @Test public void testDeleteWhere(SessionFactoryScope scope) { scope.inTransaction( - entityManager -> { - entityManager.createMutationQuery( "delete StructHolder b where b.struct is not null" ).executeUpdate(); - assertNull( entityManager.find( StructHolder.class, 1L ) ); + session -> { + session.createMutationQuery( "delete StructHolder b where b.struct is not null" ).executeUpdate(); + assertNull( session.find( StructHolder.class, 1L ) ); } ); @@ -421,9 +421,9 @@ public void testDeleteWhere(SessionFactoryScope scope) { @Test public void testUpdateAggregate(SessionFactoryScope scope) { scope.inTransaction( - entityManager -> { - entityManager.createMutationQuery( "update StructHolder b set b.struct = null" ).executeUpdate(); - assertNull( entityManager.find( StructHolder.class, 1L ).getAggregate() ); + session -> { + session.createMutationQuery( "update StructHolder b set b.struct = null" ).executeUpdate(); + assertNull( session.find( StructHolder.class, 1L ).getAggregate() ); } ); } @@ -431,11 +431,11 @@ public void testUpdateAggregate(SessionFactoryScope scope) { @Test public void testUpdateAggregateMember(SessionFactoryScope scope) { scope.inTransaction( - entityManager -> { - entityManager.createMutationQuery( "update StructHolder b set b.struct.nested.theString = null" ).executeUpdate(); + session -> { + session.createMutationQuery( "update StructHolder b set b.struct.nested.theString = null" ).executeUpdate(); EmbeddableAggregate struct = EmbeddableAggregate.createAggregate1(); struct.setTheString( null ); - assertStructEquals( struct, entityManager.find( StructHolder.class, 1L ).getAggregate() ); + assertStructEquals( struct, session.find( StructHolder.class, 1L ).getAggregate() ); } ); } @@ -443,12 +443,12 @@ public void testUpdateAggregateMember(SessionFactoryScope scope) { @Test public void testUpdateMultipleAggregateMembers(SessionFactoryScope scope) { scope.inTransaction( - entityManager -> { - entityManager.createMutationQuery( "update StructHolder b set b.struct.nested.theString = null, b.struct.nested.theUuid = null" ).executeUpdate(); + session -> { + session.createMutationQuery( "update StructHolder b set b.struct.nested.theString = null, b.struct.nested.theUuid = null" ).executeUpdate(); EmbeddableAggregate struct = EmbeddableAggregate.createAggregate1(); struct.setTheString( null ); struct.setTheUuid( null ); - assertStructEquals( struct, entityManager.find( StructHolder.class, 1L ).getAggregate() ); + assertStructEquals( struct, session.find( StructHolder.class, 1L ).getAggregate() ); } ); } @@ -456,9 +456,9 @@ public void testUpdateMultipleAggregateMembers(SessionFactoryScope scope) { @Test public void testUpdateAllAggregateMembers(SessionFactoryScope scope) { scope.inTransaction( - entityManager -> { + session -> { EmbeddableAggregate struct = EmbeddableAggregate.createAggregate1(); - entityManager.createMutationQuery( + session.createMutationQuery( "update StructHolder b set " + "b.struct.nested.theInt = :theInt," + "b.struct.nested.theDouble = :theDouble," + @@ -515,7 +515,7 @@ public void testUpdateAllAggregateMembers(SessionFactoryScope scope) { .setParameter( "mutableValue", struct.getMutableValue() ) .setParameter( "integerField", 5 ) .executeUpdate(); - StructHolder structHolder = entityManager.find( StructHolder.class, 2L ); + StructHolder structHolder = session.find( StructHolder.class, 2L ); assertEquals( 5, structHolder.struct.simpleEmbeddable.integerField ); assertStructEquals( EmbeddableAggregate.createAggregate1(), structHolder.getAggregate() ); } @@ -525,9 +525,9 @@ public void testUpdateAllAggregateMembers(SessionFactoryScope scope) { @Test public void testNativeQuery(SessionFactoryScope scope) { scope.inTransaction( - entityManager -> { + session -> { //noinspection unchecked - List resultList = entityManager.createNativeQuery( + List resultList = session.createNativeQuery( "select b.struct from StructHolder b where b.id = 1", // DB2 does not support structs on the driver level, and we instead do a XML serialization/deserialization // So in order to receive the correct value, we have to specify the actual type that we expect @@ -551,8 +551,8 @@ public void testNativeQuery(SessionFactoryScope scope) { @Test public void testFunction(SessionFactoryScope scope) { scope.inTransaction( - entityManager -> { - ProcedureCall structFunction = entityManager.createStoredProcedureCall( "structFunction" ) + session -> { + ProcedureCall structFunction = session.createStoredProcedureCall( "structFunction" ) .markAsFunctionCall( TheStruct.class ); //noinspection unchecked final List resultList = structFunction.getResultList(); @@ -571,8 +571,8 @@ public void testFunction(SessionFactoryScope scope) { @SkipForDialect(dialectClass = DB2Dialect.class, reason = "DB2 does not support struct types in procedures") public void testProcedure(SessionFactoryScope scope) { scope.inTransaction( - entityManager -> { - final Dialect dialect = entityManager.getJdbcServices().getDialect(); + session -> { + final Dialect dialect = session.getJdbcServices().getDialect(); final ParameterMode parameterMode; if ( dialect instanceof PostgreSQLDialect ) { parameterMode = ParameterMode.INOUT; @@ -580,7 +580,7 @@ public void testProcedure(SessionFactoryScope scope) { else { parameterMode = ParameterMode.OUT; } - ProcedureCall structFunction = entityManager.createStoredProcedureCall( "structProcedure" ); + ProcedureCall structFunction = session.createStoredProcedureCall( "structProcedure" ); ProcedureParameter resultParameter = structFunction.registerParameter( "result", TheStruct.class, diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/embeddable/NestedStructWithArrayEmbeddableTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/embeddable/NestedStructWithArrayEmbeddableTest.java index 75cecd2b34da..02b63aa5b456 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/embeddable/NestedStructWithArrayEmbeddableTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/embeddable/NestedStructWithArrayEmbeddableTest.java @@ -90,12 +90,12 @@ protected void cleanupTest(SessionFactoryScope scope) { @Test public void testUpdate(SessionFactoryScope scope) { scope.inTransaction( - entityManager -> { - StructHolder structHolder = entityManager.find( StructHolder.class, 1L ); + session -> { + StructHolder structHolder = session.find( StructHolder.class, 1L ); structHolder.setAggregate( EmbeddableWithArrayAggregate.createAggregate2() ); - entityManager.flush(); - entityManager.clear(); - structHolder = entityManager.find( StructHolder.class, 1L ); + session.flush(); + session.clear(); + structHolder = session.find( StructHolder.class, 1L ); assertEquals( "XYZ", structHolder.struct.stringField ); assertArrayEquals( new Integer[]{ 10 }, structHolder.struct.simpleEmbeddable.integerField ); assertStructEquals( EmbeddableWithArrayAggregate.createAggregate2(), structHolder.getAggregate() ); @@ -106,8 +106,8 @@ public void testUpdate(SessionFactoryScope scope) { @Test public void testFetch(SessionFactoryScope scope) { scope.inSession( - entityManager -> { - List structHolders = entityManager.createQuery( "from StructHolder b where b.id = 1", StructHolder.class ).getResultList(); + session -> { + List structHolders = session.createQuery( "from StructHolder b where b.id = 1", StructHolder.class ).getResultList(); assertEquals( 1, structHolders.size() ); StructHolder structHolder = structHolders.get( 0 ); assertEquals( 1L, structHolder.getId() ); @@ -122,8 +122,8 @@ public void testFetch(SessionFactoryScope scope) { @Test public void testFetchNull(SessionFactoryScope scope) { scope.inSession( - entityManager -> { - List structHolders = entityManager.createQuery( "from StructHolder b where b.id = 2", StructHolder.class ).getResultList(); + session -> { + List structHolders = session.createQuery( "from StructHolder b where b.id = 2", StructHolder.class ).getResultList(); assertEquals( 1, structHolders.size() ); StructHolder structHolder = structHolders.get( 0 ); assertEquals( 2L, structHolder.getId() ); @@ -137,8 +137,8 @@ public void testFetchNull(SessionFactoryScope scope) { @Test public void testDomainResult(SessionFactoryScope scope) { scope.inSession( - entityManager -> { - List structs = entityManager.createQuery( "select b.struct from StructHolder b where b.id = 1", TheStruct.class ).getResultList(); + session -> { + List structs = session.createQuery( "select b.struct from StructHolder b where b.id = 1", TheStruct.class ).getResultList(); assertEquals( 1, structs.size() ); TheStruct theStruct = structs.get( 0 ); assertEquals( "XYZ", theStruct.stringField ); @@ -153,8 +153,8 @@ public void testDomainResult(SessionFactoryScope scope) { @SkipForDialect(dialectClass = OracleDialect.class, reason = "We have to use TABLE storage in this test because Oracle doesn't support LOBs in struct arrays, but TABLE is not indexed") public void testSelectionItems(SessionFactoryScope scope) { scope.inSession( - entityManager -> { - List tuples = entityManager.createQuery( + session -> { + List tuples = session.createQuery( "select " + "b.struct.nested[1].theInt," + "b.struct.nested[1].theDouble," + @@ -229,9 +229,9 @@ public void testSelectionItems(SessionFactoryScope scope) { @Test public void testDeleteWhere(SessionFactoryScope scope) { scope.inTransaction( - entityManager -> { - entityManager.createMutationQuery( "delete StructHolder b where b.struct is not null" ).executeUpdate(); - assertNull( entityManager.find( StructHolder.class, 1L ) ); + session -> { + session.createMutationQuery( "delete StructHolder b where b.struct is not null" ).executeUpdate(); + assertNull( session.find( StructHolder.class, 1L ) ); } ); @@ -240,9 +240,9 @@ public void testDeleteWhere(SessionFactoryScope scope) { @Test public void testUpdateAggregate(SessionFactoryScope scope) { scope.inTransaction( - entityManager -> { - entityManager.createMutationQuery( "update StructHolder b set b.struct = null" ).executeUpdate(); - assertNull( entityManager.find( StructHolder.class, 1L ).getAggregate() ); + session -> { + session.createMutationQuery( "update StructHolder b set b.struct = null" ).executeUpdate(); + assertNull( session.find( StructHolder.class, 1L ).getAggregate() ); } ); } @@ -252,11 +252,11 @@ public void testUpdateAggregate(SessionFactoryScope scope) { @SkipForDialect(dialectClass = OracleDialect.class, reason = "We have to use TABLE storage in this test because Oracle doesn't support LOBs in struct arrays, but TABLE is not indexed") public void testUpdateAggregateMember(SessionFactoryScope scope) { scope.inTransaction( - entityManager -> { - entityManager.createMutationQuery( "update StructHolder b set b.struct.nested[1].theString = null" ).executeUpdate(); + session -> { + session.createMutationQuery( "update StructHolder b set b.struct.nested[1].theString = null" ).executeUpdate(); EmbeddableWithArrayAggregate struct = EmbeddableWithArrayAggregate.createAggregate1(); struct.setTheString( null ); - assertStructEquals( struct, entityManager.find( StructHolder.class, 1L ).getAggregate() ); + assertStructEquals( struct, session.find( StructHolder.class, 1L ).getAggregate() ); } ); } @@ -266,12 +266,12 @@ public void testUpdateAggregateMember(SessionFactoryScope scope) { @SkipForDialect(dialectClass = OracleDialect.class, reason = "We have to use TABLE storage in this test because Oracle doesn't support LOBs in struct arrays, but TABLE is not indexed") public void testUpdateMultipleAggregateMembers(SessionFactoryScope scope) { scope.inTransaction( - entityManager -> { - entityManager.createMutationQuery( "update StructHolder b set b.struct.nested[1].theString = null, b.struct.nested[1].theUuid = null" ).executeUpdate(); + session -> { + session.createMutationQuery( "update StructHolder b set b.struct.nested[1].theString = null, b.struct.nested[1].theUuid = null" ).executeUpdate(); EmbeddableWithArrayAggregate struct = EmbeddableWithArrayAggregate.createAggregate1(); struct.setTheString( null ); struct.setTheUuid( null ); - assertStructEquals( struct, entityManager.find( StructHolder.class, 1L ).getAggregate() ); + assertStructEquals( struct, session.find( StructHolder.class, 1L ).getAggregate() ); } ); } @@ -281,9 +281,9 @@ public void testUpdateMultipleAggregateMembers(SessionFactoryScope scope) { @SkipForDialect(dialectClass = OracleDialect.class, reason = "We have to use TABLE storage in this test because Oracle doesn't support LOBs in struct arrays, but TABLE is not indexed") public void testUpdateAllAggregateMembers(SessionFactoryScope scope) { scope.inTransaction( - entityManager -> { + session -> { EmbeddableWithArrayAggregate struct = EmbeddableWithArrayAggregate.createAggregate1(); - entityManager.createMutationQuery( + session.createMutationQuery( "update StructHolder b set " + "b.struct.nested[1].theInt = :theInt," + "b.struct.nested[1].theDouble = :theDouble," + @@ -340,7 +340,7 @@ public void testUpdateAllAggregateMembers(SessionFactoryScope scope) { .setParameter( "mutableValue", struct.getMutableValue() ) .setParameter( "integerField", new Integer[]{ 5 } ) .executeUpdate(); - StructHolder structHolder = entityManager.find( StructHolder.class, 2L ); + StructHolder structHolder = session.find( StructHolder.class, 2L ); assertArrayEquals( new Integer[]{ 5 }, structHolder.struct.simpleEmbeddable.integerField ); assertStructEquals( EmbeddableWithArrayAggregate.createAggregate1(), structHolder.getAggregate() ); } @@ -350,9 +350,9 @@ public void testUpdateAllAggregateMembers(SessionFactoryScope scope) { @Test public void testNativeQuery(SessionFactoryScope scope) { scope.inTransaction( - entityManager -> { + session -> { //noinspection unchecked - List resultList = entityManager.createNativeQuery( + List resultList = session.createNativeQuery( "select b.struct from StructHolder b where b.id = 1", Object.class ) .getResultList(); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/embeddable/NestedXmlEmbeddableTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/embeddable/NestedXmlEmbeddableTest.java index 90f646d6d5ac..d1105cdc0820 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/embeddable/NestedXmlEmbeddableTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/embeddable/NestedXmlEmbeddableTest.java @@ -12,10 +12,12 @@ import org.hibernate.dialect.OracleDialect; import org.hibernate.testing.orm.domain.gambit.EntityOfBasics; import org.hibernate.testing.orm.domain.gambit.MutableValue; -import org.hibernate.testing.orm.junit.BaseSessionFactoryFunctionalTest; import org.hibernate.testing.orm.junit.DialectFeatureChecks; +import org.hibernate.testing.orm.junit.DomainModel; import org.hibernate.testing.orm.junit.Jira; import org.hibernate.testing.orm.junit.RequiresDialectFeature; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; import org.hibernate.testing.orm.junit.SkipForDialect; import org.hibernate.testing.orm.junit.VersionMatchMode; import org.hibernate.type.SqlTypes; @@ -45,18 +47,13 @@ @RequiresDialectFeature(feature = DialectFeatureChecks.SupportsXmlAggregate.class) @SkipForDialect(dialectClass = OracleDialect.class, majorVersion = 23, versionMatchMode = VersionMatchMode.SAME_OR_NEWER, reason = "Currently failing on Oracle 23+ due to Bug 37319693 - ORA-00600 with check constraint on xml type") -public class NestedXmlEmbeddableTest extends BaseSessionFactoryFunctionalTest { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - XmlHolder.class - }; - } +@DomainModel(annotatedClasses = {NestedXmlEmbeddableTest.XmlHolder.class}) +@SessionFactory +public class NestedXmlEmbeddableTest { @BeforeEach - public void setUp() { - inTransaction( + public void setUp(SessionFactoryScope scope) { + scope.inTransaction( session -> { session.persist( new XmlHolder( 1L, "XYZ", 10, "String \"A&B\"", EmbeddableAggregate.createAggregate1() ) ); session.persist( new XmlHolder( 2L, null, 20, "String 'abc'", EmbeddableAggregate.createAggregate2() ) ); @@ -65,13 +62,13 @@ public void setUp() { } @AfterEach - protected void cleanupTest() { - sessionFactoryScope().getSessionFactory().getSchemaManager().truncate(); + protected void cleanupTest(SessionFactoryScope scope) { + scope.dropData(); } @Test - public void testUpdate() { - sessionFactoryScope().inTransaction( + public void testUpdate(SessionFactoryScope scope) { + scope.inTransaction( entityManager -> { XmlHolder XmlHolder = entityManager.find( XmlHolder.class, 1L ); XmlHolder.setAggregate( EmbeddableAggregate.createAggregate2() ); @@ -86,8 +83,8 @@ public void testUpdate() { } @Test - public void testFetch() { - sessionFactoryScope().inSession( + public void testFetch(SessionFactoryScope scope) { + scope.inSession( entityManager -> { List XmlHolders = entityManager.createQuery( "from XmlHolder b where b.id = 1", XmlHolder.class ).getResultList(); assertEquals( 1, XmlHolders.size() ); @@ -102,8 +99,8 @@ public void testFetch() { } @Test - public void testFetchNull() { - sessionFactoryScope().inSession( + public void testFetchNull(SessionFactoryScope scope) { + scope.inSession( entityManager -> { List XmlHolders = entityManager.createQuery( "from XmlHolder b where b.id = 2", XmlHolder.class ).getResultList(); assertEquals( 1, XmlHolders.size() ); @@ -117,8 +114,8 @@ public void testFetchNull() { } @Test - public void testDomainResult() { - sessionFactoryScope().inSession( + public void testDomainResult(SessionFactoryScope scope) { + scope.inSession( entityManager -> { List structs = entityManager.createQuery( "select b.theXml from XmlHolder b where b.id = 1", TheXml.class ).getResultList(); assertEquals( 1, structs.size() ); @@ -132,8 +129,8 @@ public void testDomainResult() { } @Test - public void testSelectionItems() { - sessionFactoryScope().inSession( + public void testSelectionItems(SessionFactoryScope scope) { + scope.inSession( entityManager -> { List tuples = entityManager.createQuery( "select " + @@ -210,8 +207,8 @@ public void testSelectionItems() { } @Test - public void testDeleteWhere() { - sessionFactoryScope().inTransaction( + public void testDeleteWhere(SessionFactoryScope scope) { + scope.inTransaction( entityManager -> { entityManager.createMutationQuery( "delete XmlHolder b where b.theXml is not null" ).executeUpdate(); assertNull( entityManager.find( XmlHolder.class, 1L ) ); @@ -221,8 +218,8 @@ public void testDeleteWhere() { } @Test - public void testUpdateAggregate() { - sessionFactoryScope().inTransaction( + public void testUpdateAggregate(SessionFactoryScope scope) { + scope.inTransaction( entityManager -> { entityManager.createMutationQuery( "update XmlHolder b set b.theXml = null" ).executeUpdate(); assertNull( entityManager.find( XmlHolder.class, 1L ).getAggregate() ); @@ -232,14 +229,14 @@ public void testUpdateAggregate() { @Test @Jira( "https://hibernate.atlassian.net/browse/HHH-17695" ) - public void testNullNestedAggregate() { - sessionFactoryScope().inTransaction( + public void testNullNestedAggregate(SessionFactoryScope scope) { + scope.inTransaction( entityManager -> { XmlHolder XmlHolder = new XmlHolder(3L, "abc", 30, "String 'xyz'", null ); entityManager.persist( XmlHolder ); } ); - sessionFactoryScope().inTransaction( + scope.inTransaction( entityManager -> { XmlHolder XmlHolder = entityManager.createQuery( "from XmlHolder b where b.id = 3", XmlHolder.class ).getSingleResult(); assertEquals( "abc", XmlHolder.theXml.stringField ); @@ -252,8 +249,8 @@ public void testNullNestedAggregate() { @Test @Jira( "https://hibernate.atlassian.net/browse/HHH-17695" ) - public void testNullNestedEmbeddable() { - sessionFactoryScope().inTransaction( + public void testNullNestedEmbeddable(SessionFactoryScope scope) { + scope.inTransaction( entityManager -> { XmlHolder XmlHolder = new XmlHolder( ); XmlHolder.setId( 3L ); @@ -261,7 +258,7 @@ public void testNullNestedEmbeddable() { entityManager.persist( XmlHolder ); } ); - sessionFactoryScope().inTransaction( + scope.inTransaction( entityManager -> { XmlHolder XmlHolder = entityManager.createQuery( "from XmlHolder b where b.id = 3", XmlHolder.class ).getSingleResult(); assertEquals( "abc", XmlHolder.theXml.stringField ); @@ -273,8 +270,8 @@ public void testNullNestedEmbeddable() { @Test @Jira( "https://hibernate.atlassian.net/browse/HHH-17695" ) - public void testNullNestedEmbeddableAndAggregate() { - sessionFactoryScope().inTransaction( + public void testNullNestedEmbeddableAndAggregate(SessionFactoryScope scope) { + scope.inTransaction( entityManager -> { XmlHolder XmlHolder = new XmlHolder( ); XmlHolder.setId( 3L ); @@ -282,7 +279,7 @@ public void testNullNestedEmbeddableAndAggregate() { entityManager.persist( XmlHolder ); } ); - sessionFactoryScope().inTransaction( + scope.inTransaction( entityManager -> { XmlHolder XmlHolder = entityManager.createQuery( "from XmlHolder b where b.id = 3", XmlHolder.class ).getSingleResult(); assertEquals( "abc", XmlHolder.theXml.stringField ); @@ -294,8 +291,8 @@ public void testNullNestedEmbeddableAndAggregate() { @Test @RequiresDialectFeature(feature = DialectFeatureChecks.SupportsXmlComponentUpdate.class) - public void testUpdateAggregateMember() { - sessionFactoryScope().inTransaction( + public void testUpdateAggregateMember(SessionFactoryScope scope) { + scope.inTransaction( entityManager -> { entityManager.createMutationQuery( "update XmlHolder b set b.theXml.nested.theString = null" ).executeUpdate(); EmbeddableAggregate struct = EmbeddableAggregate.createAggregate1(); @@ -307,8 +304,8 @@ public void testUpdateAggregateMember() { @Test @RequiresDialectFeature(feature = DialectFeatureChecks.SupportsXmlComponentUpdate.class) - public void testUpdateAggregateMemberOnNestedNull() { - sessionFactoryScope().inTransaction( + public void testUpdateAggregateMemberOnNestedNull(SessionFactoryScope scope) { + scope.inTransaction( entityManager -> { entityManager.createMutationQuery( "update XmlHolder b set b.theXml.simpleEmbeddable.doubleNested = null" ).executeUpdate(); entityManager.createMutationQuery( "update XmlHolder b set b.theXml.simpleEmbeddable.doubleNested.theNested.theLeaf.stringField = 'Abc'" ).executeUpdate(); @@ -319,8 +316,8 @@ public void testUpdateAggregateMemberOnNestedNull() { @Test @RequiresDialectFeature(feature = DialectFeatureChecks.SupportsXmlComponentUpdate.class) - public void testUpdateMultipleAggregateMembers() { - sessionFactoryScope().inTransaction( + public void testUpdateMultipleAggregateMembers(SessionFactoryScope scope) { + scope.inTransaction( entityManager -> { entityManager.createMutationQuery( "update XmlHolder b set b.theXml.nested.theString = null, b.theXml.nested.theUuid = null" ).executeUpdate(); EmbeddableAggregate struct = EmbeddableAggregate.createAggregate1(); @@ -333,8 +330,8 @@ public void testUpdateMultipleAggregateMembers() { @Test @RequiresDialectFeature(feature = DialectFeatureChecks.SupportsXmlComponentUpdate.class) - public void testUpdateAllAggregateMembers() { - sessionFactoryScope().inTransaction( + public void testUpdateAllAggregateMembers(SessionFactoryScope scope) { + scope.inTransaction( entityManager -> { EmbeddableAggregate struct = EmbeddableAggregate.createAggregate1(); entityManager.createMutationQuery( diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/embeddable/ParentTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/embeddable/ParentTest.java index 58a9e6780965..78908d2f9704 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/embeddable/ParentTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/embeddable/ParentTest.java @@ -12,29 +12,23 @@ import org.hibernate.annotations.Parent; import org.hibernate.annotations.TargetEmbeddable; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; -import org.junit.Test; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.Test; -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; -import static org.junit.Assert.assertSame; +import static org.junit.jupiter.api.Assertions.assertSame; /** * @author Vlad Mihalcea */ -public class ParentTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - City.class, - }; - } +@Jpa(annotatedClasses = {ParentTest.City.class}) +public class ParentTest { @Test - public void testLifecycle() { + public void testLifecycle(EntityManagerFactoryScope scope) { //tag::embeddable-Parent-persist-example[] - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { City cluj = new City(); cluj.setName("Cluj"); @@ -46,7 +40,7 @@ public void testLifecycle() { //tag::embeddable-Parent-fetching-example[] - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { City cluj = entityManager.find(City.class, 1L); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/embeddable/SimpleEmbeddableEquivalentTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/embeddable/SimpleEmbeddableEquivalentTest.java index c9a7adb5ec2b..2d7335bd8150 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/embeddable/SimpleEmbeddableEquivalentTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/embeddable/SimpleEmbeddableEquivalentTest.java @@ -9,28 +9,20 @@ import jakarta.persistence.GeneratedValue; import jakarta.persistence.Id; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; - -import org.junit.Test; - -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.Test; /** * @author Vlad Mihalcea */ -public class SimpleEmbeddableEquivalentTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Book.class - }; - } +@Jpa(annotatedClasses = {SimpleEmbeddableEquivalentTest.Book.class}) +public class SimpleEmbeddableEquivalentTest { @Test - public void testLifecycle() { + public void testLifecycle(EntityManagerFactoryScope scope) { - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { Book book = new Book(); book.setTitle("High-Performance Java Persistence"); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/embeddable/SimpleEmbeddableTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/embeddable/SimpleEmbeddableTest.java index bf7de4a3f54d..02041c58907c 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/embeddable/SimpleEmbeddableTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/embeddable/SimpleEmbeddableTest.java @@ -10,28 +10,20 @@ import jakarta.persistence.GeneratedValue; import jakarta.persistence.Id; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; - -import org.junit.Test; - -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.Test; /** * @author Vlad Mihalcea */ -public class SimpleEmbeddableTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Book.class - }; - } +@Jpa(annotatedClasses = {SimpleEmbeddableTest.Book.class}) +public class SimpleEmbeddableTest { @Test - public void testLifecycle() { + public void testLifecycle(EntityManagerFactoryScope scope) { - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { Book book = new Book(); book.setTitle("High-Performance Java Persistence"); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/embeddable/UpdateEntityWithIdClassAndJsonFieldTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/embeddable/UpdateEntityWithIdClassAndJsonFieldTest.java index c204a240e66d..268060252e2f 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/embeddable/UpdateEntityWithIdClassAndJsonFieldTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/embeddable/UpdateEntityWithIdClassAndJsonFieldTest.java @@ -26,7 +26,7 @@ import jakarta.persistence.IdClass; import static org.assertj.core.api.AssertionsForClassTypes.assertThat; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; @DomainModel( annotatedClasses = { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/embeddable/XmlEmbeddableTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/embeddable/XmlEmbeddableTest.java index 4fed7e4f5523..ec52ced91c60 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/embeddable/XmlEmbeddableTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/embeddable/XmlEmbeddableTest.java @@ -11,10 +11,12 @@ import org.hibernate.dialect.OracleDialect; import org.hibernate.testing.orm.domain.gambit.EntityOfBasics; import org.hibernate.testing.orm.domain.gambit.MutableValue; -import org.hibernate.testing.orm.junit.BaseSessionFactoryFunctionalTest; import org.hibernate.testing.orm.junit.DialectFeatureChecks; +import org.hibernate.testing.orm.junit.DomainModel; import org.hibernate.testing.orm.junit.JiraKey; import org.hibernate.testing.orm.junit.RequiresDialectFeature; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; import org.hibernate.testing.orm.junit.SkipForDialect; import org.hibernate.testing.orm.junit.VersionMatchMode; import org.hibernate.type.SqlTypes; @@ -42,18 +44,13 @@ @RequiresDialectFeature(feature = DialectFeatureChecks.SupportsXmlAggregate.class) @SkipForDialect(dialectClass = OracleDialect.class, majorVersion = 23, versionMatchMode = VersionMatchMode.SAME_OR_NEWER, reason = "Currently failing on Oracle 23+ due to Bug 37319693 - ORA-00600 with check constraint on xml type") -public class XmlEmbeddableTest extends BaseSessionFactoryFunctionalTest { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - XmlHolder.class - }; - } +@DomainModel(annotatedClasses = {XmlEmbeddableTest.XmlHolder.class}) +@SessionFactory +public class XmlEmbeddableTest { @BeforeEach - public void setUp() { - inTransaction( + public void setUp(SessionFactoryScope scope) { + scope.inTransaction( session -> { session.persist( new XmlHolder( 1L, EmbeddableAggregate.createAggregate1() ) ); session.persist( new XmlHolder( 2L, EmbeddableAggregate.createAggregate2() ) ); @@ -62,42 +59,42 @@ public void setUp() { } @AfterEach - protected void cleanupTest() { - sessionFactoryScope().getSessionFactory().getSchemaManager().truncate(); + protected void cleanupTest(SessionFactoryScope scope) { + scope.dropData(); } @Test - public void testUpdate() { - sessionFactoryScope().inTransaction( - entityManager -> { - XmlHolder XmlHolder = entityManager.find( XmlHolder.class, 1L ); + public void testUpdate(SessionFactoryScope scope) { + scope.inTransaction( + session -> { + XmlHolder XmlHolder = session.find( XmlHolder.class, 1L ); XmlHolder.setAggregate( EmbeddableAggregate.createAggregate2() ); - entityManager.flush(); - entityManager.clear(); - EmbeddableAggregate.assertEquals( EmbeddableAggregate.createAggregate2(), entityManager.find( XmlHolder.class, 1L ).getAggregate() ); + session.flush(); + session.clear(); + EmbeddableAggregate.assertEquals( EmbeddableAggregate.createAggregate2(), session.find( XmlHolder.class, 1L ).getAggregate() ); } ); } @Test @JiraKey( "HHH-16682" ) - public void testDirtyChecking() { - sessionFactoryScope().inTransaction( - entityManager -> { - XmlHolder XmlHolder = entityManager.find( XmlHolder.class, 1L ); + public void testDirtyChecking(SessionFactoryScope scope) { + scope.inTransaction( + session -> { + XmlHolder XmlHolder = session.find( XmlHolder.class, 1L ); XmlHolder.getAggregate().setTheString( "MyString" ); - entityManager.flush(); - entityManager.clear(); - assertEquals( "MyString", entityManager.find( XmlHolder.class, 1L ).getAggregate().getTheString() ); + session.flush(); + session.clear(); + assertEquals( "MyString", session.find( XmlHolder.class, 1L ).getAggregate().getTheString() ); } ); } @Test - public void testFetch() { - sessionFactoryScope().inSession( - entityManager -> { - List XmlHolders = entityManager.createQuery( "from XmlHolder b where b.id = 1", XmlHolder.class ).getResultList(); + public void testFetch(SessionFactoryScope scope) { + scope.inSession( + session -> { + List XmlHolders = session.createQuery( "from XmlHolder b where b.id = 1", XmlHolder.class ).getResultList(); assertEquals( 1, XmlHolders.size() ); assertEquals( 1L, XmlHolders.get( 0 ).getId() ); EmbeddableAggregate.assertEquals( EmbeddableAggregate.createAggregate1(), XmlHolders.get( 0 ).getAggregate() ); @@ -106,10 +103,10 @@ public void testFetch() { } @Test - public void testFetchNull() { - sessionFactoryScope().inSession( - entityManager -> { - List xmlHolders = entityManager.createQuery( "from XmlHolder b where b.id = 2", XmlHolder.class ).getResultList(); + public void testFetchNull(SessionFactoryScope scope) { + scope.inSession( + session -> { + List xmlHolders = session.createQuery( "from XmlHolder b where b.id = 2", XmlHolder.class ).getResultList(); assertEquals( 1, xmlHolders.size() ); assertEquals( 2L, xmlHolders.get( 0 ).getId() ); EmbeddableAggregate.assertEquals( EmbeddableAggregate.createAggregate2(), xmlHolders.get( 0 ).getAggregate() ); @@ -118,10 +115,10 @@ public void testFetchNull() { } @Test - public void testDomainResult() { - sessionFactoryScope().inSession( - entityManager -> { - List structs = entityManager.createQuery( "select b.aggregate from XmlHolder b where b.id = 1", EmbeddableAggregate.class ).getResultList(); + public void testDomainResult(SessionFactoryScope scope) { + scope.inSession( + session -> { + List structs = session.createQuery( "select b.aggregate from XmlHolder b where b.id = 1", EmbeddableAggregate.class ).getResultList(); assertEquals( 1, structs.size() ); EmbeddableAggregate.assertEquals( EmbeddableAggregate.createAggregate1(), structs.get( 0 ) ); } @@ -129,10 +126,10 @@ public void testDomainResult() { } @Test - public void testSelectionItems() { - sessionFactoryScope().inSession( - entityManager -> { - List tuples = entityManager.createQuery( + public void testSelectionItems(SessionFactoryScope scope) { + scope.inSession( + session -> { + List tuples = session.createQuery( "select " + "b.aggregate.theInt," + "b.aggregate.theDouble," + @@ -196,60 +193,60 @@ public void testSelectionItems() { } @Test - public void testDeleteWhere() { - sessionFactoryScope().inTransaction( - entityManager -> { - entityManager.createMutationQuery( "delete XmlHolder b where b.aggregate is not null" ).executeUpdate(); - assertNull( entityManager.find( XmlHolder.class, 1L ) ); + public void testDeleteWhere(SessionFactoryScope scope) { + scope.inTransaction( + session -> { + session.createMutationQuery( "delete XmlHolder b where b.aggregate is not null" ).executeUpdate(); + assertNull( session.find( XmlHolder.class, 1L ) ); } ); } @Test - public void testUpdateAggregate() { - sessionFactoryScope().inTransaction( - entityManager -> { - entityManager.createMutationQuery( "update XmlHolder b set b.aggregate = null" ).executeUpdate(); - assertNull( entityManager.find( XmlHolder.class, 1L ).getAggregate() ); + public void testUpdateAggregate(SessionFactoryScope scope) { + scope.inTransaction( + session -> { + session.createMutationQuery( "update XmlHolder b set b.aggregate = null" ).executeUpdate(); + assertNull( session.find( XmlHolder.class, 1L ).getAggregate() ); } ); } @Test @RequiresDialectFeature(feature = DialectFeatureChecks.SupportsXmlComponentUpdate.class) - public void testUpdateAggregateMember() { - sessionFactoryScope().inTransaction( - entityManager -> { - entityManager.createMutationQuery( "update XmlHolder b set b.aggregate.theString = null" ).executeUpdate(); + public void testUpdateAggregateMember(SessionFactoryScope scope) { + scope.inTransaction( + session -> { + session.createMutationQuery( "update XmlHolder b set b.aggregate.theString = null" ).executeUpdate(); EmbeddableAggregate struct = EmbeddableAggregate.createAggregate1(); struct.setTheString( null ); - EmbeddableAggregate.assertEquals( struct, entityManager.find( XmlHolder.class, 1L ).getAggregate() ); + EmbeddableAggregate.assertEquals( struct, session.find( XmlHolder.class, 1L ).getAggregate() ); } ); } @Test @RequiresDialectFeature(feature = DialectFeatureChecks.SupportsXmlComponentUpdate.class) - public void testUpdateMultipleAggregateMembers() { - sessionFactoryScope().inTransaction( - entityManager -> { - entityManager.createMutationQuery( "update XmlHolder b set b.aggregate.theString = null, b.aggregate.theUuid = null" ).executeUpdate(); + public void testUpdateMultipleAggregateMembers(SessionFactoryScope scope) { + scope.inTransaction( + session -> { + session.createMutationQuery( "update XmlHolder b set b.aggregate.theString = null, b.aggregate.theUuid = null" ).executeUpdate(); EmbeddableAggregate struct = EmbeddableAggregate.createAggregate1(); struct.setTheString( null ); struct.setTheUuid( null ); - EmbeddableAggregate.assertEquals( struct, entityManager.find( XmlHolder.class, 1L ).getAggregate() ); + EmbeddableAggregate.assertEquals( struct, session.find( XmlHolder.class, 1L ).getAggregate() ); } ); } @Test @RequiresDialectFeature(feature = DialectFeatureChecks.SupportsXmlComponentUpdate.class) - public void testUpdateAllAggregateMembers() { - sessionFactoryScope().inTransaction( - entityManager -> { + public void testUpdateAllAggregateMembers(SessionFactoryScope scope) { + scope.inTransaction( + session -> { EmbeddableAggregate struct = EmbeddableAggregate.createAggregate1(); - entityManager.createMutationQuery( + session.createMutationQuery( "update XmlHolder b set " + "b.aggregate.theInt = :theInt," + "b.aggregate.theDouble = :theDouble," + @@ -304,7 +301,7 @@ public void testUpdateAllAggregateMembers() { .setParameter( "theOffsetDateTime", struct.getTheOffsetDateTime() ) .setParameter( "mutableValue", struct.getMutableValue() ) .executeUpdate(); - EmbeddableAggregate.assertEquals( EmbeddableAggregate.createAggregate1(), entityManager.find( XmlHolder.class, 2L ).getAggregate() ); + EmbeddableAggregate.assertEquals( EmbeddableAggregate.createAggregate1(), session.find( XmlHolder.class, 2L ).getAggregate() ); } ); } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/embeddable/XmlWithArrayEmbeddableTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/embeddable/XmlWithArrayEmbeddableTest.java index 97d853244ad3..44c9597df506 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/embeddable/XmlWithArrayEmbeddableTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/embeddable/XmlWithArrayEmbeddableTest.java @@ -78,12 +78,12 @@ protected void cleanupTest(SessionFactoryScope scope) { @Test public void testUpdate(SessionFactoryScope scope) { scope.inTransaction( - entityManager -> { - XmlHolder XmlHolder = entityManager.find( XmlHolder.class, 1L ); + session -> { + XmlHolder XmlHolder = session.find( XmlHolder.class, 1L ); XmlHolder.setAggregate( EmbeddableWithArrayAggregate.createAggregate2() ); - entityManager.flush(); - entityManager.clear(); - EmbeddableWithArrayAggregate.assertEquals( EmbeddableWithArrayAggregate.createAggregate2(), entityManager.find( XmlHolder.class, 1L ).getAggregate() ); + session.flush(); + session.clear(); + EmbeddableWithArrayAggregate.assertEquals( EmbeddableWithArrayAggregate.createAggregate2(), session.find( XmlHolder.class, 1L ).getAggregate() ); } ); } @@ -91,8 +91,8 @@ public void testUpdate(SessionFactoryScope scope) { @Test public void testFetch(SessionFactoryScope scope) { scope.inSession( - entityManager -> { - List XmlHolders = entityManager.createQuery( "from XmlHolder b where b.id = 1", XmlHolder.class ).getResultList(); + session -> { + List XmlHolders = session.createQuery( "from XmlHolder b where b.id = 1", XmlHolder.class ).getResultList(); assertEquals( 1, XmlHolders.size() ); assertEquals( 1L, XmlHolders.get( 0 ).getId() ); EmbeddableWithArrayAggregate.assertEquals( EmbeddableWithArrayAggregate.createAggregate1(), XmlHolders.get( 0 ).getAggregate() ); @@ -103,8 +103,8 @@ public void testFetch(SessionFactoryScope scope) { @Test public void testFetchNull(SessionFactoryScope scope) { scope.inSession( - entityManager -> { - List XmlHolders = entityManager.createQuery( "from XmlHolder b where b.id = 2", XmlHolder.class ).getResultList(); + session -> { + List XmlHolders = session.createQuery( "from XmlHolder b where b.id = 2", XmlHolder.class ).getResultList(); assertEquals( 1, XmlHolders.size() ); assertEquals( 2L, XmlHolders.get( 0 ).getId() ); EmbeddableWithArrayAggregate.assertEquals( EmbeddableWithArrayAggregate.createAggregate2(), XmlHolders.get( 0 ).getAggregate() ); @@ -115,8 +115,8 @@ public void testFetchNull(SessionFactoryScope scope) { @Test public void testDomainResult(SessionFactoryScope scope) { scope.inSession( - entityManager -> { - List structs = entityManager.createQuery( "select b.aggregate from XmlHolder b where b.id = 1", EmbeddableWithArrayAggregate.class ).getResultList(); + session -> { + List structs = session.createQuery( "select b.aggregate from XmlHolder b where b.id = 1", EmbeddableWithArrayAggregate.class ).getResultList(); assertEquals( 1, structs.size() ); EmbeddableWithArrayAggregate.assertEquals( EmbeddableWithArrayAggregate.createAggregate1(), structs.get( 0 ) ); } @@ -126,8 +126,8 @@ public void testDomainResult(SessionFactoryScope scope) { @Test public void testSelectionItems(SessionFactoryScope scope) { scope.inSession( - entityManager -> { - List tuples = entityManager.createQuery( + session -> { + List tuples = session.createQuery( "select " + "b.aggregate.theInt," + "b.aggregate.theDouble," + @@ -193,9 +193,9 @@ public void testSelectionItems(SessionFactoryScope scope) { @Test public void testDeleteWhere(SessionFactoryScope scope) { scope.inTransaction( - entityManager -> { - entityManager.createMutationQuery( "delete XmlHolder b where b.aggregate is not null" ).executeUpdate(); - assertNull( entityManager.find( XmlHolder.class, 1L ) ); + session -> { + session.createMutationQuery( "delete XmlHolder b where b.aggregate is not null" ).executeUpdate(); + assertNull( session.find( XmlHolder.class, 1L ) ); } ); @@ -204,9 +204,9 @@ public void testDeleteWhere(SessionFactoryScope scope) { @Test public void testUpdateAggregate(SessionFactoryScope scope) { scope.inTransaction( - entityManager -> { - entityManager.createMutationQuery( "update XmlHolder b set b.aggregate = null" ).executeUpdate(); - assertNull( entityManager.find( XmlHolder.class, 1L ).getAggregate() ); + session -> { + session.createMutationQuery( "update XmlHolder b set b.aggregate = null" ).executeUpdate(); + assertNull( session.find( XmlHolder.class, 1L ).getAggregate() ); } ); } @@ -215,11 +215,11 @@ public void testUpdateAggregate(SessionFactoryScope scope) { @RequiresDialectFeature(feature = DialectFeatureChecks.SupportsXmlComponentUpdate.class) public void testUpdateAggregateMember(SessionFactoryScope scope) { scope.inTransaction( - entityManager -> { - entityManager.createMutationQuery( "update XmlHolder b set b.aggregate.theString = null" ).executeUpdate(); + session -> { + session.createMutationQuery( "update XmlHolder b set b.aggregate.theString = null" ).executeUpdate(); EmbeddableWithArrayAggregate struct = EmbeddableWithArrayAggregate.createAggregate1(); struct.setTheString( null ); - EmbeddableWithArrayAggregate.assertEquals( struct, entityManager.find( XmlHolder.class, 1L ).getAggregate() ); + EmbeddableWithArrayAggregate.assertEquals( struct, session.find( XmlHolder.class, 1L ).getAggregate() ); } ); } @@ -228,12 +228,12 @@ public void testUpdateAggregateMember(SessionFactoryScope scope) { @RequiresDialectFeature(feature = DialectFeatureChecks.SupportsXmlComponentUpdate.class) public void testUpdateMultipleAggregateMembers(SessionFactoryScope scope) { scope.inTransaction( - entityManager -> { - entityManager.createMutationQuery( "update XmlHolder b set b.aggregate.theString = null, b.aggregate.theUuid = null" ).executeUpdate(); + session -> { + session.createMutationQuery( "update XmlHolder b set b.aggregate.theString = null, b.aggregate.theUuid = null" ).executeUpdate(); EmbeddableWithArrayAggregate struct = EmbeddableWithArrayAggregate.createAggregate1(); struct.setTheString( null ); struct.setTheUuid( null ); - EmbeddableWithArrayAggregate.assertEquals( struct, entityManager.find( XmlHolder.class, 1L ).getAggregate() ); + EmbeddableWithArrayAggregate.assertEquals( struct, session.find( XmlHolder.class, 1L ).getAggregate() ); } ); } @@ -243,9 +243,9 @@ public void testUpdateMultipleAggregateMembers(SessionFactoryScope scope) { @SkipForDialect( dialectClass = OracleDialect.class, reason = "External driver fix required") public void testUpdateAllAggregateMembers(SessionFactoryScope scope) { scope.inTransaction( - entityManager -> { + session -> { EmbeddableWithArrayAggregate struct = EmbeddableWithArrayAggregate.createAggregate1(); - entityManager.createMutationQuery( + session.createMutationQuery( "update XmlHolder b set " + "b.aggregate.theInt = :theInt," + "b.aggregate.theDouble = :theDouble," + @@ -300,7 +300,7 @@ public void testUpdateAllAggregateMembers(SessionFactoryScope scope) { .setParameter( "theOffsetDateTime", struct.getTheOffsetDateTime() ) .setParameter( "mutableValue", struct.getMutableValue() ) .executeUpdate(); - EmbeddableWithArrayAggregate.assertEquals( EmbeddableWithArrayAggregate.createAggregate1(), entityManager.find( XmlHolder.class, 2L ).getAggregate() ); + EmbeddableWithArrayAggregate.assertEquals( EmbeddableWithArrayAggregate.createAggregate1(), session.find( XmlHolder.class, 2L ).getAggregate() ); } ); } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/embeddable/strategy/usertype/embedded/record/RecordAsCompositeTypeEmbeddableTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/embeddable/strategy/usertype/embedded/record/RecordAsCompositeTypeEmbeddableTest.java index 32307696a1a3..4fb1d4a1b5e2 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/embeddable/strategy/usertype/embedded/record/RecordAsCompositeTypeEmbeddableTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/embeddable/strategy/usertype/embedded/record/RecordAsCompositeTypeEmbeddableTest.java @@ -13,40 +13,37 @@ import org.hibernate.annotations.CompositeType; import org.hibernate.metamodel.spi.ValueAccess; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; - +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; import org.hibernate.usertype.CompositeUserType; import org.javamoney.moneta.FastMoney; -import org.junit.Test; +import org.junit.jupiter.api.Test; import javax.money.MonetaryAmount; import java.io.Serializable; import java.math.BigDecimal; import java.util.Objects; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -public class RecordAsCompositeTypeEmbeddableTest extends BaseCoreFunctionalTestCase { - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { RecordAsCompositeTypeEmbeddableEntity.class }; - } +@DomainModel(annotatedClasses = RecordAsCompositeTypeEmbeddableTest.RecordAsCompositeTypeEmbeddableEntity.class) +@SessionFactory +public class RecordAsCompositeTypeEmbeddableTest { @Test - public void test() { + public void test(SessionFactoryScope scope) { MonetaryAmount amount = FastMoney.of( 1, "BRL" ); RecordAsCompositeTypeEmbeddableEntity entity = new RecordAsCompositeTypeEmbeddableEntity(); entity.setAmount( amount ); entity.setId( 1L ); - inTransaction( session -> { - session.persist( entity ); - } ); + scope.inTransaction( session -> session.persist(entity) ); - inTransaction( session -> { + scope.inTransaction( session -> { RecordAsCompositeTypeEmbeddableEntity result = session.find( RecordAsCompositeTypeEmbeddableEntity.class, 1L @@ -60,9 +57,7 @@ public record MonetaryAmountMapper( BigDecimal amount, String currency ) { - } - - ; + } public MonetaryAmountType() { } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/fetch/subselect/SubselectFetchCollectionFromBatchTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/fetch/subselect/SubselectFetchCollectionFromBatchTest.java index 44110947884b..66c6dfd32246 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/fetch/subselect/SubselectFetchCollectionFromBatchTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/fetch/subselect/SubselectFetchCollectionFromBatchTest.java @@ -34,9 +34,9 @@ import jakarta.persistence.Table; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Stephen Fikes diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/formula/FormulaBasicsTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/formula/FormulaBasicsTest.java index 7b47362595b8..fbd22fd770fe 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/formula/FormulaBasicsTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/formula/FormulaBasicsTest.java @@ -20,7 +20,7 @@ import org.junit.jupiter.api.Test; import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; +import static org.hamcrest.MatcherAssert.assertThat; /** * @author Nathan Xu diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/formula/FormulaNativeQueryTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/formula/FormulaNativeQueryTest.java index 214e6f22e344..13c293ee0988 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/formula/FormulaNativeQueryTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/formula/FormulaNativeQueryTest.java @@ -27,7 +27,7 @@ import org.junit.jupiter.api.Test; import static org.hibernate.testing.hamcrest.CollectionMatchers.hasSize; -import static org.junit.Assert.assertThat; +import static org.hamcrest.MatcherAssert.assertThat; /** * @author Алексей Макаров diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/formula/FormulaTests.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/formula/FormulaTests.java index 50d42109a738..a947d9373f7c 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/formula/FormulaTests.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/formula/FormulaTests.java @@ -30,7 +30,7 @@ import org.junit.jupiter.api.Test; import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; +import static org.hamcrest.MatcherAssert.assertThat; /** * @author Nathan Xu diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/formula/FormulaWithAliasTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/formula/FormulaWithAliasTest.java index 75ab3352530c..0933700e243e 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/formula/FormulaWithAliasTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/formula/FormulaWithAliasTest.java @@ -25,7 +25,7 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Yanming Zhou diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/formula/FormulaWithPartitionByTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/formula/FormulaWithPartitionByTest.java index ba36e98f1150..ed095d45d1a4 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/formula/FormulaWithPartitionByTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/formula/FormulaWithPartitionByTest.java @@ -22,8 +22,8 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; /** * @author Vlad Mihalcea diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/generated/AbstractGeneratedPropertyTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/generated/AbstractGeneratedPropertyTest.java index fdec1a613ecb..b472ce38055c 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/generated/AbstractGeneratedPropertyTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/generated/AbstractGeneratedPropertyTest.java @@ -3,66 +3,54 @@ * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.mapping.generated; -import org.junit.Test; -import org.hibernate.Session; -import org.hibernate.Transaction; + import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; import org.hibernate.type.descriptor.java.PrimitiveByteArrayJavaType; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * Implementation of AbstractGeneratedPropertyTest. * * @author Steve Ebersole */ -public abstract class AbstractGeneratedPropertyTest extends BaseCoreFunctionalTestCase { - - @Override - protected String getBaseForMappings() { - return "org/hibernate/orm/test/"; - } +@SessionFactory +public abstract class AbstractGeneratedPropertyTest { @Test @JiraKey( value = "HHH-2627" ) - public final void testGeneratedProperty() { + public final void testGeneratedProperty(SessionFactoryScope scope) { // The following block is repeated 300 times to reproduce HHH-2627. // Without the fix, Oracle will run out of cursors using 10g with // a default installation (ORA-01000: maximum open cursors exceeded). - // The number of loops may need to be adjusted depending on the how + // The number of loops may need to be adjusted depending on how // Oracle is configured. // Note: The block is not indented to avoid a lot of irrelevant differences. for ( int i=0; i<300; i++ ) { - GeneratedPropertyEntity entity = new GeneratedPropertyEntity(); + final GeneratedPropertyEntity entity = new GeneratedPropertyEntity(); entity.setName( "entity-1" ); - Session s = openSession(); - Transaction t = s.beginTransaction(); - s.persist( entity ); - s.flush(); - assertNotNull( "no timestamp retrieved", entity.getLastModified() ); - t.commit(); - s.close(); + scope.inTransaction( session -> { + session.persist( entity ); + session.flush(); + assertNotNull( entity.getLastModified(), "no timestamp retrieved" ); + } ); byte[] bytes = entity.getLastModified(); - s = openSession(); - t = s.beginTransaction(); - entity = ( GeneratedPropertyEntity ) s.get( GeneratedPropertyEntity.class, entity.getId() ); - assertTrue( PrimitiveByteArrayJavaType.INSTANCE.areEqual( bytes, entity.getLastModified() ) ); - t.commit(); - s.close(); + scope.inTransaction( session -> { + GeneratedPropertyEntity _entity = session.find( GeneratedPropertyEntity.class, entity.getId() ); + assertTrue( PrimitiveByteArrayJavaType.INSTANCE.areEqual( bytes, _entity.getLastModified() ) ); + } ); assertTrue( PrimitiveByteArrayJavaType.INSTANCE.areEqual( bytes, entity.getLastModified() ) ); - s = openSession(); - t = s.beginTransaction(); - s.remove( entity ); - t.commit(); - s.close(); + scope.inTransaction( session -> session.remove( entity ) ); } } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/generated/CreationTimestampTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/generated/CreationTimestampTest.java index bd2ecf15e571..8d96dc56c233 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/generated/CreationTimestampTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/generated/CreationTimestampTest.java @@ -11,27 +11,20 @@ import jakarta.persistence.Id; import org.hibernate.annotations.CreationTimestamp; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; -import org.junit.Test; - -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.Test; /** * @author Vlad Mihalcea */ -public class CreationTimestampTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Event.class - }; - } +@Jpa(annotatedClasses = {CreationTimestampTest.Event.class}) +public class CreationTimestampTest { @Test - public void test() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { //tag::mapping-generated-CreationTimestamp-persist-example[] Event dateEvent = new Event(); entityManager.persist(dateEvent); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/generated/DatabaseValueGenerationTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/generated/DatabaseValueGenerationTest.java index d483e0dced36..61fbf6f064ca 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/generated/DatabaseValueGenerationTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/generated/DatabaseValueGenerationTest.java @@ -14,32 +14,25 @@ import org.hibernate.generator.EventType; import org.hibernate.generator.EventTypeSets; import org.hibernate.generator.OnExecutionGenerator; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; -import org.junit.Test; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.Test; import jakarta.persistence.Column; import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; import jakarta.persistence.Id; -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; - /** * @author Vlad Mihalcea */ -public class DatabaseValueGenerationTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Event.class - }; - } +@Jpa(annotatedClasses = {DatabaseValueGenerationTest.Event.class}) +public class DatabaseValueGenerationTest { @Test - public void test() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { Event dateEvent = new Event(); entityManager.persist(dateEvent); }); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/generated/DefaultGeneratedValueIdentityTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/generated/DefaultGeneratedValueIdentityTest.java index 363a617dd856..db6b58ff7afd 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/generated/DefaultGeneratedValueIdentityTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/generated/DefaultGeneratedValueIdentityTest.java @@ -46,9 +46,9 @@ import jakarta.persistence.GenerationType; import jakarta.persistence.Id; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; @RequiresDialectFeature( feature = DialectFeatureChecks.SupportsIdentityColumns.class) @RequiresDialectFeature( feature = DialectFeatureChecks.CurrentTimestampHasMicrosecondPrecision.class ) @@ -109,7 +109,7 @@ public void testGenerationWithIdentityInsert(SessionFactoryScope scope) { assertEquals( "Bob", theEntity.name ); scope.inTransaction( (session) -> { - TheEntity _theEntity = session.get( TheEntity.class, theEntity.id ); + TheEntity _theEntity = session.find( TheEntity.class, theEntity.id ); assertNotNull( _theEntity.createdDate ); assertNotNull( _theEntity.alwaysDate ); assertNotNull( _theEntity.vmCreatedDate ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/generated/DefaultGeneratedValueTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/generated/DefaultGeneratedValueTest.java index ae4a8630827c..d34316a39002 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/generated/DefaultGeneratedValueTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/generated/DefaultGeneratedValueTest.java @@ -46,10 +46,10 @@ import jakarta.persistence.Id; import jakarta.persistence.Table; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * Test for the generation of column values using different value generation strategies. @@ -123,7 +123,7 @@ public void testGeneration(SessionFactoryScope scope) { assertEquals( "Bob", created.name ); scope.inTransaction( (s) -> { - final TheEntity theEntity = s.get( TheEntity.class, 1 ); + final TheEntity theEntity = s.find( TheEntity.class, 1 ); assertNotNull( theEntity.createdDate ); assertNotNull( theEntity.alwaysDate ); assertNotNull( theEntity.vmCreatedDate ); @@ -163,15 +163,15 @@ public void testUpdateTimestampGeneration(SessionFactoryScope scope) { clock.tick(); scope.inTransaction( (s) -> { - final TheEntity theEntity = s.get( TheEntity.class, 1 ); + final TheEntity theEntity = s.find( TheEntity.class, 1 ); theEntity.lastName = "Smith"; } ); scope.inTransaction( (s) -> { - final TheEntity theEntity = s.get( TheEntity.class, 1 ); + final TheEntity theEntity = s.find( TheEntity.class, 1 ); - assertEquals( "Creation timestamp should not change on update", created.vmCreatedSqlTimestamp, theEntity.vmCreatedSqlTimestamp ); - assertTrue( "Update timestamp should have changed due to update", theEntity.updated.after( created.updated ) ); + assertEquals( created.vmCreatedSqlTimestamp, theEntity.vmCreatedSqlTimestamp, "Creation timestamp should not change on update" ); + assertTrue( theEntity.updated.after( created.updated ), "Update timestamp should have changed due to update" ); } ); } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/generated/GeneratorTypeTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/generated/GeneratorTypeTest.java index 84a991819508..94267a1bb0f3 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/generated/GeneratorTypeTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/generated/GeneratorTypeTest.java @@ -13,33 +13,26 @@ import org.hibernate.generator.EventType; import org.hibernate.generator.EventTypeSets; import org.hibernate.generator.GeneratorCreationContext; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; -import org.junit.Test; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.Test; import jakarta.persistence.Entity; import jakarta.persistence.Id; -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; - /** * @author Vlad Mihalcea */ -public class GeneratorTypeTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Person.class - }; - } +@Jpa(annotatedClasses = {GeneratorTypeTest.Person.class}) +public class GeneratorTypeTest { @Test - public void test() { + public void test(EntityManagerFactoryScope scope) { //tag::mapping-generated-GeneratorType-persist-example[] CurrentUser.INSTANCE.logIn("Alice"); - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { Person person = new Person(); person.setId(1L); @@ -55,7 +48,7 @@ public void test() { //tag::mapping-generated-GeneratorType-update-example[] CurrentUser.INSTANCE.logIn("Bob"); - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { Person person = entityManager.find(Person.class, 1L); person.setFirstName("Mr. John"); }); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/generated/InMemoryValueGenerationTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/generated/InMemoryValueGenerationTest.java index 26abcabe40d0..0d61d41bb64c 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/generated/InMemoryValueGenerationTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/generated/InMemoryValueGenerationTest.java @@ -14,32 +14,25 @@ import org.hibernate.generator.BeforeExecutionGenerator; import org.hibernate.generator.EventType; import org.hibernate.generator.EventTypeSets; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; -import org.junit.Test; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.Test; import jakarta.persistence.Column; import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; import jakarta.persistence.Id; -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; - /** * @author Vlad Mihalcea */ -public class InMemoryValueGenerationTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Event.class - }; - } +@Jpa(annotatedClasses = {InMemoryValueGenerationTest.Event.class}) +public class InMemoryValueGenerationTest { @Test - public void test() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { Event dateEvent = new Event(); entityManager.persist(dateEvent); }); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/generated/InVmGenerationsWithAnnotationsTests.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/generated/InVmGenerationsWithAnnotationsTests.java index dc9cf4723804..0383b7624125 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/generated/InVmGenerationsWithAnnotationsTests.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/generated/InVmGenerationsWithAnnotationsTests.java @@ -73,7 +73,7 @@ public void testGenerations(SessionFactoryScope scope) { assertThat( merged.lastUpdatedOn ).isNotEqualTo( merged.createdOn ); // lastly, make sure we can load it.. - final AuditedEntity loaded = scope.fromTransaction( session, s -> s.get( AuditedEntity.class, 1 ) ); + final AuditedEntity loaded = scope.fromTransaction( session, s -> s.find( AuditedEntity.class, 1 ) ); assertThat( loaded ).isNotNull(); assertThat( loaded.createdOn ).isEqualTo( merged.createdOn ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/generated/InVmGenerationsWithAnnotationsWithMixedSqlTypesTests.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/generated/InVmGenerationsWithAnnotationsWithMixedSqlTypesTests.java index 5791a6a92e6f..a15c2159211b 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/generated/InVmGenerationsWithAnnotationsWithMixedSqlTypesTests.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/generated/InVmGenerationsWithAnnotationsWithMixedSqlTypesTests.java @@ -74,7 +74,7 @@ public void testGenerations(SessionFactoryScope scope) { assertThat( merged.lastUpdatedOn ).isNotEqualTo( merged.createdOn ); // lastly, make sure we can load it.. - final AuditedEntity loaded = scope.fromTransaction( session, s -> s.get( AuditedEntity.class, 1 ) ); + final AuditedEntity loaded = scope.fromTransaction( session, s -> s.find( AuditedEntity.class, 1 ) ); assertThat( loaded ).isNotNull(); assertThat( loaded.createdOn ).isEqualTo( merged.createdOn ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/generated/InVmGenerationsWithAnnotationsWithSqlDateTests.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/generated/InVmGenerationsWithAnnotationsWithSqlDateTests.java index 56cb4a70a6d7..489c06391b13 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/generated/InVmGenerationsWithAnnotationsWithSqlDateTests.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/generated/InVmGenerationsWithAnnotationsWithSqlDateTests.java @@ -73,7 +73,7 @@ public void testGenerations(SessionFactoryScope scope) { assertThat( merged.lastUpdatedOn ).isNotEqualTo( merged.createdOn ); // lastly, make sure we can load it.. - final AuditedEntity loaded = scope.fromTransaction( session, s -> s.get( AuditedEntity.class, 1 ) ); + final AuditedEntity loaded = scope.fromTransaction( session, s -> s.find( AuditedEntity.class, 1 ) ); assertThat( loaded ).isNotNull(); assertThat( loaded.createdOn ).isEqualTo( merged.createdOn ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/generated/InVmGenerationsWithMultipleAnnotationsTests.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/generated/InVmGenerationsWithMultipleAnnotationsTests.java index 7c7b684eeafd..b0610f17bcd8 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/generated/InVmGenerationsWithMultipleAnnotationsTests.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/generated/InVmGenerationsWithMultipleAnnotationsTests.java @@ -74,7 +74,7 @@ public void testGenerations(SessionFactoryScope scope) { assertThat( merged.lastUpdatedOn ).isNotEqualTo( merged.createdOn ); // lastly, make sure we can load it.. - final AuditedEntity loaded = scope.fromTransaction( session, s -> s.get( AuditedEntity.class, 1 ) ); + final AuditedEntity loaded = scope.fromTransaction( session, s -> s.find( AuditedEntity.class, 1 ) ); assertThat( loaded ).isNotNull(); assertThat( loaded.createdOn ).isEqualTo( merged.createdOn ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/generated/PartiallyGeneratedComponentTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/generated/PartiallyGeneratedComponentTest.java index 3da260cfb922..9a13c1727f7c 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/generated/PartiallyGeneratedComponentTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/generated/PartiallyGeneratedComponentTest.java @@ -42,7 +42,7 @@ public void testPartialComponentGeneration(SessionFactoryScope scope) { ComponentOwner owner2 = scope.fromTransaction( s -> { - ComponentOwner _owner = s.get( ComponentOwner.class, owner.getId() ); + ComponentOwner _owner = s.find( ComponentOwner.class, owner.getId() ); assertEquals( previousValue, _owner.getComponent().getGenerated(), "expecting insert value generation" ); _owner.setName( "subsequent" ); return _owner; @@ -54,7 +54,7 @@ public void testPartialComponentGeneration(SessionFactoryScope scope) { scope.inTransaction( s -> { - ComponentOwner _owner = s.get( ComponentOwner.class, owner.getId() ); + ComponentOwner _owner = s.find( ComponentOwner.class, owner.getId() ); assertEquals( previousValue2, _owner.getComponent().getGenerated(), "expecting update value generation" ); s.remove( _owner ); } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/generated/SimpleValueGenerationBaselineTests.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/generated/SimpleValueGenerationBaselineTests.java index d9fc1869336d..12d2f02b3b9e 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/generated/SimpleValueGenerationBaselineTests.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/generated/SimpleValueGenerationBaselineTests.java @@ -36,7 +36,7 @@ public void testLoading(SessionFactoryScope scope) { // lastly, make sure we can load it.. scope.inTransaction( (session) -> { - assertThat( session.get( NonAuditedEntity.class, 1 ) ).isNotNull(); + assertThat( session.find( NonAuditedEntity.class, 1 ) ).isNotNull(); } ); } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/generated/TimestampGeneratedValuesWithCachingTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/generated/TimestampGeneratedValuesWithCachingTest.java index 229d4d4a0584..cd9057cc0f18 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/generated/TimestampGeneratedValuesWithCachingTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/generated/TimestampGeneratedValuesWithCachingTest.java @@ -6,15 +6,14 @@ import org.hibernate.dialect.SQLServerDialect; import org.hibernate.dialect.SybaseDialect; -import org.hibernate.testing.RequiresDialect; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.RequiresDialect; /** * @author Steve Ebersole */ @RequiresDialect(SybaseDialect.class) @RequiresDialect(SQLServerDialect.class) +@DomainModel(xmlMappings = "org/hibernate/orm/test/mapping/generated/MSSQLGeneratedPropertyEntity.hbm.xml") public class TimestampGeneratedValuesWithCachingTest extends AbstractGeneratedPropertyTest { - public final String[] getMappings() { - return new String[] { "mapping/generated/MSSQLGeneratedPropertyEntity.hbm.xml" }; - } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/generated/TriggerGeneratedValuesWithCachingTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/generated/TriggerGeneratedValuesWithCachingTest.java index ef6c656ad4e8..8ee1cb328e6b 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/generated/TriggerGeneratedValuesWithCachingTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/generated/TriggerGeneratedValuesWithCachingTest.java @@ -6,7 +6,8 @@ import org.hibernate.dialect.OracleDialect; -import org.hibernate.testing.RequiresDialect; +import org.hibernate.testing.orm.junit.RequiresDialect; +import org.hibernate.testing.orm.junit.DomainModel; /** * Implementation of TriggerGeneratedValuesWithoutCachingTest. @@ -14,8 +15,6 @@ * @author Steve Ebersole */ @RequiresDialect( value = OracleDialect.class ) +@DomainModel(xmlMappings = "org/hibernate/orm/test/mapping/generated/GeneratedPropertyEntity.hbm.xml") public class TriggerGeneratedValuesWithCachingTest extends AbstractGeneratedPropertyTest { - public final String[] getMappings() { - return new String[] { "mapping/generated/GeneratedPropertyEntity.hbm.xml" }; - } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/generated/TriggerGeneratedValuesWithoutCachingTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/generated/TriggerGeneratedValuesWithoutCachingTest.java index 2740276a4762..f82bfd575cc6 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/generated/TriggerGeneratedValuesWithoutCachingTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/generated/TriggerGeneratedValuesWithoutCachingTest.java @@ -6,18 +6,13 @@ import org.hibernate.dialect.OracleDialect; -import org.hibernate.testing.RequiresDialect; +import org.hibernate.testing.orm.junit.RequiresDialect; +import org.hibernate.testing.orm.junit.DomainModel; /** * @author Steve Ebersole */ @RequiresDialect( value = OracleDialect.class ) +@DomainModel(xmlMappings = "org/hibernate/orm/test/mapping/generated/GeneratedPropertyEntity.hbm.xml") public class TriggerGeneratedValuesWithoutCachingTest extends AbstractGeneratedPropertyTest { - public final String[] getMappings() { - return new String[] { "mapping/generated/GeneratedPropertyEntity.hbm.xml" }; - } - - public String getCacheConcurrencyStrategy() { - return null; - } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/generated/UpdateTimestampTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/generated/UpdateTimestampTest.java index a2c3aee5115e..94ebed368c7c 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/generated/UpdateTimestampTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/generated/UpdateTimestampTest.java @@ -11,27 +11,20 @@ import jakarta.persistence.Id; import org.hibernate.annotations.UpdateTimestamp; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.Test; -import org.junit.Test; - -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; /** * @author Vlad Mihalcea */ -public class UpdateTimestampTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Bid.class - }; - } +@Jpa(annotatedClasses = {UpdateTimestampTest.Bid.class}) +public class UpdateTimestampTest { @Test - public void test() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { //tag::mapping-generated-UpdateTimestamp-persist-example[] Bid bid = new Bid(); bid.setUpdatedBy("John Doe"); @@ -40,7 +33,7 @@ public void test() { //end::mapping-generated-UpdateTimestamp-persist-example[] }); - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { //tag::mapping-generated-UpdateTimestamp-update-example[] Bid bid = entityManager.find(Bid.class, 1L); 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 b8e3c65bdc32..358f9e5e99b1 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 @@ -26,7 +26,7 @@ import java.math.BigDecimal; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Gavin King diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/generated/formula/FormulaGeneratedTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/generated/formula/FormulaGeneratedTest.java index 545cee48e577..4b225cf3ebd1 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/generated/formula/FormulaGeneratedTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/generated/formula/FormulaGeneratedTest.java @@ -17,7 +17,7 @@ import java.math.BigDecimal; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Gavin King diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/generated/sql/SqlGeneratedTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/generated/sql/SqlGeneratedTest.java index 28c6cb2ddad8..9eeecf109119 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/generated/sql/SqlGeneratedTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/generated/sql/SqlGeneratedTest.java @@ -20,9 +20,9 @@ import java.math.BigDecimal; import java.time.LocalDateTime; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; /** * @author Gavin King 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 c36cc1a1754e..1c5ea552a999 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 @@ -18,7 +18,7 @@ import jakarta.persistence.Entity; import jakarta.persistence.Id; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Gavin King 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 66886fdab0df..fd9335d21a1b 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 @@ -16,8 +16,8 @@ import java.math.BigDecimal; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; /** * @author Gavin King diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/generated/sqldefault/ImmutableDefaultTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/generated/sqldefault/ImmutableDefaultTest.java index a5fc5cae918d..86b93f69b444 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/generated/sqldefault/ImmutableDefaultTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/generated/sqldefault/ImmutableDefaultTest.java @@ -17,7 +17,7 @@ import java.math.BigDecimal; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Gavin King 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 b19f4979b66c..2c57b8abb88c 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 @@ -20,7 +20,7 @@ import jakarta.persistence.Entity; import jakarta.persistence.Id; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Gavin King 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 50283b2a4408..a4b7579a388e 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 @@ -16,7 +16,7 @@ import java.math.BigDecimal; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Gavin King diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/AssignedIdentifierTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/AssignedIdentifierTest.java index 28a68857ad96..28b79854dab0 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/AssignedIdentifierTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/AssignedIdentifierTest.java @@ -7,28 +7,20 @@ import jakarta.persistence.Entity; import jakarta.persistence.Id; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; - -import org.junit.Before; -import org.junit.Test; - -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * @author Vlad Mihalcea */ -public class AssignedIdentifierTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Book.class - }; - } +@Jpa(annotatedClasses = {AssignedIdentifierTest.Book.class}) +public class AssignedIdentifierTest { - @Before - public void init() { - doInJPA(this::entityManagerFactory, entityManager -> { + @BeforeEach + public void init(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { Book book = new Book(); book.setId(1L); book.setTitle("High-Performance Java Persistence"); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/CompositeNaturalIdTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/CompositeNaturalIdTest.java index 3fbeef033339..091bf2fcc7de 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/CompositeNaturalIdTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/CompositeNaturalIdTest.java @@ -13,28 +13,22 @@ import org.hibernate.Session; import org.hibernate.annotations.NaturalId; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; -import org.junit.Test; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.Test; -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Vlad Mihalcea */ -public class CompositeNaturalIdTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Book.class - }; - } +@Jpa(annotatedClasses = {CompositeNaturalIdTest.Book.class}) +public class CompositeNaturalIdTest { @Test - public void test() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { Book book = new Book(); book.setId(1L); book.setTitle("High-Performance Java Persistence"); @@ -46,7 +40,7 @@ public void test() { entityManager.persist(book); }); - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { //tag::naturalid-simple-load-access-example[] Book book = entityManager @@ -62,7 +56,7 @@ public void test() { assertEquals("High-Performance Java Persistence", book.getTitle()); }); - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { //tag::naturalid-load-access-example[] Book book = entityManager diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/EmbeddedIdManyToOneTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/EmbeddedIdManyToOneTest.java index 76024b7d4872..6a6abd04122f 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/EmbeddedIdManyToOneTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/EmbeddedIdManyToOneTest.java @@ -13,30 +13,25 @@ import jakarta.persistence.Id; import jakarta.persistence.ManyToOne; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import org.junit.Before; -import org.junit.Test; - -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Vlad Mihalcea */ -public class EmbeddedIdManyToOneTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - SystemUser.class, - Subsystem.class - }; - } - - @Before - public void init() { - doInJPA(this::entityManagerFactory, entityManager -> { +@Jpa(annotatedClasses = { + EmbeddedIdManyToOneTest.SystemUser.class, + EmbeddedIdManyToOneTest.Subsystem.class} +) +public class EmbeddedIdManyToOneTest { + + @BeforeEach + public void init(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { Subsystem subsystem = new Subsystem(); subsystem.setId("Hibernate Forum"); subsystem.setDescription("Hibernate projects forum"); @@ -55,8 +50,8 @@ public void init() { @Test - public void test() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { Subsystem subsystem = entityManager.find( Subsystem.class, "Hibernate Forum" diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/EmbeddedIdTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/EmbeddedIdTest.java index 6c1054162462..c383e136a58c 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/EmbeddedIdTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/EmbeddedIdTest.java @@ -10,29 +10,22 @@ import jakarta.persistence.EmbeddedId; import jakarta.persistence.Entity; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import org.junit.Before; -import org.junit.Test; - -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Vlad Mihalcea */ -public class EmbeddedIdTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - SystemUser.class - }; - } +@Jpa(annotatedClasses = {EmbeddedIdTest.SystemUser.class}) +public class EmbeddedIdTest { - @Before - public void init() { - doInJPA(this::entityManagerFactory, entityManager -> { + @BeforeEach + public void init(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { SystemUser systemUser = new SystemUser(); systemUser.setPk(new PK( "Hibernate Forum", @@ -46,8 +39,8 @@ public void init() { @Test - public void test() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { SystemUser systemUser = entityManager.find( SystemUser.class, new PK( diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/EntityTableCatalogTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/EntityTableCatalogTest.java index f1c6ee4120e5..6b2409698de4 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/EntityTableCatalogTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/EntityTableCatalogTest.java @@ -9,28 +9,21 @@ import jakarta.persistence.Table; import org.hibernate.dialect.MySQLDialect; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; -import org.hibernate.testing.RequiresDialect; -import org.junit.Test; +import org.hibernate.testing.orm.junit.RequiresDialect; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.Test; /** * @author Vlad Mihalcea */ +@Jpa(annotatedClasses = {EntityTableCatalogTest.Book.class}) @RequiresDialect(MySQLDialect.class) -public class EntityTableCatalogTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Book.class - }; - } +public class EntityTableCatalogTest { @Test public void test() { - } //tag::mapping-entity-table-catalog-mysql-example[] diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/EntityTableSchemaTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/EntityTableSchemaTest.java index ba6b087f2df4..cd78a61edc33 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/EntityTableSchemaTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/EntityTableSchemaTest.java @@ -9,27 +9,20 @@ import jakarta.persistence.Table; import org.hibernate.dialect.PostgreSQLDialect; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; -import org.hibernate.testing.RequiresDialect; -import org.junit.Test; +import org.hibernate.testing.orm.junit.RequiresDialect; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.Test; /** * @author Vlad Mihalcea */ @RequiresDialect(PostgreSQLDialect.class) -public class EntityTableSchemaTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Book.class - }; - } +@Jpa(annotatedClasses = {EntityTableSchemaTest.Book.class}) +public class EntityTableSchemaTest { @Test public void test() { - } //tag::mapping-entity-table-schema-postgresql-example[] diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/GeneratedIdentifierTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/GeneratedIdentifierTest.java index a129e80e9701..286c83f86d94 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/GeneratedIdentifierTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/GeneratedIdentifierTest.java @@ -8,28 +8,21 @@ import jakarta.persistence.GeneratedValue; import jakarta.persistence.Id; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import org.junit.Before; -import org.junit.Test; - -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; /** * @author Vlad Mihalcea */ -public class GeneratedIdentifierTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Book.class - }; - } +@Jpa(annotatedClasses = {GeneratedIdentifierTest.Book.class}) +public class GeneratedIdentifierTest { - @Before - public void init() { - doInJPA(this::entityManagerFactory, entityManager -> { + @BeforeEach + public void init(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { Book book = new Book(); book.setTitle("High-Performance Java Persistence"); book.setAuthor("Vlad Mihalcea"); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/IdClassGeneratedValueTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/IdClassGeneratedValueTest.java index 0a28cab7dd33..6d283817527e 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/IdClassGeneratedValueTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/IdClassGeneratedValueTest.java @@ -11,28 +11,21 @@ import jakarta.persistence.Id; import jakarta.persistence.IdClass; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.Test; -import org.junit.Test; - -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Vlad Mihalcea */ -public class IdClassGeneratedValueTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - SystemUser.class - }; - } +@Jpa(annotatedClasses = {IdClassGeneratedValueTest.SystemUser.class}) +public class IdClassGeneratedValueTest { @Test - public void test() { - SystemUser _systemUser = doInJPA(this::entityManagerFactory, entityManager -> { + public void test(EntityManagerFactoryScope scope) { + SystemUser _systemUser = scope.fromTransaction( entityManager -> { SystemUser systemUser = new SystemUser(); systemUser.setId( new PK( @@ -47,12 +40,8 @@ public void test() { return systemUser; }); - doInJPA(this::entityManagerFactory, entityManager -> { - SystemUser systemUser = entityManager.find( - SystemUser.class, - _systemUser.getId() - ); - + scope.inTransaction( entityManager -> { + SystemUser systemUser = entityManager.find( SystemUser.class, _systemUser.getId() ); assertEquals("Vlad Mihalcea", systemUser.getName()); }); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/IdClassManyToOneTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/IdClassManyToOneTest.java index 4bcc7634be89..a0439a9f7b6b 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/IdClassManyToOneTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/IdClassManyToOneTest.java @@ -12,30 +12,25 @@ import jakarta.persistence.IdClass; import jakarta.persistence.ManyToOne; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import org.junit.Before; -import org.junit.Test; - -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Vlad Mihalcea */ -public class IdClassManyToOneTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - SystemUser.class, - Subsystem.class - }; - } - - @Before - public void init() { - doInJPA(this::entityManagerFactory, entityManager -> { +@Jpa(annotatedClasses = { + IdClassManyToOneTest.SystemUser.class, + IdClassManyToOneTest.Subsystem.class} +) +public class IdClassManyToOneTest { + + @BeforeEach + public void init(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { Subsystem subsystem = new Subsystem(); subsystem.setId("Hibernate Forum"); subsystem.setDescription("Hibernate projects forum"); @@ -54,8 +49,8 @@ public void init() { @Test - public void test() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { Subsystem subsystem = entityManager.find( Subsystem.class, "Hibernate Forum" diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/IdClassTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/IdClassTest.java index 18c4921a6920..181cc4e5ffa9 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/IdClassTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/IdClassTest.java @@ -10,29 +10,22 @@ import jakarta.persistence.Id; import jakarta.persistence.IdClass; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import org.junit.Before; -import org.junit.Test; - -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Vlad Mihalcea */ -public class IdClassTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - SystemUser.class - }; - } +@Jpa(annotatedClasses = {IdClassTest.SystemUser.class}) +public class IdClassTest { - @Before - public void init() { - doInJPA(this::entityManagerFactory, entityManager -> { + @BeforeEach + public void init(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { SystemUser systemUser = new SystemUser(); systemUser.setId( new PK( @@ -48,8 +41,8 @@ public void init() { @Test - public void test() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { SystemUser systemUser = entityManager.find( SystemUser.class, new PK( diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/IdManyToOneTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/IdManyToOneTest.java index 2d4782172059..2cdcf5b06580 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/IdManyToOneTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/IdManyToOneTest.java @@ -12,34 +12,30 @@ import jakarta.persistence.ManyToOne; import org.hibernate.annotations.processing.Exclude; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; -import org.junit.Test; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.Test; -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Vlad Mihalcea */ @Exclude -public class IdManyToOneTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Book.class, - Author.class, - Publisher.class - }; - } +@Jpa(annotatedClasses = { + IdManyToOneTest.Book.class, + IdManyToOneTest.Author.class, + IdManyToOneTest.Publisher.class +}) +public class IdManyToOneTest { @Test - public void test() { + public void test(EntityManagerFactoryScope scope) { Author author = new Author(); Publisher publisher = new Publisher(); - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { author.setName("Vlad Mihalcea"); entityManager.persist(author); @@ -53,7 +49,7 @@ public void test() { entityManager.persist(book); }); - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { //tag::identifiers-composite-id-fetching-example[] Book book = entityManager.find(Book.class, new Book( author, diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/MultipleNaturalIdTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/MultipleNaturalIdTest.java index 52f5dd918732..3b4e698ce84d 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/MultipleNaturalIdTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/MultipleNaturalIdTest.java @@ -14,29 +14,24 @@ import org.hibernate.Session; import org.hibernate.annotations.NaturalId; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; -import org.junit.Test; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.Test; -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Vlad Mihalcea */ -public class MultipleNaturalIdTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Book.class, - Publisher.class - }; - } +@Jpa(annotatedClasses = { + MultipleNaturalIdTest.Book.class, MultipleNaturalIdTest.Publisher.class +}) +public class MultipleNaturalIdTest { @Test - public void test() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { Publisher publisher = new Publisher(); publisher.setId(1L); publisher.setName("Amazon"); @@ -51,7 +46,7 @@ public void test() { entityManager.persist(book); }); - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { Publisher publisher = entityManager.getReference(Publisher.class, 1L); //tag::naturalid-load-access-example[] @@ -65,7 +60,7 @@ public void test() { assertEquals("High-Performance Java Persistence", book.getTitle()); }); - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { Publisher publisher = entityManager.getReference(Publisher.class, 1L); Book book = entityManager .unwrap(Session.class) diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/MutableNaturalIdTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/MutableNaturalIdTest.java index fe41847f6c4c..88cd8244dbb0 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/MutableNaturalIdTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/MutableNaturalIdTest.java @@ -9,29 +9,23 @@ import org.hibernate.Session; import org.hibernate.annotations.NaturalId; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; -import org.junit.Test; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.Test; -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; /** * @author Vlad Mihalcea */ -public class MutableNaturalIdTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Author.class - }; - } +@Jpa(annotatedClasses = {MutableNaturalIdTest.Author.class}) +public class MutableNaturalIdTest { @Test - public void test() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { Author author = new Author(); author.setId(1L); author.setName("John Doe"); @@ -39,7 +33,7 @@ public void test() { entityManager.persist(author); }); - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { //tag::naturalid-mutable-synchronized-example[] //tag::naturalid-mutable-example[] Author author = entityManager diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/MutableNaturalIdsTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/MutableNaturalIdsTest.java index 8dad8b7ef577..fe70a065a3df 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/MutableNaturalIdsTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/MutableNaturalIdsTest.java @@ -4,14 +4,16 @@ */ package org.hibernate.orm.test.mapping.identifier; -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; + +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; import org.hibernate.Session; import org.hibernate.annotations.NaturalId; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; -import org.junit.Test; + +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.Test; import jakarta.persistence.Entity; import jakarta.persistence.Id; @@ -19,7 +21,8 @@ /** * @author Gary Gregory */ -public class MutableNaturalIdsTest extends BaseEntityManagerFunctionalTestCase { +@Jpa(annotatedClasses = {MutableNaturalIdsTest.Author.class}) +public class MutableNaturalIdsTest { private static final String FIELD_1 = "email1"; private static final String FIELD_2 = "email2"; @@ -32,16 +35,9 @@ public class MutableNaturalIdsTest extends BaseEntityManagerFunctionalTestCase { private static final String NEW_VALUE_1 = "john.doe1@acme.com"; private static final String NEW_VALUE_2 = "john.doe2@acme.com"; - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Author.class - }; - } - @Test - public void test() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { Author author = new Author(); author.setId(1L); author.setName("John Doe"); @@ -51,7 +47,7 @@ public void test() { entityManager.persist(author); }); - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { Author author = entityManager .unwrap(Session.class) .byNaturalId(Author.class) diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/NaiveEqualsHashCodeEntityTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/NaiveEqualsHashCodeEntityTest.java index 130b03e98dd8..319ba77185e2 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/NaiveEqualsHashCodeEntityTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/NaiveEqualsHashCodeEntityTest.java @@ -14,31 +14,26 @@ import jakarta.persistence.JoinColumn; import jakarta.persistence.OneToMany; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import org.junit.Before; -import org.junit.Test; - -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Vlad Mihalcea */ -public class NaiveEqualsHashCodeEntityTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Library.class, - Book.class - }; - } - - @Before - public void init() { - doInJPA(this::entityManagerFactory, entityManager -> { +@Jpa(annotatedClasses = { + NaiveEqualsHashCodeEntityTest.Book.class, NaiveEqualsHashCodeEntityTest.Library.class +}) +public class NaiveEqualsHashCodeEntityTest { + + @BeforeEach + public void init(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { Library library = new Library(); library.setId(1L); library.setName("Amazon"); @@ -47,8 +42,15 @@ public void init() { }); } + @AfterEach + public void tearDown(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { + scope.getEntityManagerFactory().getSchemaManager().truncate(); + } ); + } + @Test - public void testPersist() { + public void testPersist(EntityManagerFactoryScope scope) { //tag::entity-pojo-naive-equals-hashcode-persist-example[] Book book1 = new Book(); @@ -57,7 +59,7 @@ public void testPersist() { Book book2 = new Book(); book2.setTitle("Java Persistence with Hibernate"); - Library library = doInJPA(this::entityManagerFactory, entityManager -> { + Library library = scope.fromTransaction( entityManager -> { Library _library = entityManager.find(Library.class, 1L); _library.getBooks().add(book1); @@ -72,7 +74,7 @@ public void testPersist() { } @Test - public void testPersistForceFlush() { + public void testPersistForceFlush(EntityManagerFactoryScope scope) { //tag::entity-pojo-naive-equals-hashcode-persist-force-flush-example[] Book book1 = new Book(); @@ -81,7 +83,7 @@ public void testPersistForceFlush() { Book book2 = new Book(); book2.setTitle("Java Persistence with Hibernate"); - Library library = doInJPA(this::entityManagerFactory, entityManager -> { + Library library = scope.fromTransaction( entityManager -> { Library _library = entityManager.find(Library.class, 1L); entityManager.persist(book1); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/NaturalIdEqualsHashCodeEntityTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/NaturalIdEqualsHashCodeEntityTest.java index 6d90765f17a9..9ae56f006139 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/NaturalIdEqualsHashCodeEntityTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/NaturalIdEqualsHashCodeEntityTest.java @@ -15,30 +15,25 @@ import jakarta.persistence.OneToMany; import org.hibernate.annotations.NaturalId; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; -import org.junit.Before; -import org.junit.Test; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Vlad Mihalcea */ -public class NaturalIdEqualsHashCodeEntityTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Library.class, - Book.class - }; - } - - @Before - public void init() { - doInJPA(this::entityManagerFactory, entityManager -> { +@Jpa(annotatedClasses = { + NaturalIdEqualsHashCodeEntityTest.Book.class, NaturalIdEqualsHashCodeEntityTest.Library.class +}) +public class NaturalIdEqualsHashCodeEntityTest { + + @BeforeEach + public void init(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { Library library = new Library(); library.setId(1L); library.setName("Amazon"); @@ -48,14 +43,14 @@ public void init() { } @Test - public void testPersist() { + public void testPersist(EntityManagerFactoryScope scope) { //tag::entity-pojo-natural-id-equals-hashcode-persist-example[] Book book1 = new Book(); book1.setTitle("High-Performance Java Persistence"); book1.setIsbn("978-9730228236"); - Library library = doInJPA(this::entityManagerFactory, entityManager -> { + Library library = scope.fromTransaction( entityManager -> { Library _library = entityManager.find(Library.class, 1L); _library.getBooks().add(book1); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/PooledOptimizerTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/PooledOptimizerTest.java index 9bbf74b003c0..a6c02811e4b0 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/PooledOptimizerTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/PooledOptimizerTest.java @@ -12,27 +12,21 @@ import org.hibernate.annotations.GenericGenerator; import org.hibernate.annotations.Parameter; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; -import org.junit.Test; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.Test; -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; /** * @author Vlad Mihalcea */ -public class PooledOptimizerTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Product.class - }; - } +@Jpa(annotatedClasses = {PooledOptimizerTest.Product.class}) +public class PooledOptimizerTest { @Test - public void test() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { //tag::identifiers-generators-pooled-lo-optimizer-persist-example[] for (long i = 1; i <= 5; i++) { if(i % 3 == 0) { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/SequenceGeneratorAnnotationNameTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/SequenceGeneratorAnnotationNameTest.java index 6f0beb5c7c7b..3fa13ba2dd0d 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/SequenceGeneratorAnnotationNameTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/SequenceGeneratorAnnotationNameTest.java @@ -4,11 +4,11 @@ */ package org.hibernate.orm.test.mapping.identifier; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; - -import org.hibernate.testing.DialectChecks; -import org.hibernate.testing.RequiresDialectFeature; -import org.junit.Test; +import org.hibernate.testing.orm.junit.DialectFeatureChecks; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.RequiresDialectFeature; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.Test; import jakarta.persistence.Column; import jakarta.persistence.Entity; @@ -16,24 +16,17 @@ import jakarta.persistence.Id; import static jakarta.persistence.GenerationType.SEQUENCE; -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; /** * @author Vlad Mihalcea */ -@RequiresDialectFeature(DialectChecks.SupportsSequences.class) -public class SequenceGeneratorAnnotationNameTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Product.class - }; - } +@Jpa(annotatedClasses = {SequenceGeneratorAnnotationNameTest.Product.class}) +@RequiresDialectFeature(feature = DialectFeatureChecks.SupportsSequences.class) +public class SequenceGeneratorAnnotationNameTest { @Test - public void test() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { for (long i = 1; i <= 5; i++) { if(i % 3 == 0) { entityManager.flush(); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/SequenceGeneratorConfiguredTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/SequenceGeneratorConfiguredTest.java index 3dc8d8aa3393..54f655b58ce9 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/SequenceGeneratorConfiguredTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/SequenceGeneratorConfiguredTest.java @@ -11,30 +11,23 @@ import jakarta.persistence.Id; import jakarta.persistence.SequenceGenerator; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; +import org.hibernate.testing.orm.junit.DialectFeatureChecks; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.hibernate.testing.orm.junit.RequiresDialectFeature; +import org.junit.jupiter.api.Test; -import org.hibernate.testing.DialectChecks; -import org.hibernate.testing.RequiresDialectFeature; -import org.junit.Test; - -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; /** * @author Vlad Mihalcea */ -@RequiresDialectFeature(DialectChecks.SupportsSequences.class) -public class SequenceGeneratorConfiguredTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Product.class - }; - } +@Jpa(annotatedClasses = {SequenceGeneratorConfiguredTest.Product.class}) +@RequiresDialectFeature(feature = DialectFeatureChecks.SupportsSequences.class) +public class SequenceGeneratorConfiguredTest { @Test - public void test() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { for (long i = 1; i <= 5; i++) { if(i % 3 == 0) { entityManager.flush(); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/SequenceGeneratorNamedTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/SequenceGeneratorNamedTest.java index a253b8d1f04a..d775c0ad4bda 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/SequenceGeneratorNamedTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/SequenceGeneratorNamedTest.java @@ -10,31 +10,25 @@ import jakarta.persistence.Id; import jakarta.persistence.SequenceGenerator; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; - -import org.hibernate.testing.DialectChecks; -import org.hibernate.testing.RequiresDialectFeature; -import org.junit.Test; +import org.hibernate.testing.orm.junit.DialectFeatureChecks; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.hibernate.testing.orm.junit.RequiresDialectFeature; +import org.junit.jupiter.api.Test; import static jakarta.persistence.GenerationType.SEQUENCE; -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; + /** * @author Vlad Mihalcea */ -@RequiresDialectFeature(DialectChecks.SupportsSequences.class) -public class SequenceGeneratorNamedTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Product.class - }; - } +@Jpa(annotatedClasses = {SequenceGeneratorNamedTest.Product.class}) +@RequiresDialectFeature(feature = DialectFeatureChecks.SupportsSequences.class) +public class SequenceGeneratorNamedTest { @Test - public void test() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { for (long i = 1; i <= 5; i++) { if(i % 3 == 0) { entityManager.flush(); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/SequenceGeneratorUnnamedTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/SequenceGeneratorUnnamedTest.java index 802370604999..150cf82536ac 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/SequenceGeneratorUnnamedTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/SequenceGeneratorUnnamedTest.java @@ -9,31 +9,25 @@ import jakarta.persistence.GeneratedValue; import jakarta.persistence.Id; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; - -import org.hibernate.testing.DialectChecks; -import org.hibernate.testing.RequiresDialectFeature; -import org.junit.Test; +import org.hibernate.testing.orm.junit.DialectFeatureChecks; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.hibernate.testing.orm.junit.RequiresDialectFeature; +import org.junit.jupiter.api.Test; import static jakarta.persistence.GenerationType.SEQUENCE; -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; + /** * @author Vlad Mihalcea */ -@RequiresDialectFeature(DialectChecks.SupportsSequences.class) -public class SequenceGeneratorUnnamedTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Product.class - }; - } +@Jpa(annotatedClasses = {SequenceGeneratorUnnamedTest.Product.class}) +@RequiresDialectFeature(feature = DialectFeatureChecks.SupportsSequences.class) +public class SequenceGeneratorUnnamedTest { @Test - public void test() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { for (long i = 1; i <= 5; i++) { if(i % 3 == 0) { entityManager.flush(); 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 b64d2146c1a9..562457f2f42a 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 @@ -8,26 +8,18 @@ import jakarta.persistence.Id; import jakarta.persistence.Table; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; - -import org.junit.Test; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.Test; /** * @author Vlad Mihalcea */ -public class SimpleEntityTableTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Book.class - }; - } +@Jpa(annotatedClasses = {SimpleEntityTableTest.Book.class}) +public class SimpleEntityTableTest { @Test public void test() { - } //tag::entity-pojo-table-mapping-example[] diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/SimpleEntityTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/SimpleEntityTest.java index 4157605cc8f8..f4596dc5447b 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/SimpleEntityTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/SimpleEntityTest.java @@ -12,32 +12,27 @@ import jakarta.persistence.JoinColumn; import jakarta.persistence.OneToMany; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import org.junit.Before; -import org.junit.Test; - -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Vlad Mihalcea */ -public class SimpleEntityTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Library.class, - Book.class - }; - } - - @Before - public void init() { - doInJPA(this::entityManagerFactory, entityManager -> { +@Jpa(annotatedClasses = { + SimpleEntityTest.Book.class, SimpleEntityTest.Library.class +}) +public class SimpleEntityTest { + + @BeforeEach + public void init(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { Library library = new Library(); library.setId(1L); library.setName("Amazon"); @@ -53,11 +48,17 @@ public void init() { }); } + @AfterEach + public void tearDown(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { + scope.getEntityManagerFactory().getSchemaManager().truncate(); + } ); + } @Test - public void testIdentityScope() { + public void testIdentityScope(EntityManagerFactoryScope scope) { - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { //tag::entity-pojo-identity-scope-example[] Book book1 = entityManager.find(Book.class, 1L); Book book2 = entityManager.find(Book.class, 1L); @@ -69,9 +70,9 @@ public void testIdentityScope() { } @Test - public void testSetIdentityScope() { + public void testSetIdentityScope(EntityManagerFactoryScope scope) { - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { //tag::entity-pojo-set-identity-scope-example[] Library library = entityManager.find(Library.class, 1L); @@ -87,34 +88,26 @@ public void testSetIdentityScope() { } @Test - public void testMultiSessionIdentityScope() { + public void testMultiSessionIdentityScope(EntityManagerFactoryScope scope) { //tag::entity-pojo-multi-session-identity-scope-example[] - Book book1 = doInJPA(this::entityManagerFactory, entityManager -> { - return entityManager.find(Book.class, 1L); - }); + Book book1 = scope.fromTransaction( entityManager -> entityManager.find(Book.class, 1L) ); - Book book2 = doInJPA(this::entityManagerFactory, entityManager -> { - return entityManager.find(Book.class, 1L); - }); + Book book2 = scope.fromTransaction( entityManager -> entityManager.find(Book.class, 1L) ); assertFalse(book1 == book2); //end::entity-pojo-multi-session-identity-scope-example[] } @Test - public void testMultiSessionSetIdentityScope() { + public void testMultiSessionSetIdentityScope(EntityManagerFactoryScope scope) { - Book book1 = doInJPA(this::entityManagerFactory, entityManager -> { - return entityManager.find(Book.class, 1L); - }); + Book book1 = scope.fromTransaction( entityManager -> entityManager.find(Book.class, 1L) ); - Book book2 = doInJPA(this::entityManagerFactory, entityManager -> { - return entityManager.find(Book.class, 1L); - }); + Book book2 = scope.fromTransaction( entityManager -> entityManager.find(Book.class, 1L) ); //tag::entity-pojo-multi-session-set-identity-scope-example[] - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { Set books = new HashSet<>(); books.add(book1); @@ -126,9 +119,9 @@ public void testMultiSessionSetIdentityScope() { } @Test - public void testTransientSetIdentityScope() { + public void testTransientSetIdentityScope(EntityManagerFactoryScope scope) { - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { //tag::entity-pojo-transient-set-identity-scope-example[] Library library = entityManager.find(Library.class, 1L); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/SimpleNaturalIdTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/SimpleNaturalIdTest.java index 6e630d688097..e3484a35099e 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/SimpleNaturalIdTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/SimpleNaturalIdTest.java @@ -9,28 +9,22 @@ import org.hibernate.Session; import org.hibernate.annotations.NaturalId; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; -import org.junit.Test; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.Test; -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Vlad Mihalcea */ -public class SimpleNaturalIdTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Book.class - }; - } +@Jpa(annotatedClasses = {SimpleNaturalIdTest.Book.class}) +public class SimpleNaturalIdTest { @Test - public void test() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { Book book = new Book(); book.setId(1L); book.setTitle("High-Performance Java Persistence"); @@ -39,7 +33,7 @@ public void test() { entityManager.persist(book); }); - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { //tag::naturalid-simple-load-access-example[] Book book = entityManager .unwrap(Session.class) @@ -49,7 +43,7 @@ public void test() { assertEquals("High-Performance Java Persistence", book.getTitle()); }); - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { //tag::naturalid-load-access-example[] Book book = entityManager .unwrap(Session.class) diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/SimplePartitionKeyTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/SimplePartitionKeyTest.java index e0eb1e0f6164..9e470d05538e 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/SimplePartitionKeyTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/SimplePartitionKeyTest.java @@ -5,31 +5,25 @@ package org.hibernate.orm.test.mapping.identifier; import org.hibernate.annotations.PartitionKey; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; -import org.junit.Test; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.Test; import jakarta.persistence.Entity; import jakarta.persistence.Id; import jakarta.persistence.Table; -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; /** * @author Christian Beikov */ -public class SimplePartitionKeyTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - User.class - }; - } +@Jpa(annotatedClasses = {SimplePartitionKeyTest.User.class}) +public class SimplePartitionKeyTest { @Test - public void test() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { User user = new User(); user.setId( 1L ); user.setFirstname( "John" ); @@ -38,11 +32,11 @@ public void test() { entityManager.persist( user ); }); - doInJPA( this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { User user = entityManager.find( User.class, 1L ); user.setLastname( "Cash" ); } ); - doInJPA( this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { entityManager.remove( entityManager.find( User.class, 1L ) ); } ); } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/TableGeneratorConfiguredTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/TableGeneratorConfiguredTest.java index 1156aa7e1081..a95ed8769011 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/TableGeneratorConfiguredTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/TableGeneratorConfiguredTest.java @@ -11,27 +11,20 @@ import jakarta.persistence.Id; import jakarta.persistence.TableGenerator; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.Test; -import org.junit.Test; - -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; /** * @author Vlad Mihalcea */ -public class TableGeneratorConfiguredTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Product.class - }; - } +@Jpa(annotatedClasses = {TableGeneratorConfiguredTest.Product.class}) +public class TableGeneratorConfiguredTest { @Test - public void test() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { //tag::identifiers-generators-table-persist-example[] for (long i = 1; i <= 3; i++) { Product product = new Product(); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/TableGeneratorUnnamedTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/TableGeneratorUnnamedTest.java index 579ce2aa2704..4c924a1078fc 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/TableGeneratorUnnamedTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/TableGeneratorUnnamedTest.java @@ -10,27 +10,20 @@ import jakarta.persistence.GenerationType; import jakarta.persistence.Id; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.Test; -import org.junit.Test; - -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; /** * @author Vlad Mihalcea */ -public class TableGeneratorUnnamedTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Product.class - }; - } +@Jpa(annotatedClasses = {TableGeneratorUnnamedTest.Product.class}) +public class TableGeneratorUnnamedTest { @Test - public void test() { - doInJPA(this::entityManagerFactory, entityManager -> { + public void test(EntityManagerFactoryScope scope) { + scope.inTransaction( entityManager -> { for (long i = 1; i <= 5; i++) { if(i % 3 == 0) { entityManager.flush(); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/UuidCustomGeneratedValueTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/UuidCustomGeneratedValueTest.java index d9b6d3b35978..c30f54f7c83d 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/UuidCustomGeneratedValueTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/UuidCustomGeneratedValueTest.java @@ -12,32 +12,29 @@ import org.hibernate.annotations.GenericGenerator; import org.hibernate.annotations.Parameter; import org.hibernate.dialect.SybaseDialect; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; import org.hibernate.testing.orm.junit.SkipForDialect; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNotNull; /** * @author Vlad Mihalcea */ -@SkipForDialect( dialectClass = SybaseDialect.class, matchSubTypes = true, reason = "Skipped for Sybase to avoid problems with UUIDs potentially ending with a trailing 0 byte") -public class UuidCustomGeneratedValueTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Book.class - }; - } +@SkipForDialect( + dialectClass = SybaseDialect.class, matchSubTypes = true, + reason = "Skipped for Sybase to avoid problems with UUIDs potentially ending with a trailing 0 byte" +) +@Jpa(annotatedClasses = {UuidCustomGeneratedValueTest.Book.class}) +public class UuidCustomGeneratedValueTest { @Test - public void test() { + public void test(EntityManagerFactoryScope scope) { Book book = new Book(); - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { book.setTitle("High-Performance Java Persistence"); book.setAuthor("Vlad Mihalcea"); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/UuidGeneratedValueTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/UuidGeneratedValueTest.java index c9b4eb6eb2da..f2c07ae42b12 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/UuidGeneratedValueTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/UuidGeneratedValueTest.java @@ -10,33 +10,30 @@ import jakarta.persistence.Id; import org.hibernate.dialect.SybaseDialect; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; import org.hibernate.testing.orm.junit.SkipForDialect; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; /** * @author Vlad Mihalcea */ -@SkipForDialect( dialectClass = SybaseDialect.class, matchSubTypes = true, reason = "Skipped for Sybase to avoid problems with UUIDs potentially ending with a trailing 0 byte") -public class UuidGeneratedValueTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Book.class - }; - } +@SkipForDialect( + dialectClass = SybaseDialect.class, matchSubTypes = true, + reason = "Skipped for Sybase to avoid problems with UUIDs potentially ending with a trailing 0 byte" +) +@Jpa(annotatedClasses = {UuidGeneratedValueTest.Book.class}) +public class UuidGeneratedValueTest { @Test - public void test() { + public void test(EntityManagerFactoryScope scope) { Book book = new Book(); - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { book.setTitle("High-Performance Java Persistence"); book.setAuthor("Vlad Mihalcea"); @@ -45,7 +42,7 @@ public void test() { assertNotNull(book.getId()); - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { Book foundBook = entityManager.find( Book.class, book.getId() ); assertEquals( book.getAuthor(), foundBook.getAuthor() ); }); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/composite/EmbeddedIdDatabaseGeneratedValueTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/composite/EmbeddedIdDatabaseGeneratedValueTest.java index 4d0dd107aa1c..eb0290ee76a6 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/composite/EmbeddedIdDatabaseGeneratedValueTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/composite/EmbeddedIdDatabaseGeneratedValueTest.java @@ -17,7 +17,7 @@ import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Vlad Mihalcea diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/composite/EmbeddedIdInMemoryGeneratedValueTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/composite/EmbeddedIdInMemoryGeneratedValueTest.java index 0076cb4b9adc..7d6f79fd63d5 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/composite/EmbeddedIdInMemoryGeneratedValueTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/composite/EmbeddedIdInMemoryGeneratedValueTest.java @@ -6,28 +6,23 @@ import java.sql.Timestamp; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; - +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; import org.hibernate.testing.orm.junit.JiraKey; -import org.junit.Test; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.Test; -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Vlad Mihalcea */ -public class EmbeddedIdInMemoryGeneratedValueTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { Event.class }; - } +@Jpa(annotatedClasses = {Event.class}) +public class EmbeddedIdInMemoryGeneratedValueTest { @Test @JiraKey(value = "HHH-13096") - public void test() { - final EventId eventId = doInJPA(this::entityManagerFactory, entityManager -> { + public void test(EntityManagerFactoryScope scope) { + final EventId eventId = scope.fromTransaction( entityManager -> { //tag::identifiers-composite-generated-in-memory-example[] EventId id = new EventId(); id.setCategory(1); @@ -43,14 +38,11 @@ public void test() { return event.getId(); }); - doInJPA(this::entityManagerFactory, entityManager -> { - + scope.inTransaction( entityManager -> { Event event = entityManager.find(Event.class, eventId); assertEquals("Temperature", event.getKey()); assertEquals("9", event.getValue()); - - return event.getId(); }); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/inheritance/discriminator/JoinedInheritanceEagerTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/inheritance/discriminator/JoinedInheritanceEagerTest.java index ae9f1da926e6..2f00179d2368 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/inheritance/discriminator/JoinedInheritanceEagerTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/inheritance/discriminator/JoinedInheritanceEagerTest.java @@ -17,7 +17,7 @@ import org.hibernate.testing.orm.junit.JiraKey; import org.hibernate.testing.orm.junit.SessionFactory; import org.hibernate.testing.orm.junit.SessionFactoryScope; -import org.junit.Assert; +import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -77,7 +77,7 @@ public void joinUnrelatedCollectionOnBaseType(SessionFactoryScope scope) { fail( "Expected a resolution exception for property 'attributes'!" ); } catch (IllegalArgumentException ex) { - Assert.assertTrue( ex.getCause().getMessage().contains( "Could not resolve attribute 'attributes' ")); + Assertions.assertTrue( ex.getCause().getMessage().contains( "Could not resolve attribute 'attributes' ")); } finally { session.getTransaction().commit(); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/inheritance/discriminator/MultiInheritanceDiscriminatorTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/inheritance/discriminator/MultiInheritanceDiscriminatorTest.java index 208dd2e99eff..aea1ca712062 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/inheritance/discriminator/MultiInheritanceDiscriminatorTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/inheritance/discriminator/MultiInheritanceDiscriminatorTest.java @@ -68,7 +68,7 @@ public void testAbstractSuperClassMappingHbm(SessionFactoryScope scope) { scope.inTransaction( session -> { - AccountOwner _owner = session.get( AccountOwner.class, ownerId ); + AccountOwner _owner = session.find( AccountOwner.class, ownerId ); assertEquals( 2, _owner.getCreditAccounts().size() ); assertEquals( "CreditAccount", _owner.getCreditAccounts().iterator().next().getClass().getSimpleName() ); @@ -113,7 +113,7 @@ public void testAbstractSuperClassMappingAnn(SessionFactoryScope scope) { scope.inTransaction( session -> { - AccOwner _owner = session.get( AccOwner.class, ownerId ); + AccOwner _owner = session.find( AccOwner.class, ownerId ); assertEquals( 2, _owner.getCreditAccs().size() ); assertEquals( "CreditAcc", _owner.getCreditAccs().iterator().next().getClass().getSimpleName() ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/inheritance/discriminator/joined/JoinedSubclassInheritanceTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/inheritance/discriminator/joined/JoinedSubclassInheritanceTest.java index 8f0adb6717ef..3274a8dd93ca 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/inheritance/discriminator/joined/JoinedSubclassInheritanceTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/inheritance/discriminator/joined/JoinedSubclassInheritanceTest.java @@ -8,7 +8,7 @@ import org.hibernate.testing.orm.junit.DomainModel; import org.hibernate.testing.orm.junit.SessionFactory; import org.hibernate.testing.orm.junit.SessionFactoryScope; -import org.junit.After; +import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import static org.hamcrest.CoreMatchers.is; @@ -24,7 +24,7 @@ @SessionFactory public class JoinedSubclassInheritanceTest { - @After + @AfterEach public void tearDown(SessionFactoryScope scope) { scope.inTransaction( session -> diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/inheritance/joined/JoinedInheritanceSameTableDifferentSchemaTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/inheritance/joined/JoinedInheritanceSameTableDifferentSchemaTest.java index 888257a7a4c2..ef876e75e85f 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/inheritance/joined/JoinedInheritanceSameTableDifferentSchemaTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/inheritance/joined/JoinedInheritanceSameTableDifferentSchemaTest.java @@ -15,7 +15,7 @@ import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.testing.orm.junit.Jira; import org.hibernate.testing.util.ServiceRegistryUtil; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/inheritance/joined/JoinedInheritanceTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/inheritance/joined/JoinedInheritanceTest.java index 4ae561d0f43a..725bd23a3375 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/inheritance/joined/JoinedInheritanceTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/inheritance/joined/JoinedInheritanceTest.java @@ -26,7 +26,7 @@ import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.notNullValue; import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Andrea Boriero diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/inheritance/joined/JoinedInheritanceWithConcreteRootTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/inheritance/joined/JoinedInheritanceWithConcreteRootTest.java index 913a0434417f..120f80693d89 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/inheritance/joined/JoinedInheritanceWithConcreteRootTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/inheritance/joined/JoinedInheritanceWithConcreteRootTest.java @@ -26,7 +26,7 @@ import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.notNullValue; import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Andrea Boriero diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/inheritance/joined/JoinedInheritanceWithExplicitDiscriminatorTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/inheritance/joined/JoinedInheritanceWithExplicitDiscriminatorTest.java index c8727861b2b4..bb8f0a3daeb6 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/inheritance/joined/JoinedInheritanceWithExplicitDiscriminatorTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/inheritance/joined/JoinedInheritanceWithExplicitDiscriminatorTest.java @@ -25,7 +25,7 @@ import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.notNullValue; import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Andrea Boriero 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 f7792848c218..4b66300c2c9f 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 @@ -4,7 +4,6 @@ */ package org.hibernate.orm.test.mapping.inheritance.joined; -import java.util.Iterator; import java.util.List; import jakarta.persistence.criteria.CriteriaBuilder; import jakarta.persistence.criteria.CriteriaQuery; @@ -66,46 +65,46 @@ public void testJoinedSubclass(SessionFactoryScope scope) { s.persist( mark ); s.persist( joe ); - assertEquals( s.createQuery( "from Person" ).list().size(), 3 ); - 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" ) + assertEquals( 3, s.createQuery( "from Person" ).list().size() ); + assertEquals( 1, s.createQuery( "from Person p where p.class = Customer" ).list().size() ); + assertEquals( 1, s.createQuery( "from Person p where p.class = Person" ).list().size() ); + assertEquals( 1, s.createQuery( "from Person p where type(p) in :who" ) .setParameter( "who", Customer.class ) .list() - .size(), 1 ); - assertEquals( s.createQuery( "from Person p where type(p) in :who" ).setParameterList( + .size() ); + assertEquals( 2, s.createQuery( "from Person p where type(p) in :who" ).setParameterList( "who", new Class[] { Customer.class, Person.class } - ).list().size(), 2 ); + ).list().size() ); s.clear(); List customers = s.createQuery( "from Customer c left join fetch c.salesperson" ).list(); - for ( Iterator iter = customers.iterator(); iter.hasNext(); ) { - Customer c = (Customer) iter.next(); + for ( Object o : customers ) { + Customer c = (Customer) o; assertTrue( Hibernate.isInitialized( c.getSalesperson() ) ); - assertEquals( c.getSalesperson().getName(), "Mark" ); + assertEquals( "Mark", c.getSalesperson().getName() ); } - assertEquals( customers.size(), 1 ); + assertEquals( 1, customers.size() ); s.clear(); customers = s.createQuery( "from Customer" ).list(); - for ( Iterator iter = customers.iterator(); iter.hasNext(); ) { - Customer c = (Customer) iter.next(); + for ( Object customer : customers ) { + Customer c = (Customer) customer; assertFalse( Hibernate.isInitialized( c.getSalesperson() ) ); - assertEquals( c.getSalesperson().getName(), "Mark" ); + assertEquals( "Mark", c.getSalesperson().getName() ); } - assertEquals( customers.size(), 1 ); + assertEquals( 1, customers.size() ); s.clear(); - mark = (Employee) s.get( Employee.class, new Long( mark.getId() ) ); - joe = (Customer) s.get( Customer.class, new Long( joe.getId() ) ); + mark = s.find( Employee.class, mark.getId() ); + joe = s.find( Customer.class, joe.getId() ); mark.setZip( "30306" ); - assertEquals( s.createQuery( "from Person p where p.address.zip = '30306'" ).list().size(), 1 ); + assertEquals( 1, s.createQuery( "from Person p where p.address.zip = '30306'" ).list().size() ); CriteriaBuilder criteriaBuilder = s.getCriteriaBuilder(); CriteriaQuery criteria = criteriaBuilder.createQuery( Person.class ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/inheritance/joined/MixedInheritanceTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/inheritance/joined/MixedInheritanceTest.java index 5d1ba08770d9..ade3826fdeb7 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/inheritance/joined/MixedInheritanceTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/inheritance/joined/MixedInheritanceTest.java @@ -28,8 +28,8 @@ import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.notNullValue; import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Andrea Boriero @@ -155,7 +155,7 @@ public void subclassQueryExecutionTest(SessionFactoryScope scope) { ForeignCustomer.class ).list(); - assertEquals( results.size(), 2 ); + assertEquals( 2, results.size() ); for ( ForeignCustomer foreignCustomer : results ) { if ( foreignCustomer.getId() == 2 ) { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/javatime/JavaTimeJdbcTypeTests.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/javatime/JavaTimeJdbcTypeTests.java index 7b212737f837..864f6f282a61 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/javatime/JavaTimeJdbcTypeTests.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/javatime/JavaTimeJdbcTypeTests.java @@ -94,19 +94,19 @@ void testInstant(SessionFactoryScope scope) { } ); scope.inTransaction( (session) -> { - final EntityWithJavaTimeValues entity = session.get( EntityWithJavaTimeValues.class, 1 ); + final EntityWithJavaTimeValues entity = session.find( EntityWithJavaTimeValues.class, 1 ); assertThat( entity.theInstant ).isEqualTo( start ); entity.theInstant = start.plus( 2000, ChronoUnit.DAYS ); } ); scope.inTransaction( (session) -> { - final EntityWithJavaTimeValues entity = session.get( EntityWithJavaTimeValues.class, 1 ); + final EntityWithJavaTimeValues entity = session.find( EntityWithJavaTimeValues.class, 1 ); assertThat( entity.theInstant ).isEqualTo( start.plus( 2000, ChronoUnit.DAYS ) ); entity.theInstant = start.minus( 2000, ChronoUnit.DAYS ); } ); scope.inTransaction( (session) -> { - final EntityWithJavaTimeValues entity = session.get( EntityWithJavaTimeValues.class, 1 ); + final EntityWithJavaTimeValues entity = session.find( EntityWithJavaTimeValues.class, 1 ); assertThat( entity.theInstant ).isEqualTo( start.minus( 2000, ChronoUnit.DAYS ) ); } ); } @@ -124,19 +124,19 @@ void testLocalDateTime(SessionFactoryScope scope) { } ); scope.inTransaction( (session) -> { - final EntityWithJavaTimeValues entity = session.get( EntityWithJavaTimeValues.class, 1 ); + final EntityWithJavaTimeValues entity = session.find( EntityWithJavaTimeValues.class, 1 ); assertThat( entity.theLocalDateTime ).isEqualTo( start ); entity.theLocalDateTime = start.plusDays( 2000 ); } ); scope.inTransaction( (session) -> { - final EntityWithJavaTimeValues entity = session.get( EntityWithJavaTimeValues.class, 1 ); + final EntityWithJavaTimeValues entity = session.find( EntityWithJavaTimeValues.class, 1 ); assertThat( entity.theLocalDateTime ).isEqualTo( start.plusDays( 2000 ) ); entity.theLocalDateTime = start.minusDays( 2000 ); } ); scope.inTransaction( (session) -> { - final EntityWithJavaTimeValues entity = session.get( EntityWithJavaTimeValues.class, 1 ); + final EntityWithJavaTimeValues entity = session.find( EntityWithJavaTimeValues.class, 1 ); assertThat( entity.theLocalDateTime ).isEqualTo( start.minusDays( 2000 ) ); } ); } @@ -154,19 +154,19 @@ void testLocalDate(SessionFactoryScope scope) { } ); scope.inTransaction( (session) -> { - final EntityWithJavaTimeValues entity = session.get( EntityWithJavaTimeValues.class, 1 ); + final EntityWithJavaTimeValues entity = session.find( EntityWithJavaTimeValues.class, 1 ); assertThat( entity.theLocalDate ).isEqualTo( startTime ); entity.theLocalDate = startTime.plusDays( 2000 ); } ); scope.inTransaction( (session) -> { - final EntityWithJavaTimeValues entity = session.get( EntityWithJavaTimeValues.class, 1 ); + final EntityWithJavaTimeValues entity = session.find( EntityWithJavaTimeValues.class, 1 ); assertThat( entity.theLocalDate ).isEqualTo( startTime.plusDays( 2000 ) ); entity.theLocalDate = startTime.minusDays( 2000 ); } ); scope.inTransaction( (session) -> { - final EntityWithJavaTimeValues entity = session.get( EntityWithJavaTimeValues.class, 1 ); + final EntityWithJavaTimeValues entity = session.find( EntityWithJavaTimeValues.class, 1 ); assertThat( entity.theLocalDate ).isEqualTo( startTime.minusDays( 2000 ) ); } ); } @@ -187,19 +187,19 @@ void testLocalTime(SessionFactoryScope scope) { } ); scope.inTransaction( (session) -> { - final EntityWithJavaTimeValues entity = session.get( EntityWithJavaTimeValues.class, 1 ); + final EntityWithJavaTimeValues entity = session.find( EntityWithJavaTimeValues.class, 1 ); assertThat( entity.theLocalTime ).isEqualTo( startTime ); entity.theLocalTime = startTime.plusHours( 2000 ); } ); scope.inTransaction( (session) -> { - final EntityWithJavaTimeValues entity = session.get( EntityWithJavaTimeValues.class, 1 ); + final EntityWithJavaTimeValues entity = session.find( EntityWithJavaTimeValues.class, 1 ); assertThat( entity.theLocalTime ).isEqualTo( startTime.plusHours( 2000 ) ); entity.theLocalTime = startTime.plusHours( 2000 ); } ); scope.inTransaction( (session) -> { - final EntityWithJavaTimeValues entity = session.get( EntityWithJavaTimeValues.class, 1 ); + final EntityWithJavaTimeValues entity = session.find( EntityWithJavaTimeValues.class, 1 ); assertThat( entity.theLocalTime ).isEqualTo( startTime.plusHours( 2000 ) ); } ); } 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 426a69b739e6..83b4286e570d 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 @@ -32,7 +32,7 @@ import static org.hamcrest.CoreMatchers.sameInstance; import static org.hamcrest.MatcherAssert.assertThat; import static org.hibernate.annotations.FetchMode.JOIN; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/lazytoone/LanyProxylessManyToOneTests.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/lazytoone/LanyProxylessManyToOneTests.java index 64e086593352..1e9025c1b622 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/lazytoone/LanyProxylessManyToOneTests.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/lazytoone/LanyProxylessManyToOneTests.java @@ -32,7 +32,7 @@ import static org.hamcrest.CoreMatchers.nullValue; import static org.hamcrest.CoreMatchers.sameInstance; import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/lazytoone/LazyToOneTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/lazytoone/LazyToOneTest.java index e2b10ecefe6d..f3a5fd512adf 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/lazytoone/LazyToOneTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/lazytoone/LazyToOneTest.java @@ -5,13 +5,15 @@ package org.hibernate.orm.test.mapping.lazytoone; import org.hibernate.Hibernate; -import org.hibernate.boot.registry.StandardServiceRegistryBuilder; -import org.hibernate.cfg.AvailableSettings; import org.hibernate.proxy.HibernateProxy; import org.hibernate.stat.spi.StatisticsImplementor; -import org.hibernate.testing.junit4.BaseNonConfigCoreFunctionalTestCase; -import org.junit.Test; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.CoreMatchers.is; @@ -20,22 +22,14 @@ /** * @author Steve Ebersole */ -public class LazyToOneTest extends BaseNonConfigCoreFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { Airport.class, Flight.class }; - } - - @Override - protected void configureStandardServiceRegistryBuilder(StandardServiceRegistryBuilder ssrb) { - ssrb.applySetting( AvailableSettings.GENERATE_STATISTICS, "true" ); - } - - @Override - protected void prepareTest() throws Exception { - inTransaction( - (session) -> { +@DomainModel(annotatedClasses = {Airport.class, Flight.class}) +@SessionFactory(generateStatistics = true) +public class LazyToOneTest { + + @BeforeEach + protected void prepareTest(SessionFactoryScope scope) throws Exception { + scope.inTransaction( + session -> { final Airport austin = new Airport( 1, "AUS" ); final Airport baltimore = new Airport( 2, "BWI" ); @@ -51,18 +45,18 @@ protected void prepareTest() throws Exception { ); } - @Override - protected void cleanupTestData() throws Exception { - sessionFactory().getSchemaManager().truncate(); + @AfterEach + protected void cleanupTestData(SessionFactoryScope scope) throws Exception { + scope.dropData(); } @Test - public void testNonEnhanced() { - final StatisticsImplementor statistics = sessionFactory().getStatistics(); + public void testNonEnhanced(SessionFactoryScope scope) { + final StatisticsImplementor statistics = scope.getSessionFactory().getStatistics(); statistics.clear(); - inTransaction( - (session) -> { + scope.inTransaction( + session -> { final Flight flight1 = session.byId( Flight.class ).load( 1 ); assertThat( statistics.getPrepareStatementCount(), is( 1L ) ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/lazytoone/ManyToOneExplicitOptionTests.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/lazytoone/ManyToOneExplicitOptionTests.java index f1123ac7fea1..9dba352e90af 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/lazytoone/ManyToOneExplicitOptionTests.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/lazytoone/ManyToOneExplicitOptionTests.java @@ -37,7 +37,7 @@ import static org.hamcrest.CoreMatchers.nullValue; import static org.hamcrest.CoreMatchers.sameInstance; import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * Baseline test for uni-directional to-one, using an explicit @LazyToOne(NO_PROXY) diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/lazytoone/mappedby/InverseToOneExplicitOptionTests.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/lazytoone/mappedby/InverseToOneExplicitOptionTests.java index a72af71229ff..a4a2f874c731 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/lazytoone/mappedby/InverseToOneExplicitOptionTests.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/lazytoone/mappedby/InverseToOneExplicitOptionTests.java @@ -30,7 +30,7 @@ import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * Baseline test for inverse (mappedBy) to-one, using an explicit @LazyToOne(NO_PROXY) diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/manytomany/ManyToManyUnidirectionalFetchTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/manytomany/ManyToManyUnidirectionalFetchTest.java index 40245908c984..f8aa1c7ca5ec 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/manytomany/ManyToManyUnidirectionalFetchTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/manytomany/ManyToManyUnidirectionalFetchTest.java @@ -121,7 +121,7 @@ public void testJoin(SessionFactoryScope scope) { private void addSpeakerToEvent(SessionFactoryScope scope) { scope.inTransaction( session -> { - Event event = session.get( Event.class, 1l ); + Event event = session.find( Event.class, 1l ); Speaker speaker = new Speaker( 2l, "Steve" ); event.addSpeaker( speaker ); session.persist( speaker ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/manytoone/ManyToOneBidirectionalCircularityTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/manytoone/ManyToOneBidirectionalCircularityTest.java index 1f44eba417d8..3ffaf7820445 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/manytoone/ManyToOneBidirectionalCircularityTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/manytoone/ManyToOneBidirectionalCircularityTest.java @@ -52,7 +52,7 @@ public void testGet(SessionFactoryScope scope) { statementInspector.clear(); scope.inTransaction( session -> { - EntityTest entity = session.get( EntityTest.class, 1 ); + EntityTest entity = session.find( EntityTest.class, 1 ); EntityTest2 entity2 = entity.getEntity2(); assertThat( entity2.getName(), is( "e2" ) ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/manytoone/ManyToOneBidirectionalTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/manytoone/ManyToOneBidirectionalTest.java index af7d2dd9b385..5b8c9e7b51f1 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/manytoone/ManyToOneBidirectionalTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/manytoone/ManyToOneBidirectionalTest.java @@ -48,7 +48,7 @@ public void testGet(SessionFactoryScope scope) { statementInspector.clear(); scope.inTransaction( session -> { - EntityTest entity = session.get( EntityTest.class, 1 ); + EntityTest entity = session.find( EntityTest.class, 1 ); EntityTest2 entity2 = entity.getEntity2(); assertThat( entity2.getName(), is( "e2" ) ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/manytoone/ManyToOneWithAnyAndSecondaryTable.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/manytoone/ManyToOneWithAnyAndSecondaryTable.java index d92c276dcb67..d913f3b0f2f8 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/manytoone/ManyToOneWithAnyAndSecondaryTable.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/manytoone/ManyToOneWithAnyAndSecondaryTable.java @@ -58,7 +58,7 @@ void testMappingManyToOneMappedByAnyPersistedInSecondaryTable(EntityManagerFacto List actors = entityManager.createQuery( "select a from actor a", Actor.class ) .getResultList(); - Assertions.assertEquals( actors.size(), 2 ); + Assertions.assertEquals( 2, actors.size() ); } ); } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/manytoone/ManyToOneWithAnyTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/manytoone/ManyToOneWithAnyTest.java index 50bb81dd9231..e0010eb98d6c 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/manytoone/ManyToOneWithAnyTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/manytoone/ManyToOneWithAnyTest.java @@ -62,16 +62,14 @@ void testMappingManyToOneMappedByAny(EntityManagerFactoryScope scope) { entityManager.clear(); firstBook = entityManager.unwrap( Session.class ) - .byId( firstBook.getClass() ) - .load( firstBook.getId() ); + .find( firstBook.getClass(), firstBook.getId() ); assertNotNull( firstBook ); entityManager.clear(); library = entityManager.unwrap( Session.class ) - .byId( library.getClass() ) - .load( library.getId() ); + .find( library.getClass(), library.getId() ); assertNotNull( library ); assertEquals( 2, library.getBooks().size() ); @@ -96,11 +94,11 @@ void testWithSameIdentifiantButSubTypeDifferent(EntityManagerFactoryScope scope) session.flush(); session.clear(); - library = session.byId( library.getClass() ).load( library.getId() ); + library = session.find( library.getClass(), library.getId() ); assertNotNull( library ); assertEquals( 2, library.getBooks().size() ); - shop = session.byId( shop.getClass() ).load( shop.getId() ); + shop = session.find( shop.getClass(), shop.getId() ); assertNotNull( shop ); assertEquals( 3, shop.getBooks().size() ); } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/manytoone/jointable/InverseManyToOneJoinTableCompositeIdTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/manytoone/jointable/InverseManyToOneJoinTableCompositeIdTest.java index 76bb9e67a3d5..eff59b3e38ef 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/manytoone/jointable/InverseManyToOneJoinTableCompositeIdTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/manytoone/jointable/InverseManyToOneJoinTableCompositeIdTest.java @@ -92,7 +92,7 @@ public void usageSmokeTest(SessionFactoryScope scope) { try { scope.inTransaction( (session) -> { - final Author stephenKing = session.get( Author.class, 1 ); + final Author stephenKing = session.find( Author.class, 1 ); verifyStephenKingBooks( stephenKing ); } ); 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 007673e0861b..5036f1344fce 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 @@ -66,7 +66,7 @@ public void usageSmokeTest(SessionFactoryScope scope) { try { scope.inTransaction( (session) -> { - final Author stephenKing = session.get( Author.class, 1 ); + final Author stephenKing = session.find( Author.class, 1 ); verifyStephenKingBooks( stephenKing ); } ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/mappedBy/MappedByCompositeNonAssociationTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/mappedBy/MappedByCompositeNonAssociationTest.java index 66c7453d367d..3bc7c3b5ce4d 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/mappedBy/MappedByCompositeNonAssociationTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/mappedBy/MappedByCompositeNonAssociationTest.java @@ -40,7 +40,7 @@ public class MappedByCompositeNonAssociationTest { scope.inTransaction(s -> s.persist(loan)); Loan l1 = scope.fromTransaction(s -> { - Loan ll = s.get(Loan.class, loan.id); + Loan ll = s.find(Loan.class, loan.id); Hibernate.initialize(ll.extensions); return ll; }); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/mappedBy/MappedByNonAssociationTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/mappedBy/MappedByNonAssociationTest.java index 8e386f3b3fed..53383740bdbd 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/mappedBy/MappedByNonAssociationTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/mappedBy/MappedByNonAssociationTest.java @@ -38,7 +38,7 @@ public class MappedByNonAssociationTest { scope.inTransaction(s -> s.persist(loan)); Loan l1 = scope.fromTransaction(s -> { - Loan ll = s.get(Loan.class, loan.id); + Loan ll = s.find(Loan.class, loan.id); Hibernate.initialize(ll.extensions); return ll; }); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/mutability/attribute/AttributeImmutabilityTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/mutability/attribute/AttributeImmutabilityTest.java index 665b202b3e5e..dcadd90401a9 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/mutability/attribute/AttributeImmutabilityTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/mutability/attribute/AttributeImmutabilityTest.java @@ -8,27 +8,21 @@ import jakarta.persistence.Entity; import jakarta.persistence.Id; import org.hibernate.annotations.Immutable; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; -import org.junit.Test; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.junit.jupiter.api.Test; import java.util.Date; -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -public class AttributeImmutabilityTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Event1.class, Event2.class - }; - } +@Jpa(annotatedClasses = {AttributeImmutabilityTest.Event1.class, AttributeImmutabilityTest.Event2.class}) +public class AttributeImmutabilityTest { @Test - public void test1() { + public void test1(EntityManagerFactoryScope scope) { //tag::entity-immutability-persist-example[] - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { Event1 event = new Event1(); event.setId(1L); event.setCreatedOn(new Date()); @@ -38,21 +32,21 @@ public void test1() { }); //end::entity-immutability-persist-example[] //tag::entity-immutability-update-example[] - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { Event1 event = entityManager.find(Event1.class, 1L); - log.info("Change event message"); + // "Change event message" event.setMessage("Hibernate User Guide"); }); - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { Event1 event = entityManager.find(Event1.class, 1L); assertEquals("Hibernate User Guide rocks!", event.getMessage()); }); } @Test - public void test2() { + public void test2(EntityManagerFactoryScope scope) { //tag::entity-immutability-persist-example[] - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { Event2 event = new Event2(); event.setId(1L); event.setCreatedOn(new Date()); @@ -62,12 +56,12 @@ public void test2() { }); //end::entity-immutability-persist-example[] //tag::entity-immutability-update-example[] - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { Event2 event = entityManager.find(Event2.class, 1L); - log.info("Change event message"); + // "Change event message" event.setMessage("Hibernate User Guide"); }); - doInJPA(this::entityManagerFactory, entityManager -> { + scope.inTransaction( entityManager -> { Event2 event = entityManager.find(Event2.class, 1L); assertEquals("Hibernate User Guide rocks!", event.getMessage()); }); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/mutability/attribute/ImmutableMapAsBasicTests.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/mutability/attribute/ImmutableMapAsBasicTests.java index 5642b9ad8f02..d0fd51860be4 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/mutability/attribute/ImmutableMapAsBasicTests.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/mutability/attribute/ImmutableMapAsBasicTests.java @@ -86,7 +86,7 @@ void testDirtyCheckingManaged(SessionFactoryScope scope) { // mutate the managed entity state scope.inTransaction( (session) -> { // load a managed reference - final TestEntity managed = session.get( TestEntity.class, 1 ); + final TestEntity managed = session.find( TestEntity.class, 1 ); assertThat( managed.data ).hasSize( 2 ); // make the change @@ -109,7 +109,7 @@ void testDirtyCheckingMerge(SessionFactoryScope scope) { final SQLStatementInspector statementInspector = scope.getCollectingStatementInspector(); // load a detached reference - final TestEntity detached = scope.fromTransaction( (session) -> session.get( TestEntity.class, 1 ) ); + final TestEntity detached = scope.fromTransaction( (session) -> session.find( TestEntity.class, 1 ) ); assertThat( detached.data ).hasSize( 2 ); // make the change @@ -134,7 +134,7 @@ void testNotDirtyCheckingManaged(SessionFactoryScope scope) { // make no changes to a managed entity scope.inTransaction( (session) -> { // Load a managed reference - final TestEntity managed = session.get( TestEntity.class, 1 ); + final TestEntity managed = session.find( TestEntity.class, 1 ); assertThat( managed.data ).hasSize( 2 ); // make no changes @@ -153,7 +153,7 @@ void testNotDirtyCheckingMerge(SessionFactoryScope scope) { final SQLStatementInspector statementInspector = scope.getCollectingStatementInspector(); // load a detached instance - final TestEntity detached = scope.fromTransaction( (session) -> session.get( TestEntity.class, 1 ) ); + final TestEntity detached = scope.fromTransaction( (session) -> session.find( TestEntity.class, 1 ) ); assertThat( detached.data ).hasSize( 2 ); // clear statements in prep for next check diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/mutability/attribute/MutableMapAsBasicTests.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/mutability/attribute/MutableMapAsBasicTests.java index ff99c7addca1..e93b587f55e7 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/mutability/attribute/MutableMapAsBasicTests.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/mutability/attribute/MutableMapAsBasicTests.java @@ -39,7 +39,7 @@ void testDirtyChecking(SessionFactoryScope scope) { // make changes to a managed entity - should trigger update scope.inTransaction( (session) -> { - final TestEntity managed = session.get( TestEntity.class, 1 ); + final TestEntity managed = session.find( TestEntity.class, 1 ); statementInspector.clear(); assertThat( managed.data ).hasSize( 2 ); // make the change @@ -48,7 +48,7 @@ void testDirtyChecking(SessionFactoryScope scope) { assertThat( statementInspector.getSqlQueries() ).hasSize( 1 ); // make changes to a detached entity and merge it - should trigger update - final TestEntity loaded = scope.fromTransaction( (session) -> session.get( TestEntity.class, 1 ) ); + final TestEntity loaded = scope.fromTransaction( (session) -> session.find( TestEntity.class, 1 ) ); assertThat( loaded.data ).hasSize( 3 ); // make the change loaded.data.put( "jkl", "007" ); @@ -65,14 +65,14 @@ void testNotDirtyChecking(SessionFactoryScope scope) { // make no changes to a managed entity - should not trigger update scope.inTransaction( (session) -> { - final TestEntity managed = session.get( TestEntity.class, 1 ); + final TestEntity managed = session.find( TestEntity.class, 1 ); statementInspector.clear(); assertThat( managed.data ).hasSize( 2 ); } ); assertThat( statementInspector.getSqlQueries() ).isEmpty(); // make no changes to a detached entity and merge it - should not trigger update - final TestEntity loaded = scope.fromTransaction( (session) -> session.get( TestEntity.class, 1 ) ); + final TestEntity loaded = scope.fromTransaction( (session) -> session.find( TestEntity.class, 1 ) ); assertThat( loaded.data ).hasSize( 2 ); statementInspector.clear(); scope.inTransaction( (session) -> session.merge( loaded ) ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/naturalid/ValidationTests.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/naturalid/ValidationTests.java index b8eff0820b5e..2c06ed4524e5 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/naturalid/ValidationTests.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/naturalid/ValidationTests.java @@ -36,7 +36,7 @@ void checkManyToOne(ServiceRegistryScope registryScope) { final MetadataSources metadataSources = new MetadataSources( registry ) .addAnnotatedClass( Thing1.class ) .addAnnotatedClass( Thing2.class ); - try (final SessionFactory sessionFactory = metadataSources.buildMetadata().buildSessionFactory(); ) { + try (final SessionFactory sessionFactory = metadataSources.buildMetadata().buildSessionFactory() ) { fail( "Expecting an exception" ); } catch (MappingException expected) { @@ -51,7 +51,7 @@ void checkEmbeddable(ServiceRegistryScope registryScope) { .addAnnotatedClass( Thing1.class ) .addAnnotatedClass( Thing3.class ) .addAnnotatedClass( Container.class ); - try (final SessionFactory sessionFactory = metadataSources.buildMetadata().buildSessionFactory(); ) { + try (final SessionFactory sessionFactory = metadataSources.buildMetadata().buildSessionFactory() ) { fail( "Expecting an exception" ); } catch (MappingException expected) { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/naturalid/cid/AbstractCompositeIdAndNaturalIdTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/naturalid/cid/AbstractCompositeIdAndNaturalIdTest.java index 8d1f64fb50a5..648ce07f23eb 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/naturalid/cid/AbstractCompositeIdAndNaturalIdTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/naturalid/cid/AbstractCompositeIdAndNaturalIdTest.java @@ -18,7 +18,7 @@ import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; -import static org.junit.Assert.assertThat; +import static org.hamcrest.MatcherAssert.assertThat; /** * @author Steve Ebersole diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/naturalid/composite/EmbeddedNaturalIdTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/naturalid/composite/EmbeddedNaturalIdTest.java index 8c1901dd0168..66557fb3300e 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/naturalid/composite/EmbeddedNaturalIdTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/naturalid/composite/EmbeddedNaturalIdTest.java @@ -12,7 +12,7 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Vlad Mihalcea 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 708405ff0067..0e5d24c0e0a4 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 @@ -19,10 +19,10 @@ import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.lessThan; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertTrue; @DomainModel( annotatedClasses = { Child.class, Parent.class } ) @SessionFactory 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 e1ea9f249471..81716bff10c8 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 @@ -26,10 +26,10 @@ import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.lessThan; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Alex Burgel @@ -102,7 +102,7 @@ public void checkingMapping(SessionFactoryScope scope) { @Test public void testNaturalIdCheck(SessionFactoryScope scope) { - final Child child = scope.fromTransaction( (s) -> s.get( Child.class, 1 ) ); + final Child child = scope.fromTransaction( (s) -> s.find( Child.class, 1 ) ); // child is detached... // - change the name and attempt to reattach it, which should fail diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/naturalid/immutable/ImmutableNaturalIdTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/naturalid/immutable/ImmutableNaturalIdTest.java index 9247b2b91061..1280a47e1bbf 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/naturalid/immutable/ImmutableNaturalIdTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/naturalid/immutable/ImmutableNaturalIdTest.java @@ -22,11 +22,11 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Steve Ebersole @@ -75,10 +75,7 @@ public void testNaturalIdCheck(SessionFactoryScope scope) { detachedUser.setUserName( "Steve" ); try { scope.inTransaction( - (session) -> { - session.merge( detachedUser ); - } - ); + (session) -> session.merge( detachedUser ) ); fail(); } catch (PersistenceException expected) { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/naturalid/immutableentity/ImmutableEntityNaturalIdTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/naturalid/immutableentity/ImmutableEntityNaturalIdTest.java index 31363dd037ee..6f2ee18cac3a 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/naturalid/immutableentity/ImmutableEntityNaturalIdTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/naturalid/immutableentity/ImmutableEntityNaturalIdTest.java @@ -26,11 +26,11 @@ import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * Test case for NaturalId annotation on an {@link Immutable} entity @@ -69,9 +69,9 @@ public void createTestData(SessionFactoryScope scope) { } ); - assertEquals( "Cache hits should be empty", 0, stats.getNaturalIdCacheHitCount() ); - assertEquals( "Cache misses should be empty", 0, stats.getNaturalIdCacheMissCount() ); - assertEquals( "Cache put should be one after insert", 1, stats.getNaturalIdCachePutCount() ); + assertEquals( 0, stats.getNaturalIdCacheHitCount(), "Cache hits should be empty" ); + assertEquals( 0, stats.getNaturalIdCacheMissCount(), "Cache misses should be empty" ); + assertEquals( 1, stats.getNaturalIdCachePutCount(), "Cache put should be one after insert" ); } @AfterEach @@ -135,9 +135,9 @@ public void testImmutableNaturalIdLifecycle(SessionFactoryScope scope) { .using( "state", "WI" ) .load(); assertThat( building, notNullValue() ); - assertEquals( "Cache hits should be empty", 0, stats.getNaturalIdCacheHitCount() ); - assertEquals( "Cache misses should be one", 1, stats.getNaturalIdCacheMissCount() ); - assertEquals( "Cache put should be one after load", 1, stats.getNaturalIdCachePutCount() ); + assertEquals( 0, stats.getNaturalIdCacheHitCount(), "Cache hits should be empty" ); + assertEquals( 1, stats.getNaturalIdCacheMissCount(), "Cache misses should be one" ); + assertEquals( 1, stats.getNaturalIdCachePutCount(), "Cache put should be one after load" ); assertThat( stats.getPrepareStatementCount(), is( 1L ) ); } ); @@ -154,18 +154,18 @@ public void testImmutableNaturalIdLifecycle(SessionFactoryScope scope) { .using( "state", "WI" ) .load(); assertThat( building, notNullValue() ); - assertEquals( "Cache hits should be one after second query", 1, stats.getNaturalIdCacheHitCount() ); - assertEquals( "Cache misses should be one after second query", 1, stats.getNaturalIdCacheMissCount() ); - assertEquals( "Cache put should be one after second query", 1, stats.getNaturalIdCachePutCount() ); + assertEquals( 1, stats.getNaturalIdCacheHitCount(), "Cache hits should be one after second query" ); + assertEquals( 1, stats.getNaturalIdCacheMissCount(), "Cache misses should be one after second query" ); + assertEquals( 1, stats.getNaturalIdCachePutCount(), "Cache put should be one after second query" ); // Try Deleting session.remove( building ); // third query naturalIdLoader.load(); - assertEquals( "Cache hits should be one after second query", 1, stats.getNaturalIdCacheHitCount() ); - assertEquals( "Cache misses should be two after second query", 1, stats.getNaturalIdCacheMissCount() ); - assertEquals( "Cache put should be one after second query", 1, stats.getNaturalIdCachePutCount() ); + assertEquals( 1, stats.getNaturalIdCacheHitCount(), "Cache hits should be one after second query" ); + assertEquals( 1, stats.getNaturalIdCacheMissCount(), "Cache misses should be two after second query" ); + assertEquals( 1, stats.getNaturalIdCachePutCount(), "Cache put should be one after second query" ); } ); @@ -181,9 +181,9 @@ public void testImmutableNaturalIdLifecycle(SessionFactoryScope scope) { // second query assertNull( building ); - assertEquals( "Cache hits should be one after third query", 1, stats.getNaturalIdCacheHitCount() ); - assertEquals( "Cache misses should be one after third query", 2, stats.getNaturalIdCacheMissCount() ); - assertEquals( "Cache put should be one after third query", 1, stats.getNaturalIdCachePutCount() ); + assertEquals( 1, stats.getNaturalIdCacheHitCount(), "Cache hits should be one after third query" ); + assertEquals( 2, stats.getNaturalIdCacheMissCount(), "Cache misses should be one after third query" ); + assertEquals( 1, stats.getNaturalIdCachePutCount(), "Cache put should be one after third query" ); // here, we should know that that natural-id does not exist as part of the Session... session.byNaturalId( Building.class ) @@ -192,9 +192,9 @@ public void testImmutableNaturalIdLifecycle(SessionFactoryScope scope) { .using( "state", "WI" ) .load(); - assertEquals( "Cache hits should still be one", 1, stats.getNaturalIdCacheHitCount() ); - assertEquals( "Cache misses should now be four", 3, stats.getNaturalIdCacheMissCount() ); - assertEquals( "Cache put should still be one", 1, stats.getNaturalIdCachePutCount() ); + assertEquals( 1, stats.getNaturalIdCacheHitCount(), "Cache hits should still be one" ); + assertEquals( 3, stats.getNaturalIdCacheMissCount(), "Cache misses should now be four" ); + assertEquals( 1, stats.getNaturalIdCachePutCount(), "Cache put should still be one" ); } ); } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/naturalid/inheritance/InheritedNaturalIdTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/naturalid/inheritance/InheritedNaturalIdTest.java index 330ff49fbd65..c3d9ed12b4db 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/naturalid/inheritance/InheritedNaturalIdTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/naturalid/inheritance/InheritedNaturalIdTest.java @@ -26,8 +26,8 @@ import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.Matchers.nullValue; import static org.hibernate.cfg.AvailableSettings.GENERATE_STATISTICS; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.hamcrest.MatcherAssert.assertThat; /** * @author Steve Ebersole @@ -124,7 +124,7 @@ public void testWrongClassLoadingById(SessionFactoryScope scope) { scope.inTransaction( (session) -> { - final System loaded = session.byId( System.class ).load( 1L ); + final System loaded = session.find( System.class, 1L ); assertThat( loaded, nullValue() ); } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/naturalid/inheritance/MappedSuperclassOverrideTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/naturalid/inheritance/MappedSuperclassOverrideTest.java index 42abc6145c56..63bf45568f3b 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/naturalid/inheritance/MappedSuperclassOverrideTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/naturalid/inheritance/MappedSuperclassOverrideTest.java @@ -17,7 +17,7 @@ import org.hibernate.testing.orm.junit.SessionFactoryScope; import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertFalse; +import static org.junit.jupiter.api.Assertions.assertFalse; @DomainModel( annotatedClasses = { MappedSuperclassOverrideTest.MyMappedSuperclass.class, MappedSuperclassOverrideTest.MyEntity.class } ) @SessionFactory( exportSchema = false ) diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/naturalid/inheritance/cache/InheritedNaturalIdCacheTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/naturalid/inheritance/cache/InheritedNaturalIdCacheTest.java index 9978cf27eb3f..78757a9df879 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/naturalid/inheritance/cache/InheritedNaturalIdCacheTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/naturalid/inheritance/cache/InheritedNaturalIdCacheTest.java @@ -44,7 +44,7 @@ public void testLoadWrongClassById(SessionFactoryScope scope) { // try to load `MyEntity#1` as an ExtendedEntity scope.inTransaction( (session) -> { - final ExtendedEntity loaded = session.byId( ExtendedEntity.class ).load( 1 ); + final ExtendedEntity loaded = session.find( ExtendedEntity.class, 1 ); assertThat( loaded ).isNull(); } ); } @@ -55,7 +55,7 @@ public void testLoadWrongClassByIdFromCache(SessionFactoryScope scope) { // load `MyEntity#1` into the cache scope.inTransaction( (session) -> { - final MyEntity loaded = session.byId( MyEntity.class ).load( 1 ); + final MyEntity loaded = session.find( MyEntity.class, 1 ); assertThat( loaded ).isNotNull(); } ); @@ -64,7 +64,7 @@ public void testLoadWrongClassByIdFromCache(SessionFactoryScope scope) { // now try to access it as an ExtendedEntity scope.inTransaction( (session) -> { - final ExtendedEntity loaded = session.byId( ExtendedEntity.class ).load( 1 ); + final ExtendedEntity loaded = session.find( ExtendedEntity.class, 1 ); assertThat( loaded ).isNull(); } ); } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/naturalid/inheritance/cache/InheritedNaturalIdNoCacheTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/naturalid/inheritance/cache/InheritedNaturalIdNoCacheTest.java index 4d64b7507903..377328f195a9 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/naturalid/inheritance/cache/InheritedNaturalIdNoCacheTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/naturalid/inheritance/cache/InheritedNaturalIdNoCacheTest.java @@ -87,7 +87,7 @@ public void testLoadWrongClassById(SessionFactoryScope scope) { // 1) caching is enabled && the natural-id resolution is cached -> WrongClassException // 2) otherwise -> return null scope.inTransaction( (session) -> { - final ExtendedEntity loaded = session.byId( ExtendedEntity.class ).load( 1 ); + final ExtendedEntity loaded = session.find( ExtendedEntity.class, 1 ); assertThat( loaded ).isNull(); } ); } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/naturalid/inheritance/spread/SpreadNaturalIdTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/naturalid/inheritance/spread/SpreadNaturalIdTest.java index 5a9e1d9d5db1..92142c3a0cbb 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/naturalid/inheritance/spread/SpreadNaturalIdTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/naturalid/inheritance/spread/SpreadNaturalIdTest.java @@ -14,7 +14,7 @@ import org.hibernate.testing.util.ServiceRegistryUtil; import org.junit.jupiter.api.Test; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Steve Ebersole diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/naturalid/lazy/NaturalIdInUninitializedAssociationTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/naturalid/lazy/NaturalIdInUninitializedAssociationTest.java index 0266112f7b9c..4135abbde74c 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/naturalid/lazy/NaturalIdInUninitializedAssociationTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/naturalid/lazy/NaturalIdInUninitializedAssociationTest.java @@ -24,8 +24,8 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; /** * @author Gail Badner @@ -53,14 +53,14 @@ public class NaturalIdInUninitializedAssociationTest { public void testImmutableNaturalId(SessionFactoryScope scope) { scope.inTransaction( (session) -> { - final AnEntity e = session.get( AnEntity.class, 3 ); + final AnEntity e = session.find( AnEntity.class, 3 ); assertFalse( Hibernate.isInitialized( e.entityImmutableNaturalId ) ); } ); scope.inTransaction( (session) -> { - final AnEntity e = session.get( AnEntity.class, 3 ); + final AnEntity e = session.find( AnEntity.class, 3 ); Hibernate.initialize( e.entityImmutableNaturalId ); assertEquals( "immutable name", e.entityImmutableNaturalId.getName() ); } @@ -71,14 +71,14 @@ public void testImmutableNaturalId(SessionFactoryScope scope) { public void testMutableNaturalId(SessionFactoryScope scope) { scope.inTransaction( (session) -> { - final AnEntity e = session.get( AnEntity.class, 3 ); + final AnEntity e = session.find( AnEntity.class, 3 ); assertFalse( Hibernate.isInitialized( e.entityMutableNaturalId ) ); } ); scope.inTransaction( (session) -> { - final AnEntity e = session.get( AnEntity.class, 3 ); + final AnEntity e = session.find( AnEntity.class, 3 ); assertEquals( "mutable name", e.entityMutableNaturalId.getName() ); } ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/naturalid/lazy/NaturalIdInUninitializedProxyTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/naturalid/lazy/NaturalIdInUninitializedProxyTest.java index c5c974ed34a6..f1e263af6589 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/naturalid/lazy/NaturalIdInUninitializedProxyTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/naturalid/lazy/NaturalIdInUninitializedProxyTest.java @@ -21,8 +21,8 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; /** * @author Gail Badner @@ -66,7 +66,7 @@ public void testMutableNaturalId(SessionFactoryScope scope) { scope.inTransaction( (session) -> { - final EntityMutableNaturalId e = session.get( EntityMutableNaturalId.class, 1 ); + final EntityMutableNaturalId e = session.find( EntityMutableNaturalId.class, 1 ); assertEquals( "name", e.name ); } ); @@ -83,7 +83,7 @@ public void testImmutableNaturalId(SessionFactoryScope scope) { scope.inTransaction( (session) -> { - final EntityImmutableNaturalId e = session.get( EntityImmutableNaturalId.class, 1 ); + final EntityImmutableNaturalId e = session.find( EntityImmutableNaturalId.class, 1 ); assertEquals( "name", e.name ); } ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/naturalid/mutable/MutableNaturalIdTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/naturalid/mutable/MutableNaturalIdTest.java index 3ba806ab4839..36a5cf0671dd 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/naturalid/mutable/MutableNaturalIdTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/naturalid/mutable/MutableNaturalIdTest.java @@ -24,11 +24,11 @@ import static org.hibernate.cfg.AvailableSettings.GENERATE_STATISTICS; import static org.hibernate.cfg.AvailableSettings.USE_QUERY_CACHE; import static org.hibernate.cfg.AvailableSettings.USE_SECOND_LEVEL_CACHE; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertNull; /** * @author Gavin King @@ -315,7 +315,7 @@ public void testClear(SessionFactoryScope scope) { .using( "org", "hb" ) .load(); assertNotNull( beforeClear ); - assertEquals( statistics.getPrepareStatementCount(), 1 ); + assertEquals( 1, statistics.getPrepareStatementCount() ); session.clear(); @@ -324,7 +324,7 @@ public void testClear(SessionFactoryScope scope) { .using( "org", "hb" ) .load(); assertNotNull( afterClear ); - assertEquals( statistics.getPrepareStatementCount(), 2 ); + assertEquals( 2, statistics.getPrepareStatementCount() ); assertNotSame( beforeClear, afterClear ); } @@ -347,7 +347,7 @@ public void testEviction(SessionFactoryScope scope) { .using( "org", "hb" ) .load(); assertNotNull( beforeEvict ); - assertEquals( statistics.getPrepareStatementCount(), 1 ); + assertEquals( 1, statistics.getPrepareStatementCount() ); session.evict( beforeEvict ); @@ -356,7 +356,7 @@ public void testEviction(SessionFactoryScope scope) { .using( "org", "hb" ) .load(); assertNotNull( afterEvict ); - assertEquals( statistics.getPrepareStatementCount(), 2 ); + assertEquals( 2, statistics.getPrepareStatementCount() ); assertNotSame( beforeEvict, afterEvict ); } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/naturalid/mutable/cached/CachedMutableNaturalIdStrictReadWriteTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/naturalid/mutable/cached/CachedMutableNaturalIdStrictReadWriteTest.java index 2356e5836d82..f5270e673ee9 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/naturalid/mutable/cached/CachedMutableNaturalIdStrictReadWriteTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/naturalid/mutable/cached/CachedMutableNaturalIdStrictReadWriteTest.java @@ -19,9 +19,9 @@ import static org.hibernate.cfg.AvailableSettings.GENERATE_STATISTICS; import static org.hibernate.cfg.AvailableSettings.USE_SECOND_LEVEL_CACHE; import static org.hibernate.testing.cache.CachingRegionFactory.DEFAULT_ACCESSTYPE; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; @ServiceRegistry( settings = { @@ -186,7 +186,7 @@ public void testInsertUpdateEntity_NaturalIdCachedAfterTransactionSuccess(Sessio } ); - assertEquals( "In a strict access strategy we would expect a hit here", 1, statistics.getNaturalIdCacheHitCount() ); + assertEquals( 1, statistics.getNaturalIdCacheHitCount(), "In a strict access strategy we would expect a hit here" ); } @Test diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/naturalid/mutable/cached/CachedMutableNaturalIdTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/naturalid/mutable/cached/CachedMutableNaturalIdTest.java index 5f00486dd9c6..84cde0624f52 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/naturalid/mutable/cached/CachedMutableNaturalIdTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/naturalid/mutable/cached/CachedMutableNaturalIdTest.java @@ -12,9 +12,9 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; /** * Tests of mutable natural ids stored in second level cache @@ -100,7 +100,7 @@ public void testNaturalIdReCachingWhenNeeded(SessionFactoryScope scope) { scope.inTransaction( (session) -> { - final Another it = session.byId( Another.class ).load( id ); + final Another it = session.find( Another.class, id ); it.setName( "it2" ); // changing something but not the natural-id's it.setSurname( "surname" ); @@ -134,7 +134,7 @@ public void testNaturalIdChangeAfterResolveEntityFrom2LCache(SessionFactoryScope scope.inTransaction( (session) -> { - final AllCached it = session.byId( AllCached.class ).load( id ); + final AllCached it = session.find( AllCached.class, id ); it.setName( "it2" ); final AllCached shouldBeGone = session.bySimpleNaturalId( AllCached.class ).load( "it" ); @@ -255,7 +255,7 @@ public void testCacheVerifyHits(SessionFactoryScope scope) { System.out.println("Native load by natural-id, generate 4. hit"); person = session.bySimpleNaturalId(AllCached.class).load("John Doe"); System.out.println("NaturalIdCacheHitCount: " + sfi.getStatistics().getNaturalIdCacheHitCount()); - assertEquals("we expected now 4 hits", 4, sfi.getStatistics().getNaturalIdCacheHitCount()); + assertEquals(4, sfi.getStatistics().getNaturalIdCacheHitCount(), "we expected now 4 hits"); assertNotNull(person); session.remove(person); // evicts natural-id from first & second level cache person = session.bySimpleNaturalId(AllCached.class).load("John Doe"); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/naturalid/nullable/NullableNaturalIdTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/naturalid/nullable/NullableNaturalIdTest.java index 0c826b98bee6..63e698c6bf7d 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/naturalid/nullable/NullableNaturalIdTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/naturalid/nullable/NullableNaturalIdTest.java @@ -19,9 +19,9 @@ import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Steve Ebersole @@ -154,7 +154,7 @@ public void testNaturalIdNullValueOnPersist(SessionFactoryScope scope) { scope.inTransaction( (session) -> { - final C c = session.get(C.class, 1); + final C c = session.find(C.class, 1); assertThat( c, notNullValue() ); assertThat( c.name, nullValue() ); } @@ -174,12 +174,12 @@ public void testUniqueAssociation(SessionFactoryScope scope) { scope.inTransaction( (session) -> { - final A a = session.get( A.class, 1 ); + final A a = session.find( A.class, 1 ); assertThat( a, notNullValue() ); assertThat( a.assC, nullValue() ); assertThat( a.myname, nullValue() ); - final B b = session.get( B.class, 1 ); + final B b = session.find( B.class, 1 ); assertThat( b, notNullValue() ); assertThat( b.assA, nullValue() ); assertThat( b.naturalid, notNullValue() ); @@ -190,7 +190,7 @@ public void testUniqueAssociation(SessionFactoryScope scope) { scope.inTransaction( (session) -> { - final B b = session.get( B.class, 1 ); + final B b = session.find( B.class, 1 ); assertThat( b, notNullValue() ); assertThat( b.assA, notNullValue() ); } 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 99cc48c04255..88db2ce25c0f 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 @@ -24,9 +24,8 @@ import org.hibernate.testing.orm.junit.SessionFactory; import org.hibernate.testing.orm.junit.SessionFactoryScope; import org.hibernate.testing.orm.junit.Setting; -import org.junit.Assert; -import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -187,7 +186,7 @@ public void testRetrievingItem(SessionFactoryScope scope) { assertTrue( Hibernate.isInitialized( order ) ); assertThat( statistics.getPrepareStatementCount(), is( 2L ) ); - Assert.assertFalse( Hibernate.isInitialized( order.getLineItems() ) ); + Assertions.assertFalse( Hibernate.isInitialized( order.getLineItems() ) ); assertThat( order.getLineItems().size(), is( 2 ) ); @@ -231,7 +230,7 @@ public void testRetrievingItem(SessionFactoryScope scope) { assertTrue( Hibernate.isInitialized( order ) ); assertThat( statistics.getPrepareStatementCount(), is( 2L ) ); - Assert.assertFalse( Hibernate.isInitialized( order.getLineItems() ) ); + Assertions.assertFalse( Hibernate.isInitialized( order.getLineItems() ) ); assertThat( order.getLineItems().size(), is( 2 ) ); /* @@ -271,7 +270,7 @@ public void testRetrievingItem(SessionFactoryScope scope) { assertTrue( Hibernate.isInitialized( order ) ); assertThat( statistics.getPrepareStatementCount(), is( 1L ) ); - Assert.assertFalse( Hibernate.isInitialized( order.getLineItems() ) ); + Assertions.assertFalse( Hibernate.isInitialized( order.getLineItems() ) ); assertThat( order.getLineItems().size(), is( 2 ) ); @@ -286,7 +285,7 @@ public void testRetrievingItem(SessionFactoryScope scope) { assertThat( statistics.getPrepareStatementCount(), is( 2L ) ); - Assert.assertTrue( Hibernate.isInitialized( order.getLineItems() ) ); + Assertions.assertTrue( Hibernate.isInitialized( order.getLineItems() ) ); for ( Item itm : order.getLineItems() ) { assertThat( itm.getOrder(), is( order ) ); @@ -323,7 +322,7 @@ public void testRetrievingItem(SessionFactoryScope scope) { assertTrue( Hibernate.isInitialized( order ) ); assertThat( statistics.getPrepareStatementCount(), is( 2L ) ); - Assert.assertFalse( Hibernate.isInitialized( order.getLineItems() ) ); + Assertions.assertFalse( Hibernate.isInitialized( order.getLineItems() ) ); assertThat( order.getLineItems().size(), is( 2 ) ); /* diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/onetomany/OneToManyTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/onetomany/OneToManyTest.java index 28d9f5a7d4d1..721a74aa459b 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/onetomany/OneToManyTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/onetomany/OneToManyTest.java @@ -72,7 +72,7 @@ public void testGet(SessionFactoryScope scope) { scope.inTransaction( session -> { try { - Card card = session.get( Card.class, CARD_ID ); + Card card = session.find( Card.class, CARD_ID ); assertEquals( 1, card.getFields().size() ); CardField cf = card.getFields().iterator().next(); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/onetoone/OneToOneErrorTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/onetoone/OneToOneErrorTest.java index 9f73934a11f8..738bad8e12f5 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/onetoone/OneToOneErrorTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/onetoone/OneToOneErrorTest.java @@ -13,7 +13,7 @@ import org.hibernate.testing.ServiceRegistryBuilder; import org.hibernate.orm.test.annotations.onetoone.Show; import org.hibernate.orm.test.annotations.onetoone.ShowDescription; -import org.junit.Assert; +import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; /** @@ -31,7 +31,7 @@ public void testWrongOneToOne() { try { serviceRegistry = ServiceRegistryBuilder.buildServiceRegistry( Environment.getProperties() ); sessionFactory = cfg.buildSessionFactory( serviceRegistry ); - Assert.fail( "Wrong mappedBy does not fail property" ); + Assertions.fail( "Wrong mappedBy does not fail property" ); } catch (AnnotationException e) { //success diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/onetoone/OneToOneJoinTableNonOptionalTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/onetoone/OneToOneJoinTableNonOptionalTest.java index 12ddf1e5437f..cb60c198b423 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/onetoone/OneToOneJoinTableNonOptionalTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/onetoone/OneToOneJoinTableNonOptionalTest.java @@ -23,8 +23,8 @@ import org.hibernate.testing.orm.junit.SessionFactoryScope; import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Andrea Boriero diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/onetoone/ToOneSelfReferenceTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/onetoone/ToOneSelfReferenceTest.java index e7742f025e87..38ef17d54cfa 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/onetoone/ToOneSelfReferenceTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/onetoone/ToOneSelfReferenceTest.java @@ -52,7 +52,7 @@ public void testGet(SessionFactoryScope scope) { statementInspector.clear(); scope.inTransaction( session -> { - final EntityTest entity = session.get( EntityTest.class, 1 ); + final EntityTest entity = session.find( EntityTest.class, 1 ); assertThat( entity.getName(), is( "e1" ) ); final EntityTest entity2 = entity.getEntity(); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/onetoone/hhh9798/OneToOneJoinTableTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/onetoone/hhh9798/OneToOneJoinTableTest.java index e5b94049dfcf..32511090b73f 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/onetoone/hhh9798/OneToOneJoinTableTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/onetoone/hhh9798/OneToOneJoinTableTest.java @@ -17,7 +17,7 @@ import org.junit.jupiter.api.Test; import static org.hibernate.testing.junit4.ExtraAssertions.assertTyping; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.fail; @JiraKey(value = "HHH-9798") @DomainModel( annotatedClasses = { Shipment.class, Item.class } ) diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/onetoone/primarykey/NullablePrimaryKeyTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/onetoone/primarykey/NullablePrimaryKeyTest.java index 009f82aed1de..37743ae36fe2 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/onetoone/primarykey/NullablePrimaryKeyTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/onetoone/primarykey/NullablePrimaryKeyTest.java @@ -20,8 +20,8 @@ import org.hibernate.testing.orm.junit.BaseUnitTest; import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; /** * Test harness for ANN-742. @@ -53,7 +53,7 @@ public void testGeneratedSql() { String expectedMappingTableSql = "create table personAddress (address_id bigint, " + "person_id bigint not null, primary key (person_id))"; - assertEquals( "Wrong SQL", expectedMappingTableSql, commands.get( 2 ) ); + assertEquals( expectedMappingTableSql, commands.get( 2 ), "Wrong SQL" ); } catch (Exception e) { fail( e.getMessage() ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/quote/ColumnQuoteTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/quote/ColumnQuoteTest.java index ecddea96314a..334225406cb8 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/quote/ColumnQuoteTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/quote/ColumnQuoteTest.java @@ -55,7 +55,7 @@ public void tearDown(SessionFactoryScope scope) { @Test public void testGet(SessionFactoryScope scope) { scope.inTransaction( session -> { - Product product = session.get( Product.class, testProductId ); + Product product = session.find( Product.class, testProductId ); assertThat( product.fieldWithHibernateQuoating, is( fieldWithHibernateQuotingValue ) ); assertThat( product.fieldWithJpaQuoting, is( fieldWithJpaQuotingValue ) ); } ); @@ -64,13 +64,13 @@ public void testGet(SessionFactoryScope scope) { @Test public void testUpdate(SessionFactoryScope scope) { scope.inTransaction( session -> { - Product product = session.get( Product.class, testProductId ); + Product product = session.find( Product.class, testProductId ); product.fieldWithHibernateQuoating = changedFieldWithHibernateQuotingValue; product.fieldWithJpaQuoting = changedFieldWithJpaQuotingValue; session.flush(); } ); scope.inTransaction( session -> { - Product product = session.get( Product.class, testProductId ); + Product product = session.find( Product.class, testProductId ); assertThat( product.fieldWithHibernateQuoating, is( changedFieldWithHibernateQuotingValue ) ); assertThat( product.fieldWithJpaQuoting, is( changedFieldWithJpaQuotingValue ) ); } ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/typedmanytoone/TypedManyToOneTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/typedmanytoone/TypedManyToOneTest.java index 80f9e418dfdd..242f7d8cd4d4 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/typedmanytoone/TypedManyToOneTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/mapping/typedmanytoone/TypedManyToOneTest.java @@ -70,7 +70,7 @@ public void testCreateQuery(SessionFactoryScope scope) { merged.setShippingAddress(null); s.remove( shipAddress ); s.flush(); - assertNull( s.get( "ShippingAddress", shipAddress.getAddressId() ) ); + assertNull( s.find( "ShippingAddress", shipAddress.getAddressId() ) ); s.remove( merged ); } ); }