From c6a11d99fd9894b1743a46559274ccc1b88a3a93 Mon Sep 17 00:00:00 2001 From: Steve Ebersole Date: Tue, 9 Jul 2019 15:06:56 -0500 Subject: [PATCH] 6 - SQM based on JPA type system - focus on reducing compilation errors --- .../tuplizer/DynamicEmbeddableTuplizer.java | 2 +- .../proxy/tuplizer/DynamicEntityTuplizer.java | 2 +- .../proxy/tuplizer/DynamicInstantiator.java | 2 +- .../org/hibernate/userguide/sql/SQLTest.java | 3 - .../test/c3p0/StatementCacheTest.java | 1 - .../main/java/org/hibernate/CacheMode.java | 63 +- .../src/main/java/org/hibernate/Criteria.java | 566 --------- .../java/org/hibernate/StatelessSession.java | 7 +- .../org/hibernate/annotations/Remove.java | 33 + .../internal/SessionFactoryBuilderImpl.java | 1 - .../SessionFactoryOptionsBuilder.java | 17 - .../internal/StrategySelectorBuilder.java | 8 - ...stractDelegatingSessionFactoryBuilder.java | 1 - ...stractDelegatingSessionFactoryOptions.java | 6 - .../boot/spi/SessionFactoryOptions.java | 2 - .../java/org/hibernate/cfg/Configuration.java | 21 +- .../main/java/org/hibernate/cfg/Settings.java | 10 - .../cfg/annotations/CollectionBinder.java | 3 - .../internal/AbstractBagSemantics.java | 6 +- .../internal/StandardArraySemantics.java | 11 +- .../internal/StandardBagSemantics.java | 9 +- .../StandardIdentifierBagSemantics.java | 13 +- .../internal/StandardListSemantics.java | 10 +- .../internal/StandardMapSemantics.java | 10 +- .../internal/StandardOrderedMapSemantics.java | 18 +- .../internal/StandardOrderedSetSemantics.java | 18 +- .../internal/StandardSetSemantics.java | 13 +- .../internal/StandardSortedMapSemantics.java | 10 +- .../internal/StandardSortedSetSemantics.java | 15 +- .../collection/spi/CollectionSemantics.java | 8 +- .../dialect/AbstractTransactSQLDialect.java | 4 - .../org/hibernate/dialect/Cache71Dialect.java | 4 - .../org/hibernate/dialect/DB297Dialect.java | 4 - .../org/hibernate/dialect/DerbyDialect.java | 4 - .../java/org/hibernate/dialect/H2Dialect.java | 4 - .../dialect/HANAColumnStoreDialect.java | 4 - .../dialect/HANARowStoreDialect.java | 5 - .../org/hibernate/dialect/HSQLDialect.java | 5 - .../hibernate/dialect/InformixDialect.java | 4 - .../org/hibernate/dialect/IngresDialect.java | 4 - .../org/hibernate/dialect/MySQLDialect.java | 4 - .../hibernate/dialect/Oracle8iDialect.java | 5 +- .../org/hibernate/dialect/Oracle9Dialect.java | 4 - .../dialect/PostgreSQL81Dialect.java | 4 - .../dialect/PostgreSQL82Dialect.java | 4 - .../org/hibernate/dialect/SAPDBDialect.java | 4 - .../hibernate/dialect/Teradata14Dialect.java | 1 + .../hibernate/dialect/TeradataDialect.java | 541 +++++---- .../hibernate/dialect/TimesTenDialect.java | 4 - .../org/hibernate/ejb/HibernateQuery.java | 14 - .../engine/internal/ParameterBinder.java | 1 + .../internal/StatefulPersistenceContext.java | 4 +- .../internal/CollectionLoadContext.java | 431 ------- .../loading/internal/EntityLoadContext.java | 47 - .../engine/loading/internal/LoadContexts.java | 292 ----- .../internal/LoadingCollectionEntry.java | 58 - .../engine/loading/internal/package-info.java | 11 - .../engine/query/spi/HQLQueryPlan.java | 454 -------- .../engine/query/spi/NativeSQLQueryPlan.java | 1 + .../hibernate/engine/spi/CollectionKey.java | 12 +- .../engine/spi/LoadQueryInfluencers.java | 52 +- .../engine/spi/PersistenceContext.java | 15 +- .../hibernate/engine/spi/QueryParameters.java | 35 +- .../hibernate/engine/spi/RowSelection.java | 10 + .../internal/DefaultMergeEventListener.java | 15 +- .../internal/DefaultRefreshEventListener.java | 23 +- .../hibernate/internal/CoreMessageLogger.java | 16 +- .../org/hibernate/internal/CriteriaImpl.java | 730 ------------ .../org/hibernate/internal/SessionImpl.java | 2 +- .../internal/StatelessSessionImpl.java | 114 +- .../util/streams/GenericArrayCollector.java | 62 + .../util/streams/StingArrayCollector.java | 57 + .../internal/util/streams/StreamUtils.java | 21 + .../org/hibernate/jpa/HibernateQuery.java | 25 - .../spi/CriteriaQueryTupleTransformer.java | 151 --- ...edProcedureQueryParameterRegistration.java | 2 - .../collection/SubselectCollectionLoader.java | 1 + .../collection/SubselectOneToManyLoader.java | 1 + .../hibernate/loader/custom/CustomLoader.java | 1 + .../loader/custom/sql/NamedParamBinder.java | 1 + .../custom/sql/PositionalParamBinder.java | 1 + .../MultiIdEntityLoaderStandardImpl.java | 45 + .../internal/NaturalIdLoaderStandardImpl.java | 34 + .../internal/Preparable.java} | 9 +- ...SingleIdEntityLoaderProvidedQueryImpl.java | 44 + .../SingleIdEntityLoaderStandardImpl.java | 140 +++ .../internal/ResultSetProcessorHelper.java | 1 + .../internal/ResultSetProcessorImpl.java | 4 +- .../spi/ResultSetProcessingContext.java | 1 + .../spi/ScrollableResultSetProcessor.java | 1 + .../loader/spi/InternalFetchProfile.java | 46 + .../org/hibernate/loader/spi/Loadable.java | 25 + .../spi/Loader.java} | 13 +- .../loader/spi/MultiIdEntityLoader.java | 26 + .../hibernate/loader/spi/NaturalIdLoader.java | 45 + .../loader/spi/SingleEntityLoader.java | 27 + .../loader/spi/SingleIdEntityLoader.java | 28 + .../spi/SingleUniqueKeyEntityLoader.java | 23 + .../model/domain/AllowableParameterType.java | 2 +- .../model/mapping/spi/Writeable.java | 11 + ...ectionFilterKeyParameterSpecification.java | 1 + .../DynamicFilterParameterSpecification.java | 1 + .../param/NamedParameterSpecification.java | 1 + .../org/hibernate/param/ParameterBinder.java | 1 + .../PositionalParameterSpecification.java | 1 + ...VersionTypeSeedParameterSpecification.java | 1 + .../AbstractCollectionPersister.java | 130 +-- .../NamedQueryCollectionInitializer.java | 4 +- .../entity/AbstractEntityPersister.java | 112 +- .../persister/entity/EntityPersister.java | 3 +- .../org/hibernate/pretty/MessageHelper.java | 22 +- .../PostgresCallableStatementSupport.java | 144 +-- .../StandardCallableStatementSupport.java | 110 +- .../query/internal/AbstractProducedQuery.java | 563 ++++----- .../query/internal/QueryOptionsImpl.java | 34 +- .../internal/QueryParameterBindingsImpl.java | 37 +- .../query/spi/MutableQueryOptions.java | 18 +- .../org/hibernate/query/spi/QueryEngine.java | 1 + .../org/hibernate/query/spi/QueryOptions.java | 36 +- .../query/spi/QueryParameterBindings.java | 18 +- .../query/spi/QueryParameterListBinding.java | 3 +- .../consume/internal/SqmConsumeHelper.java | 62 - .../consume/spi/BaseSqmToSqlAstConverter.java | 1018 ----------------- .../spi/SqmExpressionInterpretation.java | 29 - .../internal/ConcreteSqmSelectQueryPlan.java | 176 ++- .../sqm/internal/SimpleDeleteQueryPlan.java | 61 +- .../internal/SqmIdSelectGenerator.java | 132 --- .../internal/SqmMutationStrategyHelper.java | 267 ----- .../mutation/spi/AbstractMutationHandler.java | 11 +- .../sqm/mutation/spi/SqmMutationStrategy.java | 1 - .../spi/cte/AbstractCteMutationHandler.java | 43 - .../spi/cte/CteBasedMutationStrategy.java | 165 --- .../spi/cte/CteDeleteHandlerImpl.java | 193 ---- .../query/sqm/mutation/spi/cte/CteTable.java | 201 ---- .../sqm/mutation/spi/cte/CteTableColumn.java | 37 - .../sqm/mutation/spi/cte/CteTableGroup.java | 65 -- .../mutation/spi/cte/CteTableReference.java | 30 - .../spi/cte/CteUpdateHandlerImpl.java | 38 - .../sqm/mutation/spi/cte/package-info.java | 13 - .../idtable/AbstractTableBasedHandler.java | 291 ----- .../AbstractTableBasedMutationStrategy.java | 276 ----- .../spi/idtable/GlobalTempTableExporter.java | 17 - .../idtable/GlobalTemporaryTableStrategy.java | 154 --- .../sqm/mutation/spi/idtable/IdTable.java | 197 ---- .../mutation/spi/idtable/IdTableColumn.java | 88 -- .../spi/idtable/IdTableExporterImpl.java | 89 -- .../mutation/spi/idtable/IdTableGroup.java | 65 -- .../mutation/spi/idtable/IdTableHelper.java | 312 ----- .../IdTableManagementTransactionality.java | 29 - .../spi/idtable/IdTableReference.java | 62 - .../spi/idtable/IdTableSessionUidColumn.java | 33 - .../mutation/spi/idtable/IdTableSupport.java | 34 - .../spi/idtable/LocalTempTableExporter.java | 17 - .../idtable/LocalTemporaryTableStrategy.java | 103 -- .../PersistentTableSessionUidSupport.java | 36 - .../spi/idtable/PersistentTableStrategy.java | 183 --- .../spi/idtable/SessionUidSupport.java | 51 - .../spi/idtable/StandardIdTableSupport.java | 63 - .../idtable/TableBasedDeleteHandlerImpl.java | 204 ---- .../idtable/TableBasedUpdateHandlerImpl.java | 150 --- .../mutation/spi/idtable/package-info.java | 50 - .../spi/inline/AbstractInlineHandler.java | 52 - .../spi/inline/InlineDeleteHandler.java | 169 --- .../spi/inline/InlineMutationStrategy.java | 54 - .../sqm/mutation/spi/inline/package-info.java | 13 - .../spi/simple/SimpleDeleteHandler.java | 82 -- .../spi/simple/SimpleSqmMutationStrategy.java | 37 - .../spi/simple/SimpleUpdateHandler.java | 37 - .../function/internal/PatternRenderer.java | 2 +- ...SelfRenderingFunctionSqlAstExpression.java | 121 -- .../internal/SelfRenderingSqmFunction.java | 10 +- .../spi/FunctionAsExpressionTemplate.java | 2 +- .../spi/NamedSqmFunctionTemplate.java | 2 +- .../spi/PatternBasedSqmFunctionTemplate.java | 2 +- .../spi/SelfRenderingFunctionSupport.java | 2 +- .../tree/expression/SqmUnaryOperation.java | 11 +- .../tree/expression/function/SqmFunction.java | 23 +- .../sqm/tree/expression/function/SqmStar.java | 4 - .../result/internal/OutputsImpl.java | 1 + .../service/StandardServiceInitiators.java | 2 - .../main/java/org/hibernate/sql/Template.java | 103 -- .../hibernate/sql/ast/spi/SqlAstWalker.java | 2 + .../sql/ast/spi/SqlExpressionResolver.java | 42 +- .../hibernate/sql/ast/spi/SqlSelection.java | 5 +- .../sql/ast/tree/from/TableGroup.java | 2 +- .../sql/ast/tree/from/TableGroupJoin.java | 8 +- .../ast/tree/from/TableGroupJoinProducer.java | 1 + .../sql/ast/tree/from/TableReference.java | 116 ++ .../tree/from/TableReferenceContributor.java | 18 +- .../sql/ast/tree/from/TableReferenceJoin.java | 57 + .../sql/ast/tree/update/UpdateStatement.java | 13 +- .../org/hibernate/sql/exec/spi/JdbcCall.java | 46 +- .../JdbcValuesMappingProducerDefined.java | 13 +- .../JdbcValuesMappingProducerLegacy.java | 252 ++-- .../JdbcValuesMappingProducerStandard.java | 5 +- .../JdbcValuesMappingProducerUndefined.java | 150 ++- ...luesSourceProcessingStateStandardImpl.java | 189 +++ .../internal/RowTransformerJpaTupleImpl.java | 2 +- .../internal/RowTransformerPassThruImpl.java | 2 +- .../RowTransformerSingularReturnImpl.java | 2 +- .../internal/StandardJdbcValuesMapping.java | 62 + .../results/internal/TupleElementImpl.java | 35 + .../sql/results/internal/TupleImpl.java | 123 ++ .../internal/domain/ArrayInitializer.java | 75 ++ .../results/spi/CollectionInitializer.java | 34 + .../sql/results/spi/CompositeInitializer.java | 28 + .../spi/JdbcValuesMappingDescriptor.java | 30 - .../sql/results/spi/LoadContexts.java | 11 +- .../results/spi/LoadingCollectionEntry.java | 17 +- .../MultipleLinesSqlCommandExtractor.java | 24 +- .../SqlStatementParserListenerImpl.java | 30 + .../tuple/DynamicMapInstantiator.java | 1 - .../org/hibernate/tuple/Instantiator.java | 44 + .../org/hibernate/tuple/PojoInstantiator.java | 8 - .../component/AbstractComponentTuplizer.java | 2 +- .../DynamicMapComponentTuplizer.java | 2 +- .../component/PojoComponentTuplizer.java | 2 +- .../tuple/entity/AbstractEntityTuplizer.java | 2 +- .../entity/DynamicMapEntityTuplizer.java | 2 +- .../tuple/entity/PojoEntityInstantiator.java | 2 - .../tuple/entity/PojoEntityTuplizer.java | 2 +- .../internal/AliasWithCriterionTest.java | 2 - .../cid/CompositeIdIdentityTest.java | 7 - .../test/annotations/cid/CompositeIdTest.java | 2 - .../idmanytoone/IdManyToOneTest.java | 1 - .../test/annotations/join/JoinTest.java | 2 - .../ImmutableNaturalKeyLookupTest.java | 1 - .../NaturalIdOnSingleManyToOneTest.java | 3 - .../onetomany/DefaultNullOrderingTest.java | 1 - .../annotations/onetomany/OrderByTest.java | 3 - .../SecondaryTableSchemaTest.java | 10 - .../tuplizer/DynamicComponentTuplizer.java | 2 +- .../tuplizer/DynamicEntityTuplizer.java | 2 +- .../tuplizer/DynamicInstantiator.java | 2 +- .../MyEntityInstantiator.java | 2 +- .../bytebuddysubclass/MyTuplizer.java | 2 +- .../hibernate/test/cid/CompositeIdTest.java | 1 - .../test/criteria/ComplexJoinAliasTest.java | 1 - .../test/criteria/CriteriaAliasFetchTest.java | 2 - .../test/criteria/CriteriaLockingTest.java | 1 - .../test/criteria/CriteriaOrderByTest.java | 1 - .../test/criteria/CriteriaQueryTest.java | 1 - .../test/criteria/LongInElementsTest.java | 1 - .../test/criteria/OuterJoinCriteriaTest.java | 2 - .../limitexpression/LimitExpressionTest.java | 4 - .../many_to_many/CriteriaManyToManyTest.java | 1 - .../test/criterion/CriterionTest.java | 1 - .../criterion/NationalizedIgnoreCaseTest.java | 1 - .../tuplizer/MyEntityInstantiator.java | 2 +- .../tuplizer/MyEntityTuplizer.java | 2 +- .../tuplizer2/MyEntityInstantiator.java | 2 +- .../tuplizer2/MyEntityTuplizer.java | 2 +- .../CriteriaQueryWithAppliedFilterTest.java | 1 - .../test/filter/DynamicFilterTest.java | 1 - .../test/flush/NativeCriteriaSyncTest.java | 6 - .../hibernate/test/hql/EntityJoinTest.java | 2 - .../java/org/hibernate/test/hql/HQLTest.java | 1 - .../test/hql/QueryTranslatorTestCase.java | 1 - .../hibernate/test/hql/TupleSupportTest.java | 1 - .../IdentifierPropertyReferencesTest.java | 1 - .../MultiInheritanceImplicitDowncastTest.java | 1 - .../bidir/embedded/KeyManyToOneTest.java | 1 - .../org/hibernate/test/legacy/FooBarTest.java | 3 - .../org/hibernate/test/legacy/FumTest.java | 1 - .../hibernate/test/legacy/MultiTableTest.java | 1 - .../test/legacy/ParentChildTest.java | 1 - .../test/legacy/QueryByExampleTest.java | 1 - .../locking/paging/PagingAndLockingTest.java | 1 - .../ordered/OrderedManyToManyTest.java | 1 - .../test/pagination/PaginationTest.java | 3 +- .../CachedPropertyRefCollectionTest.java | 1 - ...stractQueryCacheResultTransformerTest.java | 2 - .../test/querycache/QueryCacheTest.java | 1 - .../test/queryhint/QueryHintHANATest.java | 1 - .../queryhint/QueryHintSQLServer2012Test.java | 1 - .../test/queryhint/QueryHintTest.java | 1 - .../test/queryplan/GetHqlQueryPlanTest.java | 1 - .../readonly/ReadOnlyCriteriaQueryTest.java | 1 - .../stateless/StatelessSessionQueryTest.java | 46 - .../spatial/criterion/DWithinExpression.java | 1 - .../spatial/criterion/ExpressionUtil.java | 1 - .../criterion/HavingSridExpression.java | 1 - .../spatial/criterion/IsEmptyExpression.java | 1 - .../spatial/criterion/SpatialFilter.java | 1 - .../spatial/criterion/SpatialProjections.java | 1 - .../criterion/SpatialRelateExpression.java | 1 - .../criterion/OracleSpatialProjection.java | 1 - .../criterion/OracleSpatialRestrictions.java | 1 - .../AbstractTestStoreRetrieve.java | 1 - .../integration/TestSpatialRestrictions.java | 1 - 290 files changed, 3067 insertions(+), 10258 deletions(-) delete mode 100644 hibernate-core/src/main/java/org/hibernate/Criteria.java create mode 100644 hibernate-core/src/main/java/org/hibernate/annotations/Remove.java delete mode 100644 hibernate-core/src/main/java/org/hibernate/ejb/HibernateQuery.java delete mode 100644 hibernate-core/src/main/java/org/hibernate/engine/loading/internal/CollectionLoadContext.java delete mode 100644 hibernate-core/src/main/java/org/hibernate/engine/loading/internal/EntityLoadContext.java delete mode 100644 hibernate-core/src/main/java/org/hibernate/engine/loading/internal/LoadContexts.java delete mode 100644 hibernate-core/src/main/java/org/hibernate/engine/loading/internal/LoadingCollectionEntry.java delete mode 100644 hibernate-core/src/main/java/org/hibernate/engine/loading/internal/package-info.java delete mode 100644 hibernate-core/src/main/java/org/hibernate/engine/query/spi/HQLQueryPlan.java delete mode 100644 hibernate-core/src/main/java/org/hibernate/internal/CriteriaImpl.java create mode 100644 hibernate-core/src/main/java/org/hibernate/internal/util/streams/GenericArrayCollector.java create mode 100644 hibernate-core/src/main/java/org/hibernate/internal/util/streams/StingArrayCollector.java create mode 100644 hibernate-core/src/main/java/org/hibernate/internal/util/streams/StreamUtils.java delete mode 100755 hibernate-core/src/main/java/org/hibernate/jpa/HibernateQuery.java delete mode 100644 hibernate-core/src/main/java/org/hibernate/jpa/spi/CriteriaQueryTupleTransformer.java create mode 100644 hibernate-core/src/main/java/org/hibernate/loader/internal/MultiIdEntityLoaderStandardImpl.java create mode 100644 hibernate-core/src/main/java/org/hibernate/loader/internal/NaturalIdLoaderStandardImpl.java rename hibernate-core/src/main/java/org/hibernate/{query/sqm/mutation/spi/idtable/BeforeUseAction.java => loader/internal/Preparable.java} (61%) create mode 100644 hibernate-core/src/main/java/org/hibernate/loader/internal/SingleIdEntityLoaderProvidedQueryImpl.java create mode 100644 hibernate-core/src/main/java/org/hibernate/loader/internal/SingleIdEntityLoaderStandardImpl.java create mode 100644 hibernate-core/src/main/java/org/hibernate/loader/spi/InternalFetchProfile.java create mode 100644 hibernate-core/src/main/java/org/hibernate/loader/spi/Loadable.java rename hibernate-core/src/main/java/org/hibernate/{query/sqm/mutation/spi/idtable/AfterUseAction.java => loader/spi/Loader.java} (58%) create mode 100644 hibernate-core/src/main/java/org/hibernate/loader/spi/MultiIdEntityLoader.java create mode 100644 hibernate-core/src/main/java/org/hibernate/loader/spi/NaturalIdLoader.java create mode 100644 hibernate-core/src/main/java/org/hibernate/loader/spi/SingleEntityLoader.java create mode 100644 hibernate-core/src/main/java/org/hibernate/loader/spi/SingleIdEntityLoader.java create mode 100644 hibernate-core/src/main/java/org/hibernate/loader/spi/SingleUniqueKeyEntityLoader.java delete mode 100644 hibernate-core/src/main/java/org/hibernate/query/sqm/consume/internal/SqmConsumeHelper.java delete mode 100644 hibernate-core/src/main/java/org/hibernate/query/sqm/consume/spi/BaseSqmToSqlAstConverter.java delete mode 100644 hibernate-core/src/main/java/org/hibernate/query/sqm/consume/spi/SqmExpressionInterpretation.java delete mode 100644 hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/internal/SqmIdSelectGenerator.java delete mode 100644 hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/internal/SqmMutationStrategyHelper.java delete mode 100644 hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/cte/AbstractCteMutationHandler.java delete mode 100644 hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/cte/CteBasedMutationStrategy.java delete mode 100644 hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/cte/CteDeleteHandlerImpl.java delete mode 100644 hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/cte/CteTable.java delete mode 100644 hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/cte/CteTableColumn.java delete mode 100644 hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/cte/CteTableGroup.java delete mode 100644 hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/cte/CteTableReference.java delete mode 100644 hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/cte/CteUpdateHandlerImpl.java delete mode 100644 hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/cte/package-info.java delete mode 100644 hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/idtable/AbstractTableBasedHandler.java delete mode 100644 hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/idtable/AbstractTableBasedMutationStrategy.java delete mode 100644 hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/idtable/GlobalTempTableExporter.java delete mode 100644 hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/idtable/GlobalTemporaryTableStrategy.java delete mode 100644 hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/idtable/IdTable.java delete mode 100644 hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/idtable/IdTableColumn.java delete mode 100644 hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/idtable/IdTableExporterImpl.java delete mode 100644 hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/idtable/IdTableGroup.java delete mode 100644 hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/idtable/IdTableHelper.java delete mode 100644 hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/idtable/IdTableManagementTransactionality.java delete mode 100644 hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/idtable/IdTableReference.java delete mode 100644 hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/idtable/IdTableSessionUidColumn.java delete mode 100644 hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/idtable/IdTableSupport.java delete mode 100644 hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/idtable/LocalTempTableExporter.java delete mode 100644 hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/idtable/LocalTemporaryTableStrategy.java delete mode 100644 hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/idtable/PersistentTableSessionUidSupport.java delete mode 100644 hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/idtable/PersistentTableStrategy.java delete mode 100644 hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/idtable/SessionUidSupport.java delete mode 100644 hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/idtable/StandardIdTableSupport.java delete mode 100644 hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/idtable/TableBasedDeleteHandlerImpl.java delete mode 100644 hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/idtable/TableBasedUpdateHandlerImpl.java delete mode 100644 hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/idtable/package-info.java delete mode 100644 hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/inline/AbstractInlineHandler.java delete mode 100644 hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/inline/InlineDeleteHandler.java delete mode 100644 hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/inline/InlineMutationStrategy.java delete mode 100644 hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/inline/package-info.java delete mode 100644 hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/simple/SimpleDeleteHandler.java delete mode 100644 hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/simple/SimpleSqmMutationStrategy.java delete mode 100644 hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/simple/SimpleUpdateHandler.java delete mode 100644 hibernate-core/src/main/java/org/hibernate/query/sqm/produce/function/internal/SelfRenderingFunctionSqlAstExpression.java create mode 100644 hibernate-core/src/main/java/org/hibernate/sql/ast/tree/from/TableReference.java create mode 100644 hibernate-core/src/main/java/org/hibernate/sql/ast/tree/from/TableReferenceJoin.java create mode 100644 hibernate-core/src/main/java/org/hibernate/sql/results/internal/JdbcValuesSourceProcessingStateStandardImpl.java create mode 100644 hibernate-core/src/main/java/org/hibernate/sql/results/internal/StandardJdbcValuesMapping.java create mode 100644 hibernate-core/src/main/java/org/hibernate/sql/results/internal/TupleElementImpl.java create mode 100644 hibernate-core/src/main/java/org/hibernate/sql/results/internal/TupleImpl.java create mode 100644 hibernate-core/src/main/java/org/hibernate/sql/results/internal/domain/ArrayInitializer.java create mode 100644 hibernate-core/src/main/java/org/hibernate/sql/results/spi/CollectionInitializer.java create mode 100644 hibernate-core/src/main/java/org/hibernate/sql/results/spi/CompositeInitializer.java create mode 100644 hibernate-core/src/main/java/org/hibernate/tool/hbm2ddl/SqlStatementParserListenerImpl.java create mode 100644 hibernate-core/src/main/java/org/hibernate/tuple/Instantiator.java diff --git a/documentation/src/test/java/org/hibernate/userguide/proxy/tuplizer/DynamicEmbeddableTuplizer.java b/documentation/src/test/java/org/hibernate/userguide/proxy/tuplizer/DynamicEmbeddableTuplizer.java index 326b099d5d..932021beb6 100644 --- a/documentation/src/test/java/org/hibernate/userguide/proxy/tuplizer/DynamicEmbeddableTuplizer.java +++ b/documentation/src/test/java/org/hibernate/userguide/proxy/tuplizer/DynamicEmbeddableTuplizer.java @@ -8,7 +8,7 @@ //$Id$ package org.hibernate.userguide.proxy.tuplizer; import org.hibernate.mapping.Component; -import org.hibernate.metamodel.spi.Instantiator; +import org.hibernate.tuple.Instantiator; import org.hibernate.tuple.component.PojoComponentTuplizer; /** diff --git a/documentation/src/test/java/org/hibernate/userguide/proxy/tuplizer/DynamicEntityTuplizer.java b/documentation/src/test/java/org/hibernate/userguide/proxy/tuplizer/DynamicEntityTuplizer.java index 647782e276..cbb364986d 100644 --- a/documentation/src/test/java/org/hibernate/userguide/proxy/tuplizer/DynamicEntityTuplizer.java +++ b/documentation/src/test/java/org/hibernate/userguide/proxy/tuplizer/DynamicEntityTuplizer.java @@ -10,7 +10,7 @@ import org.hibernate.mapping.PersistentClass; import org.hibernate.property.access.spi.Getter; import org.hibernate.property.access.spi.Setter; import org.hibernate.proxy.ProxyFactory; -import org.hibernate.metamodel.spi.Instantiator; +import org.hibernate.tuple.Instantiator; import org.hibernate.tuple.entity.EntityMetamodel; import org.hibernate.tuple.entity.PojoEntityTuplizer; diff --git a/documentation/src/test/java/org/hibernate/userguide/proxy/tuplizer/DynamicInstantiator.java b/documentation/src/test/java/org/hibernate/userguide/proxy/tuplizer/DynamicInstantiator.java index c735d3755f..820c6305b8 100644 --- a/documentation/src/test/java/org/hibernate/userguide/proxy/tuplizer/DynamicInstantiator.java +++ b/documentation/src/test/java/org/hibernate/userguide/proxy/tuplizer/DynamicInstantiator.java @@ -11,7 +11,7 @@ package org.hibernate.userguide.proxy.tuplizer; import java.io.Serializable; import org.hibernate.HibernateException; -import org.hibernate.metamodel.spi.Instantiator; +import org.hibernate.tuple.Instantiator; /** * @author Emmanuel Bernard diff --git a/documentation/src/test/java/org/hibernate/userguide/sql/SQLTest.java b/documentation/src/test/java/org/hibernate/userguide/sql/SQLTest.java index dec186e2a2..78c90496df 100644 --- a/documentation/src/test/java/org/hibernate/userguide/sql/SQLTest.java +++ b/documentation/src/test/java/org/hibernate/userguide/sql/SQLTest.java @@ -13,7 +13,6 @@ import java.time.ZoneOffset; import java.util.List; import javax.persistence.PersistenceException; -import org.hibernate.Criteria; import org.hibernate.Session; import org.hibernate.dialect.H2Dialect; import org.hibernate.dialect.Oracle8iDialect; @@ -38,8 +37,6 @@ import org.hibernate.testing.RequiresDialect; import org.junit.Before; import org.junit.Test; -import org.jboss.logging.Logger; - import static org.hibernate.testing.junit4.ExtraAssertions.assertTyping; import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; import static org.junit.Assert.assertEquals; diff --git a/hibernate-c3p0/src/test/java/org/hibernate/test/c3p0/StatementCacheTest.java b/hibernate-c3p0/src/test/java/org/hibernate/test/c3p0/StatementCacheTest.java index 479f50279f..938bf97937 100644 --- a/hibernate-c3p0/src/test/java/org/hibernate/test/c3p0/StatementCacheTest.java +++ b/hibernate-c3p0/src/test/java/org/hibernate/test/c3p0/StatementCacheTest.java @@ -8,7 +8,6 @@ package org.hibernate.test.c3p0; import java.util.List; -import org.hibernate.Criteria; import org.hibernate.Session; import org.junit.Assert; diff --git a/hibernate-core/src/main/java/org/hibernate/CacheMode.java b/hibernate-core/src/main/java/org/hibernate/CacheMode.java index 8e4a0f73eb..96f91c6a35 100755 --- a/hibernate-core/src/main/java/org/hibernate/CacheMode.java +++ b/hibernate-core/src/main/java/org/hibernate/CacheMode.java @@ -7,6 +7,8 @@ package org.hibernate; import java.util.Locale; +import javax.persistence.CacheRetrieveMode; +import javax.persistence.CacheStoreMode; /** * Controls how the session interacts with the second-level cache and query cache. @@ -19,37 +21,44 @@ public enum CacheMode { /** * The session may read items from the cache, and add items to the cache. */ - NORMAL( true, true ), + NORMAL( CacheStoreMode.USE, CacheRetrieveMode.USE ), /** * The session will never interact with the cache, except to invalidate * cache items when updates occur. */ - IGNORE( false, false ), + IGNORE( CacheStoreMode.BYPASS, CacheRetrieveMode.BYPASS ), /** * The session may read items from the cache, but will not add items, * except to invalidate items when updates occur. */ - GET( false, true ), + GET( CacheStoreMode.BYPASS, CacheRetrieveMode.USE ), /** * The session will never read items from the cache, but will add items * to the cache as it reads them from the database. */ - PUT( true, false ), + PUT( CacheStoreMode.USE, CacheRetrieveMode.BYPASS ), /** * The session will never read items from the cache, but will add items * to the cache as it reads them from the database. In this mode, the * effect of hibernate.cache.use_minimal_puts is bypassed, in * order to force a cache refresh. */ - REFRESH( true, false ); + REFRESH( CacheStoreMode.REFRESH, CacheRetrieveMode.BYPASS ); + private final CacheStoreMode storeMode; + private final CacheRetrieveMode retrieveMode; - private final boolean isPutEnabled; - private final boolean isGetEnabled; + CacheMode(CacheStoreMode storeMode, CacheRetrieveMode retrieveMode) { + this.storeMode = storeMode; + this.retrieveMode = retrieveMode; + } - private CacheMode( boolean isPutEnabled, boolean isGetEnabled) { - this.isPutEnabled = isPutEnabled; - this.isGetEnabled = isGetEnabled; + public CacheStoreMode getJpaStoreMode() { + return storeMode; + } + + public CacheRetrieveMode getJpaRetrieveMode() { + return retrieveMode; } /** @@ -58,7 +67,7 @@ public enum CacheMode { * @return {@code true} if cache reads are allowed; {@code false} otherwise. */ public boolean isGetEnabled() { - return isGetEnabled; + return retrieveMode == CacheRetrieveMode.USE; } /** @@ -67,7 +76,7 @@ public enum CacheMode { * @return {@code true} if cache writes are allowed; {@code false} otherwise. */ public boolean isPutEnabled() { - return isPutEnabled; + return storeMode == CacheStoreMode.USE || storeMode == CacheStoreMode.REFRESH; } /** @@ -91,4 +100,34 @@ public enum CacheMode { throw new MappingException( "Unknown Cache Mode: " + setting ); } } + + public static CacheMode fromJpaModes(CacheRetrieveMode retrieveMode, CacheStoreMode storeMode) { + if ( storeMode == null ) { + storeMode = CacheStoreMode.BYPASS; + } + + if ( retrieveMode == null ) { + retrieveMode = CacheRetrieveMode.BYPASS; + } + + switch ( storeMode ) { + case BYPASS: { + return retrieveMode == CacheRetrieveMode.USE + ? GET + : IGNORE; + } + case REFRESH: { + // technically should combo `CacheStoreMode#REFRESH` and `CacheRetrieveMode#USE` be illegal? + return REFRESH; + } + case USE: { + return retrieveMode == CacheRetrieveMode.USE + ? NORMAL + : PUT; + } + default: { + throw new UnsupportedOperationException( "Unrecognized CacheStoreMode : " + storeMode ); + } + } + } } diff --git a/hibernate-core/src/main/java/org/hibernate/Criteria.java b/hibernate-core/src/main/java/org/hibernate/Criteria.java deleted file mode 100644 index 3487995ccc..0000000000 --- a/hibernate-core/src/main/java/org/hibernate/Criteria.java +++ /dev/null @@ -1,566 +0,0 @@ -/* - * Hibernate, Relational Persistence for Idiomatic Java - * - * License: GNU Lesser General Public License (LGPL), version 2.1 or later. - * See the lgpl.txt file in the root directory or . - */ -package org.hibernate; - -import java.util.List; - -import org.hibernate.criterion.CriteriaSpecification; -import org.hibernate.criterion.Criterion; -import org.hibernate.criterion.Order; -import org.hibernate.criterion.Projection; -import org.hibernate.sql.JoinType; -import org.hibernate.transform.ResultTransformer; - - -/** - * Criteria is a simplified API for retrieving entities - * by composing Criterion objects. This is a very - * convenient approach for functionality like "search" screens - * where there is a variable number of conditions to be placed - * upon the result set.
- *
- * The Session is a factory for Criteria. - * Criterion instances are usually obtained via - * the factory methods on Restrictions. eg. - *
- * List cats = session.createCriteria(Cat.class)
- *     .add( Restrictions.like("name", "Iz%") )
- *     .add( Restrictions.gt( "weight", new Float(minWeight) ) )
- *     .addOrder( Order.asc("age") )
- *     .list();
- * 
- * You may navigate associations using createAlias() or - * createCriteria(). - *
- * List cats = session.createCriteria(Cat.class)
- *     .createCriteria("kittens")
- *         .add( Restrictions.like("name", "Iz%") )
- *     .list();
- * 
- *
- * List cats = session.createCriteria(Cat.class)
- *     .createAlias("kittens", "kit")
- *     .add( Restrictions.like("kit.name", "Iz%") )
- *     .list();
- * 
- * You may specify projection and aggregation using Projection - * instances obtained via the factory methods on Projections. - *
- * List cats = session.createCriteria(Cat.class)
- *     .setProjection( Projections.projectionList()
- *         .add( Projections.rowCount() )
- *         .add( Projections.avg("weight") )
- *         .add( Projections.max("weight") )
- *         .add( Projections.min("weight") )
- *         .add( Projections.groupProperty("color") )
- *     )
- *     .addOrder( Order.asc("color") )
- *     .list();
- * 
- * - * @see Session#createCriteria(java.lang.Class) - * @see org.hibernate.criterion.Restrictions - * @see org.hibernate.criterion.Projections - * @see org.hibernate.criterion.Order - * @see org.hibernate.criterion.Criterion - * @see org.hibernate.criterion.Projection - * @see org.hibernate.criterion.DetachedCriteria a disconnected version of this API - * @author Gavin King - */ -public interface Criteria extends CriteriaSpecification { - - /** - * Get the alias of the entity encapsulated by this criteria instance. - * - * @return The alias for the encapsulated entity. - */ - public String getAlias(); - - /** - * Used to specify that the query results will be a projection (scalar in - * nature). Implicitly specifies the {@link #PROJECTION} result transformer. - *

- * The individual components contained within the given - * {@link Projection projection} determines the overall "shape" of the - * query result. - * - * @param projection The projection representing the overall "shape" of the - * query results. - * @return this (for method chaining) - */ - public Criteria setProjection(Projection projection); - - /** - * Add a {@link Criterion restriction} to constrain the results to be - * retrieved. - * - * @param criterion The {@link Criterion criterion} object representing the - * restriction to be applied. - * @return this (for method chaining) - */ - public Criteria add(Criterion criterion); - - /** - * Add an {@link Order ordering} to the result set. - * - * @param order The {@link Order order} object representing an ordering - * to be applied to the results. - * @return this (for method chaining) - */ - public Criteria addOrder(Order order); - - /** - * Specify an association fetching strategy for an association or a - * collection of values. - * - * @param associationPath a dot separated property path - * @param mode The fetch mode for the referenced association - * - * @return this (for method chaining) - * - * @throws HibernateException Indicates a problem applying the given fetch mode - */ - public Criteria setFetchMode(String associationPath, FetchMode mode) throws HibernateException; - - /** - * Set the lock mode of the current entity. - * - * @param lockMode The lock mode to be applied - * - * @return this (for method chaining) - */ - public Criteria setLockMode(LockMode lockMode); - - /** - * Set the lock mode of the aliased entity. - * - * @param alias The previously assigned alias representing the entity to - * which the given lock mode should apply. - * @param lockMode The lock mode to be applied - * - * @return this (for method chaining) - */ - public Criteria setLockMode(String alias, LockMode lockMode); - - /** - * Join an association, assigning an alias to the joined association. - *

- * Functionally equivalent to {@link #createAlias(String, String, JoinType )} using - * {@link JoinType#INNER_JOIN} for the joinType. - * - * @param associationPath A dot-separated property path - * @param alias The alias to assign to the joined association (for later reference). - * - * @return this (for method chaining) - * - * @throws HibernateException Indicates a problem creating the sub criteria - */ - public Criteria createAlias(String associationPath, String alias) throws HibernateException; - - /** - * Join an association using the specified join-type, assigning an alias - * to the joined association. - *

- * The joinType is expected to be one of {@link JoinType#INNER_JOIN} (the default), - * {@link JoinType#FULL_JOIN}, or {@link JoinType#LEFT_OUTER_JOIN}. - * - * @param associationPath A dot-separated property path - * @param alias The alias to assign to the joined association (for later reference). - * @param joinType The type of join to use. - * - * @return this (for method chaining) - * - * @throws HibernateException Indicates a problem creating the sub criteria - */ - public Criteria createAlias(String associationPath, String alias, JoinType joinType) throws HibernateException; - - /** - * Join an association using the specified join-type, assigning an alias - * to the joined association. - *

- * The joinType is expected to be one of {@link #INNER_JOIN} (the default), - * {@link #FULL_JOIN}, or {@link #LEFT_JOIN}. - * - * @param associationPath A dot-separated property path - * @param alias The alias to assign to the joined association (for later reference). - * @param joinType The type of join to use. - * - * @return this (for method chaining) - * - * @throws HibernateException Indicates a problem creating the sub criteria - * @deprecated use {@link #createAlias(String, String, org.hibernate.sql.JoinType)} - */ - @Deprecated - public Criteria createAlias(String associationPath, String alias, int joinType) throws HibernateException; - - /** - * Join an association using the specified join-type, assigning an alias - * to the joined association. - *

- * The joinType is expected to be one of {@link JoinType#INNER_JOIN} (the default), - * {@link JoinType#FULL_JOIN}, or {@link JoinType#LEFT_OUTER_JOIN}. - * - * @param associationPath A dot-separated property path - * @param alias The alias to assign to the joined association (for later reference). - * @param joinType The type of join to use. - * @param withClause The criteria to be added to the join condition (ON clause) - * - * @return this (for method chaining) - * - * @throws HibernateException Indicates a problem creating the sub criteria - */ - public Criteria createAlias(String associationPath, String alias, JoinType joinType, Criterion withClause) throws HibernateException; - - /** - * Join an association using the specified join-type, assigning an alias - * to the joined association. - *

- * The joinType is expected to be one of {@link #INNER_JOIN} (the default), - * {@link #FULL_JOIN}, or {@link #LEFT_JOIN}. - * - * @param associationPath A dot-separated property path - * @param alias The alias to assign to the joined association (for later reference). - * @param joinType The type of join to use. - * @param withClause The criteria to be added to the join condition (ON clause) - * - * @return this (for method chaining) - * - * @throws HibernateException Indicates a problem creating the sub criteria - * @deprecated use {@link #createAlias(String, String, JoinType, Criterion)} - */ - @Deprecated - public Criteria createAlias(String associationPath, String alias, int joinType, Criterion withClause) throws HibernateException; - - /** - * Create a new Criteria, "rooted" at the associated entity. - *

- * Functionally equivalent to {@link #createCriteria(String, org.hibernate.sql.JoinType)} using - * {@link JoinType#INNER_JOIN} for the joinType. - * - * @param associationPath A dot-separated property path - * - * @return the created "sub criteria" - * - * @throws HibernateException Indicates a problem creating the sub criteria - */ - public Criteria createCriteria(String associationPath) throws HibernateException; - - /** - * Create a new Criteria, "rooted" at the associated entity, using the - * specified join type. - * - * @param associationPath A dot-separated property path - * @param joinType The type of join to use. - * - * @return the created "sub criteria" - * - * @throws HibernateException Indicates a problem creating the sub criteria - */ - public Criteria createCriteria(String associationPath, JoinType joinType) throws HibernateException; - - /** - * Create a new Criteria, "rooted" at the associated entity, using the - * specified join type. - * - * @param associationPath A dot-separated property path - * @param joinType The type of join to use. - * - * @return the created "sub criteria" - * - * @throws HibernateException Indicates a problem creating the sub criteria - * @deprecated use {@link #createAlias(String, String, org.hibernate.sql.JoinType)} - */ - @Deprecated - public Criteria createCriteria(String associationPath, int joinType) throws HibernateException; - - /** - * Create a new Criteria, "rooted" at the associated entity, - * assigning the given alias. - *

- * Functionally equivalent to {@link #createCriteria(String, String, org.hibernate.sql.JoinType)} using - * {@link JoinType#INNER_JOIN} for the joinType. - * - * @param associationPath A dot-separated property path - * @param alias The alias to assign to the joined association (for later reference). - * - * @return the created "sub criteria" - * - * @throws HibernateException Indicates a problem creating the sub criteria - */ - public Criteria createCriteria(String associationPath, String alias) throws HibernateException; - - /** - * Create a new Criteria, "rooted" at the associated entity, - * assigning the given alias and using the specified join type. - * - * @param associationPath A dot-separated property path - * @param alias The alias to assign to the joined association (for later reference). - * @param joinType The type of join to use. - * - * @return the created "sub criteria" - * - * @throws HibernateException Indicates a problem creating the sub criteria - */ - public Criteria createCriteria(String associationPath, String alias, JoinType joinType) throws HibernateException; - - /** - * Create a new Criteria, "rooted" at the associated entity, - * assigning the given alias and using the specified join type. - * - * @param associationPath A dot-separated property path - * @param alias The alias to assign to the joined association (for later reference). - * @param joinType The type of join to use. - * - * @return the created "sub criteria" - * - * @throws HibernateException Indicates a problem creating the sub criteria - * @deprecated use {@link #createCriteria(String, org.hibernate.sql.JoinType)} - */ - @Deprecated - public Criteria createCriteria(String associationPath, String alias, int joinType) throws HibernateException; - - - /** - * Create a new Criteria, "rooted" at the associated entity, - * assigning the given alias and using the specified join type. - * - * @param associationPath A dot-separated property path - * @param alias The alias to assign to the joined association (for later reference). - * @param joinType The type of join to use. - * @param withClause The criteria to be added to the join condition (ON clause) - * - * @return the created "sub criteria" - * - * @throws HibernateException Indicates a problem creating the sub criteria - */ - public Criteria createCriteria(String associationPath, String alias, JoinType joinType, Criterion withClause) throws HibernateException; - - /** - * Create a new Criteria, "rooted" at the associated entity, - * assigning the given alias and using the specified join type. - * - * @param associationPath A dot-separated property path - * @param alias The alias to assign to the joined association (for later reference). - * @param joinType The type of join to use. - * @param withClause The criteria to be added to the join condition (ON clause) - * - * @return the created "sub criteria" - * - * @throws HibernateException Indicates a problem creating the sub criteria - * @deprecated use {@link #createCriteria(String, String, org.hibernate.sql.JoinType, org.hibernate.criterion.Criterion)} - */ - @Deprecated - public Criteria createCriteria(String associationPath, String alias, int joinType, Criterion withClause) throws HibernateException; - - /** - * Set a strategy for handling the query results. This determines the - * "shape" of the query result. - * - * @param resultTransformer The transformer to apply - * @return this (for method chaining) - * - * @see #ROOT_ENTITY - * @see #DISTINCT_ROOT_ENTITY - * @see #ALIAS_TO_ENTITY_MAP - * @see #PROJECTION - */ - public Criteria setResultTransformer(ResultTransformer resultTransformer); - - /** - * Set a limit upon the number of objects to be retrieved. - * - * @param maxResults the maximum number of results - * @return this (for method chaining) - */ - public Criteria setMaxResults(int maxResults); - - /** - * Set the first result to be retrieved. - * - * @param firstResult the first result to retrieve, numbered from 0 - * @return this (for method chaining) - */ - public Criteria setFirstResult(int firstResult); - - /** - * Was the read-only/modifiable mode explicitly initialized? - * - * @return true, the read-only/modifiable mode was explicitly initialized; false, otherwise. - * - * @see Criteria#setReadOnly(boolean) - */ - public boolean isReadOnlyInitialized(); - - /** - * Should entities and proxies loaded by this Criteria be put in read-only mode? If the - * read-only/modifiable setting was not initialized, then the default - * read-only/modifiable setting for the persistence context is returned instead. - * @see Criteria#setReadOnly(boolean) - * @see org.hibernate.engine.spi.PersistenceContext#isDefaultReadOnly() - * - * The read-only/modifiable setting has no impact on entities/proxies returned by the - * Criteria that existed in the session before the Criteria was executed. - * - * @return true, entities and proxies loaded by the criteria will be put in read-only mode - * false, entities and proxies loaded by the criteria will be put in modifiable mode - * @throws IllegalStateException if isReadOnlyInitialized() returns false - * and this Criteria is not associated with a session. - * @see Criteria#isReadOnlyInitialized() - */ - public boolean isReadOnly(); - - /** - * Set the read-only/modifiable mode for entities and proxies - * loaded by this Criteria. This setting overrides the default setting - * for the persistence context. - * @see org.hibernate.engine.spi.PersistenceContext#isDefaultReadOnly() - * - * To set the default read-only/modifiable setting used for - * entities and proxies that are loaded into the session: - * @see org.hibernate.engine.spi.PersistenceContext#setDefaultReadOnly(boolean) - * @see org.hibernate.Session#setDefaultReadOnly(boolean) - * - * Read-only entities are not dirty-checked and snapshots of persistent - * state are not maintained. Read-only entities can be modified, but - * changes are not persisted. - * - * When a proxy is initialized, the loaded entity will have the same - * read-only/modifiable setting as the uninitialized - * proxy has, regardless of the session's current setting. - * - * The read-only/modifiable setting has no impact on entities/proxies - * returned by the criteria that existed in the session before the criteria was executed. - * - * @param readOnly true, entities and proxies loaded by the criteria will be put in read-only mode - * false, entities and proxies loaded by the criteria will be put in modifiable mode - * @return {@code this}, for method chaining - */ - public Criteria setReadOnly(boolean readOnly); - - /** - * Set a fetch size for the underlying JDBC query. - * - * @param fetchSize the fetch size - * @return this (for method chaining) - * - * @see java.sql.Statement#setFetchSize - */ - public Criteria setFetchSize(int fetchSize); - - /** - * Set a timeout for the underlying JDBC query. - * - * @param timeout The timeout value to apply. - * @return this (for method chaining) - * - * @see java.sql.Statement#setQueryTimeout - */ - public Criteria setTimeout(int timeout); - - /** - * Enable caching of this query result, provided query caching is enabled - * for the underlying session factory. - * - * @param cacheable Should the result be considered cacheable; default is - * to not cache (false). - * @return this (for method chaining) - */ - public Criteria setCacheable(boolean cacheable); - - /** - * Set the name of the cache region to use for query result caching. - * - * @param cacheRegion the name of a query cache region, or null - * for the default query cache - * @return this (for method chaining) - * - * @see #setCacheable - */ - public Criteria setCacheRegion(String cacheRegion); - - /** - * Add a comment to the generated SQL. - * - * @param comment a human-readable string - * @return this (for method chaining) - */ - public Criteria setComment(String comment); - - - /** - * Add a DB query hint to the SQL. These differ from JPA's {@link javax.persistence.QueryHint}, which is specific - * to the JPA implementation and ignores DB vendor-specific hints. Instead, these are intended solely for the - * vendor-specific hints, such as Oracle's optimizers. Multiple query hints are supported; the Dialect will - * determine concatenation and placement. - * - * @param hint The database specific query hint to add. - * @return this (for method chaining) - */ - public Criteria addQueryHint(String hint); - - /** - * Override the flush mode for this particular query. - * - * @param flushMode The flush mode to use. - * @return this (for method chaining) - */ - public Criteria setFlushMode(FlushMode flushMode); - - /** - * Override the cache mode for this particular query. - * - * @param cacheMode The cache mode to use. - * @return this (for method chaining) - */ - public Criteria setCacheMode(CacheMode cacheMode); - - /** - * Get the results. - * - * @return The list of matched query results. - * - * @throws HibernateException Indicates a problem either translating the criteria to SQL, - * exeucting the SQL or processing the SQL results. - */ - public List list() throws HibernateException; - - /** - * Get the results as an instance of {@link ScrollableResults}. - * - * @return The {@link ScrollableResults} representing the matched - * query results. - * - * @throws HibernateException Indicates a problem either translating the criteria to SQL, - * exeucting the SQL or processing the SQL results. - */ - public ScrollableResults scroll() throws HibernateException; - - /** - * Get the results as an instance of {@link ScrollableResults} based on the - * given scroll mode. - * - * @param scrollMode Indicates the type of underlying database cursor to - * request. - * - * @return The {@link ScrollableResults} representing the matched - * query results. - * - * @throws HibernateException Indicates a problem either translating the criteria to SQL, - * exeucting the SQL or processing the SQL results. - */ - public ScrollableResults scroll(ScrollMode scrollMode) throws HibernateException; - - /** - * Convenience method to return a single instance that matches - * the query, or null if the query returns no results. - * - * @return the single result or null - * @throws HibernateException if there is more than one matching result - */ - public Object uniqueResult() throws HibernateException; - -} diff --git a/hibernate-core/src/main/java/org/hibernate/StatelessSession.java b/hibernate-core/src/main/java/org/hibernate/StatelessSession.java index 8a15cf1f75..e8d87b6209 100755 --- a/hibernate-core/src/main/java/org/hibernate/StatelessSession.java +++ b/hibernate-core/src/main/java/org/hibernate/StatelessSession.java @@ -10,6 +10,7 @@ import java.io.Closeable; import java.io.Serializable; import java.sql.Connection; +import org.hibernate.annotations.Remove; import org.hibernate.query.NativeQuery; /** @@ -173,6 +174,8 @@ public interface StatelessSession extends SharedSessionContract, AutoCloseable, @Deprecated Connection connection(); - @Override - NativeQuery createSQLQuery(String queryString); + @Remove + default <@Remove T> NativeQuery createSQLQuery(String queryString) { + return createNativeQuery( queryString ); + } } diff --git a/hibernate-core/src/main/java/org/hibernate/annotations/Remove.java b/hibernate-core/src/main/java/org/hibernate/annotations/Remove.java new file mode 100644 index 0000000000..a120471b77 --- /dev/null +++ b/hibernate-core/src/main/java/org/hibernate/annotations/Remove.java @@ -0,0 +1,33 @@ +/* + * Hibernate, Relational Persistence for Idiomatic Java + * + * License: GNU Lesser General Public License (LGPL), version 2.1 or later + * See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html + */ +package org.hibernate.annotations; + +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +import static java.lang.annotation.ElementType.CONSTRUCTOR; +import static java.lang.annotation.ElementType.FIELD; +import static java.lang.annotation.ElementType.METHOD; +import static java.lang.annotation.ElementType.PACKAGE; +import static java.lang.annotation.ElementType.TYPE; +import static java.lang.annotation.ElementType.TYPE_PARAMETER; +import static java.lang.annotation.ElementType.TYPE_USE; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +/** + * Indicates that the annotated element is planned for removal as part + * of a deprecation lifecycle. + * + * @apiNote Intended for use at development-time for developers to better understand + * the lifecycle of the annotated element. + * + * @author Steve Ebersole + */ +@Target({METHOD, FIELD, TYPE, PACKAGE, CONSTRUCTOR, TYPE_PARAMETER, TYPE_USE}) +@Retention(RUNTIME) +public @interface Remove { +} diff --git a/hibernate-core/src/main/java/org/hibernate/boot/internal/SessionFactoryBuilderImpl.java b/hibernate-core/src/main/java/org/hibernate/boot/internal/SessionFactoryBuilderImpl.java index bc8a5f7928..724e62e2b9 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/internal/SessionFactoryBuilderImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/internal/SessionFactoryBuilderImpl.java @@ -27,7 +27,6 @@ import org.hibernate.boot.spi.SessionFactoryOptions; import org.hibernate.cache.spi.TimestampsCacheFactory; import org.hibernate.context.spi.CurrentTenantIdentifierResolver; import org.hibernate.dialect.function.SQLFunction; -import org.hibernate.hql.spi.id.MultiTableBulkIdStrategy; import org.hibernate.internal.SessionFactoryImpl; import org.hibernate.loader.BatchFetchStyle; import org.hibernate.proxy.EntityNotFoundDelegate; diff --git a/hibernate-core/src/main/java/org/hibernate/boot/internal/SessionFactoryOptionsBuilder.java b/hibernate-core/src/main/java/org/hibernate/boot/internal/SessionFactoryOptionsBuilder.java index 52cf2f8ce5..537a668a99 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/internal/SessionFactoryOptionsBuilder.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/internal/SessionFactoryOptionsBuilder.java @@ -45,7 +45,6 @@ import org.hibernate.engine.config.internal.ConfigurationServiceImpl; import org.hibernate.engine.config.spi.ConfigurationService; import org.hibernate.engine.jdbc.env.spi.ExtractedDatabaseMetaData; import org.hibernate.engine.jdbc.spi.JdbcServices; -import org.hibernate.hql.spi.id.MultiTableBulkIdStrategy; import org.hibernate.id.uuid.LocalObjectUuidHelper; import org.hibernate.internal.CoreMessageLogger; import org.hibernate.internal.log.DeprecationLogger; @@ -187,7 +186,6 @@ public class SessionFactoryOptionsBuilder implements SessionFactoryOptions { private EntityTuplizerFactory entityTuplizerFactory = new EntityTuplizerFactory(); private boolean checkNullability; private boolean initializeLazyStateOutsideTransactions; - private MultiTableBulkIdStrategy multiTableBulkIdStrategy; private TempTableDdlTransactionHandling tempTableDdlTransactionHandling; private BatchFetchStyle batchFetchStyle; private boolean delayBatchFetchLoaderCreations; @@ -334,12 +332,6 @@ public class SessionFactoryOptionsBuilder implements SessionFactoryOptions { configurationSettings.get( MULTI_TENANT_IDENTIFIER_RESOLVER ) ); - this.multiTableBulkIdStrategy = strategySelector.resolveDefaultableStrategy( - MultiTableBulkIdStrategy.class, - configurationSettings.get( HQL_BULK_ID_STRATEGY ), - jdbcServices.getJdbcEnvironment().getDialect().getDefaultMultiTableBulkIdStrategy() - ); - this.batchFetchStyle = BatchFetchStyle.interpret( configurationSettings.get( BATCH_FETCH_STYLE ) ); this.delayBatchFetchLoaderCreations = cfgService.getSetting( DELAY_ENTITY_LOADER_CREATIONS, BOOLEAN, true ); this.defaultBatchFetchSize = ConfigurationHelper.getInt( DEFAULT_BATCH_FETCH_SIZE, configurationSettings, -1 ); @@ -797,11 +789,6 @@ public class SessionFactoryOptionsBuilder implements SessionFactoryOptions { return initializeLazyStateOutsideTransactions; } - @Override - public MultiTableBulkIdStrategy getMultiTableBulkIdStrategy() { - return multiTableBulkIdStrategy; - } - @Override public TempTableDdlTransactionHandling getTempTableDdlTransactionHandling() { return tempTableDdlTransactionHandling; @@ -1168,10 +1155,6 @@ public class SessionFactoryOptionsBuilder implements SessionFactoryOptions { this.entityTuplizerFactory.registerDefaultTuplizerClass( entityMode, tuplizerClass ); } - public void applyMultiTableBulkIdStrategy(MultiTableBulkIdStrategy strategy) { - this.multiTableBulkIdStrategy = strategy; - } - public void applyTempTableDdlTransactionHandling(TempTableDdlTransactionHandling handling) { this.tempTableDdlTransactionHandling = handling; } diff --git a/hibernate-core/src/main/java/org/hibernate/boot/registry/selector/internal/StrategySelectorBuilder.java b/hibernate-core/src/main/java/org/hibernate/boot/registry/selector/internal/StrategySelectorBuilder.java index 4ddf9c3c41..090849c61a 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/registry/selector/internal/StrategySelectorBuilder.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/registry/selector/internal/StrategySelectorBuilder.java @@ -89,14 +89,6 @@ import org.hibernate.engine.transaction.jta.platform.internal.WebSphereJtaPlatfo import org.hibernate.engine.transaction.jta.platform.internal.WebSphereLibertyJtaPlatform; import org.hibernate.engine.transaction.jta.platform.internal.WeblogicJtaPlatform; import org.hibernate.engine.transaction.jta.platform.spi.JtaPlatform; -import org.hibernate.event.internal.EntityCopyAllowedLoggedObserver; -import org.hibernate.event.internal.EntityCopyAllowedObserver; -import org.hibernate.event.internal.EntityCopyNotAllowedObserver; -import org.hibernate.event.spi.EntityCopyObserver; -import org.hibernate.hql.spi.id.MultiTableBulkIdStrategy; -import org.hibernate.hql.spi.id.global.GlobalTemporaryTableBulkIdStrategy; -import org.hibernate.hql.spi.id.local.LocalTemporaryTableBulkIdStrategy; -import org.hibernate.hql.spi.id.persistent.PersistentTableBulkIdStrategy; import org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorBuilderImpl; import org.hibernate.resource.transaction.backend.jta.internal.JtaTransactionCoordinatorBuilderImpl; import org.hibernate.resource.transaction.spi.TransactionCoordinatorBuilder; diff --git a/hibernate-core/src/main/java/org/hibernate/boot/spi/AbstractDelegatingSessionFactoryBuilder.java b/hibernate-core/src/main/java/org/hibernate/boot/spi/AbstractDelegatingSessionFactoryBuilder.java index a706120947..26fbe5a94e 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/spi/AbstractDelegatingSessionFactoryBuilder.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/spi/AbstractDelegatingSessionFactoryBuilder.java @@ -23,7 +23,6 @@ import org.hibernate.boot.TempTableDdlTransactionHandling; import org.hibernate.cache.spi.TimestampsCacheFactory; import org.hibernate.context.spi.CurrentTenantIdentifierResolver; import org.hibernate.dialect.function.SQLFunction; -import org.hibernate.hql.spi.id.MultiTableBulkIdStrategy; import org.hibernate.loader.BatchFetchStyle; import org.hibernate.proxy.EntityNotFoundDelegate; import org.hibernate.resource.jdbc.spi.PhysicalConnectionHandlingMode; diff --git a/hibernate-core/src/main/java/org/hibernate/boot/spi/AbstractDelegatingSessionFactoryOptions.java b/hibernate-core/src/main/java/org/hibernate/boot/spi/AbstractDelegatingSessionFactoryOptions.java index a3de3a7963..e3a9c94004 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/spi/AbstractDelegatingSessionFactoryOptions.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/spi/AbstractDelegatingSessionFactoryOptions.java @@ -25,7 +25,6 @@ import org.hibernate.cache.spi.TimestampsCacheFactory; import org.hibernate.cfg.BaselineSessionEventsListenerBuilder; import org.hibernate.context.spi.CurrentTenantIdentifierResolver; import org.hibernate.dialect.function.SQLFunction; -import org.hibernate.hql.spi.id.MultiTableBulkIdStrategy; import org.hibernate.jpa.spi.JpaCompliance; import org.hibernate.loader.BatchFetchStyle; import org.hibernate.proxy.EntityNotFoundDelegate; @@ -157,11 +156,6 @@ public class AbstractDelegatingSessionFactoryOptions implements SessionFactoryOp return delegate.isInitializeLazyStateOutsideTransactionsEnabled(); } - @Override - public MultiTableBulkIdStrategy getMultiTableBulkIdStrategy() { - return delegate.getMultiTableBulkIdStrategy(); - } - @Override public TempTableDdlTransactionHandling getTempTableDdlTransactionHandling() { return delegate.getTempTableDdlTransactionHandling(); diff --git a/hibernate-core/src/main/java/org/hibernate/boot/spi/SessionFactoryOptions.java b/hibernate-core/src/main/java/org/hibernate/boot/spi/SessionFactoryOptions.java index 32d9ea6c83..9e31012fb5 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/spi/SessionFactoryOptions.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/spi/SessionFactoryOptions.java @@ -156,8 +156,6 @@ public interface SessionFactoryOptions { boolean isInitializeLazyStateOutsideTransactionsEnabled(); - MultiTableBulkIdStrategy getMultiTableBulkIdStrategy(); - TempTableDdlTransactionHandling getTempTableDdlTransactionHandling(); BatchFetchStyle getBatchFetchStyle(); diff --git a/hibernate-core/src/main/java/org/hibernate/cfg/Configuration.java b/hibernate-core/src/main/java/org/hibernate/cfg/Configuration.java index ea8b3b349f..194b2a6091 100644 --- a/hibernate-core/src/main/java/org/hibernate/cfg/Configuration.java +++ b/hibernate-core/src/main/java/org/hibernate/cfg/Configuration.java @@ -43,6 +43,7 @@ import org.hibernate.cfg.annotations.NamedEntityGraphDefinition; import org.hibernate.boot.internal.NamedProcedureCallDefinitionImpl; import org.hibernate.context.spi.CurrentTenantIdentifierResolver; import org.hibernate.dialect.function.SQLFunction; +import org.hibernate.query.sql.spi.NamedNativeQueryMemento; import org.hibernate.query.sql.spi.ResultSetMappingDescriptor; import org.hibernate.query.hql.internal.NamedHqlQueryMementoImpl; import org.hibernate.internal.CoreLogging; @@ -91,10 +92,10 @@ public class Configuration { // used during processing mappings private ImplicitNamingStrategy implicitNamingStrategy; private PhysicalNamingStrategy physicalNamingStrategy; - private List basicTypes = new ArrayList(); - private List typeContributorRegistrations = new ArrayList(); + private List basicTypes = new ArrayList<>(); + private List typeContributorRegistrations = new ArrayList<>(); private Map namedQueries; - private Map namedSqlQueries; + private Map namedSqlQueries; private Map namedProcedureCallMap; private Map sqlResultSetMappings; private Map namedEntityGraphMap; @@ -130,10 +131,10 @@ public class Configuration { } private static BootstrapServiceRegistry getBootstrapRegistry(ServiceRegistry serviceRegistry) { - if ( BootstrapServiceRegistry.class.isInstance( serviceRegistry ) ) { + if ( serviceRegistry instanceof BootstrapServiceRegistry ) { return (BootstrapServiceRegistry) serviceRegistry; } - else if ( StandardServiceRegistry.class.isInstance( serviceRegistry ) ) { + else if ( serviceRegistry instanceof StandardServiceRegistry ) { final StandardServiceRegistry ssr = (StandardServiceRegistry) serviceRegistry; return (BootstrapServiceRegistry) ssr.getParentServiceRegistry(); } @@ -148,11 +149,11 @@ public class Configuration { protected void reset() { implicitNamingStrategy = ImplicitNamingStrategyJpaCompliantImpl.INSTANCE; physicalNamingStrategy = PhysicalNamingStrategyStandardImpl.INSTANCE; - namedQueries = new HashMap(); - namedSqlQueries = new HashMap(); - sqlResultSetMappings = new HashMap(); - namedEntityGraphMap = new HashMap(); - namedProcedureCallMap = new HashMap( ); + namedQueries = new HashMap<>(); + namedSqlQueries = new HashMap<>(); + sqlResultSetMappings = new HashMap<>(); + namedEntityGraphMap = new HashMap<>(); + namedProcedureCallMap = new HashMap<>(); standardServiceRegistryBuilder = new StandardServiceRegistryBuilder( bootstrapServiceRegistry ); entityTuplizerFactory = new EntityTuplizerFactory(); diff --git a/hibernate-core/src/main/java/org/hibernate/cfg/Settings.java b/hibernate-core/src/main/java/org/hibernate/cfg/Settings.java index c2d590d984..ee0e533be0 100644 --- a/hibernate-core/src/main/java/org/hibernate/cfg/Settings.java +++ b/hibernate-core/src/main/java/org/hibernate/cfg/Settings.java @@ -19,8 +19,6 @@ import org.hibernate.boot.spi.SessionFactoryOptions; import org.hibernate.cache.spi.RegionFactory; import org.hibernate.cache.spi.TimestampsCacheFactory; import org.hibernate.engine.transaction.jta.platform.spi.JtaPlatform; -import org.hibernate.hql.spi.QueryTranslatorFactory; -import org.hibernate.hql.spi.id.MultiTableBulkIdStrategy; import org.hibernate.loader.BatchFetchStyle; import org.hibernate.tuple.entity.EntityTuplizerFactory; @@ -171,10 +169,6 @@ public final class Settings { return sessionFactoryOptions.isInitializeLazyStateOutsideTransactionsEnabled(); } - public MultiTableBulkIdStrategy getMultiTableBulkIdStrategy() { - return sessionFactoryOptions.getMultiTableBulkIdStrategy(); - } - public BatchFetchStyle getBatchFetchStyle() { return sessionFactoryOptions.getBatchFetchStyle(); } @@ -308,10 +302,6 @@ public final class Settings { return sessionFactoryOptions.getServiceRegistry().getService( JtaPlatform.class ); } - public QueryTranslatorFactory getQueryTranslatorFactory() { - return sessionFactoryOptions.getServiceRegistry().getService( QueryTranslatorFactory.class ); - } - public void setCheckNullability(boolean enabled) { // ugh, used by org.hibernate.cfg.beanvalidation.TypeSafeActivator as part of the BV integrator sessionFactoryOptions.setCheckNullability( enabled ); diff --git a/hibernate-core/src/main/java/org/hibernate/cfg/annotations/CollectionBinder.java b/hibernate-core/src/main/java/org/hibernate/cfg/annotations/CollectionBinder.java index ec8a65fbf9..04dfb45900 100644 --- a/hibernate-core/src/main/java/org/hibernate/cfg/annotations/CollectionBinder.java +++ b/hibernate-core/src/main/java/org/hibernate/cfg/annotations/CollectionBinder.java @@ -32,7 +32,6 @@ import javax.persistence.OneToMany; import org.hibernate.AnnotationException; import org.hibernate.FetchMode; -import org.hibernate.HibernateException; import org.hibernate.MappingException; import org.hibernate.annotations.BatchSize; import org.hibernate.annotations.Cache; @@ -89,11 +88,9 @@ import org.hibernate.cfg.PropertyHolderBuilder; import org.hibernate.cfg.PropertyInferredData; import org.hibernate.cfg.PropertyPreloadedData; import org.hibernate.cfg.SecondPass; -import org.hibernate.criterion.Junction; import org.hibernate.engine.config.spi.ConfigurationService; import org.hibernate.engine.spi.ExecuteUpdateResultCheckStyle; import org.hibernate.internal.CoreMessageLogger; -import org.hibernate.internal.util.ReflectHelper; import org.hibernate.internal.util.StringHelper; import org.hibernate.internal.util.config.ConfigurationHelper; import org.hibernate.mapping.Any; diff --git a/hibernate-core/src/main/java/org/hibernate/collection/internal/AbstractBagSemantics.java b/hibernate-core/src/main/java/org/hibernate/collection/internal/AbstractBagSemantics.java index 3e518f0c3a..55e929ee48 100644 --- a/hibernate-core/src/main/java/org/hibernate/collection/internal/AbstractBagSemantics.java +++ b/hibernate-core/src/main/java/org/hibernate/collection/internal/AbstractBagSemantics.java @@ -33,13 +33,11 @@ public abstract class AbstractBagSemantics> implements C } @Override - @SuppressWarnings("unchecked") - public Iterator getElementIterator(B rawCollection) { + public Iterator getElementIterator(B rawCollection) { if ( rawCollection == null ) { return null; } - - return (Iterator) rawCollection.iterator(); + return rawCollection.iterator(); } @Override diff --git a/hibernate-core/src/main/java/org/hibernate/collection/internal/StandardArraySemantics.java b/hibernate-core/src/main/java/org/hibernate/collection/internal/StandardArraySemantics.java index 873732a057..4699b07c1c 100644 --- a/hibernate-core/src/main/java/org/hibernate/collection/internal/StandardArraySemantics.java +++ b/hibernate-core/src/main/java/org/hibernate/collection/internal/StandardArraySemantics.java @@ -10,10 +10,10 @@ import java.util.Arrays; import java.util.Iterator; import java.util.function.Consumer; -import org.hibernate.collection.spi.CollectionClassification; import org.hibernate.collection.spi.CollectionSemantics; import org.hibernate.collection.spi.PersistentCollection; import org.hibernate.engine.spi.SharedSessionContractImplementor; +import org.hibernate.metamodel.CollectionClassification; import org.hibernate.persister.collection.CollectionPersister; /** @@ -52,7 +52,7 @@ public class StandardArraySemantics implements CollectionSemantics { Object key, CollectionPersister collectionDescriptor, SharedSessionContractImplementor session) { - return new PersistentArrayHolder( key, session, collectionDescriptor ); + return new PersistentArrayHolder( session, collectionDescriptor ); } @Override @@ -60,13 +60,12 @@ public class StandardArraySemantics implements CollectionSemantics { Object rawCollection, CollectionPersister collectionDescriptor, SharedSessionContractImplementor session) { - return new PersistentArrayHolder( session, collectionDescriptor, rawCollection ); + return new PersistentArrayHolder( session, rawCollection ); } @Override - @SuppressWarnings("unchecked") - public Iterator getElementIterator(Object[] rawCollection) { - return (Iterator) Arrays.stream( rawCollection ).iterator(); + public Iterator getElementIterator(Object[] rawCollection) { + return Arrays.stream( rawCollection ).iterator(); } @Override diff --git a/hibernate-core/src/main/java/org/hibernate/collection/internal/StandardBagSemantics.java b/hibernate-core/src/main/java/org/hibernate/collection/internal/StandardBagSemantics.java index 0c3edc3b87..aeba48da18 100644 --- a/hibernate-core/src/main/java/org/hibernate/collection/internal/StandardBagSemantics.java +++ b/hibernate-core/src/main/java/org/hibernate/collection/internal/StandardBagSemantics.java @@ -8,9 +8,9 @@ package org.hibernate.collection.internal; import java.util.Collection; -import org.hibernate.collection.spi.CollectionClassification; import org.hibernate.collection.spi.PersistentCollection; import org.hibernate.engine.spi.SharedSessionContractImplementor; +import org.hibernate.metamodel.CollectionClassification; import org.hibernate.persister.collection.CollectionPersister; /** @@ -37,16 +37,15 @@ public class StandardBagSemantics extends AbstractBagSemantics> { Object key, CollectionPersister collectionDescriptor, SharedSessionContractImplementor session) { - return new PersistentBag( session, collectionDescriptor ); + return new PersistentBag( session ); } @Override - @SuppressWarnings("unchecked") - public PersistentCollection wrap( + public PersistentCollection wrap( Object rawCollection, CollectionPersister collectionDescriptor, SharedSessionContractImplementor session) { - return new PersistentBag( session, collectionDescriptor, (Collection) rawCollection ); + return new PersistentBag( session, (Collection) rawCollection ); } } diff --git a/hibernate-core/src/main/java/org/hibernate/collection/internal/StandardIdentifierBagSemantics.java b/hibernate-core/src/main/java/org/hibernate/collection/internal/StandardIdentifierBagSemantics.java index 56de1ad941..9003edebe5 100644 --- a/hibernate-core/src/main/java/org/hibernate/collection/internal/StandardIdentifierBagSemantics.java +++ b/hibernate-core/src/main/java/org/hibernate/collection/internal/StandardIdentifierBagSemantics.java @@ -7,10 +7,11 @@ package org.hibernate.collection.internal; import java.util.Collection; +import java.util.Iterator; -import org.hibernate.collection.spi.CollectionClassification; import org.hibernate.collection.spi.PersistentCollection; import org.hibernate.engine.spi.SharedSessionContractImplementor; +import org.hibernate.metamodel.CollectionClassification; import org.hibernate.persister.collection.CollectionPersister; /** @@ -33,20 +34,18 @@ public class StandardIdentifierBagSemantics extends AbstractBagSemantics instantiateWrapper( + public PersistentCollection instantiateWrapper( Object key, CollectionPersister collectionDescriptor, SharedSessionContractImplementor session) { - return new PersistentIdentifierBag( session, collectionDescriptor, key ); + return new PersistentIdentifierBag( session ); } @Override - @SuppressWarnings("unchecked") - public PersistentCollection wrap( + public PersistentCollection wrap( Object rawCollection, CollectionPersister collectionDescriptor, SharedSessionContractImplementor session) { - return new PersistentIdentifierBag( session, collectionDescriptor, (Collection) rawCollection ); + return new PersistentIdentifierBag( session, (Collection) rawCollection ); } } diff --git a/hibernate-core/src/main/java/org/hibernate/collection/internal/StandardListSemantics.java b/hibernate-core/src/main/java/org/hibernate/collection/internal/StandardListSemantics.java index 79aaf4c20b..21622bbafb 100644 --- a/hibernate-core/src/main/java/org/hibernate/collection/internal/StandardListSemantics.java +++ b/hibernate-core/src/main/java/org/hibernate/collection/internal/StandardListSemantics.java @@ -10,11 +10,11 @@ import java.util.Iterator; import java.util.List; import java.util.function.Consumer; -import org.hibernate.collection.spi.CollectionClassification; import org.hibernate.collection.spi.CollectionSemantics; import org.hibernate.collection.spi.PersistentCollection; import org.hibernate.engine.spi.SharedSessionContractImplementor; import org.hibernate.internal.util.collections.CollectionHelper; +import org.hibernate.metamodel.CollectionClassification; import org.hibernate.persister.collection.CollectionPersister; /** @@ -44,7 +44,6 @@ public class StandardListSemantics implements CollectionSemantics { } @Override - @SuppressWarnings("unchecked") public Iterator getElementIterator(List rawCollection) { return rawCollection.iterator(); } @@ -60,15 +59,14 @@ public class StandardListSemantics implements CollectionSemantics { Object key, CollectionPersister collectionDescriptor, SharedSessionContractImplementor session) { - return new PersistentList( session, collectionDescriptor, key ); + return new PersistentList( session ); } @Override - @SuppressWarnings("unchecked") - public PersistentCollection wrap( + public PersistentCollection wrap( Object rawCollection, CollectionPersister collectionDescriptor, SharedSessionContractImplementor session) { - return new PersistentList( session, collectionDescriptor, (List) rawCollection ); + return new PersistentList( session, (List) rawCollection ); } } diff --git a/hibernate-core/src/main/java/org/hibernate/collection/internal/StandardMapSemantics.java b/hibernate-core/src/main/java/org/hibernate/collection/internal/StandardMapSemantics.java index a95bd24f7f..86b3436241 100644 --- a/hibernate-core/src/main/java/org/hibernate/collection/internal/StandardMapSemantics.java +++ b/hibernate-core/src/main/java/org/hibernate/collection/internal/StandardMapSemantics.java @@ -8,10 +8,10 @@ package org.hibernate.collection.internal; import java.util.Map; -import org.hibernate.collection.spi.CollectionClassification; import org.hibernate.collection.spi.PersistentCollection; import org.hibernate.engine.spi.SharedSessionContractImplementor; import org.hibernate.internal.util.collections.CollectionHelper; +import org.hibernate.metamodel.CollectionClassification; import org.hibernate.persister.collection.CollectionPersister; /** @@ -41,18 +41,18 @@ public class StandardMapSemantics extends AbstractMapSemantics> { } @Override - public PersistentCollection instantiateWrapper( + public PersistentCollection instantiateWrapper( Object key, CollectionPersister collectionDescriptor, SharedSessionContractImplementor session) { - return new PersistentMap( session, collectionDescriptor, key ); + return new PersistentMap( session ); } @Override - public PersistentCollection wrap( + public PersistentCollection wrap( Object rawCollection, CollectionPersister collectionDescriptor, SharedSessionContractImplementor session) { - return new PersistentMap( session, collectionDescriptor, (Map) rawCollection ); + return new PersistentMap( session, (Map) rawCollection ); } } diff --git a/hibernate-core/src/main/java/org/hibernate/collection/internal/StandardOrderedMapSemantics.java b/hibernate-core/src/main/java/org/hibernate/collection/internal/StandardOrderedMapSemantics.java index ee2b8da382..82486edc47 100644 --- a/hibernate-core/src/main/java/org/hibernate/collection/internal/StandardOrderedMapSemantics.java +++ b/hibernate-core/src/main/java/org/hibernate/collection/internal/StandardOrderedMapSemantics.java @@ -10,10 +10,10 @@ import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; -import org.hibernate.collection.spi.CollectionClassification; import org.hibernate.collection.spi.PersistentCollection; import org.hibernate.engine.spi.SharedSessionContractImplementor; -import org.hibernate.metamodel.model.mapping.PersistentCollectionDescriptor; +import org.hibernate.metamodel.CollectionClassification; +import org.hibernate.persister.collection.CollectionPersister; /** * @author Steve Ebersole @@ -35,24 +35,24 @@ public class StandardOrderedMapSemantics extends AbstractMapSemantics instantiateRaw( int anticipatedSize, - PersistentCollectionDescriptor collectionDescriptor) { + CollectionPersister collectionDescriptor) { return anticipatedSize < 1 ? new LinkedHashMap<>() : new LinkedHashMap<>( anticipatedSize ); } @Override - public PersistentCollection instantiateWrapper( + public PersistentCollection instantiateWrapper( Object key, - PersistentCollectionDescriptor, E> collectionDescriptor, + CollectionPersister collectionDescriptor, SharedSessionContractImplementor session) { - return new PersistentMap<>( session, collectionDescriptor, key ); + return new PersistentMap( session ); } @Override - public PersistentCollection wrap( + public PersistentCollection wrap( Object rawCollection, - PersistentCollectionDescriptor, E> collectionDescriptor, + CollectionPersister collectionDescriptor, SharedSessionContractImplementor session) { - return new PersistentMap<>( session, collectionDescriptor, (Map) rawCollection ); + return new PersistentMap( session, (Map) rawCollection ); } @Override diff --git a/hibernate-core/src/main/java/org/hibernate/collection/internal/StandardOrderedSetSemantics.java b/hibernate-core/src/main/java/org/hibernate/collection/internal/StandardOrderedSetSemantics.java index f438694f4b..90a3e9d182 100644 --- a/hibernate-core/src/main/java/org/hibernate/collection/internal/StandardOrderedSetSemantics.java +++ b/hibernate-core/src/main/java/org/hibernate/collection/internal/StandardOrderedSetSemantics.java @@ -10,10 +10,10 @@ import java.util.Iterator; import java.util.LinkedHashSet; import java.util.Set; -import org.hibernate.collection.spi.CollectionClassification; import org.hibernate.collection.spi.PersistentCollection; import org.hibernate.engine.spi.SharedSessionContractImplementor; -import org.hibernate.metamodel.model.mapping.PersistentCollectionDescriptor; +import org.hibernate.metamodel.CollectionClassification; +import org.hibernate.persister.collection.CollectionPersister; /** * @author Steve Ebersole @@ -35,24 +35,24 @@ public class StandardOrderedSetSemantics extends AbstractSetSemantics instantiateRaw( int anticipatedSize, - PersistentCollectionDescriptor collectionDescriptor) { + CollectionPersister collectionDescriptor) { return anticipatedSize < 1 ? new LinkedHashSet() : new LinkedHashSet<>( anticipatedSize ); } @Override - public PersistentCollection instantiateWrapper( + public PersistentCollection instantiateWrapper( Object key, - PersistentCollectionDescriptor, E> collectionDescriptor, + CollectionPersister collectionDescriptor, SharedSessionContractImplementor session) { - return new PersistentSet( session, collectionDescriptor, key ); + return new PersistentSet( session ); } @Override - public PersistentCollection wrap( + public PersistentCollection wrap( Object rawCollection, - PersistentCollectionDescriptor, E> collectionDescriptor, + CollectionPersister collectionDescriptor, SharedSessionContractImplementor session) { - return new PersistentSet( session, collectionDescriptor, (Set) rawCollection ); + return new PersistentSet( session, (Set) rawCollection ); } @Override diff --git a/hibernate-core/src/main/java/org/hibernate/collection/internal/StandardSetSemantics.java b/hibernate-core/src/main/java/org/hibernate/collection/internal/StandardSetSemantics.java index e584d21b90..6f3c5a71c2 100644 --- a/hibernate-core/src/main/java/org/hibernate/collection/internal/StandardSetSemantics.java +++ b/hibernate-core/src/main/java/org/hibernate/collection/internal/StandardSetSemantics.java @@ -9,9 +9,8 @@ package org.hibernate.collection.internal; import java.util.HashSet; import java.util.Set; -import org.hibernate.collection.spi.CollectionClassification; -import org.hibernate.collection.spi.PersistentCollection; import org.hibernate.engine.spi.SharedSessionContractImplementor; +import org.hibernate.metamodel.CollectionClassification; import org.hibernate.persister.collection.CollectionPersister; /** @@ -39,21 +38,19 @@ public class StandardSetSemantics extends AbstractSetSemantics> { } @Override - public PersistentCollection instantiateWrapper( + public PersistentSet instantiateWrapper( Object key, CollectionPersister collectionDescriptor, SharedSessionContractImplementor session) { - //noinspection unchecked - return new PersistentSet( session, collectionDescriptor, key ); + return new PersistentSet( session ); } @Override - public PersistentCollection wrap( + public PersistentSet wrap( Object rawCollection, CollectionPersister collectionDescriptor, SharedSessionContractImplementor session) { - //noinspection unchecked - return new PersistentSet( session, collectionDescriptor, (Set) rawCollection ); + return new PersistentSet( session, (Set) rawCollection ); } } diff --git a/hibernate-core/src/main/java/org/hibernate/collection/internal/StandardSortedMapSemantics.java b/hibernate-core/src/main/java/org/hibernate/collection/internal/StandardSortedMapSemantics.java index acf045cd0f..5e78995f36 100644 --- a/hibernate-core/src/main/java/org/hibernate/collection/internal/StandardSortedMapSemantics.java +++ b/hibernate-core/src/main/java/org/hibernate/collection/internal/StandardSortedMapSemantics.java @@ -9,9 +9,9 @@ package org.hibernate.collection.internal; import java.util.SortedMap; import java.util.TreeMap; -import org.hibernate.collection.spi.CollectionClassification; import org.hibernate.collection.spi.PersistentCollection; import org.hibernate.engine.spi.SharedSessionContractImplementor; +import org.hibernate.metamodel.CollectionClassification; import org.hibernate.persister.collection.CollectionPersister; /** @@ -35,24 +35,22 @@ public class StandardSortedMapSemantics extends AbstractMapSemantics instantiateRaw( int anticipatedSize, CollectionPersister collectionDescriptor) { - return new TreeMap<>( collectionDescriptor.getSortingComparator() ); + return new TreeMap( collectionDescriptor.getSortingComparator() ); } @Override - @SuppressWarnings("unchecked") public PersistentCollection instantiateWrapper( Object key, CollectionPersister collectionDescriptor, SharedSessionContractImplementor session) { - return new PersistentSortedMap( session, collectionDescriptor, key ); + return new PersistentSortedMap( session ); } @Override - @SuppressWarnings("unchecked") public PersistentCollection wrap( Object rawCollection, CollectionPersister collectionDescriptor, SharedSessionContractImplementor session) { - return new PersistentSortedMap( session, collectionDescriptor, (SortedMap) rawCollection ); + return new PersistentSortedMap( session, (SortedMap) rawCollection ); } } diff --git a/hibernate-core/src/main/java/org/hibernate/collection/internal/StandardSortedSetSemantics.java b/hibernate-core/src/main/java/org/hibernate/collection/internal/StandardSortedSetSemantics.java index a9cb8508ac..546d635aa9 100644 --- a/hibernate-core/src/main/java/org/hibernate/collection/internal/StandardSortedSetSemantics.java +++ b/hibernate-core/src/main/java/org/hibernate/collection/internal/StandardSortedSetSemantics.java @@ -10,9 +10,9 @@ import java.util.Iterator; import java.util.SortedSet; import java.util.TreeSet; -import org.hibernate.collection.spi.CollectionClassification; import org.hibernate.collection.spi.PersistentCollection; import org.hibernate.engine.spi.SharedSessionContractImplementor; +import org.hibernate.metamodel.CollectionClassification; import org.hibernate.persister.collection.CollectionPersister; /** @@ -36,30 +36,27 @@ public class StandardSortedSetSemantics extends AbstractSetSemantics( collectionDescriptor.getSortingComparator() ); + return new TreeSet( collectionDescriptor.getSortingComparator() ); } @Override - @SuppressWarnings("unchecked") public PersistentCollection instantiateWrapper( Object key, CollectionPersister collectionDescriptor, SharedSessionContractImplementor session) { - return new PersistentSortedSet( session, collectionDescriptor, key ); + return new PersistentSortedSet( session ); } @Override - @SuppressWarnings("unchecked") public PersistentCollection wrap( Object rawCollection, CollectionPersister collectionDescriptor, SharedSessionContractImplementor session) { - return new PersistentSortedSet( session, collectionDescriptor, (SortedSet) rawCollection ); + return new PersistentSortedSet( session, (SortedSet) rawCollection ); } @Override - @SuppressWarnings("unchecked") - public Iterator getElementIterator(SortedSet rawCollection) { - return (Iterator) rawCollection.iterator(); + public Iterator getElementIterator(SortedSet rawCollection) { + return rawCollection.iterator(); } } diff --git a/hibernate-core/src/main/java/org/hibernate/collection/spi/CollectionSemantics.java b/hibernate-core/src/main/java/org/hibernate/collection/spi/CollectionSemantics.java index d23d76f1a3..33078e0dd4 100644 --- a/hibernate-core/src/main/java/org/hibernate/collection/spi/CollectionSemantics.java +++ b/hibernate-core/src/main/java/org/hibernate/collection/spi/CollectionSemantics.java @@ -28,21 +28,21 @@ public interface CollectionSemantics { */ CollectionClassification getCollectionClassification(); - C instantiateRaw( + C instantiateRaw( int anticipatedSize, CollectionPersister collectionDescriptor); - PersistentCollection instantiateWrapper( + PersistentCollection instantiateWrapper( Object key, CollectionPersister collectionDescriptor, SharedSessionContractImplementor session); - PersistentCollection wrap( + PersistentCollection wrap( Object rawCollection, CollectionPersister collectionDescriptor, SharedSessionContractImplementor session); - Iterator getElementIterator(C rawCollection); + Iterator getElementIterator(C rawCollection); void visitElements(C rawCollection, Consumer action); } diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/AbstractTransactSQLDialect.java b/hibernate-core/src/main/java/org/hibernate/dialect/AbstractTransactSQLDialect.java index 36f9cd928f..9c1c04a290 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/AbstractTransactSQLDialect.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/AbstractTransactSQLDialect.java @@ -24,10 +24,6 @@ import org.hibernate.dialect.function.StandardSQLFunction; import org.hibernate.dialect.function.VarArgsSQLFunction; import org.hibernate.dialect.identity.AbstractTransactSQLIdentityColumnSupport; import org.hibernate.dialect.identity.IdentityColumnSupport; -import org.hibernate.hql.spi.id.IdTableSupportStandardImpl; -import org.hibernate.hql.spi.id.MultiTableBulkIdStrategy; -import org.hibernate.hql.spi.id.local.AfterUseAction; -import org.hibernate.hql.spi.id.local.LocalTemporaryTableBulkIdStrategy; import org.hibernate.type.StandardBasicTypes; /** diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/Cache71Dialect.java b/hibernate-core/src/main/java/org/hibernate/dialect/Cache71Dialect.java index 652b7bb6ca..3270d836d1 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/Cache71Dialect.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/Cache71Dialect.java @@ -37,10 +37,6 @@ import org.hibernate.exception.internal.CacheSQLExceptionConversionDelegate; import org.hibernate.exception.spi.SQLExceptionConversionDelegate; import org.hibernate.exception.spi.TemplatedViolatedConstraintNameExtracter; import org.hibernate.exception.spi.ViolatedConstraintNameExtracter; -import org.hibernate.hql.spi.id.IdTableSupportStandardImpl; -import org.hibernate.hql.spi.id.MultiTableBulkIdStrategy; -import org.hibernate.hql.spi.id.global.GlobalTemporaryTableBulkIdStrategy; -import org.hibernate.hql.spi.id.local.AfterUseAction; import org.hibernate.persister.entity.Lockable; import org.hibernate.sql.CacheJoinFragment; import org.hibernate.sql.JoinFragment; diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/DB297Dialect.java b/hibernate-core/src/main/java/org/hibernate/dialect/DB297Dialect.java index e7841d2417..f098fac41c 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/DB297Dialect.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/DB297Dialect.java @@ -9,10 +9,6 @@ package org.hibernate.dialect; import java.sql.Types; import org.hibernate.dialect.function.DB2SubstringFunction; -import org.hibernate.hql.spi.id.IdTableSupportStandardImpl; -import org.hibernate.hql.spi.id.MultiTableBulkIdStrategy; -import org.hibernate.hql.spi.id.global.GlobalTemporaryTableBulkIdStrategy; -import org.hibernate.hql.spi.id.local.AfterUseAction; import org.hibernate.type.descriptor.sql.CharTypeDescriptor; import org.hibernate.type.descriptor.sql.ClobTypeDescriptor; import org.hibernate.type.descriptor.sql.SqlTypeDescriptor; diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/DerbyDialect.java b/hibernate-core/src/main/java/org/hibernate/dialect/DerbyDialect.java index 421a8085dd..1da5e5088e 100755 --- a/hibernate-core/src/main/java/org/hibernate/dialect/DerbyDialect.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/DerbyDialect.java @@ -21,10 +21,6 @@ import org.hibernate.dialect.pagination.LimitHelper; import org.hibernate.engine.jdbc.env.spi.IdentifierHelper; import org.hibernate.engine.jdbc.env.spi.IdentifierHelperBuilder; import org.hibernate.engine.spi.RowSelection; -import org.hibernate.hql.spi.id.IdTableSupportStandardImpl; -import org.hibernate.hql.spi.id.MultiTableBulkIdStrategy; -import org.hibernate.hql.spi.id.local.AfterUseAction; -import org.hibernate.hql.spi.id.local.LocalTemporaryTableBulkIdStrategy; import org.hibernate.internal.CoreMessageLogger; import org.hibernate.internal.util.ReflectHelper; import org.hibernate.sql.CaseFragment; diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/H2Dialect.java b/hibernate-core/src/main/java/org/hibernate/dialect/H2Dialect.java index 74a2e9b34b..17a5441bd6 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/H2Dialect.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/H2Dialect.java @@ -29,10 +29,6 @@ import org.hibernate.exception.LockAcquisitionException; import org.hibernate.exception.spi.SQLExceptionConversionDelegate; import org.hibernate.exception.spi.TemplatedViolatedConstraintNameExtracter; import org.hibernate.exception.spi.ViolatedConstraintNameExtracter; -import org.hibernate.hql.spi.id.IdTableSupportStandardImpl; -import org.hibernate.hql.spi.id.MultiTableBulkIdStrategy; -import org.hibernate.hql.spi.id.local.AfterUseAction; -import org.hibernate.hql.spi.id.local.LocalTemporaryTableBulkIdStrategy; import org.hibernate.internal.CoreMessageLogger; import org.hibernate.internal.util.JdbcExceptionHelper; import org.hibernate.internal.util.ReflectHelper; diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/HANAColumnStoreDialect.java b/hibernate-core/src/main/java/org/hibernate/dialect/HANAColumnStoreDialect.java index c1c1832220..f73b435b97 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/HANAColumnStoreDialect.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/HANAColumnStoreDialect.java @@ -9,10 +9,6 @@ package org.hibernate.dialect; import org.hibernate.dialect.function.SQLFunctionTemplate; import org.hibernate.dialect.function.StandardSQLFunction; import org.hibernate.dialect.function.VarArgsSQLFunction; -import org.hibernate.hql.spi.id.IdTableSupportStandardImpl; -import org.hibernate.hql.spi.id.MultiTableBulkIdStrategy; -import org.hibernate.hql.spi.id.global.GlobalTemporaryTableBulkIdStrategy; -import org.hibernate.hql.spi.id.local.AfterUseAction; import org.hibernate.type.StandardBasicTypes; /** diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/HANARowStoreDialect.java b/hibernate-core/src/main/java/org/hibernate/dialect/HANARowStoreDialect.java index dc87a92645..6ea774a07b 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/HANARowStoreDialect.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/HANARowStoreDialect.java @@ -6,11 +6,6 @@ */ package org.hibernate.dialect; -import org.hibernate.hql.spi.id.IdTableSupportStandardImpl; -import org.hibernate.hql.spi.id.MultiTableBulkIdStrategy; -import org.hibernate.hql.spi.id.global.GlobalTemporaryTableBulkIdStrategy; -import org.hibernate.hql.spi.id.local.AfterUseAction; - /** * An SQL dialect for the SAP HANA row store. *

diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/HSQLDialect.java b/hibernate-core/src/main/java/org/hibernate/dialect/HSQLDialect.java index 3c3c96d363..8040afd9e4 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/HSQLDialect.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/HSQLDialect.java @@ -40,11 +40,6 @@ import org.hibernate.engine.spi.RowSelection; import org.hibernate.engine.spi.SharedSessionContractImplementor; import org.hibernate.exception.spi.TemplatedViolatedConstraintNameExtracter; import org.hibernate.exception.spi.ViolatedConstraintNameExtracter; -import org.hibernate.hql.spi.id.IdTableSupportStandardImpl; -import org.hibernate.hql.spi.id.MultiTableBulkIdStrategy; -import org.hibernate.hql.spi.id.global.GlobalTemporaryTableBulkIdStrategy; -import org.hibernate.hql.spi.id.local.AfterUseAction; -import org.hibernate.hql.spi.id.local.LocalTemporaryTableBulkIdStrategy; import org.hibernate.internal.CoreMessageLogger; import org.hibernate.internal.util.JdbcExceptionHelper; import org.hibernate.internal.util.ReflectHelper; diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/InformixDialect.java b/hibernate-core/src/main/java/org/hibernate/dialect/InformixDialect.java index 96ea458be7..7de40be1ff 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/InformixDialect.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/InformixDialect.java @@ -23,10 +23,6 @@ import org.hibernate.dialect.unique.InformixUniqueDelegate; import org.hibernate.dialect.unique.UniqueDelegate; import org.hibernate.exception.spi.TemplatedViolatedConstraintNameExtracter; import org.hibernate.exception.spi.ViolatedConstraintNameExtracter; -import org.hibernate.hql.spi.id.IdTableSupportStandardImpl; -import org.hibernate.hql.spi.id.MultiTableBulkIdStrategy; -import org.hibernate.hql.spi.id.local.AfterUseAction; -import org.hibernate.hql.spi.id.local.LocalTemporaryTableBulkIdStrategy; import org.hibernate.internal.util.JdbcExceptionHelper; import org.hibernate.tool.schema.extract.internal.SequenceInformationExtractorInformixDatabaseImpl; import org.hibernate.tool.schema.extract.spi.SequenceInformationExtractor; diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/IngresDialect.java b/hibernate-core/src/main/java/org/hibernate/dialect/IngresDialect.java index 33affffe4b..ff1d028541 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/IngresDialect.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/IngresDialect.java @@ -16,10 +16,6 @@ import org.hibernate.dialect.function.VarArgsSQLFunction; import org.hibernate.dialect.pagination.FirstLimitHandler; import org.hibernate.dialect.pagination.LegacyFirstLimitHandler; import org.hibernate.dialect.pagination.LimitHandler; -import org.hibernate.hql.spi.id.IdTableSupportStandardImpl; -import org.hibernate.hql.spi.id.MultiTableBulkIdStrategy; -import org.hibernate.hql.spi.id.global.GlobalTemporaryTableBulkIdStrategy; -import org.hibernate.hql.spi.id.local.AfterUseAction; import org.hibernate.tool.schema.extract.internal.SequenceNameExtractorImpl; import org.hibernate.tool.schema.extract.spi.SequenceInformationExtractor; import org.hibernate.type.StandardBasicTypes; diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/MySQLDialect.java b/hibernate-core/src/main/java/org/hibernate/dialect/MySQLDialect.java index bb60c0f0e1..4aca11cc8c 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/MySQLDialect.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/MySQLDialect.java @@ -31,10 +31,6 @@ import org.hibernate.engine.spi.RowSelection; import org.hibernate.exception.LockAcquisitionException; import org.hibernate.exception.LockTimeoutException; import org.hibernate.exception.spi.SQLExceptionConversionDelegate; -import org.hibernate.hql.spi.id.IdTableSupportStandardImpl; -import org.hibernate.hql.spi.id.MultiTableBulkIdStrategy; -import org.hibernate.hql.spi.id.local.AfterUseAction; -import org.hibernate.hql.spi.id.local.LocalTemporaryTableBulkIdStrategy; import org.hibernate.internal.util.JdbcExceptionHelper; import org.hibernate.mapping.Column; import org.hibernate.type.StandardBasicTypes; diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/Oracle8iDialect.java b/hibernate-core/src/main/java/org/hibernate/dialect/Oracle8iDialect.java index 4a36a1c125..4a14f8aeba 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/Oracle8iDialect.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/Oracle8iDialect.java @@ -25,6 +25,7 @@ import org.hibernate.dialect.function.VarArgsSQLFunction; import org.hibernate.dialect.pagination.AbstractLimitHandler; import org.hibernate.dialect.pagination.LimitHandler; import org.hibernate.dialect.pagination.LimitHelper; +import org.hibernate.engine.spi.QueryParameters; import org.hibernate.engine.spi.RowSelection; import org.hibernate.exception.ConstraintViolationException; import org.hibernate.exception.LockAcquisitionException; @@ -32,10 +33,6 @@ import org.hibernate.exception.LockTimeoutException; import org.hibernate.exception.spi.SQLExceptionConversionDelegate; import org.hibernate.exception.spi.TemplatedViolatedConstraintNameExtracter; import org.hibernate.exception.spi.ViolatedConstraintNameExtracter; -import org.hibernate.hql.spi.id.IdTableSupportStandardImpl; -import org.hibernate.hql.spi.id.MultiTableBulkIdStrategy; -import org.hibernate.hql.spi.id.global.GlobalTemporaryTableBulkIdStrategy; -import org.hibernate.hql.spi.id.local.AfterUseAction; import org.hibernate.internal.util.JdbcExceptionHelper; import org.hibernate.procedure.internal.StandardCallableStatementSupport; import org.hibernate.procedure.spi.CallableStatementSupport; diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/Oracle9Dialect.java b/hibernate-core/src/main/java/org/hibernate/dialect/Oracle9Dialect.java index 1fe9a24a41..d9cbb13170 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/Oracle9Dialect.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/Oracle9Dialect.java @@ -14,10 +14,6 @@ import org.hibernate.dialect.function.StandardSQLFunction; import org.hibernate.dialect.function.VarArgsSQLFunction; import org.hibernate.exception.spi.TemplatedViolatedConstraintNameExtracter; import org.hibernate.exception.spi.ViolatedConstraintNameExtracter; -import org.hibernate.hql.spi.id.IdTableSupportStandardImpl; -import org.hibernate.hql.spi.id.MultiTableBulkIdStrategy; -import org.hibernate.hql.spi.id.global.GlobalTemporaryTableBulkIdStrategy; -import org.hibernate.hql.spi.id.local.AfterUseAction; import org.hibernate.internal.CoreMessageLogger; import org.hibernate.internal.util.JdbcExceptionHelper; import org.hibernate.tool.schema.extract.internal.SequenceInformationExtractorOracleDatabaseImpl; diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/PostgreSQL81Dialect.java b/hibernate-core/src/main/java/org/hibernate/dialect/PostgreSQL81Dialect.java index 4792de5252..334bfdb935 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/PostgreSQL81Dialect.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/PostgreSQL81Dialect.java @@ -34,10 +34,6 @@ import org.hibernate.exception.LockAcquisitionException; import org.hibernate.exception.spi.SQLExceptionConversionDelegate; import org.hibernate.exception.spi.TemplatedViolatedConstraintNameExtracter; import org.hibernate.exception.spi.ViolatedConstraintNameExtracter; -import org.hibernate.hql.spi.id.IdTableSupportStandardImpl; -import org.hibernate.hql.spi.id.MultiTableBulkIdStrategy; -import org.hibernate.hql.spi.id.local.AfterUseAction; -import org.hibernate.hql.spi.id.local.LocalTemporaryTableBulkIdStrategy; import org.hibernate.internal.util.JdbcExceptionHelper; import org.hibernate.procedure.internal.PostgresCallableStatementSupport; import org.hibernate.procedure.spi.CallableStatementSupport; diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/PostgreSQL82Dialect.java b/hibernate-core/src/main/java/org/hibernate/dialect/PostgreSQL82Dialect.java index 5199d26067..bfd5054ccf 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/PostgreSQL82Dialect.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/PostgreSQL82Dialect.java @@ -7,10 +7,6 @@ package org.hibernate.dialect; import org.hibernate.boot.model.TypeContributions; -import org.hibernate.hql.spi.id.IdTableSupportStandardImpl; -import org.hibernate.hql.spi.id.MultiTableBulkIdStrategy; -import org.hibernate.hql.spi.id.local.AfterUseAction; -import org.hibernate.hql.spi.id.local.LocalTemporaryTableBulkIdStrategy; import org.hibernate.service.ServiceRegistry; import org.hibernate.type.PostgresUUIDType; diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/SAPDBDialect.java b/hibernate-core/src/main/java/org/hibernate/dialect/SAPDBDialect.java index f8ef508156..639126ee0d 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/SAPDBDialect.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/SAPDBDialect.java @@ -14,10 +14,6 @@ import org.hibernate.dialect.function.NoArgSQLFunction; import org.hibernate.dialect.function.SQLFunctionTemplate; import org.hibernate.dialect.function.StandardSQLFunction; import org.hibernate.dialect.function.VarArgsSQLFunction; -import org.hibernate.hql.spi.id.IdTableSupportStandardImpl; -import org.hibernate.hql.spi.id.MultiTableBulkIdStrategy; -import org.hibernate.hql.spi.id.local.AfterUseAction; -import org.hibernate.hql.spi.id.local.LocalTemporaryTableBulkIdStrategy; import org.hibernate.sql.CaseFragment; import org.hibernate.sql.DecodeCaseFragment; import org.hibernate.tool.schema.extract.internal.SequenceInformationExtractorSAPDBDatabaseImpl; diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/Teradata14Dialect.java b/hibernate-core/src/main/java/org/hibernate/dialect/Teradata14Dialect.java index 56b9a9dfda..9744036649 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/Teradata14Dialect.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/Teradata14Dialect.java @@ -22,6 +22,7 @@ import org.hibernate.dialect.function.SQLFunctionTemplate; import org.hibernate.dialect.identity.IdentityColumnSupport; import org.hibernate.dialect.identity.Teradata14IdentityColumnSupport; import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment; +import org.hibernate.engine.spi.QueryParameters; import org.hibernate.exception.spi.TemplatedViolatedConstraintNameExtracter; import org.hibernate.exception.spi.ViolatedConstraintNameExtracter; import org.hibernate.mapping.Column; diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/TeradataDialect.java b/hibernate-core/src/main/java/org/hibernate/dialect/TeradataDialect.java index e27281c217..c89ffe73e5 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/TeradataDialect.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/TeradataDialect.java @@ -1,273 +1,268 @@ -/* - * Hibernate, Relational Persistence for Idiomatic Java - * - * License: GNU Lesser General Public License (LGPL), version 2.1 or later. - * See the lgpl.txt file in the root directory or . - */ -package org.hibernate.dialect; -import java.sql.Types; - -import org.hibernate.HibernateException; -import org.hibernate.cfg.Environment; -import org.hibernate.dialect.function.SQLFunctionTemplate; -import org.hibernate.dialect.function.VarArgsSQLFunction; -import org.hibernate.hql.spi.id.IdTableSupport; -import org.hibernate.hql.spi.id.IdTableSupportStandardImpl; -import org.hibernate.hql.spi.id.MultiTableBulkIdStrategy; -import org.hibernate.hql.spi.id.global.GlobalTemporaryTableBulkIdStrategy; -import org.hibernate.hql.spi.id.local.AfterUseAction; -import org.hibernate.type.StandardBasicTypes; - -/** - * A dialect for the Teradata database created by MCR as part of the - * dialect certification process. - * - * @author Jay Nance - */ -public class TeradataDialect extends Dialect implements IdTableSupport { - - private static final int PARAM_LIST_SIZE_LIMIT = 1024; - - /** - * Constructor - */ - public TeradataDialect() { - super(); - //registerColumnType data types - registerColumnType( Types.NUMERIC, "NUMERIC($p,$s)" ); - registerColumnType( Types.DOUBLE, "DOUBLE PRECISION" ); - registerColumnType( Types.BIGINT, "NUMERIC(18,0)" ); - registerColumnType( Types.BIT, "BYTEINT" ); - registerColumnType( Types.TINYINT, "BYTEINT" ); - registerColumnType( Types.VARBINARY, "VARBYTE($l)" ); - registerColumnType( Types.BINARY, "BYTEINT" ); - registerColumnType( Types.LONGVARCHAR, "LONG VARCHAR" ); - registerColumnType( Types.CHAR, "CHAR(1)" ); - registerColumnType( Types.DECIMAL, "DECIMAL" ); - registerColumnType( Types.INTEGER, "INTEGER" ); - registerColumnType( Types.SMALLINT, "SMALLINT" ); - registerColumnType( Types.FLOAT, "FLOAT" ); - registerColumnType( Types.VARCHAR, "VARCHAR($l)" ); - registerColumnType( Types.DATE, "DATE" ); - registerColumnType( Types.TIME, "TIME" ); - registerColumnType( Types.TIMESTAMP, "TIMESTAMP" ); - registerColumnType( Types.BOOLEAN, "BYTEINT" ); // hibernate seems to ignore this type... - registerColumnType( Types.BLOB, "BLOB" ); - registerColumnType( Types.CLOB, "CLOB" ); - - registerFunction( "year", new SQLFunctionTemplate( StandardBasicTypes.INTEGER, "extract(year from ?1)" ) ); - registerFunction( "length", new SQLFunctionTemplate( StandardBasicTypes.INTEGER, "character_length(?1)" ) ); - registerFunction( "concat", new VarArgsSQLFunction( StandardBasicTypes.STRING, "(", "||", ")" ) ); - registerFunction( "substring", new SQLFunctionTemplate( StandardBasicTypes.STRING, "substring(?1 from ?2 for ?3)" ) ); - registerFunction( "locate", new SQLFunctionTemplate( StandardBasicTypes.STRING, "position(?1 in ?2)" ) ); - registerFunction( "mod", new SQLFunctionTemplate( StandardBasicTypes.STRING, "?1 mod ?2" ) ); - registerFunction( "str", new SQLFunctionTemplate( StandardBasicTypes.STRING, "cast(?1 as varchar(255))" ) ); - - // bit_length feels a bit broken to me. We have to cast to char in order to - // pass when a numeric value is supplied. But of course the answers given will - // be wildly different for these two datatypes. 1234.5678 will be 9 bytes as - // a char string but will be 8 or 16 bytes as a true numeric. - // Jay Nance 2006-09-22 - registerFunction( - "bit_length", new SQLFunctionTemplate( StandardBasicTypes.INTEGER, "octet_length(cast(?1 as char))*4" ) - ); - - // The preference here would be - // SQLFunctionTemplate( StandardBasicTypes.TIMESTAMP, "current_timestamp(?1)", false) - // but this appears not to work. - // Jay Nance 2006-09-22 - registerFunction( "current_timestamp", new SQLFunctionTemplate( StandardBasicTypes.TIMESTAMP, "current_timestamp" ) ); - registerFunction( "current_time", new SQLFunctionTemplate( StandardBasicTypes.TIMESTAMP, "current_time" ) ); - registerFunction( "current_date", new SQLFunctionTemplate( StandardBasicTypes.TIMESTAMP, "current_date" ) ); - // IBID for current_time and current_date - - registerKeyword( "password" ); - registerKeyword( "type" ); - registerKeyword( "title" ); - registerKeyword( "year" ); - registerKeyword( "month" ); - registerKeyword( "summary" ); - registerKeyword( "alias" ); - registerKeyword( "value" ); - registerKeyword( "first" ); - registerKeyword( "role" ); - registerKeyword( "account" ); - registerKeyword( "class" ); - - // Tell hibernate to use getBytes instead of getBinaryStream - getDefaultProperties().setProperty( Environment.USE_STREAMS_FOR_BINARY, "false" ); - // No batch statements - getDefaultProperties().setProperty( Environment.STATEMENT_BATCH_SIZE, NO_BATCH ); - } - - /** - * Does this dialect support the FOR UPDATE syntax? - * - * @return empty string ... Teradata does not support FOR UPDATE syntax - */ - @Override - public String getForUpdateString() { - return ""; - } - - @Override - public boolean supportsSequences() { - return false; - } - - @Override - public String getAddColumnString() { - return "Add Column"; - } - - @Override - public MultiTableBulkIdStrategy getDefaultMultiTableBulkIdStrategy() { - return new GlobalTemporaryTableBulkIdStrategy( this, AfterUseAction.CLEAN ); - } - - @Override - public String generateIdTableName(String baseName) { - return IdTableSupportStandardImpl.INSTANCE.generateIdTableName( baseName ); - } - - @Override - public String getCreateIdTableCommand() { - return "create global temporary table"; - } - - @Override - public String getCreateIdTableStatementOptions() { - return " on commit preserve rows"; - } - - @Override - public String getDropIdTableCommand() { - return "drop table"; - } - - @Override - public String getTruncateIdTableCommand() { - return "delete from"; - } - - /** - * Get the name of the database type associated with the given - * java.sql.Types typecode. - * - * @param code java.sql.Types typecode - * @param length the length or precision of the column - * @param precision the precision of the column - * @param scale the scale of the column - * - * @return the database type name - * - * @throws HibernateException - */ - public String getTypeName(int code, int length, int precision, int scale) throws HibernateException { - /* - * We might want a special case for 19,2. This is very common for money types - * and here it is converted to 18,1 - */ - float f = precision > 0 ? ( float ) scale / ( float ) precision : 0; - int p = ( precision > 18 ? 18 : precision ); - int s = ( precision > 18 ? ( int ) ( 18.0 * f ) : ( scale > 18 ? 18 : scale ) ); - - return super.getTypeName( code, length, p, s ); - } - - @Override - public boolean supportsCascadeDelete() { - return false; - } - - @Override - public boolean supportsCircularCascadeDeleteConstraints() { - return false; - } - - @Override - public boolean areStringComparisonsCaseInsensitive() { - return true; - } - - @Override - public boolean supportsEmptyInList() { - return false; - } - - @Override - public String getSelectClauseNullString(int sqlType) { - String v = "null"; - - switch ( sqlType ) { - case Types.BIT: - case Types.TINYINT: - case Types.SMALLINT: - case Types.INTEGER: - case Types.BIGINT: - case Types.FLOAT: - case Types.REAL: - case Types.DOUBLE: - case Types.NUMERIC: - case Types.DECIMAL: - v = "cast(null as decimal)"; - break; - case Types.CHAR: - case Types.VARCHAR: - case Types.LONGVARCHAR: - v = "cast(null as varchar(255))"; - break; - case Types.DATE: - case Types.TIME: - case Types.TIMESTAMP: - v = "cast(null as timestamp)"; - break; - case Types.BINARY: - case Types.VARBINARY: - case Types.LONGVARBINARY: - case Types.NULL: - case Types.OTHER: - case Types.JAVA_OBJECT: - case Types.DISTINCT: - case Types.STRUCT: - case Types.ARRAY: - case Types.BLOB: - case Types.CLOB: - case Types.REF: - case Types.DATALINK: - case Types.BOOLEAN: - break; - } - return v; - } - - @Override - public String getCreateMultisetTableString() { - return "create multiset table "; - } - - @Override - public boolean supportsLobValueChangePropogation() { - return false; - } - - @Override - public boolean doesReadCommittedCauseWritersToBlockReaders() { - return true; - } - - @Override - public boolean doesRepeatableReadCauseReadersToBlockWriters() { - return true; - } - - @Override - public boolean supportsBindAsCallableArgument() { - return false; - } - - @Override - public int getInExpressionCountLimit() { - return PARAM_LIST_SIZE_LIMIT; - } -} +/* + * Hibernate, Relational Persistence for Idiomatic Java + * + * License: GNU Lesser General Public License (LGPL), version 2.1 or later. + * See the lgpl.txt file in the root directory or . + */ +package org.hibernate.dialect; +import java.sql.Types; + +import org.hibernate.HibernateException; +import org.hibernate.cfg.Environment; +import org.hibernate.dialect.function.SQLFunctionTemplate; +import org.hibernate.dialect.function.VarArgsSQLFunction; +import org.hibernate.type.StandardBasicTypes; + +/** + * A dialect for the Teradata database created by MCR as part of the + * dialect certification process. + * + * @author Jay Nance + */ +public class TeradataDialect extends Dialect { + + private static final int PARAM_LIST_SIZE_LIMIT = 1024; + + /** + * Constructor + */ + public TeradataDialect() { + super(); + //registerColumnType data types + registerColumnType( Types.NUMERIC, "NUMERIC($p,$s)" ); + registerColumnType( Types.DOUBLE, "DOUBLE PRECISION" ); + registerColumnType( Types.BIGINT, "NUMERIC(18,0)" ); + registerColumnType( Types.BIT, "BYTEINT" ); + registerColumnType( Types.TINYINT, "BYTEINT" ); + registerColumnType( Types.VARBINARY, "VARBYTE($l)" ); + registerColumnType( Types.BINARY, "BYTEINT" ); + registerColumnType( Types.LONGVARCHAR, "LONG VARCHAR" ); + registerColumnType( Types.CHAR, "CHAR(1)" ); + registerColumnType( Types.DECIMAL, "DECIMAL" ); + registerColumnType( Types.INTEGER, "INTEGER" ); + registerColumnType( Types.SMALLINT, "SMALLINT" ); + registerColumnType( Types.FLOAT, "FLOAT" ); + registerColumnType( Types.VARCHAR, "VARCHAR($l)" ); + registerColumnType( Types.DATE, "DATE" ); + registerColumnType( Types.TIME, "TIME" ); + registerColumnType( Types.TIMESTAMP, "TIMESTAMP" ); + registerColumnType( Types.BOOLEAN, "BYTEINT" ); // hibernate seems to ignore this type... + registerColumnType( Types.BLOB, "BLOB" ); + registerColumnType( Types.CLOB, "CLOB" ); + + registerFunction( "year", new SQLFunctionTemplate( StandardBasicTypes.INTEGER, "extract(year from ?1)" ) ); + registerFunction( "length", new SQLFunctionTemplate( StandardBasicTypes.INTEGER, "character_length(?1)" ) ); + registerFunction( "concat", new VarArgsSQLFunction( StandardBasicTypes.STRING, "(", "||", ")" ) ); + registerFunction( "substring", new SQLFunctionTemplate( StandardBasicTypes.STRING, "substring(?1 from ?2 for ?3)" ) ); + registerFunction( "locate", new SQLFunctionTemplate( StandardBasicTypes.STRING, "position(?1 in ?2)" ) ); + registerFunction( "mod", new SQLFunctionTemplate( StandardBasicTypes.STRING, "?1 mod ?2" ) ); + registerFunction( "str", new SQLFunctionTemplate( StandardBasicTypes.STRING, "cast(?1 as varchar(255))" ) ); + + // bit_length feels a bit broken to me. We have to cast to char in order to + // pass when a numeric value is supplied. But of course the answers given will + // be wildly different for these two datatypes. 1234.5678 will be 9 bytes as + // a char string but will be 8 or 16 bytes as a true numeric. + // Jay Nance 2006-09-22 + registerFunction( + "bit_length", new SQLFunctionTemplate( StandardBasicTypes.INTEGER, "octet_length(cast(?1 as char))*4" ) + ); + + // The preference here would be + // SQLFunctionTemplate( StandardBasicTypes.TIMESTAMP, "current_timestamp(?1)", false) + // but this appears not to work. + // Jay Nance 2006-09-22 + registerFunction( "current_timestamp", new SQLFunctionTemplate( StandardBasicTypes.TIMESTAMP, "current_timestamp" ) ); + registerFunction( "current_time", new SQLFunctionTemplate( StandardBasicTypes.TIMESTAMP, "current_time" ) ); + registerFunction( "current_date", new SQLFunctionTemplate( StandardBasicTypes.TIMESTAMP, "current_date" ) ); + // IBID for current_time and current_date + + registerKeyword( "password" ); + registerKeyword( "type" ); + registerKeyword( "title" ); + registerKeyword( "year" ); + registerKeyword( "month" ); + registerKeyword( "summary" ); + registerKeyword( "alias" ); + registerKeyword( "value" ); + registerKeyword( "first" ); + registerKeyword( "role" ); + registerKeyword( "account" ); + registerKeyword( "class" ); + + // Tell hibernate to use getBytes instead of getBinaryStream + getDefaultProperties().setProperty( Environment.USE_STREAMS_FOR_BINARY, "false" ); + // No batch statements + getDefaultProperties().setProperty( Environment.STATEMENT_BATCH_SIZE, NO_BATCH ); + } + + /** + * Does this dialect support the FOR UPDATE syntax? + * + * @return empty string ... Teradata does not support FOR UPDATE syntax + */ + @Override + public String getForUpdateString() { + return ""; + } + + @Override + public boolean supportsSequences() { + return false; + } + + @Override + public String getAddColumnString() { + return "Add Column"; + } + + @Override + public MultiTableBulkIdStrategy getDefaultMultiTableBulkIdStrategy() { + return new GlobalTemporaryTableBulkIdStrategy( this, AfterUseAction.CLEAN ); + } + + @Override + public String generateIdTableName(String baseName) { + return IdTableSupportStandardImpl.INSTANCE.generateIdTableName( baseName ); + } + + @Override + public String getCreateIdTableCommand() { + return "create global temporary table"; + } + + @Override + public String getCreateIdTableStatementOptions() { + return " on commit preserve rows"; + } + + @Override + public String getDropIdTableCommand() { + return "drop table"; + } + + @Override + public String getTruncateIdTableCommand() { + return "delete from"; + } + + /** + * Get the name of the database type associated with the given + * java.sql.Types typecode. + * + * @param code java.sql.Types typecode + * @param length the length or precision of the column + * @param precision the precision of the column + * @param scale the scale of the column + * + * @return the database type name + * + * @throws HibernateException + */ + public String getTypeName(int code, int length, int precision, int scale) throws HibernateException { + /* + * We might want a special case for 19,2. This is very common for money types + * and here it is converted to 18,1 + */ + float f = precision > 0 ? ( float ) scale / ( float ) precision : 0; + int p = ( precision > 18 ? 18 : precision ); + int s = ( precision > 18 ? ( int ) ( 18.0 * f ) : ( scale > 18 ? 18 : scale ) ); + + return super.getTypeName( code, length, p, s ); + } + + @Override + public boolean supportsCascadeDelete() { + return false; + } + + @Override + public boolean supportsCircularCascadeDeleteConstraints() { + return false; + } + + @Override + public boolean areStringComparisonsCaseInsensitive() { + return true; + } + + @Override + public boolean supportsEmptyInList() { + return false; + } + + @Override + public String getSelectClauseNullString(int sqlType) { + String v = "null"; + + switch ( sqlType ) { + case Types.BIT: + case Types.TINYINT: + case Types.SMALLINT: + case Types.INTEGER: + case Types.BIGINT: + case Types.FLOAT: + case Types.REAL: + case Types.DOUBLE: + case Types.NUMERIC: + case Types.DECIMAL: + v = "cast(null as decimal)"; + break; + case Types.CHAR: + case Types.VARCHAR: + case Types.LONGVARCHAR: + v = "cast(null as varchar(255))"; + break; + case Types.DATE: + case Types.TIME: + case Types.TIMESTAMP: + v = "cast(null as timestamp)"; + break; + case Types.BINARY: + case Types.VARBINARY: + case Types.LONGVARBINARY: + case Types.NULL: + case Types.OTHER: + case Types.JAVA_OBJECT: + case Types.DISTINCT: + case Types.STRUCT: + case Types.ARRAY: + case Types.BLOB: + case Types.CLOB: + case Types.REF: + case Types.DATALINK: + case Types.BOOLEAN: + break; + } + return v; + } + + @Override + public String getCreateMultisetTableString() { + return "create multiset table "; + } + + @Override + public boolean supportsLobValueChangePropogation() { + return false; + } + + @Override + public boolean doesReadCommittedCauseWritersToBlockReaders() { + return true; + } + + @Override + public boolean doesRepeatableReadCauseReadersToBlockWriters() { + return true; + } + + @Override + public boolean supportsBindAsCallableArgument() { + return false; + } + + @Override + public int getInExpressionCountLimit() { + return PARAM_LIST_SIZE_LIMIT; + } +} diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/TimesTenDialect.java b/hibernate-core/src/main/java/org/hibernate/dialect/TimesTenDialect.java index 9a1fb668af..4947f53373 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/TimesTenDialect.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/TimesTenDialect.java @@ -23,10 +23,6 @@ import org.hibernate.dialect.lock.UpdateLockingStrategy; import org.hibernate.dialect.pagination.FirstLimitHandler; import org.hibernate.dialect.pagination.LegacyFirstLimitHandler; import org.hibernate.dialect.pagination.LimitHandler; -import org.hibernate.hql.spi.id.IdTableSupportStandardImpl; -import org.hibernate.hql.spi.id.MultiTableBulkIdStrategy; -import org.hibernate.hql.spi.id.global.GlobalTemporaryTableBulkIdStrategy; -import org.hibernate.hql.spi.id.local.AfterUseAction; import org.hibernate.persister.entity.Lockable; import org.hibernate.sql.JoinFragment; import org.hibernate.sql.OracleJoinFragment; diff --git a/hibernate-core/src/main/java/org/hibernate/ejb/HibernateQuery.java b/hibernate-core/src/main/java/org/hibernate/ejb/HibernateQuery.java deleted file mode 100644 index 45b71b668b..0000000000 --- a/hibernate-core/src/main/java/org/hibernate/ejb/HibernateQuery.java +++ /dev/null @@ -1,14 +0,0 @@ -/* - * Hibernate, Relational Persistence for Idiomatic Java - * - * License: GNU Lesser General Public License (LGPL), version 2.1 or later. - * See the lgpl.txt file in the root directory or . - */ -package org.hibernate.ejb; - -/** - * @deprecated Use {@link org.hibernate.jpa.HibernateQuery} instead - */ -@Deprecated -public interface HibernateQuery extends org.hibernate.jpa.HibernateQuery { -} diff --git a/hibernate-core/src/main/java/org/hibernate/engine/internal/ParameterBinder.java b/hibernate-core/src/main/java/org/hibernate/engine/internal/ParameterBinder.java index 14eb776b3b..e160f146d3 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/internal/ParameterBinder.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/internal/ParameterBinder.java @@ -12,6 +12,7 @@ import java.util.Iterator; import java.util.Map; import org.hibernate.HibernateException; +import org.hibernate.engine.spi.QueryParameters; import org.hibernate.engine.spi.SessionImplementor; import org.hibernate.engine.spi.TypedValue; import org.hibernate.internal.CoreMessageLogger; diff --git a/hibernate-core/src/main/java/org/hibernate/engine/internal/StatefulPersistenceContext.java b/hibernate-core/src/main/java/org/hibernate/engine/internal/StatefulPersistenceContext.java index 93f7d9cc4b..0856e0a3b2 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/internal/StatefulPersistenceContext.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/internal/StatefulPersistenceContext.java @@ -40,7 +40,6 @@ import org.hibernate.bytecode.enhance.spi.interceptor.LazyAttributeLoadingInterc import org.hibernate.cache.spi.access.NaturalIdDataAccess; import org.hibernate.cache.spi.access.SoftLock; import org.hibernate.collection.spi.PersistentCollection; -import org.hibernate.engine.loading.internal.LoadContexts; import org.hibernate.engine.spi.AssociationKey; import org.hibernate.engine.spi.BatchFetchQueue; import org.hibernate.engine.spi.CachedNaturalIdValueSource; @@ -67,6 +66,7 @@ import org.hibernate.persister.entity.EntityPersister; import org.hibernate.pretty.MessageHelper; import org.hibernate.proxy.HibernateProxy; import org.hibernate.proxy.LazyInitializer; +import org.hibernate.sql.results.spi.LoadContexts; import org.hibernate.stat.internal.StatsHelper; import org.hibernate.stat.spi.StatisticsImplementor; import org.hibernate.type.CollectionType; @@ -937,7 +937,7 @@ public class StatefulPersistenceContext implements PersistenceContext { } @Override - public CollectionEntry addInitializedCollection(CollectionPersister persister, PersistentCollection collection, Serializable id) + public CollectionEntry addInitializedCollection(CollectionPersister persister, PersistentCollection collection, Object id) throws HibernateException { final CollectionEntry ce = new CollectionEntry( collection, persister, id, flushing ); ce.postInitialize( collection ); diff --git a/hibernate-core/src/main/java/org/hibernate/engine/loading/internal/CollectionLoadContext.java b/hibernate-core/src/main/java/org/hibernate/engine/loading/internal/CollectionLoadContext.java deleted file mode 100644 index 21eb11cece..0000000000 --- a/hibernate-core/src/main/java/org/hibernate/engine/loading/internal/CollectionLoadContext.java +++ /dev/null @@ -1,431 +0,0 @@ -/* - * Hibernate, Relational Persistence for Idiomatic Java - * - * License: GNU Lesser General Public License (LGPL), version 2.1 or later. - * See the lgpl.txt file in the root directory or . - */ -package org.hibernate.engine.loading.internal; - -import java.io.Serializable; -import java.sql.ResultSet; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Set; - -import org.hibernate.CacheMode; -import org.hibernate.EntityMode; -import org.hibernate.HibernateException; -import org.hibernate.bytecode.spi.BytecodeEnhancementMetadata; -import org.hibernate.cache.spi.access.CollectionDataAccess; -import org.hibernate.cache.spi.entry.CollectionCacheEntry; -import org.hibernate.collection.spi.PersistentCollection; -import org.hibernate.engine.spi.CollectionEntry; -import org.hibernate.engine.spi.CollectionKey; -import org.hibernate.engine.spi.PersistenceContext; -import org.hibernate.engine.spi.SessionEventListenerManager; -import org.hibernate.engine.spi.SessionFactoryImplementor; -import org.hibernate.engine.spi.SharedSessionContractImplementor; -import org.hibernate.engine.spi.Status; -import org.hibernate.internal.CoreLogging; -import org.hibernate.internal.CoreMessageLogger; -import org.hibernate.internal.util.StringHelper; -import org.hibernate.persister.collection.CollectionPersister; -import org.hibernate.persister.collection.QueryableCollection; -import org.hibernate.persister.entity.EntityPersister; -import org.hibernate.pretty.MessageHelper; -import org.hibernate.stat.spi.StatisticsImplementor; - -/** - * Represents state associated with the processing of a given {@link ResultSet} - * in regards to loading collections. - *

- * Another implementation option to consider is to not expose {@link ResultSet}s - * directly (in the JDBC redesign) but to always "wrap" them and apply a - * [series of] context[s] to that wrapper. - * - * @author Steve Ebersole - */ -public class CollectionLoadContext { - private static final CoreMessageLogger LOG = CoreLogging.messageLogger( CollectionLoadContext.class ); - - private final LoadContexts loadContexts; - private final ResultSet resultSet; - private Set localLoadingCollectionKeys = new HashSet<>(); - - /** - * Creates a collection load context for the given result set. - * - * @param loadContexts Callback to other collection load contexts. - * @param resultSet The result set this is "wrapping". - */ - public CollectionLoadContext(LoadContexts loadContexts, ResultSet resultSet) { - this.loadContexts = loadContexts; - this.resultSet = resultSet; - } - - public ResultSet getResultSet() { - return resultSet; - } - - public LoadContexts getLoadContext() { - return loadContexts; - } - - /** - * Retrieve the collection that is being loaded as part of processing this - * result set. - *

- * Basically, there are two valid return values from this method:

- * - * @param persister The persister for the collection being requested. - * @param key The key of the collection being requested. - * - * @return The loading collection (see discussion above). - */ - public PersistentCollection getLoadingCollection(final CollectionPersister persister, final Serializable key) { - final CollectionKey collectionKey = new CollectionKey( persister, key ); - if ( LOG.isTraceEnabled() ) { - LOG.tracev( "Starting attempt to find loading collection [{0}]", - MessageHelper.collectionInfoString( persister.getRole(), key ) ); - } - final LoadingCollectionEntry loadingCollectionEntry = loadContexts.locateLoadingCollectionEntry( collectionKey ); - if ( loadingCollectionEntry == null ) { - // look for existing collection as part of the persistence context - PersistentCollection collection = loadContexts.getPersistenceContext().getCollection( collectionKey ); - if ( collection != null ) { - if ( collection.wasInitialized() ) { - LOG.trace( "Collection already initialized; ignoring" ); - // ignore this row of results! Note the early exit - return null; - } - LOG.trace( "Collection not yet initialized; initializing" ); - } - else { - final Object owner = loadContexts.getPersistenceContext().getCollectionOwner( key, persister ); - final boolean newlySavedEntity = owner != null - && loadContexts.getPersistenceContext().getEntry( owner ).getStatus() != Status.LOADING; - if ( newlySavedEntity ) { - // important, to account for newly saved entities in query - // todo : some kind of check for new status... - LOG.trace( "Owning entity already loaded; ignoring" ); - return null; - } - // create one - LOG.tracev( "Instantiating new collection [key={0}, rs={1}]", key, resultSet ); - collection = persister.getCollectionType().instantiate( - loadContexts.getPersistenceContext().getSession(), persister, key ); - } - collection.beforeInitialize( persister, -1 ); - collection.beginRead(); - localLoadingCollectionKeys.add( collectionKey ); - loadContexts.registerLoadingCollectionXRef( collectionKey, new LoadingCollectionEntry( resultSet, persister, key, collection ) ); - return collection; - } - if ( loadingCollectionEntry.getResultSet() == resultSet ) { - LOG.trace( "Found loading collection bound to current result set processing; reading row" ); - return loadingCollectionEntry.getCollection(); - } - // ignore this row, the collection is in process of - // being loaded somewhere further "up" the stack - LOG.trace( "Collection is already being initialized; ignoring row" ); - return null; - } - - /** - * Finish the process of collection-loading for this bound result set. Mainly this - * involves cleaning up resources and notifying the collections that loading is - * complete. - * - * @param persister The persister for which to complete loading. - */ - public void endLoadingCollections(CollectionPersister persister) { - final SharedSessionContractImplementor session = getLoadContext().getPersistenceContext().getSession(); - if ( !loadContexts.hasLoadingCollectionEntries() - && localLoadingCollectionKeys.isEmpty() ) { - return; - } - - // in an effort to avoid concurrent-modification-exceptions (from - // potential recursive calls back through here as a result of the - // eventual call to PersistentCollection#endRead), we scan the - // internal loadingCollections map for matches and store those matches - // in a temp collection. the temp collection is then used to "drive" - // the #endRead processing. - List matches = null; - final Iterator itr = localLoadingCollectionKeys.iterator(); - final PersistenceContext persistenceContext = session.getPersistenceContextInternal(); - while ( itr.hasNext() ) { - final CollectionKey collectionKey = (CollectionKey) itr.next(); - final LoadingCollectionEntry lce = loadContexts.locateLoadingCollectionEntry( collectionKey ); - if ( lce == null ) { - LOG.loadingCollectionKeyNotFound( collectionKey ); - } - else if ( lce.getResultSet() == resultSet && lce.getPersister() == persister ) { - if ( matches == null ) { - matches = new ArrayList<>(); - } - matches.add( lce ); - if ( lce.getCollection().getOwner() == null ) { - persistenceContext.addUnownedCollection( - new CollectionKey( - persister, - lce.getKey() - ), - lce.getCollection() - ); - } - LOG.tracev( "Removing collection load entry [{0}]", lce ); - - // todo : i'd much rather have this done from #endLoadingCollection(CollectionPersister,LoadingCollectionEntry)... - loadContexts.unregisterLoadingCollectionXRef( collectionKey ); - itr.remove(); - } - } - - endLoadingCollections( persister, matches ); - if ( localLoadingCollectionKeys.isEmpty() ) { - // todo : hack!!! - // NOTE : here we cleanup the load context when we have no more local - // LCE entries. This "works" for the time being because really - // only the collection load contexts are implemented. Long term, - // this cleanup should become part of the "close result set" - // processing from the (sandbox/jdbc) jdbc-container code. - loadContexts.cleanup( resultSet ); - } - } - - private void endLoadingCollections(CollectionPersister persister, List matchedCollectionEntries) { - if ( matchedCollectionEntries == null ) { - if ( LOG.isDebugEnabled() ) { - LOG.debugf( "No collections were found in result set for role: %s", persister.getRole() ); - } - return; - } - - final int count = matchedCollectionEntries.size(); - if ( LOG.isDebugEnabled() ) { - LOG.debugf( "%s collections were found in result set for role: %s", count, persister.getRole() ); - } - - for ( LoadingCollectionEntry matchedCollectionEntry : matchedCollectionEntries ) { - endLoadingCollection( matchedCollectionEntry, persister ); - } - - if ( LOG.isDebugEnabled() ) { - LOG.debugf( "%s collections initialized for role: %s", count, persister.getRole() ); - } - } - - private void endLoadingCollection(LoadingCollectionEntry lce, CollectionPersister persister) { - LOG.tracev( "Ending loading collection [{0}]", lce ); - final PersistenceContext persistenceContext = getLoadContext().getPersistenceContext(); - final SharedSessionContractImplementor session = persistenceContext.getSession(); - - // warning: can cause a recursive calls! (proxy initialization) - final PersistentCollection loadingCollection = lce.getCollection(); - final boolean hasNoQueuedAdds = loadingCollection.endRead(); - - if ( persister.getCollectionType().hasHolder() ) { - persistenceContext.addCollectionHolder( loadingCollection ); - } - - CollectionEntry ce = persistenceContext.getCollectionEntry( loadingCollection ); - if ( ce == null ) { - ce = persistenceContext.addInitializedCollection( persister, loadingCollection, lce.getKey() ); - } - else { - ce.postInitialize( loadingCollection ); -// if (ce.getLoadedPersister().getBatchSize() > 1) { // not the best place for doing this, moved into ce.postInitialize -// getLoadContext().getPersistenceContext().getBatchFetchQueue().removeBatchLoadableCollection(ce); -// } - } - - // The collection has been completely initialized and added to the PersistenceContext. - - if ( loadingCollection.getOwner() != null ) { - // If the owner is bytecode-enhanced and the owner's collection value is uninitialized, - // then go ahead and set it to the newly initialized collection. - final EntityPersister ownerEntityPersister = persister.getOwnerEntityPersister(); - final BytecodeEnhancementMetadata bytecodeEnhancementMetadata = - ownerEntityPersister.getBytecodeEnhancementMetadata(); - if ( bytecodeEnhancementMetadata.isEnhancedForLazyLoading() ) { - // Lazy properties in embeddables/composites are not currently supported for embeddables (HHH-10480), - // so check to make sure the collection is not in an embeddable before checking to see if - // the collection is lazy. - // TODO: More will probably need to be done here when HHH-10480 is fixed.. - if ( StringHelper.qualifier( persister.getRole() ).length() == - ownerEntityPersister.getEntityName().length() ) { - // Assume the collection is not in an embeddable. - // Strip off to get the collection property name. - final String propertyName = persister.getRole().substring( - ownerEntityPersister.getEntityName().length() + 1 - ); - if ( !bytecodeEnhancementMetadata.isAttributeLoaded( loadingCollection.getOwner(), propertyName ) ) { - int propertyIndex = ownerEntityPersister.getEntityMetamodel().getPropertyIndex( - propertyName - ); - ownerEntityPersister.setPropertyValue( - loadingCollection.getOwner(), - propertyIndex, - loadingCollection - ); - } - } - } - } - - // add to cache if: - boolean addToCache = - // there were no queued additions - hasNoQueuedAdds - // and the role has a cache - && persister.hasCache() - // and this is not a forced initialization during flush - && session.getCacheMode().isPutEnabled() && !ce.isDoremove(); - if ( addToCache ) { - addCollectionToCache( lce, persister ); - } - - if ( LOG.isDebugEnabled() ) { - LOG.debugf( - "Collection fully initialized: %s", - MessageHelper.collectionInfoString( persister, loadingCollection, lce.getKey(), session ) - ); - } - final StatisticsImplementor statistics = session.getFactory().getStatistics(); - if ( statistics.isStatisticsEnabled() ) { - statistics.loadCollection( persister.getRole() ); - } - } - - /** - * Add the collection to the second-level cache - * - * @param lce The entry representing the collection to add - * @param persister The persister - */ - private void addCollectionToCache(LoadingCollectionEntry lce, CollectionPersister persister) { - final PersistenceContext persistenceContext = getLoadContext().getPersistenceContext(); - final SharedSessionContractImplementor session = persistenceContext.getSession(); - final SessionFactoryImplementor factory = session.getFactory(); - - if ( LOG.isDebugEnabled() ) { - LOG.debugf( "Caching collection: %s", MessageHelper.collectionInfoString( persister, lce.getCollection(), lce.getKey(), session ) ); - } - - if ( session.getLoadQueryInfluencers().hasEnabledFilters() && persister.isAffectedByEnabledFilters( session ) ) { - // some filters affecting the collection are enabled on the session, so do not do the put into the cache. - if ( LOG.isDebugEnabled() ) { - LOG.debug( "Refusing to add to cache due to enabled filters" ); - } - // todo : add the notion of enabled filters to the cache key to differentiate filtered collections from non-filtered; - // DefaultInitializeCollectionEventHandler.initializeCollectionFromCache() (which makes sure to not read from - // cache with enabled filters). - // EARLY EXIT!!!!! - return; - } - - final Object version; - if ( persister.isVersioned() ) { - Object collectionOwner = persistenceContext.getCollectionOwner( lce.getKey(), persister ); - if ( collectionOwner == null ) { - // generally speaking this would be caused by the collection key being defined by a property-ref, thus - // the collection key and the owner key would not match up. In this case, try to use the key of the - // owner instance associated with the collection itself, if one. If the collection does already know - // about its owner, that owner should be the same instance as associated with the PC, but we do the - // resolution against the PC anyway just to be safe since the lookup should not be costly. - if ( lce.getCollection() != null ) { - final Object linkedOwner = lce.getCollection().getOwner(); - if ( linkedOwner != null ) { - final Serializable ownerKey = persister.getOwnerEntityPersister().getIdentifier( linkedOwner, session ); - collectionOwner = persistenceContext.getCollectionOwner( ownerKey, persister ); - } - } - if ( collectionOwner == null ) { - throw new HibernateException( - "Unable to resolve owner of loading collection [" + - MessageHelper.collectionInfoString( persister, lce.getCollection(), lce.getKey(), session ) + - "] for second level caching" - ); - } - } - version = persistenceContext.getEntry( collectionOwner ).getVersion(); - } - else { - version = null; - } - - final CollectionCacheEntry entry = new CollectionCacheEntry( lce.getCollection(), persister ); - final CollectionDataAccess cacheAccess = persister.getCacheAccessStrategy(); - final Object cacheKey = cacheAccess.generateCacheKey( - lce.getKey(), - persister, - session.getFactory(), - session.getTenantIdentifier() - ); - - boolean isPutFromLoad = true; - if ( persister.getElementType().isAssociationType() ) { - for ( Serializable id : entry.getState() ) { - EntityPersister entityPersister = ( (QueryableCollection) persister ).getElementPersister(); - if ( persistenceContext.wasInsertedDuringTransaction( entityPersister, id ) ) { - isPutFromLoad = false; - break; - } - } - } - - // CollectionRegionAccessStrategy has no update, so avoid putting uncommitted data via putFromLoad - if (isPutFromLoad) { - final SessionEventListenerManager eventListenerManager = session.getEventListenerManager(); - try { - eventListenerManager.cachePutStart(); - final boolean put = cacheAccess.putFromLoad( - session, - cacheKey, - persister.getCacheEntryStructure().structure( entry ), - version, - factory.getSessionFactoryOptions().isMinimalPutsEnabled() && session.getCacheMode()!= CacheMode.REFRESH - ); - - final StatisticsImplementor statistics = factory.getStatistics(); - if ( put && statistics.isStatisticsEnabled() ) { - statistics.collectionCachePut( - persister.getNavigableRole(), - persister.getCacheAccessStrategy().getRegion().getName() - ); - } - } - finally { - eventListenerManager.cachePutEnd(); - } - } - } - - void cleanup() { - if ( !localLoadingCollectionKeys.isEmpty() ) { - LOG.localLoadingCollectionKeysCount( localLoadingCollectionKeys.size() ); - } - loadContexts.cleanupCollectionXRefs( localLoadingCollectionKeys ); - localLoadingCollectionKeys.clear(); - } - - - @Override - public String toString() { - return super.toString() + ""; - } -} diff --git a/hibernate-core/src/main/java/org/hibernate/engine/loading/internal/EntityLoadContext.java b/hibernate-core/src/main/java/org/hibernate/engine/loading/internal/EntityLoadContext.java deleted file mode 100644 index 36f4f67ba8..0000000000 --- a/hibernate-core/src/main/java/org/hibernate/engine/loading/internal/EntityLoadContext.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Hibernate, Relational Persistence for Idiomatic Java - * - * License: GNU Lesser General Public License (LGPL), version 2.1 or later. - * See the lgpl.txt file in the root directory or . - */ -package org.hibernate.engine.loading.internal; - -import java.sql.ResultSet; -import java.util.ArrayList; -import java.util.List; - -import org.hibernate.internal.CoreMessageLogger; - -import org.jboss.logging.Logger; - -/** - * Tracks information about loading of entities specific to a given result set. These can be hierarchical. - * - * @author Steve Ebersole - */ -public class EntityLoadContext { - private static final CoreMessageLogger LOG = Logger.getMessageLogger( CoreMessageLogger.class, EntityLoadContext.class.getName() ); - - private final LoadContexts loadContexts; - private final ResultSet resultSet; - // todo : need map? the prob is a proper key, right? - private final List hydratingEntities = new ArrayList( 20 ); - - public EntityLoadContext(LoadContexts loadContexts, ResultSet resultSet) { - this.loadContexts = loadContexts; - this.resultSet = resultSet; - } - - void cleanup() { - if ( !hydratingEntities.isEmpty() ) { - LOG.hydratingEntitiesCount( hydratingEntities.size() ); - } - hydratingEntities.clear(); - } - - - @Override - public String toString() { - return super.toString() + ""; - } -} diff --git a/hibernate-core/src/main/java/org/hibernate/engine/loading/internal/LoadContexts.java b/hibernate-core/src/main/java/org/hibernate/engine/loading/internal/LoadContexts.java deleted file mode 100644 index 53e6452c27..0000000000 --- a/hibernate-core/src/main/java/org/hibernate/engine/loading/internal/LoadContexts.java +++ /dev/null @@ -1,292 +0,0 @@ -/* - * Hibernate, Relational Persistence for Idiomatic Java - * - * License: GNU Lesser General Public License (LGPL), version 2.1 or later. - * See the lgpl.txt file in the root directory or . - */ -package org.hibernate.engine.loading.internal; - -import java.io.Serializable; -import java.sql.ResultSet; -import java.util.HashMap; -import java.util.IdentityHashMap; -import java.util.Map; -import java.util.Set; - -import org.hibernate.collection.spi.PersistentCollection; -import org.hibernate.engine.spi.CollectionKey; -import org.hibernate.engine.spi.PersistenceContext; -import org.hibernate.engine.spi.SharedSessionContractImplementor; -import org.hibernate.internal.CoreLogging; -import org.hibernate.internal.CoreMessageLogger; -import org.hibernate.persister.collection.CollectionPersister; -import org.hibernate.pretty.MessageHelper; - -/** - * Maps {@link ResultSet result-sets} to specific contextual data related to processing that result set - *

- * Considering the JDBC-redesign work, would further like this contextual info not mapped separately, but available - * based on the result set being processed. This would also allow maintaining a single mapping as we could reliably - * get notification of the result-set closing... - * - * @author Steve Ebersole - */ -public class LoadContexts { - private static final CoreMessageLogger LOG = CoreLogging.messageLogger( LoadContexts.class ); - - private final PersistenceContext persistenceContext; - private Map collectionLoadContexts; - private Map entityLoadContexts; - - private Map xrefLoadingCollectionEntries; - - /** - * Creates and binds this to the given persistence context. - * - * @param persistenceContext The persistence context to which this - * will be bound. - */ - public LoadContexts(PersistenceContext persistenceContext) { - this.persistenceContext = persistenceContext; - } - - /** - * Retrieves the persistence context to which this is bound. - * - * @return The persistence context to which this is bound. - */ - public PersistenceContext getPersistenceContext() { - return persistenceContext; - } - - private SharedSessionContractImplementor getSession() { - return getPersistenceContext().getSession(); - } - - - // cleanup code ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - /** - * Release internal state associated with the given result set. - *

- * This should be called when we are done with processing said result set, - * ideally as the result set is being closed. - * - * @param resultSet The result set for which it is ok to release - * associated resources. - */ - public void cleanup(ResultSet resultSet) { - if ( collectionLoadContexts != null ) { - final CollectionLoadContext collectionLoadContext = collectionLoadContexts.remove( resultSet ); - collectionLoadContext.cleanup(); - } - if ( entityLoadContexts != null ) { - final EntityLoadContext entityLoadContext = entityLoadContexts.remove( resultSet ); - entityLoadContext.cleanup(); - } - } - - /** - * Release internal state associated with *all* result sets. - *

- * This is intended as a "failsafe" process to make sure we get everything - * cleaned up and released. - */ - public void cleanup() { - if ( collectionLoadContexts != null ) { - for ( CollectionLoadContext collectionLoadContext : collectionLoadContexts.values() ) { - LOG.failSafeCollectionsCleanup( collectionLoadContext ); - collectionLoadContext.cleanup(); - } - collectionLoadContexts.clear(); - } - if ( entityLoadContexts != null ) { - for ( EntityLoadContext entityLoadContext : entityLoadContexts.values() ) { - LOG.failSafeEntitiesCleanup( entityLoadContext ); - entityLoadContext.cleanup(); - } - entityLoadContexts.clear(); - } - } - - - // Collection load contexts ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - /** - * Do we currently have any internal entries corresponding to loading - * collections? - * - * @return True if we currently hold state pertaining to loading collections; - * false otherwise. - */ - public boolean hasLoadingCollectionEntries() { - return ( collectionLoadContexts != null && !collectionLoadContexts.isEmpty() ); - } - - /** - * Do we currently have any registered internal entries corresponding to loading - * collections? - * - * @return True if we currently hold state pertaining to a registered loading collections; - * false otherwise. - */ - public boolean hasRegisteredLoadingCollectionEntries() { - return ( xrefLoadingCollectionEntries != null && !xrefLoadingCollectionEntries.isEmpty() ); - } - - - /** - * Get the {@link CollectionLoadContext} associated with the given - * {@link ResultSet}, creating one if needed. - * - * @param resultSet The result set for which to retrieve the context. - * @return The processing context. - */ - public CollectionLoadContext getCollectionLoadContext(ResultSet resultSet) { - CollectionLoadContext context = null; - if ( collectionLoadContexts == null ) { - collectionLoadContexts = new IdentityHashMap( 8 ); - } - else { - context = collectionLoadContexts.get(resultSet); - } - if ( context == null ) { - LOG.tracev( "Constructing collection load context for result set [{0}]", resultSet ); - context = new CollectionLoadContext( this, resultSet ); - collectionLoadContexts.put( resultSet, context ); - } - return context; - } - - /** - * Attempt to locate the loading collection given the CollectionKey obtained from the owner's key. The lookup here - * occurs against all result-set contexts... - * - * @param persister The collection persister - * @param key The collection key - * @return The loading collection, or null if not found. - */ - public PersistentCollection locateLoadingCollection(CollectionPersister persister, CollectionKey key) { - final LoadingCollectionEntry lce = locateLoadingCollectionEntry( key ) ; - if ( lce != null ) { - if ( LOG.isTraceEnabled() ) { - LOG.tracef( - "Returning loading collection: %s", - MessageHelper.collectionInfoString( persister, key.getKey(), getSession().getFactory() ) - ); - } - return lce.getCollection(); - } - return null; - } - - // loading collection xrefs ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - /** - * Register a loading collection xref. - *

- * This xref map is used because sometimes a collection is in process of - * being loaded from one result set, but needs to be accessed from the - * context of another "nested" result set processing. - *

- * Implementation note: package protected, as this is meant solely for use - * by {@link CollectionLoadContext} to be able to locate collections - * being loaded by other {@link CollectionLoadContext}s/{@link ResultSet}s. - * - * @param entryKey The xref collection key - * @param entry The corresponding loading collection entry - */ - void registerLoadingCollectionXRef(CollectionKey entryKey, LoadingCollectionEntry entry) { - if ( xrefLoadingCollectionEntries == null ) { - xrefLoadingCollectionEntries = new HashMap(); - } - xrefLoadingCollectionEntries.put( entryKey, entry ); - } - - /** - * The inverse of {@link #registerLoadingCollectionXRef}. Here, we are done - * processing the said collection entry, so we remove it from the - * load context. - *

- * The idea here is that other loading collections can now reference said - * collection directly from the {@link PersistenceContext} because it - * has completed its load cycle. - *

- * Implementation note: package protected, as this is meant solely for use - * by {@link CollectionLoadContext} to be able to locate collections - * being loaded by other {@link CollectionLoadContext}s/{@link ResultSet}s. - * - * @param key The key of the collection we are done processing. - */ - void unregisterLoadingCollectionXRef(CollectionKey key) { - if ( !hasRegisteredLoadingCollectionEntries() ) { - return; - } - xrefLoadingCollectionEntries.remove( key ); - } - - @SuppressWarnings( {"UnusedDeclaration"}) - Map getLoadingCollectionXRefs() { - return xrefLoadingCollectionEntries; - } - - - /** - * Locate the LoadingCollectionEntry within *any* of the tracked - * {@link CollectionLoadContext}s. - *

- * Implementation note: package protected, as this is meant solely for use - * by {@link CollectionLoadContext} to be able to locate collections - * being loaded by other {@link CollectionLoadContext}s/{@link ResultSet}s. - * - * @param key The collection key. - * @return The located entry; or null. - */ - LoadingCollectionEntry locateLoadingCollectionEntry(CollectionKey key) { - if ( xrefLoadingCollectionEntries == null ) { - return null; - } - LOG.tracev( "Attempting to locate loading collection entry [{0}] in any result-set context", key ); - final LoadingCollectionEntry rtn = xrefLoadingCollectionEntries.get( key ); - if ( rtn == null ) { - LOG.tracev( "Collection [{0}] not located in load context", key ); - } - else { - LOG.tracev( "Collection [{0}] located in load context", key ); - } - return rtn; - } - - /*package*/void cleanupCollectionXRefs(Set entryKeys) { - for ( CollectionKey entryKey : entryKeys ) { - xrefLoadingCollectionEntries.remove( entryKey ); - } - } - - - // Entity load contexts ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - // * currently, not yet used... - - /** - * Currently unused - * - * @param resultSet The result set - * - * @return The entity load context - */ - @SuppressWarnings( {"UnusedDeclaration"}) - public EntityLoadContext getEntityLoadContext(ResultSet resultSet) { - EntityLoadContext context = null; - if ( entityLoadContexts == null ) { - entityLoadContexts = new IdentityHashMap( 8 ); - } - else { - context = entityLoadContexts.get( resultSet ); - } - if ( context == null ) { - context = new EntityLoadContext( this, resultSet ); - entityLoadContexts.put( resultSet, context ); - } - return context; - } -} diff --git a/hibernate-core/src/main/java/org/hibernate/engine/loading/internal/LoadingCollectionEntry.java b/hibernate-core/src/main/java/org/hibernate/engine/loading/internal/LoadingCollectionEntry.java deleted file mode 100644 index 2d4e1887e3..0000000000 --- a/hibernate-core/src/main/java/org/hibernate/engine/loading/internal/LoadingCollectionEntry.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Hibernate, Relational Persistence for Idiomatic Java - * - * License: GNU Lesser General Public License (LGPL), version 2.1 or later. - * See the lgpl.txt file in the root directory or . - */ -package org.hibernate.engine.loading.internal; - -import java.io.Serializable; -import java.sql.ResultSet; - -import org.hibernate.collection.spi.PersistentCollection; -import org.hibernate.persister.collection.CollectionPersister; -import org.hibernate.pretty.MessageHelper; - -/** - * Represents a collection currently being loaded. - * - * @author Steve Ebersole - */ -public class LoadingCollectionEntry { - private final ResultSet resultSet; - private final CollectionPersister persister; - private final Serializable key; - private final PersistentCollection collection; - - LoadingCollectionEntry( - ResultSet resultSet, - CollectionPersister persister, - Serializable key, - PersistentCollection collection) { - this.resultSet = resultSet; - this.persister = persister; - this.key = key; - this.collection = collection; - } - - public ResultSet getResultSet() { - return resultSet; - } - - public CollectionPersister getPersister() { - return persister; - } - - public Serializable getKey() { - return key; - } - - public PersistentCollection getCollection() { - return collection; - } - - @Override - public String toString() { - return getClass().getName() + "@" + Integer.toHexString( hashCode() ); - } -} diff --git a/hibernate-core/src/main/java/org/hibernate/engine/loading/internal/package-info.java b/hibernate-core/src/main/java/org/hibernate/engine/loading/internal/package-info.java deleted file mode 100644 index 3acd1cf7c0..0000000000 --- a/hibernate-core/src/main/java/org/hibernate/engine/loading/internal/package-info.java +++ /dev/null @@ -1,11 +0,0 @@ -/* - * Hibernate, Relational Persistence for Idiomatic Java - * - * License: GNU Lesser General Public License (LGPL), version 2.1 or later. - * See the lgpl.txt file in the root directory or . - */ - -/** - * Internal classes used to track loading of data, potentially across multiple ResultSets - */ -package org.hibernate.engine.loading.internal; diff --git a/hibernate-core/src/main/java/org/hibernate/engine/query/spi/HQLQueryPlan.java b/hibernate-core/src/main/java/org/hibernate/engine/query/spi/HQLQueryPlan.java deleted file mode 100644 index 49e496b096..0000000000 --- a/hibernate-core/src/main/java/org/hibernate/engine/query/spi/HQLQueryPlan.java +++ /dev/null @@ -1,454 +0,0 @@ -/* - * Hibernate, Relational Persistence for Idiomatic Java - * - * License: GNU Lesser General Public License (LGPL), version 2.1 or later. - * See the lgpl.txt file in the root directory or . - */ -package org.hibernate.engine.query.spi; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.hibernate.Filter; -import org.hibernate.HibernateException; -import org.hibernate.QueryException; -import org.hibernate.engine.spi.RowSelection; -import org.hibernate.engine.spi.SessionFactoryImplementor; -import org.hibernate.engine.spi.SharedSessionContractImplementor; -import org.hibernate.event.spi.EventSource; -import org.hibernate.hql.internal.QuerySplitter; -import org.hibernate.hql.spi.FilterTranslator; -import org.hibernate.hql.spi.NamedParameterInformation; -import org.hibernate.hql.spi.ParameterTranslations; -import org.hibernate.hql.spi.PositionalParameterInformation; -import org.hibernate.hql.spi.QueryTranslator; -import org.hibernate.hql.spi.QueryTranslatorFactory; -import org.hibernate.internal.CoreLogging; -import org.hibernate.internal.CoreMessageLogger; -import org.hibernate.internal.util.collections.ArrayHelper; -import org.hibernate.internal.util.collections.IdentitySet; -import org.hibernate.internal.util.collections.JoinedIterator; -import org.hibernate.query.internal.ParameterMetadataImpl; -import org.hibernate.query.spi.ScrollableResultsImplementor; -import org.hibernate.type.Type; - -/** - * Defines a query execution plan for an HQL query (or filter). - * - * @author Steve Ebersole - */ -public class HQLQueryPlan implements Serializable { - private static final CoreMessageLogger LOG = CoreLogging.messageLogger( HQLQueryPlan.class ); - - // TODO : keep separate notions of QT[] here for shallow/non-shallow queries... - - private final String sourceQuery; - private final QueryTranslator[] translators; - - private final ParameterMetadataImpl parameterMetadata; - private final ReturnMetadata returnMetadata; - private final Set querySpaces; - - private final Set enabledFilterNames; - private final boolean shallow; - - /** - * Constructs a HQLQueryPlan - * - * @param hql The HQL query - * @param shallow Whether the execution is to be shallow or not - * @param enabledFilters The enabled filters (we only keep the names) - * @param factory The factory - */ - public HQLQueryPlan(String hql, boolean shallow, Map enabledFilters, - SessionFactoryImplementor factory) { - this( hql, null, shallow, enabledFilters, factory, null ); - } - - public HQLQueryPlan(String hql, boolean shallow, Map enabledFilters, - SessionFactoryImplementor factory, EntityGraphQueryHint entityGraphQueryHint) { - this( hql, null, shallow, enabledFilters, factory, entityGraphQueryHint ); - } - - @SuppressWarnings("unchecked") - protected HQLQueryPlan( - String hql, - String collectionRole, - boolean shallow, - Map enabledFilters, - SessionFactoryImplementor factory, - EntityGraphQueryHint entityGraphQueryHint) { - this.sourceQuery = hql; - this.shallow = shallow; - - if ( enabledFilters.isEmpty() ) { - this.enabledFilterNames = Collections.emptySet(); - } - else { - this.enabledFilterNames = Collections.unmodifiableSet( new HashSet<>( enabledFilters.keySet() ) ); - } - - final String[] concreteQueryStrings = QuerySplitter.concreteQueries( hql, factory ); - final int length = concreteQueryStrings.length; - this.translators = new QueryTranslator[length]; - - final Set combinedQuerySpaces = new HashSet<>(); - - final Map querySubstitutions = factory.getSessionFactoryOptions().getQuerySubstitutions(); - final QueryTranslatorFactory queryTranslatorFactory = factory.getServiceRegistry().getService( QueryTranslatorFactory.class ); - - - for ( int i=0; i 1 ) ? new Type[translators[0].getReturnTypes().length] : translators[0].getReturnTypes(); - returnMetadata = new ReturnMetadata( translators[0].getReturnAliases(), types ); - } - } - } - - public String getSourceQuery() { - return sourceQuery; - } - - public Set getQuerySpaces() { - return querySpaces; - } - - public ParameterMetadataImpl getParameterMetadata() { - return parameterMetadata; - } - - public ReturnMetadata getReturnMetadata() { - return returnMetadata; - } - - public Set getEnabledFilterNames() { - return enabledFilterNames; - } - - /** - * This method should only be called for debugging purposes as it regenerates a new array every time. - */ - public String[] getSqlStrings() { - List sqlStrings = new ArrayList<>(); - for ( QueryTranslator translator : translators ) { - sqlStrings.addAll( translator.collectSqlStrings() ); - } - return ArrayHelper.toStringArray( sqlStrings ); - } - - public Set getUtilizedFilterNames() { - // TODO : add this info to the translator and aggregate it here... - return null; - } - - public boolean isShallow() { - return shallow; - } - - /** - * Coordinates the efforts to perform a list across all the included query translators. - * - * @param queryParameters The query parameters - * @param session The session - * - * @return The query result list - * - * @throws HibernateException Indicates a problem performing the query - */ - @SuppressWarnings("unchecked") - public List performList( - QueryParameters queryParameters, - SharedSessionContractImplementor session) throws HibernateException { - if ( LOG.isTraceEnabled() ) { - LOG.tracev( "Find: {0}", getSourceQuery() ); - queryParameters.traceParameters( session.getFactory() ); - } - - final RowSelection rowSelection = queryParameters.getRowSelection(); - final boolean hasLimit = rowSelection != null - && rowSelection.definesLimits(); - final boolean needsLimit = hasLimit && translators.length > 1; - - final QueryParameters queryParametersToUse; - if ( needsLimit ) { - LOG.needsLimit(); - final RowSelection selection = new RowSelection(); - selection.setFetchSize( queryParameters.getRowSelection().getFetchSize() ); - selection.setTimeout( queryParameters.getRowSelection().getTimeout() ); - queryParametersToUse = queryParameters.createCopyUsing( selection ); - } - else { - queryParametersToUse = queryParameters; - } - - //fast path to avoid unnecessary allocation and copying - if ( translators.length == 1 ) { - return translators[0].list( session, queryParametersToUse ); - } - final int guessedResultSize = guessResultSize( rowSelection ); - final List combinedResults = new ArrayList( guessedResultSize ); - final IdentitySet distinction; - if ( needsLimit ) { - distinction = new IdentitySet( guessedResultSize ); - } - else { - distinction = null; - } - int includedCount = -1; - translator_loop: - for ( QueryTranslator translator : translators ) { - final List tmp = translator.list( session, queryParametersToUse ); - if ( needsLimit ) { - // NOTE : firstRow is zero-based - final int first = queryParameters.getRowSelection().getFirstRow() == null - ? 0 - : queryParameters.getRowSelection().getFirstRow(); - final int max = queryParameters.getRowSelection().getMaxRows() == null - ? -1 - : queryParameters.getRowSelection().getMaxRows(); - for ( final Object result : tmp ) { - if ( !distinction.add( result ) ) { - continue; - } - includedCount++; - if ( includedCount < first ) { - continue; - } - combinedResults.add( result ); - if ( max >= 0 && includedCount > max ) { - // break the outer loop !!! - break translator_loop; - } - } - } - else { - combinedResults.addAll( tmp ); - } - } - return combinedResults; - } - - /** - * If we're able to guess a likely size of the results we can optimize allocation - * of our datastructures. - * Essentially if we detect the user is not using pagination, we attempt to use the FetchSize - * as a reasonable hint. If fetch size is not being set either, it is reasonable to expect - * that we're going to have a single hit. In such a case it would be tempting to return a constant - * of value one, but that's dangerous as it doesn't scale up appropriately for example - * with an ArrayList if the guess is wrong. - * - * @param rowSelection - * @return a reasonable size to use for allocation - */ - @SuppressWarnings("UnnecessaryUnboxing") - private int guessResultSize(RowSelection rowSelection) { - if ( rowSelection != null ) { - final int maxReasonableAllocation = rowSelection.getFetchSize() != null ? rowSelection.getFetchSize().intValue() : 100; - if ( rowSelection.getMaxRows() != null && rowSelection.getMaxRows().intValue() > 0 ) { - return Math.min( maxReasonableAllocation, rowSelection.getMaxRows().intValue() ); - } - else if ( rowSelection.getFetchSize() != null && rowSelection.getFetchSize().intValue() > 0 ) { - return rowSelection.getFetchSize().intValue(); - } - } - return 7;//magic number guessed as a reasonable default. - } - - /** - * Coordinates the efforts to perform an iterate across all the included query translators. - * - * @param queryParameters The query parameters - * @param session The session - * - * @return The query result iterator - * - * @throws HibernateException Indicates a problem performing the query - */ - @SuppressWarnings("unchecked") - public Iterator performIterate( - QueryParameters queryParameters, - EventSource session) throws HibernateException { - if ( LOG.isTraceEnabled() ) { - LOG.tracev( "Iterate: {0}", getSourceQuery() ); - queryParameters.traceParameters( session.getFactory() ); - } - if ( translators.length == 0 ) { - return Collections.emptyIterator(); - } - - final boolean many = translators.length > 1; - Iterator[] results = null; - if ( many ) { - results = new Iterator[translators.length]; - } - - Iterator result = null; - for ( int i = 0; i < translators.length; i++ ) { - result = translators[i].iterate( queryParameters, session ); - if ( many ) { - results[i] = result; - } - } - - return many ? new JoinedIterator( results ) : result; - } - - /** - * Coordinates the efforts to perform a scroll across all the included query translators. - * - * @param queryParameters The query parameters - * @param session The session - * - * @return The query result iterator - * - * @throws HibernateException Indicates a problem performing the query - */ - public ScrollableResultsImplementor performScroll( - QueryParameters queryParameters, - SharedSessionContractImplementor session) throws HibernateException { - if ( LOG.isTraceEnabled() ) { - LOG.tracev( "Iterate: {0}", getSourceQuery() ); - queryParameters.traceParameters( session.getFactory() ); - } - if ( translators.length != 1 ) { - throw new QueryException( "implicit polymorphism not supported for scroll() queries" ); - } - if ( queryParameters.getRowSelection().definesLimits() && translators[0].containsCollectionFetches() ) { - throw new QueryException( "firstResult/maxResults not supported in conjunction with scroll() of a query containing collection fetches" ); - } - - return translators[0].scroll( queryParameters, session ); - } - - /** - * Coordinates the efforts to perform an execution across all the included query translators. - * - * @param queryParameters The query parameters - * @param session The session - * - * @return The aggregated "affected row" count - * - * @throws HibernateException Indicates a problem performing the execution - */ - public int performExecuteUpdate(QueryParameters queryParameters, SharedSessionContractImplementor session) - throws HibernateException { - if ( LOG.isTraceEnabled() ) { - LOG.tracev( "Execute update: {0}", getSourceQuery() ); - queryParameters.traceParameters( session.getFactory() ); - } - if ( translators.length != 1 ) { - LOG.splitQueries( getSourceQuery(), translators.length ); - } - int result = 0; - for ( QueryTranslator translator : translators ) { - result += translator.executeUpdate( queryParameters, session ); - } - return result; - } - - private ParameterMetadataImpl buildParameterMetadata(ParameterTranslations parameterTranslations, String hql) { - final Map ordinalParamDescriptors; - if ( parameterTranslations.getPositionalParameterInformationMap().isEmpty() ) { - ordinalParamDescriptors = Collections.emptyMap(); - } - else { - final Map temp = new HashMap<>(); - for ( Map.Entry entry : - parameterTranslations.getPositionalParameterInformationMap().entrySet() ) { - final int position = entry.getKey(); - temp.put( - position, - new OrdinalParameterDescriptor( - position, - position - 1, - entry.getValue().getExpectedType(), - entry.getValue().getSourceLocations() - ) - ); - } - ordinalParamDescriptors = Collections.unmodifiableMap( temp ); - } - - - final Map namedParamDescriptorMap; - - if ( parameterTranslations.getNamedParameterInformationMap().isEmpty() ) { - namedParamDescriptorMap = Collections.emptyMap(); - } - else { - final Map tmp = new HashMap<>(); - for ( Map.Entry namedEntry : - parameterTranslations.getNamedParameterInformationMap().entrySet() ) { - final String name = namedEntry.getKey(); - tmp.put( - name, - new NamedParameterDescriptor( - name, - parameterTranslations.getNamedParameterInformation( name ).getExpectedType(), - namedEntry.getValue().getSourceLocations() - ) - ); - } - - namedParamDescriptorMap = Collections.unmodifiableMap( tmp ); - } - - - return new ParameterMetadataImpl( ordinalParamDescriptors, namedParamDescriptorMap ); - } - - /** - * Access to the underlying translators associated with this query - * - * @return The translators - */ - public QueryTranslator[] getTranslators() { - final QueryTranslator[] copy = new QueryTranslator[translators.length]; - System.arraycopy( translators, 0, copy, 0, copy.length ); - return copy; - } - - public Class getDynamicInstantiationResultType() { - return translators[0].getDynamicInstantiationResultType(); - } - - public boolean isSelect() { - return !translators[0].isManipulationStatement(); - } - - public boolean isUpdate() { - return translators[0].isUpdateStatement(); - } -} diff --git a/hibernate-core/src/main/java/org/hibernate/engine/query/spi/NativeSQLQueryPlan.java b/hibernate-core/src/main/java/org/hibernate/engine/query/spi/NativeSQLQueryPlan.java index 7ef6a69e5c..50afb8a81f 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/query/spi/NativeSQLQueryPlan.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/query/spi/NativeSQLQueryPlan.java @@ -12,6 +12,7 @@ import java.sql.SQLException; import org.hibernate.HibernateException; import org.hibernate.action.internal.BulkOperationCleanupAction; +import org.hibernate.engine.spi.QueryParameters; import org.hibernate.engine.spi.RowSelection; import org.hibernate.engine.spi.SharedSessionContractImplementor; import org.hibernate.event.spi.EventSource; diff --git a/hibernate-core/src/main/java/org/hibernate/engine/spi/CollectionKey.java b/hibernate-core/src/main/java/org/hibernate/engine/spi/CollectionKey.java index 5db19a612d..67525696c3 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/spi/CollectionKey.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/spi/CollectionKey.java @@ -23,12 +23,12 @@ import org.hibernate.type.Type; */ public final class CollectionKey implements Serializable { private final String role; - private final Serializable key; + private final Object key; private final Type keyType; private final SessionFactoryImplementor factory; private final int hashCode; - public CollectionKey(CollectionPersister persister, Serializable key) { + public CollectionKey(CollectionPersister persister, Object key) { this( persister.getRole(), key, @@ -39,16 +39,16 @@ public final class CollectionKey implements Serializable { /** * The EntityMode parameter is now ignored. Use the other constructor. - * @deprecated Use {@link #CollectionKey(CollectionPersister, Serializable)} + * @deprecated Use {@link #CollectionKey(CollectionPersister, Object)} */ @Deprecated - public CollectionKey(CollectionPersister persister, Serializable key, EntityMode em) { + public CollectionKey(CollectionPersister persister, Object key, EntityMode em) { this( persister.getRole(), key, persister.getKeyType(), persister.getFactory() ); } private CollectionKey( String role, - Serializable key, + Object key, Type keyType, SessionFactoryImplementor factory) { this.role = role; @@ -70,7 +70,7 @@ public final class CollectionKey implements Serializable { return role; } - public Serializable getKey() { + public Object getKey() { return key; } diff --git a/hibernate-core/src/main/java/org/hibernate/engine/spi/LoadQueryInfluencers.java b/hibernate-core/src/main/java/org/hibernate/engine/spi/LoadQueryInfluencers.java index a644f35588..1cbb39b7de 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/spi/LoadQueryInfluencers.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/spi/LoadQueryInfluencers.java @@ -12,6 +12,7 @@ import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; +import java.util.function.Supplier; import javax.persistence.EntityGraph; @@ -20,6 +21,7 @@ import org.hibernate.UnknownProfileException; import org.hibernate.graph.GraphSemantic; import org.hibernate.graph.spi.RootGraphImplementor; import org.hibernate.internal.FilterImpl; +import org.hibernate.loader.spi.InternalFetchProfile; import org.hibernate.type.Type; /** @@ -42,7 +44,7 @@ public class LoadQueryInfluencers implements Serializable { private final SessionFactoryImplementor sessionFactory; - private String internalFetchProfile; + private InternalFetchProfile enabledInternalFetchProfile; //Lazily initialized! private HashSet enabledFetchProfileNames; @@ -67,17 +69,57 @@ public class LoadQueryInfluencers implements Serializable { // internal fetch profile support ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - public String getInternalFetchProfile() { - return internalFetchProfile; + public void withInternalFetchProfile(InternalFetchProfile profile, InternalFetchProfileAction action) { + final InternalFetchProfile previous = this.enabledInternalFetchProfile; + this.enabledInternalFetchProfile = profile; + action.performAction(); + this.enabledInternalFetchProfile = previous; } - public void setInternalFetchProfile(String internalFetchProfile) { + public T fromInternalFetchProfile(InternalFetchProfile profile, Supplier supplier) { + final InternalFetchProfile previous = this.enabledInternalFetchProfile; + this.enabledInternalFetchProfile = profile; + try { + return supplier.get(); + } + finally { + this.enabledInternalFetchProfile = previous; + } + } + + @FunctionalInterface + public interface InternalFetchProfileAction { + void performAction(); + } + + public InternalFetchProfile getEnabledInternalFetchProfile() { + return enabledInternalFetchProfile; + } + + public void setEnabledInternalFetchProfile(InternalFetchProfile enabledInternalFetchProfile) { if ( sessionFactory == null ) { // thats the signal that this is the immutable, context-less // variety throw new IllegalStateException( "Cannot modify context-less LoadQueryInfluencers" ); } - this.internalFetchProfile = internalFetchProfile; + + this.enabledInternalFetchProfile = enabledInternalFetchProfile; + } + + /** + * @deprecated Use {@link #getEnabledInternalFetchProfile} instead + */ + @Deprecated + public String getInternalFetchProfile() { + return getEnabledInternalFetchProfile().getLegacyName(); + } + + /** + * @deprecated Use {@link #setEnabledInternalFetchProfile} instead + */ + @Deprecated + public void setInternalFetchProfile(String internalFetchProfile) { + setEnabledInternalFetchProfile( InternalFetchProfile.fromLegacyName( internalFetchProfile ) ); } diff --git a/hibernate-core/src/main/java/org/hibernate/engine/spi/PersistenceContext.java b/hibernate-core/src/main/java/org/hibernate/engine/spi/PersistenceContext.java index f95776dcb7..27bdf27210 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/spi/PersistenceContext.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/spi/PersistenceContext.java @@ -399,14 +399,17 @@ public interface PersistenceContext { * add an (initialized) collection that was created by another session and passed * into update() (ie. one with a snapshot and existing state on the database) */ - void addInitializedDetachedCollection(CollectionPersister collectionPersister, - PersistentCollection collection) throws HibernateException; + void addInitializedDetachedCollection( + CollectionPersister collectionPersister, + PersistentCollection collection); /** * add a collection we just pulled out of the cache (does not need initializing) */ - CollectionEntry addInitializedCollection(CollectionPersister persister, - PersistentCollection collection, Serializable id) throws HibernateException; + CollectionEntry addInitializedCollection( + CollectionPersister persister, + PersistentCollection collection, + Object id); /** * Get the collection instance associated with the CollectionKey @@ -453,7 +456,11 @@ public interface PersistenceContext { * Get the collection entry for a collection passed to filter, * which might be a collection wrapper, an array, or an unwrapped * collection. Return null if there is no entry. + * + * @deprecated Intended use was in handling Hibernate's legacy + * "collection filter via Query" feature which has been removed */ + @Deprecated CollectionEntry getCollectionEntryOrNull(Object collection); /** diff --git a/hibernate-core/src/main/java/org/hibernate/engine/spi/QueryParameters.java b/hibernate-core/src/main/java/org/hibernate/engine/spi/QueryParameters.java index 4d842a5355..8366c86145 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/spi/QueryParameters.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/spi/QueryParameters.java @@ -7,23 +7,17 @@ package org.hibernate.engine.spi; import java.io.Serializable; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Iterator; import java.util.List; import java.util.Map; -import java.util.StringTokenizer; import org.hibernate.HibernateException; import org.hibernate.LockOptions; import org.hibernate.QueryException; import org.hibernate.ScrollMode; -import org.hibernate.engine.query.spi.HQLQueryPlan; - import org.hibernate.internal.CoreLogging; -import org.hibernate.internal.FilterImpl; import org.hibernate.internal.util.EntityPrinter; import org.hibernate.internal.util.collections.ArrayHelper; +import org.hibernate.query.spi.QueryOptions; import org.hibernate.query.spi.QueryParameterBindings; import org.hibernate.transform.ResultTransformer; import org.hibernate.type.ComponentType; @@ -226,13 +220,7 @@ public final class QueryParameters { public QueryParameters( QueryParameterBindings queryParameterBindings, LockOptions lockOptions, - RowSelection selection, - final boolean isReadOnlyInitialized, - boolean readOnly, - boolean cacheable, - String cacheRegion, - String comment, - List dbHints, + QueryOptions queryOptions, final Serializable[] collectionKeys, final Object optionalObject, final String optionalEntityName, @@ -243,13 +231,18 @@ public final class QueryParameters { null, null, lockOptions, - selection, - isReadOnlyInitialized, - readOnly, - cacheable, - cacheRegion, - comment, - dbHints, + new RowSelection( + queryOptions.getFirstRow(), + queryOptions.getMaxRows(), + queryOptions.getTimeout(), + queryOptions.getFetchSize() + ), + queryOptions.isReadOnly() != null, + queryOptions.isReadOnly(), + queryOptions.isResultCachingEnabled(), + queryOptions.getResultCacheRegionName(), + queryOptions.getComment(), + queryOptions.getDatabaseHints(), collectionKeys, optionalObject, optionalEntityName, diff --git a/hibernate-core/src/main/java/org/hibernate/engine/spi/RowSelection.java b/hibernate-core/src/main/java/org/hibernate/engine/spi/RowSelection.java index 225c116f93..fbf01af381 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/spi/RowSelection.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/spi/RowSelection.java @@ -17,6 +17,16 @@ public final class RowSelection { private Integer timeout; private Integer fetchSize; + public RowSelection() { + } + + public RowSelection(Integer firstRow, Integer maxRows, Integer timeout, Integer fetchSize) { + this.firstRow = firstRow; + this.maxRows = maxRows; + this.timeout = timeout; + this.fetchSize = fetchSize; + } + public void setFirstRow(Integer firstRow) { if ( firstRow != null && firstRow < 0 ) { throw new IllegalArgumentException( "first-row value cannot be negative : " + firstRow ); diff --git a/hibernate-core/src/main/java/org/hibernate/event/internal/DefaultMergeEventListener.java b/hibernate-core/src/main/java/org/hibernate/event/internal/DefaultMergeEventListener.java index 39f1f47b76..63d103497e 100644 --- a/hibernate-core/src/main/java/org/hibernate/event/internal/DefaultMergeEventListener.java +++ b/hibernate-core/src/main/java/org/hibernate/event/internal/DefaultMergeEventListener.java @@ -24,6 +24,7 @@ import org.hibernate.engine.spi.EntityKey; import org.hibernate.engine.spi.PersistenceContext; import org.hibernate.engine.spi.PersistentAttributeInterceptable; import org.hibernate.engine.spi.PersistentAttributeInterceptor; +import org.hibernate.loader.spi.InternalFetchProfile; import org.hibernate.engine.spi.SelfDirtinessTracker; import org.hibernate.engine.spi.SessionFactoryImplementor; import org.hibernate.engine.spi.SessionImplementor; @@ -297,15 +298,15 @@ public class DefaultMergeEventListener extends AbstractSaveEventListener impleme } } - String previousFetchProfile = source.getLoadQueryInfluencers().getInternalFetchProfile(); - source.getLoadQueryInfluencers().setInternalFetchProfile( "merge" ); - - //we must clone embedded composite identifiers, or - //we will get back the same instance that we pass in + // we must clone embedded composite identifiers or we will get back the same instance that we pass in final Serializable clonedIdentifier = (Serializable) persister.getIdentifierType().deepCopy( id, source.getFactory() ); - final Object result = source.get( entityName, clonedIdentifier ); - source.getLoadQueryInfluencers().setInternalFetchProfile( previousFetchProfile ); + // apply the special MERGE fetch profile and perform the resolution (Session#get) + final Object result = source.getLoadQueryInfluencers().fromInternalFetchProfile( + InternalFetchProfile.MERGE, + () -> source.get( entityName, clonedIdentifier ) + + ); if ( result == null ) { //TODO: we should throw an exception if we really *know* for sure diff --git a/hibernate-core/src/main/java/org/hibernate/event/internal/DefaultRefreshEventListener.java b/hibernate-core/src/main/java/org/hibernate/event/internal/DefaultRefreshEventListener.java index 9b8b9c41b6..1cdd0843c2 100644 --- a/hibernate-core/src/main/java/org/hibernate/event/internal/DefaultRefreshEventListener.java +++ b/hibernate-core/src/main/java/org/hibernate/event/internal/DefaultRefreshEventListener.java @@ -31,6 +31,7 @@ import org.hibernate.event.spi.RefreshEvent; import org.hibernate.event.spi.RefreshEventListener; import org.hibernate.internal.CoreLogging; import org.hibernate.internal.CoreMessageLogger; +import org.hibernate.loader.spi.InternalFetchProfile; import org.hibernate.metamodel.spi.MetamodelImplementor; import org.hibernate.persister.collection.CollectionPersister; import org.hibernate.persister.entity.EntityPersister; @@ -171,9 +172,22 @@ public class DefaultRefreshEventListener implements RefreshEventListener { evictCachedCollections( persister, id, source ); - String previousFetchProfile = source.getLoadQueryInfluencers().getInternalFetchProfile(); - source.getLoadQueryInfluencers().setInternalFetchProfile( "refresh" ); + final Object result = source.getLoadQueryInfluencers().fromInternalFetchProfile( + InternalFetchProfile.REFRESH, + () -> doRefresh( event, source, object, e, persister, id ) + ); + UnresolvableObjectException.throwIfNull( result, id, persister.getEntityName() ); + + } + + private Object doRefresh( + RefreshEvent event, + EventSource source, + Object object, + EntityEntry e, + EntityPersister persister, + Serializable id) { // Handle the requested lock-mode (if one) in relation to the entry's (if one) current lock-mode @@ -230,10 +244,7 @@ public class DefaultRefreshEventListener implements RefreshEventListener { source.setReadOnly( result, ( e == null ? source.isDefaultReadOnly() : e.isReadOnly() ) ); } } - source.getLoadQueryInfluencers().setInternalFetchProfile( previousFetchProfile ); - - UnresolvableObjectException.throwIfNull( result, id, persister.getEntityName() ); - + return result; } private void evictCachedCollections(EntityPersister persister, Serializable id, EventSource source) { diff --git a/hibernate-core/src/main/java/org/hibernate/internal/CoreMessageLogger.java b/hibernate-core/src/main/java/org/hibernate/internal/CoreMessageLogger.java index 55e392a429..5069004354 100644 --- a/hibernate-core/src/main/java/org/hibernate/internal/CoreMessageLogger.java +++ b/hibernate-core/src/main/java/org/hibernate/internal/CoreMessageLogger.java @@ -30,8 +30,6 @@ import org.hibernate.dialect.Dialect; import org.hibernate.engine.jdbc.dialect.spi.DialectResolver; import org.hibernate.engine.jndi.JndiException; import org.hibernate.engine.jndi.JndiNameException; -import org.hibernate.engine.loading.internal.CollectionLoadContext; -import org.hibernate.engine.loading.internal.EntityLoadContext; import org.hibernate.engine.spi.CollectionKey; import org.hibernate.engine.spi.SessionFactoryImplementor; import org.hibernate.id.IntegralDataTypeHolder; @@ -307,13 +305,13 @@ public interface CoreMessageLogger extends BasicLogger { + " to unsafe use of the session): %s", id = 99) void failed(Throwable throwable); - @LogMessage(level = WARN) - @Message(value = "Fail-safe cleanup (collections) : %s", id = 100) - void failSafeCollectionsCleanup(CollectionLoadContext collectionLoadContext); - - @LogMessage(level = WARN) - @Message(value = "Fail-safe cleanup (entities) : %s", id = 101) - void failSafeEntitiesCleanup(EntityLoadContext entityLoadContext); +// @LogMessage(level = WARN) +// @Message(value = "Fail-safe cleanup (collections) : %s", id = 100) +// void failSafeCollectionsCleanup(CollectionLoadContext collectionLoadContext); +// +// @LogMessage(level = WARN) +// @Message(value = "Fail-safe cleanup (entities) : %s", id = 101) +// void failSafeEntitiesCleanup(EntityLoadContext entityLoadContext); @LogMessage(level = INFO) @Message(value = "Fetching database metadata", id = 102) diff --git a/hibernate-core/src/main/java/org/hibernate/internal/CriteriaImpl.java b/hibernate-core/src/main/java/org/hibernate/internal/CriteriaImpl.java deleted file mode 100644 index fd57fc3dca..0000000000 --- a/hibernate-core/src/main/java/org/hibernate/internal/CriteriaImpl.java +++ /dev/null @@ -1,730 +0,0 @@ -/* - * Hibernate, Relational Persistence for Idiomatic Java - * - * License: GNU Lesser General Public License (LGPL), version 2.1 or later. - * See the lgpl.txt file in the root directory or . - */ -package org.hibernate.internal; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import org.hibernate.CacheMode; -import org.hibernate.Criteria; -import org.hibernate.FetchMode; -import org.hibernate.FlushMode; -import org.hibernate.HibernateException; -import org.hibernate.LockMode; -import org.hibernate.ScrollMode; -import org.hibernate.ScrollableResults; -import org.hibernate.criterion.Criterion; -import org.hibernate.criterion.NaturalIdentifier; -import org.hibernate.criterion.Order; -import org.hibernate.criterion.Projection; -import org.hibernate.engine.spi.SharedSessionContractImplementor; -import org.hibernate.internal.util.StringHelper; -import org.hibernate.query.internal.AbstractProducedQuery; -import org.hibernate.sql.JoinType; -import org.hibernate.transform.ResultTransformer; - -/** - * Implementation of the Criteria interface - * @author Gavin King - */ -public class CriteriaImpl implements Criteria, Serializable { - - private final String entityOrClassName; - private transient SharedSessionContractImplementor session; - private final String rootAlias; - - private List criterionEntries = new ArrayList<>(); - private List orderEntries = new ArrayList<>(); - private Projection projection; - private Criteria projectionCriteria; - - private List subcriteriaList = new ArrayList<>(); - - private Map fetchModes = new HashMap<>(); - private Map lockModes = new HashMap<>(); - - private Integer maxResults; - private Integer firstResult; - private Integer timeout; - private Integer fetchSize; - - private boolean cacheable; - private String cacheRegion; - private String comment; - private final List queryHints = new ArrayList(); - - private FlushMode flushMode; - private CacheMode cacheMode; - private FlushMode sessionFlushMode; - private CacheMode sessionCacheMode; - - private Boolean readOnly; - - private ResultTransformer resultTransformer = Criteria.ROOT_ENTITY; - - - // Constructors ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - public CriteriaImpl(String entityOrClassName, SharedSessionContractImplementor session) { - this(entityOrClassName, ROOT_ALIAS, session); - } - - public CriteriaImpl(String entityOrClassName, String alias, SharedSessionContractImplementor session) { - this.session = session; - this.entityOrClassName = entityOrClassName; - this.cacheable = false; - this.rootAlias = alias; - } - @Override - public String toString() { - return "CriteriaImpl(" + - entityOrClassName + ":" + - (rootAlias==null ? "" : rootAlias) + - subcriteriaList.toString() + - criterionEntries.toString() + - ( projection==null ? "" : projection.toString() ) + - ')'; - } - - - // State ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - public SharedSessionContractImplementor getSession() { - return session; - } - - public void setSession(SharedSessionContractImplementor session) { - this.session = session; - } - - public String getEntityOrClassName() { - return entityOrClassName; - } - - public Map getLockModes() { - return lockModes; - } - - public Criteria getProjectionCriteria() { - return projectionCriteria; - } - - public Iterator iterateSubcriteria() { - return subcriteriaList.iterator(); - } - - public Iterator iterateExpressionEntries() { - return criterionEntries.iterator(); - } - - public Iterator iterateOrderings() { - return orderEntries.iterator(); - } - - public Criteria add(Criteria criteriaInst, Criterion expression) { - criterionEntries.add( new CriterionEntry(expression, criteriaInst) ); - return this; - } - - - // Criteria impl ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - @Override - public String getAlias() { - return rootAlias; - } - - public Projection getProjection() { - return projection; - } - @Override - public Criteria setProjection(Projection projection) { - this.projection = projection; - this.projectionCriteria = this; - setResultTransformer( PROJECTION ); - return this; - } - @Override - public Criteria add(Criterion expression) { - add( this, expression ); - return this; - } - @Override - public Criteria addOrder(Order ordering) { - orderEntries.add( new OrderEntry( ordering, this ) ); - return this; - } - public FetchMode getFetchMode(String path) { - return fetchModes.get(path); - } - @Override - public Criteria setFetchMode(String associationPath, FetchMode mode) { - String rootAliasPathPrefix = rootAlias + "."; - if (rootAlias != null && !associationPath.startsWith(rootAliasPathPrefix)) { - associationPath = rootAliasPathPrefix + associationPath; - } - fetchModes.put( associationPath, mode ); - return this; - } - @Override - public Criteria setLockMode(LockMode lockMode) { - return setLockMode( getAlias(), lockMode ); - } - @Override - public Criteria setLockMode(String alias, LockMode lockMode) { - lockModes.put( alias, lockMode ); - return this; - } - @Override - public Criteria createAlias(String associationPath, String alias) { - return createAlias( associationPath, alias, JoinType.INNER_JOIN ); - } - @Override - public Criteria createAlias(String associationPath, String alias, JoinType joinType) { - new Subcriteria( this, associationPath, alias, joinType ); - return this; - } - - @Override - public Criteria createAlias(String associationPath, String alias, int joinType) throws HibernateException { - return createAlias( associationPath, alias, JoinType.parse( joinType ) ); - } - @Override - public Criteria createAlias(String associationPath, String alias, JoinType joinType, Criterion withClause) { - new Subcriteria( this, associationPath, alias, joinType, withClause ); - return this; - } - - @Override - public Criteria createAlias(String associationPath, String alias, int joinType, Criterion withClause) - throws HibernateException { - return createAlias( associationPath, alias, JoinType.parse( joinType ), withClause ); - } - @Override - public Criteria createCriteria(String associationPath) { - return createCriteria( associationPath, JoinType.INNER_JOIN ); - } - @Override - public Criteria createCriteria(String associationPath, JoinType joinType) { - return new Subcriteria( this, associationPath, joinType ); - } - - @Override - public Criteria createCriteria(String associationPath, int joinType) throws HibernateException { - return createCriteria(associationPath, JoinType.parse( joinType )); - } - @Override - public Criteria createCriteria(String associationPath, String alias) { - return createCriteria( associationPath, alias, JoinType.INNER_JOIN ); - } - @Override - public Criteria createCriteria(String associationPath, String alias, JoinType joinType) { - return new Subcriteria( this, associationPath, alias, joinType ); - } - - @Override - public Criteria createCriteria(String associationPath, String alias, int joinType) throws HibernateException { - return createCriteria( associationPath, alias, JoinType.parse( joinType ) ); - } - @Override - public Criteria createCriteria(String associationPath, String alias, JoinType joinType, Criterion withClause) { - return new Subcriteria( this, associationPath, alias, joinType, withClause ); - } - - @Override - public Criteria createCriteria(String associationPath, String alias, int joinType, Criterion withClause) - throws HibernateException { - return createCriteria( associationPath, alias, JoinType.parse( joinType ), withClause ); - } - - public ResultTransformer getResultTransformer() { - return resultTransformer; - } - @Override - public Criteria setResultTransformer(ResultTransformer tupleMapper) { - this.resultTransformer = tupleMapper; - return this; - } - - public Integer getMaxResults() { - return maxResults; - } - - @Override - public Criteria setMaxResults(int maxResults) { - this.maxResults = maxResults; - return this; - } - - public Integer getFirstResult() { - return firstResult; - } - @Override - public Criteria setFirstResult(int firstResult) { - this.firstResult = firstResult; - return this; - } - - public Integer getFetchSize() { - return fetchSize; - } - @Override - public Criteria setFetchSize(int fetchSize) { - this.fetchSize = fetchSize; - return this; - } - - public Integer getTimeout() { - return timeout; - } - - @Override - public Criteria setTimeout(int timeout) { - this.timeout = timeout; - return this; - } - - @Override - public boolean isReadOnlyInitialized() { - return readOnly != null; - } - - @Override - public boolean isReadOnly() { - if ( ! isReadOnlyInitialized() && getSession() == null ) { - throw new IllegalStateException( - "cannot determine readOnly/modifiable setting when it is not initialized and is not initialized and getSession() == null" - ); - } - return ( isReadOnlyInitialized() ? - readOnly : - getSession().getPersistenceContextInternal().isDefaultReadOnly() - ); - } - - @Override - public Criteria setReadOnly(boolean readOnly) { - this.readOnly = readOnly; - return this; - } - - public boolean getCacheable() { - return this.cacheable; - } - @Override - public Criteria setCacheable(boolean cacheable) { - this.cacheable = cacheable; - return this; - } - - public String getCacheRegion() { - return this.cacheRegion; - } - @Override - public Criteria setCacheRegion(String cacheRegion) { - this.cacheRegion = cacheRegion.trim(); - return this; - } - - public String getComment() { - return comment; - } - - @Override - public Criteria setComment(String comment) { - this.comment = comment; - return this; - } - - public List getQueryHints() { - return queryHints; - } - - @Override - public Criteria addQueryHint(String queryHint) { - queryHints.add( queryHint ); - return this; - } - - @Override - public Criteria setFlushMode(FlushMode flushMode) { - this.flushMode = flushMode; - return this; - } - @Override - public Criteria setCacheMode(CacheMode cacheMode) { - this.cacheMode = cacheMode; - return this; - } - @Override - public List list() throws HibernateException { - before(); - try { - return session.list( this ); - } - finally { - after(); - } - } - @Override - public ScrollableResults scroll() { - return scroll( session.getFactory().getDialect().defaultScrollMode() ); - } - @Override - public ScrollableResults scroll(ScrollMode scrollMode) { - before(); - try { - return session.scroll(this, scrollMode); - } - finally { - after(); - } - } - @Override - public Object uniqueResult() throws HibernateException { - return AbstractProducedQuery.uniqueElement( list() ); - } - - protected void before() { - if ( flushMode != null ) { - sessionFlushMode = getSession().getHibernateFlushMode(); - getSession().setHibernateFlushMode( flushMode ); - } - if ( cacheMode != null ) { - sessionCacheMode = getSession().getCacheMode(); - getSession().setCacheMode( cacheMode ); - } - } - - protected void after() { - if ( sessionFlushMode != null ) { - getSession().setHibernateFlushMode( sessionFlushMode ); - sessionFlushMode = null; - } - if ( sessionCacheMode != null ) { - getSession().setCacheMode( sessionCacheMode ); - sessionCacheMode = null; - } - } - - public boolean isLookupByNaturalKey() { - if ( projection != null ) { - return false; - } - if ( subcriteriaList.size() > 0 ) { - return false; - } - if ( criterionEntries.size() != 1 ) { - return false; - } - CriterionEntry ce = criterionEntries.get(0); - return ce.getCriterion() instanceof NaturalIdentifier; - } - - - // Inner classes ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - public final class Subcriteria implements Criteria, Serializable { - - private String alias; - private String path; - private Criteria parent; - private LockMode lockMode; - private JoinType joinType = JoinType.INNER_JOIN; - private Criterion withClause; - private boolean hasRestriction; - - // Constructors ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - private Subcriteria(Criteria parent, String path, String alias, JoinType joinType, Criterion withClause) { - this.alias = alias; - this.path = path; - this.parent = parent; - this.joinType = joinType; - this.withClause = withClause; - this.hasRestriction = withClause != null; - CriteriaImpl.this.subcriteriaList.add( this ); - } - - private Subcriteria(Criteria parent, String path, String alias, JoinType joinType) { - this( parent, path, alias, joinType, null ); - } - - private Subcriteria(Criteria parent, String path, JoinType joinType) { - this( parent, path, null, joinType ); - } - @Override - public String toString() { - return "Subcriteria(" - + path + ":" - + (alias==null ? "" : alias) - + ')'; - } - - - // State ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - @Override - public String getAlias() { - return alias; - } - - public void setAlias(String alias) { - this.alias = alias; - } - - public String getPath() { - return path; - } - - public Criteria getParent() { - return parent; - } - - public LockMode getLockMode() { - return lockMode; - } - @Override - public Criteria setLockMode(LockMode lockMode) { - this.lockMode = lockMode; - return this; - } - - public JoinType getJoinType() { - return joinType; - } - - public Criterion getWithClause() { - return this.withClause; - } - - public boolean hasRestriction() { - return hasRestriction; - } - - // Criteria impl ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - @Override - public Criteria add(Criterion expression) { - hasRestriction = true; - CriteriaImpl.this.add(this, expression); - return this; - } - @Override - public Criteria addOrder(Order order) { - CriteriaImpl.this.orderEntries.add( new OrderEntry(order, this) ); - return this; - } - @Override - public Criteria createAlias(String associationPath, String alias) { - return createAlias( associationPath, alias, JoinType.INNER_JOIN ); - } - @Override - public Criteria createAlias(String associationPath, String alias, JoinType joinType) throws HibernateException { - new Subcriteria( this, associationPath, alias, joinType ); - return this; - } - - @Override - public Criteria createAlias(String associationPath, String alias, int joinType) throws HibernateException { - return createAlias( associationPath, alias, JoinType.parse( joinType ) ); - } - @Override - public Criteria createAlias(String associationPath, String alias, JoinType joinType, Criterion withClause) throws HibernateException { - new Subcriteria( this, associationPath, alias, joinType, withClause ); - return this; - } - - @Override - public Criteria createAlias(String associationPath, String alias, int joinType, Criterion withClause) - throws HibernateException { - return createAlias( associationPath, alias, JoinType.parse( joinType ), withClause ); - } - @Override - public Criteria createCriteria(String associationPath) { - return createCriteria( associationPath, JoinType.INNER_JOIN ); - } - @Override - public Criteria createCriteria(String associationPath, JoinType joinType) throws HibernateException { - return new Subcriteria( Subcriteria.this, associationPath, joinType ); - } - - @Override - public Criteria createCriteria(String associationPath, int joinType) throws HibernateException { - return createCriteria( associationPath, JoinType.parse( joinType ) ); - } - @Override - public Criteria createCriteria(String associationPath, String alias) { - return createCriteria( associationPath, alias, JoinType.INNER_JOIN ); - } - @Override - public Criteria createCriteria(String associationPath, String alias, JoinType joinType) throws HibernateException { - return new Subcriteria( Subcriteria.this, associationPath, alias, joinType ); - } - - @Override - public Criteria createCriteria(String associationPath, String alias, int joinType) throws HibernateException { - return createCriteria( associationPath, alias, JoinType.parse( joinType ) ); - } - @Override - public Criteria createCriteria(String associationPath, String alias, JoinType joinType, Criterion withClause) throws HibernateException { - return new Subcriteria( this, associationPath, alias, joinType, withClause ); - } - - @Override - public Criteria createCriteria(String associationPath, String alias, int joinType, Criterion withClause) - throws HibernateException { - return createCriteria( associationPath, alias, JoinType.parse( joinType ), withClause ); - } - @Override - public boolean isReadOnly() { - return CriteriaImpl.this.isReadOnly(); - } - @Override - public boolean isReadOnlyInitialized() { - return CriteriaImpl.this.isReadOnlyInitialized(); - } - @Override - public Criteria setReadOnly(boolean readOnly) { - CriteriaImpl.this.setReadOnly( readOnly ); - return this; - } - @Override - public Criteria setCacheable(boolean cacheable) { - CriteriaImpl.this.setCacheable(cacheable); - return this; - } - @Override - public Criteria setCacheRegion(String cacheRegion) { - CriteriaImpl.this.setCacheRegion(cacheRegion); - return this; - } - @Override - public List list() throws HibernateException { - return CriteriaImpl.this.list(); - } - @Override - public ScrollableResults scroll() throws HibernateException { - return CriteriaImpl.this.scroll(); - } - @Override - public ScrollableResults scroll(ScrollMode scrollMode) throws HibernateException { - return CriteriaImpl.this.scroll(scrollMode); - } - @Override - public Object uniqueResult() throws HibernateException { - return CriteriaImpl.this.uniqueResult(); - } - @Override - public Criteria setFetchMode(String associationPath, FetchMode mode) { - CriteriaImpl.this.setFetchMode( StringHelper.qualify(path, associationPath), mode); - return this; - } - @Override - public Criteria setFlushMode(FlushMode flushMode) { - CriteriaImpl.this.setFlushMode(flushMode); - return this; - } - @Override - public Criteria setCacheMode(CacheMode cacheMode) { - CriteriaImpl.this.setCacheMode(cacheMode); - return this; - } - @Override - public Criteria setFirstResult(int firstResult) { - CriteriaImpl.this.setFirstResult(firstResult); - return this; - } - @Override - public Criteria setMaxResults(int maxResults) { - CriteriaImpl.this.setMaxResults(maxResults); - return this; - } - @Override - public Criteria setTimeout(int timeout) { - CriteriaImpl.this.setTimeout(timeout); - return this; - } - @Override - public Criteria setFetchSize(int fetchSize) { - CriteriaImpl.this.setFetchSize(fetchSize); - return this; - } - @Override - public Criteria setLockMode(String alias, LockMode lockMode) { - CriteriaImpl.this.setLockMode(alias, lockMode); - return this; - } - @Override - public Criteria setResultTransformer(ResultTransformer resultProcessor) { - CriteriaImpl.this.setResultTransformer(resultProcessor); - return this; - } - @Override - public Criteria setComment(String comment) { - CriteriaImpl.this.setComment(comment); - return this; - } - @Override - public Criteria addQueryHint(String queryHint) { - CriteriaImpl.this.addQueryHint( queryHint ); - return this; - } - @Override - public Criteria setProjection(Projection projection) { - CriteriaImpl.this.projection = projection; - CriteriaImpl.this.projectionCriteria = this; - setResultTransformer(PROJECTION); - return this; - } - } - - public static final class CriterionEntry implements Serializable { - private final Criterion criterion; - private final Criteria criteria; - - private CriterionEntry(Criterion criterion, Criteria criteria) { - this.criteria = criteria; - this.criterion = criterion; - } - - public Criterion getCriterion() { - return criterion; - } - - public Criteria getCriteria() { - return criteria; - } - @Override - public String toString() { - return criterion.toString(); - } - } - - public static final class OrderEntry implements Serializable { - private final Order order; - private final Criteria criteria; - - private OrderEntry(Order order, Criteria criteria) { - this.criteria = criteria; - this.order = order; - } - - public Order getOrder() { - return order; - } - - public Criteria getCriteria() { - return criteria; - } - @Override - public String toString() { - return order.toString(); - } - } -} diff --git a/hibernate-core/src/main/java/org/hibernate/internal/SessionImpl.java b/hibernate-core/src/main/java/org/hibernate/internal/SessionImpl.java index 137a6d03cd..3de2ff8923 100644 --- a/hibernate-core/src/main/java/org/hibernate/internal/SessionImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/internal/SessionImpl.java @@ -74,7 +74,6 @@ import org.hibernate.engine.internal.StatefulPersistenceContext; import org.hibernate.engine.jdbc.LobCreator; import org.hibernate.engine.jdbc.NonContextualLobCreator; import org.hibernate.engine.jdbc.spi.JdbcCoordinator; -import org.hibernate.engine.query.spi.HQLQueryPlan; import org.hibernate.engine.query.spi.NativeSQLQueryPlan; import org.hibernate.engine.query.spi.sql.NativeSQLQuerySpecification; import org.hibernate.engine.spi.ActionQueue; @@ -83,6 +82,7 @@ import org.hibernate.engine.spi.EntityEntry; import org.hibernate.engine.spi.EntityKey; import org.hibernate.engine.spi.LoadQueryInfluencers; import org.hibernate.engine.spi.PersistenceContext; +import org.hibernate.engine.spi.QueryParameters; import org.hibernate.engine.spi.SessionFactoryImplementor; import org.hibernate.engine.spi.SessionImplementor; import org.hibernate.engine.spi.SharedSessionContractImplementor; diff --git a/hibernate-core/src/main/java/org/hibernate/internal/StatelessSessionImpl.java b/hibernate-core/src/main/java/org/hibernate/internal/StatelessSessionImpl.java index 515e74ff70..c68c5baa5b 100755 --- a/hibernate-core/src/main/java/org/hibernate/internal/StatelessSessionImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/internal/StatelessSessionImpl.java @@ -9,18 +9,14 @@ package org.hibernate.internal; import java.io.Serializable; import java.sql.Connection; import java.util.Collections; -import java.util.Iterator; import java.util.List; import javax.transaction.SystemException; import org.hibernate.CacheMode; -import org.hibernate.Criteria; import org.hibernate.EntityMode; import org.hibernate.FlushMode; import org.hibernate.HibernateException; import org.hibernate.LockMode; -import org.hibernate.MappingException; -import org.hibernate.ScrollMode; import org.hibernate.SessionException; import org.hibernate.StatelessSession; import org.hibernate.UnresolvableObjectException; @@ -29,20 +25,18 @@ import org.hibernate.cache.spi.access.EntityDataAccess; import org.hibernate.collection.spi.PersistentCollection; import org.hibernate.engine.internal.StatefulPersistenceContext; import org.hibernate.engine.internal.Versioning; -import org.hibernate.engine.query.spi.HQLQueryPlan; import org.hibernate.engine.query.spi.NativeSQLQueryPlan; import org.hibernate.engine.query.spi.sql.NativeSQLQuerySpecification; import org.hibernate.engine.spi.EntityKey; import org.hibernate.engine.spi.LoadQueryInfluencers; import org.hibernate.engine.spi.PersistenceContext; +import org.hibernate.engine.spi.QueryParameters; import org.hibernate.engine.transaction.internal.jta.JtaStatusHelper; import org.hibernate.engine.transaction.jta.platform.spi.JtaPlatform; import org.hibernate.id.IdentifierGeneratorHelper; -import org.hibernate.loader.criteria.CriteriaLoader; import org.hibernate.loader.custom.CustomLoader; import org.hibernate.loader.custom.CustomQuery; import org.hibernate.persister.entity.EntityPersister; -import org.hibernate.persister.entity.OuterJoinLoadable; import org.hibernate.pretty.MessageHelper; import org.hibernate.proxy.HibernateProxy; import org.hibernate.query.spi.ScrollableResultsImplementor; @@ -64,6 +58,7 @@ public class StatelessSessionImpl extends AbstractSharedSessionContract implemen @Override public void setInternalFetchProfile(String internalFetchProfile) { } + }; private final PersistenceContext temporaryPersistenceContext = new StatefulPersistenceContext( this ); @@ -328,23 +323,6 @@ public class StatelessSessionImpl extends AbstractSharedSessionContract implemen return get( entityName, id ); } - @Override - public Iterator iterate(String query, QueryParameters queryParameters) throws HibernateException { - throw new UnsupportedOperationException(); - } - - @Override - public Iterator iterateFilter(Object collection, String filter, QueryParameters queryParameters) - throws HibernateException { - throw new UnsupportedOperationException(); - } - - @Override - public List listFilter(Object collection, String filter, QueryParameters queryParameters) - throws HibernateException { - throw new UnsupportedOperationException(); - } - @Override public boolean isAutoCloseSessionEnabled() { return getFactory().getSessionFactoryOptions().isAutoCloseSessionEnabled(); @@ -534,94 +512,6 @@ public class StatelessSessionImpl extends AbstractSharedSessionContract implemen } } - @Override - public Criteria createCriteria(Class persistentClass, String alias) { - checkOpen(); - return new CriteriaImpl( persistentClass.getName(), alias, this ); - } - - @Override - public Criteria createCriteria(String entityName, String alias) { - checkOpen(); - return new CriteriaImpl( entityName, alias, this ); - } - - @Override - public Criteria createCriteria(Class persistentClass) { - checkOpen(); - return new CriteriaImpl( persistentClass.getName(), this ); - } - - @Override - public Criteria createCriteria(String entityName) { - checkOpen(); - return new CriteriaImpl( entityName, this ); - } - - @Override - public ScrollableResultsImplementor scroll(Criteria criteria, ScrollMode scrollMode) { - // TODO: Is this guaranteed to always be CriteriaImpl? - CriteriaImpl criteriaImpl = (CriteriaImpl) criteria; - - checkOpen(); - String entityName = criteriaImpl.getEntityOrClassName(); - CriteriaLoader loader = new CriteriaLoader( - getOuterJoinLoadable( entityName ), - getFactory(), - criteriaImpl, - entityName, - getLoadQueryInfluencers() - ); - return loader.scroll( this, scrollMode ); - } - - @Override - @SuppressWarnings({"unchecked"}) - public List list(Criteria criteria) throws HibernateException { - // TODO: Is this guaranteed to always be CriteriaImpl? - CriteriaImpl criteriaImpl = (CriteriaImpl) criteria; - - checkOpen(); - String[] implementors = getFactory().getMetamodel().getImplementors( criteriaImpl.getEntityOrClassName() ); - int size = implementors.length; - - CriteriaLoader[] loaders = new CriteriaLoader[size]; - for ( int i = 0; i < size; i++ ) { - loaders[i] = new CriteriaLoader( - getOuterJoinLoadable( implementors[i] ), - getFactory(), - criteriaImpl, - implementors[i], - getLoadQueryInfluencers() - ); - } - - - List results = Collections.EMPTY_LIST; - boolean success = false; - try { - for ( int i = 0; i < size; i++ ) { - final List currentResults = loaders[i].list( this ); - currentResults.addAll( results ); - results = currentResults; - } - success = true; - } - finally { - afterOperation( success ); - } - temporaryPersistenceContext.clear(); - return results; - } - - private OuterJoinLoadable getOuterJoinLoadable(String entityName) throws MappingException { - EntityPersister persister = getFactory().getMetamodel().entityPersister( entityName ); - if ( !( persister instanceof OuterJoinLoadable ) ) { - throw new MappingException( "class persister is not OuterJoinLoadable: " + entityName ); - } - return (OuterJoinLoadable) persister; - } - @Override public List listCustomQuery(CustomQuery customQuery, QueryParameters queryParameters) throws HibernateException { diff --git a/hibernate-core/src/main/java/org/hibernate/internal/util/streams/GenericArrayCollector.java b/hibernate-core/src/main/java/org/hibernate/internal/util/streams/GenericArrayCollector.java new file mode 100644 index 0000000000..bf61ec91b4 --- /dev/null +++ b/hibernate-core/src/main/java/org/hibernate/internal/util/streams/GenericArrayCollector.java @@ -0,0 +1,62 @@ +/* + * Hibernate, Relational Persistence for Idiomatic Java + * + * License: GNU Lesser General Public License (LGPL), version 2.1 or later + * See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html + */ +package org.hibernate.internal.util.streams; + +import java.lang.reflect.Array; +import java.util.ArrayList; +import java.util.EnumSet; +import java.util.List; +import java.util.Set; +import java.util.function.BiConsumer; +import java.util.function.BinaryOperator; +import java.util.function.Function; +import java.util.function.Supplier; +import java.util.stream.Collector; + +/** + * @author Steve Ebersole + */ +public class GenericArrayCollector implements Collector, T[]> { + public static GenericArrayCollector forType(Class type) { + return new GenericArrayCollector( type ); + } + + private final Class collectedType; + + public GenericArrayCollector(Class collectedType) { + this.collectedType = collectedType; + } + + @Override + public Supplier> supplier() { + return ArrayList::new; + } + + @Override + public BiConsumer, T> accumulator() { + return List::add; + } + + @Override + public BinaryOperator> combiner() { + return (ts, ts2) -> { + ts.addAll( ts2 ); + return ts; + }; + } + + @Override + @SuppressWarnings("unchecked") + public Function, T[]> finisher() { + return ts -> ts.toArray( (T[]) Array.newInstance( collectedType, ts.size() ) ); + } + + @Override + public Set characteristics() { + return EnumSet.of( Characteristics.CONCURRENT ); + } +} diff --git a/hibernate-core/src/main/java/org/hibernate/internal/util/streams/StingArrayCollector.java b/hibernate-core/src/main/java/org/hibernate/internal/util/streams/StingArrayCollector.java new file mode 100644 index 0000000000..cda1f41b5b --- /dev/null +++ b/hibernate-core/src/main/java/org/hibernate/internal/util/streams/StingArrayCollector.java @@ -0,0 +1,57 @@ +/* + * Hibernate, Relational Persistence for Idiomatic Java + * + * License: GNU Lesser General Public License (LGPL), version 2.1 or later + * See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html + */ +package org.hibernate.internal.util.streams; + +import java.util.ArrayList; +import java.util.EnumSet; +import java.util.List; +import java.util.Set; +import java.util.function.BiConsumer; +import java.util.function.BinaryOperator; +import java.util.function.Function; +import java.util.function.Supplier; +import java.util.stream.Collector; + +/** + * A Java 8 Stream Collector for collecting Strings into a String[]. + * + * @author Steve Ebersole + */ +public class StingArrayCollector implements Collector, String[]> { + /** + * Singleton access + */ + public static final StingArrayCollector INSTANCE = new StingArrayCollector(); + + @Override + public Supplier> supplier() { + return ArrayList::new; + } + + @Override + public BiConsumer, String> accumulator() { + return List::add; + } + + @Override + public BinaryOperator> combiner() { + return (strings, strings2) -> { + strings.addAll( strings2 ); + return strings; + }; + } + + @Override + public Function, String[]> finisher() { + return strings -> strings.toArray( new String[strings.size()] ); + } + + @Override + public Set characteristics() { + return EnumSet.of( Characteristics.CONCURRENT ); + } +} diff --git a/hibernate-core/src/main/java/org/hibernate/internal/util/streams/StreamUtils.java b/hibernate-core/src/main/java/org/hibernate/internal/util/streams/StreamUtils.java new file mode 100644 index 0000000000..44a39e9b04 --- /dev/null +++ b/hibernate-core/src/main/java/org/hibernate/internal/util/streams/StreamUtils.java @@ -0,0 +1,21 @@ +/* + * Hibernate, Relational Persistence for Idiomatic Java + * + * License: GNU Lesser General Public License (LGPL), version 2.1 or later + * See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html + */ +package org.hibernate.internal.util.streams; + +/** + * @author Steve Ebersole + */ +public class StreamUtils { + public static StingArrayCollector toStringArray() { + return StingArrayCollector.INSTANCE; + } + + public static GenericArrayCollector toArray(Class collectedType) { + return new GenericArrayCollector<>( collectedType ); + } + +} diff --git a/hibernate-core/src/main/java/org/hibernate/jpa/HibernateQuery.java b/hibernate-core/src/main/java/org/hibernate/jpa/HibernateQuery.java deleted file mode 100755 index cda9c22353..0000000000 --- a/hibernate-core/src/main/java/org/hibernate/jpa/HibernateQuery.java +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Hibernate, Relational Persistence for Idiomatic Java - * - * License: GNU Lesser General Public License (LGPL), version 2.1 or later. - * See the lgpl.txt file in the root directory or . - */ -package org.hibernate.jpa; - -import javax.persistence.Query; - -/** - * Marker interface for Hibernate generated JPA queries so that we can access the underlying Hibernate query objects. - * - * @author Gavin King - * @author Emmanuel Bernard - * @author Steve Ebersole - */ -public interface HibernateQuery extends Query { - /** - * Gives access to the underlying Hibernate query object.. - * - * @return THe Hibernate query object. - */ - public org.hibernate.Query getHibernateQuery(); -} diff --git a/hibernate-core/src/main/java/org/hibernate/jpa/spi/CriteriaQueryTupleTransformer.java b/hibernate-core/src/main/java/org/hibernate/jpa/spi/CriteriaQueryTupleTransformer.java deleted file mode 100644 index 41c3f1d9de..0000000000 --- a/hibernate-core/src/main/java/org/hibernate/jpa/spi/CriteriaQueryTupleTransformer.java +++ /dev/null @@ -1,151 +0,0 @@ -/* - * Hibernate, Relational Persistence for Idiomatic Java - * - * License: GNU Lesser General Public License (LGPL), version 2.1 or later. - * See the lgpl.txt file in the root directory or . - */ -package org.hibernate.jpa.spi; - -import java.util.List; -import javax.persistence.Tuple; -import javax.persistence.TupleElement; - -import org.hibernate.query.criteria.internal.ValueHandlerFactory; -import org.hibernate.transform.BasicTransformerAdapter; - -/** - * ResultTransformer adapter for handling Tuple results from Criteria queries - * - * @author Steve Ebersole - */ -public class CriteriaQueryTupleTransformer extends BasicTransformerAdapter { - private final List valueHandlers; - private final List tupleElements; - - public CriteriaQueryTupleTransformer(List valueHandlers, List tupleElements) { - // todo : should these 2 sizes match *always*? - this.valueHandlers = valueHandlers; - this.tupleElements = tupleElements; - } - - @Override - public Object transformTuple(Object[] tuple, String[] aliases) { - final Object[] valueHandlerResult; - if ( valueHandlers == null ) { - valueHandlerResult = tuple; - } - else { - valueHandlerResult = new Object[tuple.length]; - for ( int i = 0; i < tuple.length; i++ ) { - ValueHandlerFactory.ValueHandler valueHandler = valueHandlers.get( i ); - valueHandlerResult[i] = valueHandler == null - ? tuple[i] - : valueHandler.convert( tuple[i] ); - } - } - - return tupleElements == null - ? valueHandlerResult.length == 1 ? valueHandlerResult[0] : valueHandlerResult - : new TupleImpl( tuple ); - - } - - private class TupleImpl implements Tuple { - private final Object[] tuples; - - private TupleImpl(Object[] tuples) { - if ( tuples.length != tupleElements.size() ) { - throw new IllegalArgumentException( - "Size mismatch between tuple result [" + tuples.length - + "] and expected tuple elements [" + tupleElements.size() + "]" - ); - } - this.tuples = tuples; - } - - public X get(TupleElement tupleElement) { - int index = tupleElements.indexOf( tupleElement ); - if ( index < 0 ) { - throw new IllegalArgumentException( - "Requested tuple element did not correspond to element in the result tuple" - ); - } - // index should be "in range" by nature of size check in ctor - return (X) tuples[index]; - } - - public Object get(String alias) { - int index = -1; - if ( alias != null ) { - alias = alias.trim(); - if ( alias.length() > 0 ) { - int i = 0; - for ( TupleElement selection : (List) tupleElements ) { - if ( alias.equals( selection.getAlias() ) ) { - index = i; - break; - } - i++; - } - } - } - if ( index < 0 ) { - throw new IllegalArgumentException( - "Given alias [" + alias + "] did not correspond to an element in the result tuple" - ); - } - // index should be "in range" by nature of size check in ctor - return tuples[index]; - } - - public X get(String alias, Class type) { - final Object untyped = get( alias ); - if ( untyped != null ) { - if ( !type.isInstance( untyped ) ) { - throw new IllegalArgumentException( - String.format( - "Requested tuple value [alias=%s, value=%s] cannot be assigned to requested type [%s]", - alias, - untyped, - type.getName() - ) - ); - } - } - return (X) untyped; - } - - public Object get(int i) { - if ( i >= tuples.length ) { - throw new IllegalArgumentException( - "Given index [" + i + "] was outside the range of result tuple size [" + tuples.length + "] " - ); - } - return tuples[i]; - } - - public X get(int i, Class type) { - final Object result = get( i ); - if ( result != null && !type.isInstance( result ) ) { - throw new IllegalArgumentException( - String.format( - "Requested tuple value [index=%s, realType=%s] cannot be assigned to requested type [%s]", - i, - result.getClass().getName(), - type.getName() - ) - ); - } - return (X) result; - } - - public Object[] toArray() { - // todo : make a copy? - return tuples; - } - - public List> getElements() { - return tupleElements; - } - } -} diff --git a/hibernate-core/src/main/java/org/hibernate/jpa/spi/StoredProcedureQueryParameterRegistration.java b/hibernate-core/src/main/java/org/hibernate/jpa/spi/StoredProcedureQueryParameterRegistration.java index c971f8f6a2..62893c9a88 100644 --- a/hibernate-core/src/main/java/org/hibernate/jpa/spi/StoredProcedureQueryParameterRegistration.java +++ b/hibernate-core/src/main/java/org/hibernate/jpa/spi/StoredProcedureQueryParameterRegistration.java @@ -6,8 +6,6 @@ */ package org.hibernate.jpa.spi; -import org.hibernate.procedure.spi.ParameterRegistrationImplementor; - /** * ParameterRegistration extension specifically for stored procedure parameters * exposing some functionality of Hibernate's native diff --git a/hibernate-core/src/main/java/org/hibernate/loader/collection/SubselectCollectionLoader.java b/hibernate-core/src/main/java/org/hibernate/loader/collection/SubselectCollectionLoader.java index 6652aec63f..a093cb38fc 100755 --- a/hibernate-core/src/main/java/org/hibernate/loader/collection/SubselectCollectionLoader.java +++ b/hibernate-core/src/main/java/org/hibernate/loader/collection/SubselectCollectionLoader.java @@ -15,6 +15,7 @@ import org.hibernate.HibernateException; import org.hibernate.MappingException; import org.hibernate.engine.spi.EntityKey; import org.hibernate.engine.spi.LoadQueryInfluencers; +import org.hibernate.engine.spi.QueryParameters; import org.hibernate.engine.spi.SessionFactoryImplementor; import org.hibernate.engine.spi.SharedSessionContractImplementor; import org.hibernate.engine.spi.TypedValue; diff --git a/hibernate-core/src/main/java/org/hibernate/loader/collection/SubselectOneToManyLoader.java b/hibernate-core/src/main/java/org/hibernate/loader/collection/SubselectOneToManyLoader.java index f0a9c9c357..43af21749e 100755 --- a/hibernate-core/src/main/java/org/hibernate/loader/collection/SubselectOneToManyLoader.java +++ b/hibernate-core/src/main/java/org/hibernate/loader/collection/SubselectOneToManyLoader.java @@ -15,6 +15,7 @@ import org.hibernate.HibernateException; import org.hibernate.MappingException; import org.hibernate.engine.spi.EntityKey; import org.hibernate.engine.spi.LoadQueryInfluencers; +import org.hibernate.engine.spi.QueryParameters; import org.hibernate.engine.spi.SessionFactoryImplementor; import org.hibernate.engine.spi.SharedSessionContractImplementor; import org.hibernate.engine.spi.TypedValue; diff --git a/hibernate-core/src/main/java/org/hibernate/loader/custom/CustomLoader.java b/hibernate-core/src/main/java/org/hibernate/loader/custom/CustomLoader.java index a523032111..cdde43aa9e 100644 --- a/hibernate-core/src/main/java/org/hibernate/loader/custom/CustomLoader.java +++ b/hibernate-core/src/main/java/org/hibernate/loader/custom/CustomLoader.java @@ -23,6 +23,7 @@ import org.hibernate.Session; import org.hibernate.cache.spi.QueryKey; import org.hibernate.cache.spi.QueryResultsCache; import org.hibernate.dialect.Dialect; +import org.hibernate.engine.spi.QueryParameters; import org.hibernate.engine.spi.SessionFactoryImplementor; import org.hibernate.engine.spi.SharedSessionContractImplementor; import org.hibernate.hql.internal.HolderInstantiator; diff --git a/hibernate-core/src/main/java/org/hibernate/loader/custom/sql/NamedParamBinder.java b/hibernate-core/src/main/java/org/hibernate/loader/custom/sql/NamedParamBinder.java index d900f86247..6961542283 100644 --- a/hibernate-core/src/main/java/org/hibernate/loader/custom/sql/NamedParamBinder.java +++ b/hibernate-core/src/main/java/org/hibernate/loader/custom/sql/NamedParamBinder.java @@ -9,6 +9,7 @@ package org.hibernate.loader.custom.sql; import java.sql.PreparedStatement; import java.sql.SQLException; +import org.hibernate.engine.spi.QueryParameters; import org.hibernate.engine.spi.SharedSessionContractImplementor; import org.hibernate.engine.spi.TypedValue; import org.hibernate.param.ParameterBinder; diff --git a/hibernate-core/src/main/java/org/hibernate/loader/custom/sql/PositionalParamBinder.java b/hibernate-core/src/main/java/org/hibernate/loader/custom/sql/PositionalParamBinder.java index 664eef81af..f3eb23edca 100644 --- a/hibernate-core/src/main/java/org/hibernate/loader/custom/sql/PositionalParamBinder.java +++ b/hibernate-core/src/main/java/org/hibernate/loader/custom/sql/PositionalParamBinder.java @@ -9,6 +9,7 @@ package org.hibernate.loader.custom.sql; import java.sql.PreparedStatement; import java.sql.SQLException; +import org.hibernate.engine.spi.QueryParameters; import org.hibernate.engine.spi.SharedSessionContractImplementor; import org.hibernate.engine.spi.TypedValue; import org.hibernate.param.ParameterBinder; diff --git a/hibernate-core/src/main/java/org/hibernate/loader/internal/MultiIdEntityLoaderStandardImpl.java b/hibernate-core/src/main/java/org/hibernate/loader/internal/MultiIdEntityLoaderStandardImpl.java new file mode 100644 index 0000000000..c486ece8b2 --- /dev/null +++ b/hibernate-core/src/main/java/org/hibernate/loader/internal/MultiIdEntityLoaderStandardImpl.java @@ -0,0 +1,45 @@ +/* + * Hibernate, Relational Persistence for Idiomatic Java + * + * License: GNU Lesser General Public License (LGPL), version 2.1 or later + * See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html + */ +package org.hibernate.loader.internal; + +import java.io.Serializable; +import java.util.List; + +import org.hibernate.engine.spi.SharedSessionContractImplementor; +import org.hibernate.loader.entity.DynamicBatchingEntityLoaderBuilder; +import org.hibernate.loader.spi.MultiIdEntityLoader; +import org.hibernate.persister.entity.EntityPersister; +import org.hibernate.persister.entity.MultiLoadOptions; +import org.hibernate.persister.entity.OuterJoinLoadable; + +/** + * @author Steve Ebersole + */ +public class MultiIdEntityLoaderStandardImpl implements MultiIdEntityLoader { + private final EntityPersister entityDescriptor; + + public MultiIdEntityLoaderStandardImpl(EntityPersister entityDescriptor) { + this.entityDescriptor = entityDescriptor; + } + + @Override + public EntityPersister getLoadable() { + return entityDescriptor; + } + + @Override + public List load(Object[] ids, MultiLoadOptions loadOptions, SharedSessionContractImplementor session) { + //noinspection unchecked + return DynamicBatchingEntityLoaderBuilder.INSTANCE.multiLoad( + (OuterJoinLoadable) entityDescriptor, + (Serializable[]) ids, + session, + loadOptions + ); + + } +} diff --git a/hibernate-core/src/main/java/org/hibernate/loader/internal/NaturalIdLoaderStandardImpl.java b/hibernate-core/src/main/java/org/hibernate/loader/internal/NaturalIdLoaderStandardImpl.java new file mode 100644 index 0000000000..1016d4fb0c --- /dev/null +++ b/hibernate-core/src/main/java/org/hibernate/loader/internal/NaturalIdLoaderStandardImpl.java @@ -0,0 +1,34 @@ +/* + * Hibernate, Relational Persistence for Idiomatic Java + * + * License: GNU Lesser General Public License (LGPL), version 2.1 or later + * See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html + */ +package org.hibernate.loader.internal; + +import org.hibernate.NotYetImplementedFor6Exception; +import org.hibernate.engine.spi.SharedSessionContractImplementor; +import org.hibernate.loader.spi.NaturalIdLoader; +import org.hibernate.persister.entity.EntityPersister; + +/** + * @author Steve Ebersole + */ +public class NaturalIdLoaderStandardImpl implements NaturalIdLoader { + private final EntityPersister entityDescriptor; + + public NaturalIdLoaderStandardImpl(EntityPersister entityDescriptor) { + this.entityDescriptor = entityDescriptor; + } + + @Override + @SuppressWarnings("unchecked") + public EntityPersister getLoadable() { + return entityDescriptor; + } + + @Override + public T load(Object naturalIdToLoad, LoadOptions options, SharedSessionContractImplementor session) { + throw new NotYetImplementedFor6Exception( getClass() ); + } +} diff --git a/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/idtable/BeforeUseAction.java b/hibernate-core/src/main/java/org/hibernate/loader/internal/Preparable.java similarity index 61% rename from hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/idtable/BeforeUseAction.java rename to hibernate-core/src/main/java/org/hibernate/loader/internal/Preparable.java index 06e9296568..a24f0f586a 100644 --- a/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/idtable/BeforeUseAction.java +++ b/hibernate-core/src/main/java/org/hibernate/loader/internal/Preparable.java @@ -4,14 +4,11 @@ * License: GNU Lesser General Public License (LGPL), version 2.1 or later * See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html */ -package org.hibernate.query.sqm.mutation.spi.idtable; +package org.hibernate.loader.internal; /** - * Actions to perform in regards to an id-table prior to each use. - * * @author Steve Ebersole */ -public enum BeforeUseAction { - CREATE, - NONE +public interface Preparable { + void prepare(); } diff --git a/hibernate-core/src/main/java/org/hibernate/loader/internal/SingleIdEntityLoaderProvidedQueryImpl.java b/hibernate-core/src/main/java/org/hibernate/loader/internal/SingleIdEntityLoaderProvidedQueryImpl.java new file mode 100644 index 0000000000..5cf34f1981 --- /dev/null +++ b/hibernate-core/src/main/java/org/hibernate/loader/internal/SingleIdEntityLoaderProvidedQueryImpl.java @@ -0,0 +1,44 @@ +/* + * Hibernate, Relational Persistence for Idiomatic Java + * + * License: GNU Lesser General Public License (LGPL), version 2.1 or later + * See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html + */ +package org.hibernate.loader.internal; + +import org.hibernate.LockOptions; +import org.hibernate.NotYetImplementedFor6Exception; +import org.hibernate.engine.spi.SharedSessionContractImplementor; +import org.hibernate.loader.spi.SingleIdEntityLoader; +import org.hibernate.persister.entity.EntityPersister; + +/** + * Implementation of SingleIdEntityLoader for cases where the application has + * provided the select load query + * + * @author Steve Ebersole + */ +public class SingleIdEntityLoaderProvidedQueryImpl implements SingleIdEntityLoader { + private final EntityPersister entityDescriptor; + private final String loadQueryName; + + public SingleIdEntityLoaderProvidedQueryImpl(EntityPersister entityDescriptor, String loadQueryName) { + this.entityDescriptor = entityDescriptor; + this.loadQueryName = loadQueryName; + } + + @Override + public EntityPersister getLoadable() { + return entityDescriptor; + } + + @Override + public T load(Object pkValue, LockOptions lockOptions, SharedSessionContractImplementor session) { + throw new NotYetImplementedFor6Exception( getClass() ); + } + + @Override + public Object[] loadDatabaseSnapshot(Object id, SharedSessionContractImplementor session) { + return new Object[0]; + } +} diff --git a/hibernate-core/src/main/java/org/hibernate/loader/internal/SingleIdEntityLoaderStandardImpl.java b/hibernate-core/src/main/java/org/hibernate/loader/internal/SingleIdEntityLoaderStandardImpl.java new file mode 100644 index 0000000000..97ed8196a4 --- /dev/null +++ b/hibernate-core/src/main/java/org/hibernate/loader/internal/SingleIdEntityLoaderStandardImpl.java @@ -0,0 +1,140 @@ +/* + * Hibernate, Relational Persistence for Idiomatic Java + * + * License: GNU Lesser General Public License (LGPL), version 2.1 or later + * See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html + */ +package org.hibernate.loader.internal; + +import java.util.EnumMap; + +import org.hibernate.LockMode; +import org.hibernate.LockOptions; +import org.hibernate.NotYetImplementedFor6Exception; +import org.hibernate.engine.spi.LoadQueryInfluencers; +import org.hibernate.engine.spi.SessionFactoryImplementor; +import org.hibernate.engine.spi.SharedSessionContractImplementor; +import org.hibernate.loader.spi.InternalFetchProfile; +import org.hibernate.loader.spi.SingleIdEntityLoader; +import org.hibernate.persister.entity.EntityPersister; +import org.hibernate.sql.exec.spi.JdbcSelect; + +/** + * Standard implementation of SingleIdEntityLoader + * + * @author Steve Ebersole + */ +public class SingleIdEntityLoaderStandardImpl implements SingleIdEntityLoader, Preparable { + private final EntityPersister entityDescriptor; + + private EnumMap selectByLockMode = new EnumMap<>( LockMode.class ); + private EnumMap selectByInternalCascadeProfile; + + public SingleIdEntityLoaderStandardImpl(EntityPersister entityDescriptor) { + this.entityDescriptor = entityDescriptor; + } + + public void prepare() { + // see `org.hibernate.persister.entity.AbstractEntityPersister#createLoaders` + } + + @Override + public EntityPersister getLoadable() { + return entityDescriptor; + } + + @Override + public T load(Object key, LockOptions lockOptions, SharedSessionContractImplementor session) { + + // todo (6.0) : see `org.hibernate.loader.internal.StandardSingleIdEntityLoader#load` in "upstream" 6.0 branch + // - and integrate as much as possible with the `o.h.loader.plan` stuff leveraging the similarities + // between the legacy LoadPlan stuff and DomainResult, Assembler, etc. + + final JdbcSelect jdbcSelect = resolveJdbcSelect( lockOptions, session ); + + throw new NotYetImplementedFor6Exception( getClass() ); + } + + @Override + public Object[] loadDatabaseSnapshot(Object id, SharedSessionContractImplementor session) { + throw new NotYetImplementedFor6Exception( getClass() ); + } + + private JdbcSelect resolveJdbcSelect( + LockOptions lockOptions, + SharedSessionContractImplementor session) { + final LoadQueryInfluencers loadQueryInfluencers = session.getLoadQueryInfluencers(); + if ( entityDescriptor.isAffectedByEnabledFilters( loadQueryInfluencers ) ) { + // special case of not-cacheable based on enabled filters effecting this load. + // + // This case is special because the filters need to be applied in order to + // properly restrict the SQL/JDBC results. For this reason it has higher + // precedence than even "internal" fetch profiles. + return createJdbcSelect( lockOptions, loadQueryInfluencers, session.getFactory() ); + } + + final InternalFetchProfile enabledInternalFetchProfile = loadQueryInfluencers.getEnabledInternalFetchProfile(); + if ( enabledInternalFetchProfile != null ) { + if ( LockMode.UPGRADE.greaterThan( lockOptions.getLockMode() ) ) { + if ( selectByInternalCascadeProfile == null ) { + selectByInternalCascadeProfile = new EnumMap<>( InternalFetchProfile.class ); + } + return selectByInternalCascadeProfile.computeIfAbsent( + loadQueryInfluencers.getEnabledInternalFetchProfile(), + internalFetchProfileType -> createJdbcSelect( lockOptions, loadQueryInfluencers, session.getFactory() ) + ); + } + } + + // otherwise see if the loader for the requested load can be cached - which + // also means we should look in the cache for an existing one + + final boolean cacheable = determineIfCacheable( lockOptions, loadQueryInfluencers ); + + if ( cacheable ) { + return selectByLockMode.computeIfAbsent( + lockOptions.getLockMode(), + lockMode -> createJdbcSelect( lockOptions, loadQueryInfluencers, session.getFactory() ) + ); + } + + return createJdbcSelect( lockOptions, loadQueryInfluencers, session.getFactory() ); + } + + private boolean determineIfCacheable(LockOptions lockOptions, LoadQueryInfluencers loadQueryInfluencers) { + if ( entityDescriptor.isAffectedByEntityGraph( loadQueryInfluencers ) ) { + return false; + } + + if ( entityDescriptor.isAffectedByEnabledFetchProfiles( loadQueryInfluencers ) ) { + return false; + } + + //noinspection RedundantIfStatement + if ( lockOptions.getTimeOut() != LockOptions.WAIT_FOREVER ) { + return false; + } + + return true; + } + + private JdbcSelect createJdbcSelect( + LockOptions lockOptions, + LoadQueryInfluencers queryInfluencers, + SessionFactoryImplementor sessionFactory) { + throw new NotYetImplementedFor6Exception( getClass() ); + +// final MetamodelSelectBuilder selectBuilder = new SelectByEntityIdentifierBuilder( +// entityDescriptor.getFactory(), +// entityDescriptor +// ); +// final SqlAstSelectDescriptor selectDescriptor = selectBuilder +// .generateSelectStatement( 1, queryInfluencers, lockOptions ); +// +// +// return SqlAstSelectToJdbcSelectConverter.interpret( +// selectDescriptor, +// sessionFactory +// ); + } +} diff --git a/hibernate-core/src/main/java/org/hibernate/loader/plan/exec/process/internal/ResultSetProcessorHelper.java b/hibernate-core/src/main/java/org/hibernate/loader/plan/exec/process/internal/ResultSetProcessorHelper.java index 8954c8a169..ec4576dede 100644 --- a/hibernate-core/src/main/java/org/hibernate/loader/plan/exec/process/internal/ResultSetProcessorHelper.java +++ b/hibernate-core/src/main/java/org/hibernate/loader/plan/exec/process/internal/ResultSetProcessorHelper.java @@ -11,6 +11,7 @@ import java.util.HashMap; import java.util.Map; import org.hibernate.engine.spi.EntityKey; +import org.hibernate.engine.spi.QueryParameters; import org.hibernate.engine.spi.SharedSessionContractImplementor; import org.hibernate.loader.plan.exec.query.spi.NamedParameterContext; import org.hibernate.persister.entity.EntityPersister; diff --git a/hibernate-core/src/main/java/org/hibernate/loader/plan/exec/process/internal/ResultSetProcessorImpl.java b/hibernate-core/src/main/java/org/hibernate/loader/plan/exec/process/internal/ResultSetProcessorImpl.java index 81c32a0fae..ab94213c6c 100644 --- a/hibernate-core/src/main/java/org/hibernate/loader/plan/exec/process/internal/ResultSetProcessorImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/loader/plan/exec/process/internal/ResultSetProcessorImpl.java @@ -14,7 +14,6 @@ import java.util.List; import org.hibernate.cfg.NotYetImplementedException; import org.hibernate.dialect.pagination.LimitHelper; -import org.hibernate.engine.spi.PersistenceContext; import org.hibernate.engine.spi.QueryParameters; import org.hibernate.engine.spi.RowSelection; import org.hibernate.engine.spi.SharedSessionContractImplementor; @@ -175,8 +174,7 @@ public class ResultSetProcessorImpl implements ResultSetProcessor { } persistenceContext .getLoadContexts() - .getCollectionLoadContext( resultSet ) - .getLoadingCollection( persister, key ); + .findLoadingCollectionEntry( new CollectionKey( persister, key ) ).getCollectionInstance(); } } diff --git a/hibernate-core/src/main/java/org/hibernate/loader/plan/exec/process/spi/ResultSetProcessingContext.java b/hibernate-core/src/main/java/org/hibernate/loader/plan/exec/process/spi/ResultSetProcessingContext.java index 5f205fbb81..fa16cca2bd 100644 --- a/hibernate-core/src/main/java/org/hibernate/loader/plan/exec/process/spi/ResultSetProcessingContext.java +++ b/hibernate-core/src/main/java/org/hibernate/loader/plan/exec/process/spi/ResultSetProcessingContext.java @@ -8,6 +8,7 @@ package org.hibernate.loader.plan.exec.process.spi; import org.hibernate.LockMode; import org.hibernate.engine.spi.EntityKey; +import org.hibernate.engine.spi.QueryParameters; import org.hibernate.engine.spi.SharedSessionContractImplementor; import org.hibernate.loader.plan.exec.spi.LockModeResolver; import org.hibernate.loader.plan.spi.EntityReference; diff --git a/hibernate-core/src/main/java/org/hibernate/loader/plan/exec/process/spi/ScrollableResultSetProcessor.java b/hibernate-core/src/main/java/org/hibernate/loader/plan/exec/process/spi/ScrollableResultSetProcessor.java index db38cf98f4..a594c576f4 100644 --- a/hibernate-core/src/main/java/org/hibernate/loader/plan/exec/process/spi/ScrollableResultSetProcessor.java +++ b/hibernate-core/src/main/java/org/hibernate/loader/plan/exec/process/spi/ScrollableResultSetProcessor.java @@ -8,6 +8,7 @@ package org.hibernate.loader.plan.exec.process.spi; import java.sql.ResultSet; +import org.hibernate.engine.spi.QueryParameters; import org.hibernate.engine.spi.SessionImplementor; /** diff --git a/hibernate-core/src/main/java/org/hibernate/loader/spi/InternalFetchProfile.java b/hibernate-core/src/main/java/org/hibernate/loader/spi/InternalFetchProfile.java new file mode 100644 index 0000000000..8cd117f04b --- /dev/null +++ b/hibernate-core/src/main/java/org/hibernate/loader/spi/InternalFetchProfile.java @@ -0,0 +1,46 @@ +/* + * Hibernate, Relational Persistence for Idiomatic Java + * + * License: GNU Lesser General Public License (LGPL), version 2.1 or later + * See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html + */ +package org.hibernate.loader.spi; + +import org.hibernate.internal.util.StringHelper; + +/** + * @author Steve Ebersole + */ +public enum InternalFetchProfile { + MERGE( "merge" ), + REFRESH( "refresh" ); + + private final String legacyName; + + InternalFetchProfile(String legacyName) { + this.legacyName = legacyName; + } + + public String getLegacyName() { + return legacyName; + } + + public static InternalFetchProfile fromLegacyName(String legacyName) { + if ( StringHelper.isEmpty( legacyName ) ) { + return null; + } + + if ( MERGE.legacyName.equalsIgnoreCase( legacyName ) ) { + return MERGE; + } + + if ( REFRESH.legacyName.equalsIgnoreCase( legacyName ) ) { + return REFRESH; + } + + throw new IllegalArgumentException( + "Passed name [" + legacyName + "] not recognized as a legacy internal fetch profile name; " + + "supported values include: 'merge' and 'refresh'" + ); + } +} diff --git a/hibernate-core/src/main/java/org/hibernate/loader/spi/Loadable.java b/hibernate-core/src/main/java/org/hibernate/loader/spi/Loadable.java new file mode 100644 index 0000000000..fae153d838 --- /dev/null +++ b/hibernate-core/src/main/java/org/hibernate/loader/spi/Loadable.java @@ -0,0 +1,25 @@ +/* + * Hibernate, Relational Persistence for Idiomatic Java + * + * License: GNU Lesser General Public License (LGPL), version 2.1 or later + * See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html + */ +package org.hibernate.loader.spi; + +import org.hibernate.engine.spi.LoadQueryInfluencers; +import org.hibernate.metamodel.model.mapping.spi.ModelPart; + +/** + * Contract for things that can be loaded by a Loader. + * + * Generally speaking this is limited to entities and collections + * + * @see Loader + * + * @author Steve Ebersole + */ +public interface Loadable extends ModelPart { + boolean isAffectedByEnabledFilters(LoadQueryInfluencers influencers); + boolean isAffectedByEntityGraph(LoadQueryInfluencers influencers); + boolean isAffectedByEnabledFetchProfiles(LoadQueryInfluencers influencers); +} diff --git a/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/idtable/AfterUseAction.java b/hibernate-core/src/main/java/org/hibernate/loader/spi/Loader.java similarity index 58% rename from hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/idtable/AfterUseAction.java rename to hibernate-core/src/main/java/org/hibernate/loader/spi/Loader.java index 13ca5730f2..b16b27f686 100644 --- a/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/idtable/AfterUseAction.java +++ b/hibernate-core/src/main/java/org/hibernate/loader/spi/Loader.java @@ -4,15 +4,16 @@ * License: GNU Lesser General Public License (LGPL), version 2.1 or later * See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html */ -package org.hibernate.query.sqm.mutation.spi.idtable; +package org.hibernate.loader.spi; /** - * Actions to perform in regards to an id-table after each use. + * Common contract for all value-mapping loaders. * * @author Steve Ebersole */ -public enum AfterUseAction { - CLEAN, - DROP, - NONE +public interface Loader { + /** + * The value-mapping loaded by this loader + */ + Loadable getLoadable(); } diff --git a/hibernate-core/src/main/java/org/hibernate/loader/spi/MultiIdEntityLoader.java b/hibernate-core/src/main/java/org/hibernate/loader/spi/MultiIdEntityLoader.java new file mode 100644 index 0000000000..b8aa953b5f --- /dev/null +++ b/hibernate-core/src/main/java/org/hibernate/loader/spi/MultiIdEntityLoader.java @@ -0,0 +1,26 @@ +/* + * Hibernate, Relational Persistence for Idiomatic Java + * + * License: GNU Lesser General Public License (LGPL), version 2.1 or later + * See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html + */ +package org.hibernate.loader.spi; + +import java.util.List; + +import org.hibernate.engine.spi.SharedSessionContractImplementor; +import org.hibernate.persister.entity.EntityPersister; +import org.hibernate.persister.entity.MultiLoadOptions; + +/** + * Loader subtype for loading multiple entities by multiple identifier values. + * + * @author Steve Ebersole + */ +public interface MultiIdEntityLoader extends Loader { + @Override + @SuppressWarnings("unchecked") + EntityPersister getLoadable(); + + List load(Object[] ids, MultiLoadOptions options, SharedSessionContractImplementor session); +} diff --git a/hibernate-core/src/main/java/org/hibernate/loader/spi/NaturalIdLoader.java b/hibernate-core/src/main/java/org/hibernate/loader/spi/NaturalIdLoader.java new file mode 100644 index 0000000000..3e1dc8b589 --- /dev/null +++ b/hibernate-core/src/main/java/org/hibernate/loader/spi/NaturalIdLoader.java @@ -0,0 +1,45 @@ +/* + * Hibernate, Relational Persistence for Idiomatic Java + * + * License: GNU Lesser General Public License (LGPL), version 2.1 or later + * See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html + */ +package org.hibernate.loader.spi; + +import org.hibernate.LockOptions; +import org.hibernate.engine.spi.SharedSessionContractImplementor; + +/** + * Loader for {@link org.hibernate.annotations.NaturalId} handling + * + * @author Steve Ebersole + */ +public interface NaturalIdLoader extends Loader { + interface LoadOptions { + /** + * The locking options for the loaded entity + */ + LockOptions getLockOptions(); + + /** + * Whether Hibernate should perform "synchronization" prior to performing + * look-ups? + */ + boolean isSynchronizationEnabled(); + } + + /** + * Perform the load of the entity by its natural-id + * + * @param naturalIdToLoad The natural-id to load. One of 2 forms accepted: + * * Single-value - valid for entities with a simple (single-valued) + * natural-id + * * Map - valid for any natural-id load. The map is each value keyed + * by the attribute name that the value corresponds to. Even though + * this form is allowed for simple natural-ids, the single value form + * should be used as it is more efficient + * @param options The options to apply to the load operation + * @param session The session into which the entity is being loaded + */ + T load(Object naturalIdToLoad, LoadOptions options, SharedSessionContractImplementor session); +} diff --git a/hibernate-core/src/main/java/org/hibernate/loader/spi/SingleEntityLoader.java b/hibernate-core/src/main/java/org/hibernate/loader/spi/SingleEntityLoader.java new file mode 100644 index 0000000000..03406207f7 --- /dev/null +++ b/hibernate-core/src/main/java/org/hibernate/loader/spi/SingleEntityLoader.java @@ -0,0 +1,27 @@ +/* + * Hibernate, Relational Persistence for Idiomatic Java + * + * License: GNU Lesser General Public License (LGPL), version 2.1 or later + * See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html + */ +package org.hibernate.loader.spi; + +import org.hibernate.LockOptions; +import org.hibernate.engine.spi.SharedSessionContractImplementor; +import org.hibernate.persister.entity.EntityPersister; + +/** + * Loader for loading a single entity by primary or unique key + * + * @author Steve Ebersole + */ +public interface SingleEntityLoader extends Loader { + @Override + @SuppressWarnings("unchecked") + EntityPersister getLoadable(); + + /** + * Load an entity by a primary or unique key value. + */ + T load(Object key, LockOptions lockOptions, SharedSessionContractImplementor session); +} diff --git a/hibernate-core/src/main/java/org/hibernate/loader/spi/SingleIdEntityLoader.java b/hibernate-core/src/main/java/org/hibernate/loader/spi/SingleIdEntityLoader.java new file mode 100644 index 0000000000..c0810c0e1b --- /dev/null +++ b/hibernate-core/src/main/java/org/hibernate/loader/spi/SingleIdEntityLoader.java @@ -0,0 +1,28 @@ +/* + * Hibernate, Relational Persistence for Idiomatic Java + * + * License: GNU Lesser General Public License (LGPL), version 2.1 or later + * See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html + */ +package org.hibernate.loader.spi; + +import org.hibernate.LockOptions; +import org.hibernate.engine.spi.SharedSessionContractImplementor; + +/** + * Loader for loading an entity by a single identifier value. + * + * @author Steve Ebersole + */ +public interface SingleIdEntityLoader extends SingleEntityLoader { + /** + * Load by primary key value + */ + @Override + T load(Object pkValue, LockOptions lockOptions, SharedSessionContractImplementor session); + + /** + * Load database snapshot by primary key value + */ + Object[] loadDatabaseSnapshot(Object id, SharedSessionContractImplementor session); +} diff --git a/hibernate-core/src/main/java/org/hibernate/loader/spi/SingleUniqueKeyEntityLoader.java b/hibernate-core/src/main/java/org/hibernate/loader/spi/SingleUniqueKeyEntityLoader.java new file mode 100644 index 0000000000..0d9d131358 --- /dev/null +++ b/hibernate-core/src/main/java/org/hibernate/loader/spi/SingleUniqueKeyEntityLoader.java @@ -0,0 +1,23 @@ +/* + * Hibernate, Relational Persistence for Idiomatic Java + * + * License: GNU Lesser General Public License (LGPL), version 2.1 or later + * See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html + */ +package org.hibernate.loader.spi; + +import org.hibernate.LockOptions; +import org.hibernate.engine.spi.SharedSessionContractImplementor; + +/** + * Loader subtype for loading an entity by a single unique-key value. + * + * @author Steve Ebersole + */ +public interface SingleUniqueKeyEntityLoader extends SingleEntityLoader { + /** + * Load by unique key value + */ + @Override + T load(Object ukValue, LockOptions lockOptions, SharedSessionContractImplementor session); +} diff --git a/hibernate-core/src/main/java/org/hibernate/metamodel/model/domain/AllowableParameterType.java b/hibernate-core/src/main/java/org/hibernate/metamodel/model/domain/AllowableParameterType.java index d22a19dff3..04db23db1e 100644 --- a/hibernate-core/src/main/java/org/hibernate/metamodel/model/domain/AllowableParameterType.java +++ b/hibernate-core/src/main/java/org/hibernate/metamodel/model/domain/AllowableParameterType.java @@ -18,5 +18,5 @@ import org.hibernate.query.Query; * @author Steve Ebersole */ @Incubating -public interface AllowableParameterType extends Writeable { +public interface AllowableParameterType extends Writeable { } diff --git a/hibernate-core/src/main/java/org/hibernate/metamodel/model/mapping/spi/Writeable.java b/hibernate-core/src/main/java/org/hibernate/metamodel/model/mapping/spi/Writeable.java index 64d9d7ce19..bbc412ca64 100644 --- a/hibernate-core/src/main/java/org/hibernate/metamodel/model/mapping/spi/Writeable.java +++ b/hibernate-core/src/main/java/org/hibernate/metamodel/model/mapping/spi/Writeable.java @@ -6,6 +6,7 @@ */ package org.hibernate.metamodel.model.mapping.spi; +import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Consumer; import org.hibernate.NotYetImplementedFor6Exception; @@ -20,6 +21,16 @@ import org.hibernate.type.spi.TypeConfiguration; * @author Steve Ebersole */ public interface Writeable { + default int getJdbcTypeCount(TypeConfiguration typeConfiguration) { + final AtomicInteger value = new AtomicInteger( 0 ); + visitJdbcTypes( + sqlExpressableType -> value.incrementAndGet(), + Clause.IRRELEVANT, + typeConfiguration + ); + + return value.get(); + } /** * Visit all of the SqlExpressableTypes associated with this this Writeable. diff --git a/hibernate-core/src/main/java/org/hibernate/param/CollectionFilterKeyParameterSpecification.java b/hibernate-core/src/main/java/org/hibernate/param/CollectionFilterKeyParameterSpecification.java index 07ebb786b3..782e7bd236 100644 --- a/hibernate-core/src/main/java/org/hibernate/param/CollectionFilterKeyParameterSpecification.java +++ b/hibernate-core/src/main/java/org/hibernate/param/CollectionFilterKeyParameterSpecification.java @@ -9,6 +9,7 @@ package org.hibernate.param; import java.sql.PreparedStatement; import java.sql.SQLException; +import org.hibernate.engine.spi.QueryParameters; import org.hibernate.engine.spi.SharedSessionContractImplementor; import org.hibernate.type.Type; diff --git a/hibernate-core/src/main/java/org/hibernate/param/DynamicFilterParameterSpecification.java b/hibernate-core/src/main/java/org/hibernate/param/DynamicFilterParameterSpecification.java index 90af89c14c..def45bdf99 100644 --- a/hibernate-core/src/main/java/org/hibernate/param/DynamicFilterParameterSpecification.java +++ b/hibernate-core/src/main/java/org/hibernate/param/DynamicFilterParameterSpecification.java @@ -11,6 +11,7 @@ import java.sql.SQLException; import java.util.Collection; import java.util.Iterator; +import org.hibernate.engine.spi.QueryParameters; import org.hibernate.engine.spi.SharedSessionContractImplementor; import org.hibernate.type.Type; diff --git a/hibernate-core/src/main/java/org/hibernate/param/NamedParameterSpecification.java b/hibernate-core/src/main/java/org/hibernate/param/NamedParameterSpecification.java index ebe703b7f7..b1123b5297 100644 --- a/hibernate-core/src/main/java/org/hibernate/param/NamedParameterSpecification.java +++ b/hibernate-core/src/main/java/org/hibernate/param/NamedParameterSpecification.java @@ -9,6 +9,7 @@ package org.hibernate.param; import java.sql.PreparedStatement; import java.sql.SQLException; +import org.hibernate.engine.spi.QueryParameters; import org.hibernate.engine.spi.SharedSessionContractImplementor; import org.hibernate.engine.spi.TypedValue; diff --git a/hibernate-core/src/main/java/org/hibernate/param/ParameterBinder.java b/hibernate-core/src/main/java/org/hibernate/param/ParameterBinder.java index 00ddcbf680..6a88b02fe8 100644 --- a/hibernate-core/src/main/java/org/hibernate/param/ParameterBinder.java +++ b/hibernate-core/src/main/java/org/hibernate/param/ParameterBinder.java @@ -9,6 +9,7 @@ package org.hibernate.param; import java.sql.PreparedStatement; import java.sql.SQLException; +import org.hibernate.engine.spi.QueryParameters; import org.hibernate.engine.spi.SharedSessionContractImplementor; /** diff --git a/hibernate-core/src/main/java/org/hibernate/param/PositionalParameterSpecification.java b/hibernate-core/src/main/java/org/hibernate/param/PositionalParameterSpecification.java index 8659e8874e..178fb5c5f3 100644 --- a/hibernate-core/src/main/java/org/hibernate/param/PositionalParameterSpecification.java +++ b/hibernate-core/src/main/java/org/hibernate/param/PositionalParameterSpecification.java @@ -9,6 +9,7 @@ package org.hibernate.param; import java.sql.PreparedStatement; import java.sql.SQLException; +import org.hibernate.engine.spi.QueryParameters; import org.hibernate.engine.spi.SharedSessionContractImplementor; import org.hibernate.engine.spi.TypedValue; diff --git a/hibernate-core/src/main/java/org/hibernate/param/VersionTypeSeedParameterSpecification.java b/hibernate-core/src/main/java/org/hibernate/param/VersionTypeSeedParameterSpecification.java index 77997de0fa..669b1eb1f5 100644 --- a/hibernate-core/src/main/java/org/hibernate/param/VersionTypeSeedParameterSpecification.java +++ b/hibernate-core/src/main/java/org/hibernate/param/VersionTypeSeedParameterSpecification.java @@ -9,6 +9,7 @@ package org.hibernate.param; import java.sql.PreparedStatement; import java.sql.SQLException; +import org.hibernate.engine.spi.QueryParameters; import org.hibernate.engine.spi.SharedSessionContractImplementor; import org.hibernate.type.Type; import org.hibernate.type.VersionType; diff --git a/hibernate-core/src/main/java/org/hibernate/persister/collection/AbstractCollectionPersister.java b/hibernate-core/src/main/java/org/hibernate/persister/collection/AbstractCollectionPersister.java index e7f9e2de1b..379870ddd9 100644 --- a/hibernate-core/src/main/java/org/hibernate/persister/collection/AbstractCollectionPersister.java +++ b/hibernate-core/src/main/java/org/hibernate/persister/collection/AbstractCollectionPersister.java @@ -84,12 +84,6 @@ import org.hibernate.sql.Alias; import org.hibernate.sql.SelectFragment; import org.hibernate.sql.SimpleSelect; import org.hibernate.sql.Template; -import org.hibernate.sql.ordering.antlr.ColumnMapper; -import org.hibernate.sql.ordering.antlr.ColumnReference; -import org.hibernate.sql.ordering.antlr.FormulaReference; -import org.hibernate.sql.ordering.antlr.OrderByAliasResolver; -import org.hibernate.sql.ordering.antlr.OrderByTranslation; -import org.hibernate.sql.ordering.antlr.SqlValueReference; import org.hibernate.type.AnyType; import org.hibernate.type.AssociationType; import org.hibernate.type.CollectionType; @@ -622,50 +616,50 @@ public abstract class AbstractCollectionPersister ); } - private class ColumnMapperImpl implements ColumnMapper { - @Override - public SqlValueReference[] map(String reference) { - final String[] columnNames; - final String[] formulaTemplates; - - // handle the special "$element$" property name... - if ( "$element$".equals( reference ) ) { - columnNames = elementColumnNames; - formulaTemplates = elementFormulaTemplates; - } - else { - columnNames = elementPropertyMapping.toColumns( reference ); - formulaTemplates = formulaTemplates( reference, columnNames.length ); - } - - final SqlValueReference[] result = new SqlValueReference[ columnNames.length ]; - int i = 0; - for ( final String columnName : columnNames ) { - if ( columnName == null ) { - // if the column name is null, it indicates that this index in the property value mapping is - // actually represented by a formula. -// final int propertyIndex = elementPersister.getEntityMetamodel().getPropertyIndex( reference ); - final String formulaTemplate = formulaTemplates[i]; - result[i] = new FormulaReference() { - @Override - public String getFormulaFragment() { - return formulaTemplate; - } - }; - } - else { - result[i] = new ColumnReference() { - @Override - public String getColumnName() { - return columnName; - } - }; - } - i++; - } - return result; - } - } +// private class ColumnMapperImpl implements ColumnMapper { +// @Override +// public SqlValueReference[] map(String reference) { +// final String[] columnNames; +// final String[] formulaTemplates; +// +// // handle the special "$element$" property name... +// if ( "$element$".equals( reference ) ) { +// columnNames = elementColumnNames; +// formulaTemplates = elementFormulaTemplates; +// } +// else { +// columnNames = elementPropertyMapping.toColumns( reference ); +// formulaTemplates = formulaTemplates( reference, columnNames.length ); +// } +// +// final SqlValueReference[] result = new SqlValueReference[ columnNames.length ]; +// int i = 0; +// for ( final String columnName : columnNames ) { +// if ( columnName == null ) { +// // if the column name is null, it indicates that this index in the property value mapping is +// // actually represented by a formula. +//// final int propertyIndex = elementPersister.getEntityMetamodel().getPropertyIndex( reference ); +// final String formulaTemplate = formulaTemplates[i]; +// result[i] = new FormulaReference() { +// @Override +// public String getFormulaFragment() { +// return formulaTemplate; +// } +// }; +// } +// else { +// result[i] = new ColumnReference() { +// @Override +// public String getColumnName() { +// return columnName; +// } +// }; +// } +// i++; +// } +// return result; +// } +// } private String[] formulaTemplates(String reference, int expectedSize) { try { @@ -2098,24 +2092,24 @@ public abstract class AbstractCollectionPersister return mappedByProperty; } - private class StandardOrderByAliasResolver implements OrderByAliasResolver { - private final String rootAlias; - - private StandardOrderByAliasResolver(String rootAlias) { - this.rootAlias = rootAlias; - } - - @Override - public String resolveTableAlias(String columnReference) { - if ( elementPersister == null ) { - // we have collection of non-entity elements... - return rootAlias; - } - else { - return ( (Loadable) elementPersister ).getTableAliasForColumn( columnReference, rootAlias ); - } - } - } +// private class StandardOrderByAliasResolver implements OrderByAliasResolver { +// private final String rootAlias; +// +// private StandardOrderByAliasResolver(String rootAlias) { +// this.rootAlias = rootAlias; +// } +// +// @Override +// public String resolveTableAlias(String columnReference) { +// if ( elementPersister == null ) { +// // we have collection of non-entity elements... +// return rootAlias; +// } +// else { +// return ( (Loadable) elementPersister ).getTableAliasForColumn( columnReference, rootAlias ); +// } +// } +// } public abstract FilterAliasGenerator getFilterAliasGenerator(final String rootAlias); diff --git a/hibernate-core/src/main/java/org/hibernate/persister/collection/NamedQueryCollectionInitializer.java b/hibernate-core/src/main/java/org/hibernate/persister/collection/NamedQueryCollectionInitializer.java index 053fbfd92a..e1406ef402 100755 --- a/hibernate-core/src/main/java/org/hibernate/persister/collection/NamedQueryCollectionInitializer.java +++ b/hibernate-core/src/main/java/org/hibernate/persister/collection/NamedQueryCollectionInitializer.java @@ -14,7 +14,7 @@ import org.hibernate.engine.spi.SharedSessionContractImplementor; import org.hibernate.internal.CoreLogging; import org.hibernate.internal.CoreMessageLogger; import org.hibernate.loader.collection.CollectionInitializer; -import org.hibernate.query.spi.NativeQueryImplementor; +import org.hibernate.query.sql.spi.NativeQueryImplementor; /** * A wrapper around a named query. @@ -49,6 +49,6 @@ public final class NamedQueryCollectionInitializer implements CollectionInitiali nativeQuery.setParameter( 1, key, persister.getKeyType() ); } - nativeQuery.setCollectionKey( key ).setFlushMode( FlushMode.MANUAL ).list(); + nativeQuery.setCollectionKey( key ).setHibernateFlushMode( FlushMode.MANUAL ).list(); } } diff --git a/hibernate-core/src/main/java/org/hibernate/persister/entity/AbstractEntityPersister.java b/hibernate-core/src/main/java/org/hibernate/persister/entity/AbstractEntityPersister.java index 3db58f04ec..7a97dfed91 100644 --- a/hibernate-core/src/main/java/org/hibernate/persister/entity/AbstractEntityPersister.java +++ b/hibernate-core/src/main/java/org/hibernate/persister/entity/AbstractEntityPersister.java @@ -100,9 +100,17 @@ import org.hibernate.jdbc.TooManyRowsAffectedException; import org.hibernate.loader.custom.sql.SQLQueryParser; import org.hibernate.loader.entity.BatchingEntityLoaderBuilder; import org.hibernate.loader.entity.CascadeEntityLoader; -import org.hibernate.loader.entity.DynamicBatchingEntityLoaderBuilder; import org.hibernate.loader.entity.EntityLoader; import org.hibernate.loader.entity.UniqueEntityLoader; +import org.hibernate.loader.internal.MultiIdEntityLoaderStandardImpl; +import org.hibernate.loader.internal.NaturalIdLoaderStandardImpl; +import org.hibernate.loader.internal.Preparable; +import org.hibernate.loader.internal.SingleIdEntityLoaderProvidedQueryImpl; +import org.hibernate.loader.internal.SingleIdEntityLoaderStandardImpl; +import org.hibernate.loader.spi.Loader; +import org.hibernate.loader.spi.MultiIdEntityLoader; +import org.hibernate.loader.spi.NaturalIdLoader; +import org.hibernate.loader.spi.SingleIdEntityLoader; import org.hibernate.mapping.Column; import org.hibernate.mapping.Component; import org.hibernate.mapping.Formula; @@ -247,6 +255,10 @@ public abstract class AbstractEntityPersister private final Set affectingFetchProfileNames = new HashSet<>(); + private final SingleIdEntityLoader singleIdEntityLoader; + private final MultiIdEntityLoader multiIdEntityLoader; + private final NaturalIdLoader naturalIdLoader; + private final Map uniqueKeyLoaders = new HashMap(); private final Map lockers = new HashMap(); private UniqueEntityLoader noneLockLoader; @@ -285,10 +297,6 @@ public abstract class AbstractEntityPersister private boolean[] tableHasColumns; - private final String loaderName; - - private UniqueEntityLoader queryLoader; - private final Map subclassPropertyAliases = new HashMap(); private final Map subclassPropertyColumnNames = new HashMap(); @@ -603,7 +611,19 @@ public abstract class AbstractEntityPersister rowIdName = persistentClass.getRootTable().getRowId(); - loaderName = persistentClass.getLoaderName(); + if ( persistentClass.getLoaderName() != null ) { + singleIdEntityLoader = new SingleIdEntityLoaderProvidedQueryImpl( this, persistentClass.getLoaderName() ); + } + // todo (6.0) : account for batch-size and batch-load strategies + else { + singleIdEntityLoader = new SingleIdEntityLoaderStandardImpl( this ); + } + + multiIdEntityLoader = new MultiIdEntityLoaderStandardImpl( this ); + + naturalIdLoader = persistentClass.hasNaturalId() + ? new NaturalIdLoaderStandardImpl( this ) + : null; Iterator iter = persistentClass.getIdentifier().getColumnIterator(); int i = 0; @@ -4247,13 +4267,23 @@ public abstract class AbstractEntityPersister public final void postInstantiate() throws MappingException { doLateInit(); + prepareLoader( singleIdEntityLoader ); + prepareLoader( multiIdEntityLoader ); + prepareLoader( naturalIdLoader ); + + // todo (6.0) : the init done in most of these is delayed now createLoaders(); createUniqueKeyLoaders(); - createQueryLoader(); doPostInstantiate(); } + private void prepareLoader(Loader loader) { + if ( loader instanceof Preparable ) { + ( (Preparable) loader ).prepare(); + } + } + protected void doPostInstantiate() { } @@ -4339,12 +4369,6 @@ public abstract class AbstractEntityPersister } } - protected void createQueryLoader() { - if ( loaderName != null ) { - queryLoader = new NamedQueryLoader( loaderName, this ); - } - } - /** * Load an instance using either the forUpdateLoader or the outer joining loader, * depending upon the value of the lock parameter @@ -4364,8 +4388,7 @@ public abstract class AbstractEntityPersister LOG.tracev( "Fetching entity: {0}", MessageHelper.infoString( this, id, getFactory() ) ); } - final UniqueEntityLoader loader = getAppropriateLoader( lockOptions, session ); - return loader.load( id, optionalObject, session, lockOptions ); + return singleIdEntityLoader.load( id, lockOptions, session ); } @Override @@ -4426,24 +4449,21 @@ public abstract class AbstractEntityPersister @Override public List multiLoad(Serializable[] ids, SharedSessionContractImplementor session, MultiLoadOptions loadOptions) { - return DynamicBatchingEntityLoaderBuilder.INSTANCE.multiLoad( - this, - ids, - session, - loadOptions - ); + return multiIdEntityLoader.load( ids, loadOptions, session ); } public void registerAffectingFetchProfile(String fetchProfileName) { affectingFetchProfileNames.add( fetchProfileName ); } - private boolean isAffectedByEntityGraph(SharedSessionContractImplementor session) { - return session.getLoadQueryInfluencers().getEffectiveEntityGraph().getGraph() != null; + @Override + public boolean isAffectedByEntityGraph(LoadQueryInfluencers loadQueryInfluencers) { + return loadQueryInfluencers.getEffectiveEntityGraph().getGraph() != null; } - private boolean isAffectedByEnabledFetchProfiles(SharedSessionContractImplementor session) { - for ( String s : session.getLoadQueryInfluencers().getEnabledFetchProfileNames() ) { + @Override + public boolean isAffectedByEnabledFetchProfiles(LoadQueryInfluencers loadQueryInfluencers) { + for ( String s : loadQueryInfluencers.getEnabledFetchProfileNames() ) { if ( affectingFetchProfileNames.contains( s ) ) { return true; } @@ -4451,44 +4471,10 @@ public abstract class AbstractEntityPersister return false; } - private boolean isAffectedByEnabledFilters(SharedSessionContractImplementor session) { - return session.getLoadQueryInfluencers().hasEnabledFilters() - && filterHelper.isAffectedBy( session.getLoadQueryInfluencers().getEnabledFilters() ); - } - - protected UniqueEntityLoader getAppropriateLoader(LockOptions lockOptions, SharedSessionContractImplementor session) { - if ( queryLoader != null ) { - // if the user specified a custom query loader we need to that - // regardless of any other consideration - return queryLoader; - } - else if ( isAffectedByEnabledFilters( session ) ) { - // because filters affect the rows returned (because they add - // restrictions) these need to be next in precedence - return createEntityLoader( lockOptions, session.getLoadQueryInfluencers() ); - } - else if ( session.getLoadQueryInfluencers().getInternalFetchProfile() != null && LockMode.UPGRADE.greaterThan( - lockOptions.getLockMode() - ) ) { - // Next, we consider whether an 'internal' fetch profile has been set. - // This indicates a special fetch profile Hibernate needs applied - // (for its merge loading process e.g.). - return loaders.get( session.getLoadQueryInfluencers().getInternalFetchProfile() ); - } - else if ( isAffectedByEnabledFetchProfiles( session ) ) { - // If the session has associated influencers we need to adjust the - // SQL query used for loading based on those influencers - return createEntityLoader( lockOptions, session.getLoadQueryInfluencers() ); - } - else if ( isAffectedByEntityGraph( session ) ) { - return createEntityLoader( lockOptions, session.getLoadQueryInfluencers() ); - } - else if ( lockOptions.getTimeOut() != LockOptions.WAIT_FOREVER ) { - return createEntityLoader( lockOptions, session.getLoadQueryInfluencers() ); - } - else { - return getLoaderByLockMode( lockOptions.getLockMode() ); - } + @Override + public boolean isAffectedByEnabledFilters(LoadQueryInfluencers loadQueryInfluencers) { + return loadQueryInfluencers.hasEnabledFilters() + && filterHelper.isAffectedBy( loadQueryInfluencers.getEnabledFilters() ); } protected final boolean isAllNull(Object[] array, int tableNumber) { diff --git a/hibernate-core/src/main/java/org/hibernate/persister/entity/EntityPersister.java b/hibernate-core/src/main/java/org/hibernate/persister/entity/EntityPersister.java index d8508a2e6c..f278cef92e 100644 --- a/hibernate-core/src/main/java/org/hibernate/persister/entity/EntityPersister.java +++ b/hibernate-core/src/main/java/org/hibernate/persister/entity/EntityPersister.java @@ -29,6 +29,7 @@ import org.hibernate.engine.spi.SharedSessionContractImplementor; import org.hibernate.engine.spi.ValueInclusion; import org.hibernate.id.IdentifierGenerator; import org.hibernate.internal.FilterAliasGenerator; +import org.hibernate.loader.spi.Loadable; import org.hibernate.metadata.ClassMetadata; import org.hibernate.metamodel.model.domain.NavigableRole; import org.hibernate.persister.walking.spi.EntityDefinition; @@ -69,7 +70,7 @@ import org.hibernate.type.VersionType; * @see org.hibernate.persister.spi.PersisterFactory * @see org.hibernate.persister.spi.PersisterClassResolver */ -public interface EntityPersister extends EntityDefinition { +public interface EntityPersister extends EntityDefinition, Loadable { /** * The property name of the "special" identifier property in HQL diff --git a/hibernate-core/src/main/java/org/hibernate/pretty/MessageHelper.java b/hibernate-core/src/main/java/org/hibernate/pretty/MessageHelper.java index 8a16c1c4a0..2a975b4f20 100644 --- a/hibernate-core/src/main/java/org/hibernate/pretty/MessageHelper.java +++ b/hibernate-core/src/main/java/org/hibernate/pretty/MessageHelper.java @@ -152,8 +152,8 @@ public final class MessageHelper { * @return An info string, in the form [FooBar#<1,2,3>] */ public static String infoString( - EntityPersister persister, - Serializable[] ids, + EntityPersister persister, + Object[] ids, SessionFactoryImplementor factory) { StringBuilder s = new StringBuilder(); s.append( '[' ); @@ -237,10 +237,10 @@ public final class MessageHelper { * @param session The session * @return An info string, in the form [Foo.bars#1] */ - public static String collectionInfoString( + public static String collectionInfoString( CollectionPersister persister, PersistentCollection collection, - Serializable collectionKey, + Object collectionKey, SharedSessionContractImplementor session ) { StringBuilder s = new StringBuilder(); @@ -254,7 +254,7 @@ public final class MessageHelper { Type ownerIdentifierType = persister.getOwnerEntityPersister() .getIdentifierType(); - Serializable ownerKey; + Object ownerKey; // TODO: Is it redundant to attempt to use the collectionKey, // or is always using the owner id sufficient? if ( collectionKey.getClass().isAssignableFrom( @@ -284,8 +284,8 @@ public final class MessageHelper { * @return An info string, in the form [Foo.bars#<1,2,3>] */ public static String collectionInfoString( - CollectionPersister persister, - Serializable[] ids, + CollectionPersister persister, + Object[] ids, SessionFactoryImplementor factory) { StringBuilder s = new StringBuilder(); s.append( '[' ); @@ -317,8 +317,8 @@ public final class MessageHelper { * @return An info string, in the form [Foo.bars#1] */ public static String collectionInfoString( - CollectionPersister persister, - Serializable id, + CollectionPersister persister, + Object id, SessionFactoryImplementor factory) { StringBuilder s = new StringBuilder(); s.append( '[' ); @@ -343,7 +343,7 @@ public final class MessageHelper { private static void addIdToCollectionInfoString( CollectionPersister persister, - Serializable id, + Object id, SessionFactoryImplementor factory, StringBuilder s ) { // Need to use the identifier type of the collection owner @@ -374,7 +374,7 @@ public final class MessageHelper { * @param id The id value of the owner * @return An info string, in the form [Foo.bars#1] */ - public static String collectionInfoString(String role, Serializable id) { + public static String collectionInfoString(String role, Object id) { StringBuilder s = new StringBuilder(); s.append( '[' ); if( role == null ) { diff --git a/hibernate-core/src/main/java/org/hibernate/procedure/internal/PostgresCallableStatementSupport.java b/hibernate-core/src/main/java/org/hibernate/procedure/internal/PostgresCallableStatementSupport.java index dfb052f944..f832c223b9 100644 --- a/hibernate-core/src/main/java/org/hibernate/procedure/internal/PostgresCallableStatementSupport.java +++ b/hibernate-core/src/main/java/org/hibernate/procedure/internal/PostgresCallableStatementSupport.java @@ -7,16 +7,13 @@ package org.hibernate.procedure.internal; import java.sql.CallableStatement; -import java.sql.SQLException; -import java.sql.Types; -import java.util.List; -import javax.persistence.ParameterMode; -import org.hibernate.HibernateException; +import org.hibernate.NotYetImplementedFor6Exception; import org.hibernate.engine.spi.SharedSessionContractImplementor; import org.hibernate.procedure.spi.CallableStatementSupport; -import org.hibernate.procedure.spi.ParameterRegistrationImplementor; import org.hibernate.procedure.spi.ParameterStrategy; +import org.hibernate.query.spi.ParameterMetadataImplementor; +import org.hibernate.sql.exec.spi.JdbcCall; /** * @author Steve Ebersole @@ -28,51 +25,54 @@ public class PostgresCallableStatementSupport implements CallableStatementSuppor public static final PostgresCallableStatementSupport INSTANCE = new PostgresCallableStatementSupport(); @Override - public String renderCallableStatement( + public JdbcCall interpretCall( String procedureName, - ParameterStrategy parameterStrategy, - List> parameterRegistrations, + FunctionReturnImpl functionReturn, + ParameterMetadataImplementor parameterMetadata, + ProcedureParamBindings paramBindings, SharedSessionContractImplementor session) { - // if there are any parameters, see if the first is REF_CURSOR - final boolean firstParamIsRefCursor = ! parameterRegistrations.isEmpty() - && parameterRegistrations.get( 0 ).getMode() == ParameterMode.REF_CURSOR; + throw new NotYetImplementedFor6Exception( getClass() ); - if ( firstParamIsRefCursor ) { - // validate that the parameter strategy is positional (cannot mix, and REF_CURSOR is inherently positional) - if ( parameterStrategy == ParameterStrategy.NAMED ) { - throw new HibernateException( "Cannot mix named parameters and REF_CURSOR parameter on PostgreSQL" ); - } - } - - final StringBuilder buffer; - if ( firstParamIsRefCursor ) { - buffer = new StringBuilder().append( "{? = call " ); - } - else { - buffer = new StringBuilder().append( "{call " ); - } - - buffer.append( procedureName ).append( "(" ); - - String sep = ""; - - // skip the first registration if it was a REF_CURSOR - final int startIndex = firstParamIsRefCursor ? 1 : 0; - for ( int i = startIndex; i < parameterRegistrations.size(); i++ ) { - final ParameterRegistrationImplementor parameter = parameterRegistrations.get( i ); - - // any additional REF_CURSOR parameter registrations are an error - if ( parameter.getMode() == ParameterMode.REF_CURSOR ) { - throw new HibernateException( "PostgreSQL supports only one REF_CURSOR parameter, but multiple were registered" ); - } - - for ( int ignored : parameter.getSqlTypes() ) { - buffer.append( sep ).append( "?" ); - sep = ","; - } - } - - return buffer.append( ")}" ).toString(); +// // if there are any parameters, see if the first is REF_CURSOR +// final boolean firstParamIsRefCursor = ! parameterRegistrations.isEmpty() +// && parameterRegistrations.get( 0 ).getMode() == ParameterMode.REF_CURSOR; +// +// if ( firstParamIsRefCursor ) { +// // validate that the parameter strategy is positional (cannot mix, and REF_CURSOR is inherently positional) +// if ( parameterStrategy == ParameterStrategy.NAMED ) { +// throw new HibernateException( "Cannot mix named parameters and REF_CURSOR parameter on PostgreSQL" ); +// } +// } +// +// final StringBuilder buffer; +// if ( firstParamIsRefCursor ) { +// buffer = new StringBuilder().append( "{? = call " ); +// } +// else { +// buffer = new StringBuilder().append( "{call " ); +// } +// +// buffer.append( procedureName ).append( "(" ); +// +// String sep = ""; +// +// // skip the first registration if it was a REF_CURSOR +// final int startIndex = firstParamIsRefCursor ? 1 : 0; +// for ( int i = startIndex; i < parameterRegistrations.size(); i++ ) { +// final ParameterRegistrationImplementor parameter = parameterRegistrations.get( i ); +// +// // any additional REF_CURSOR parameter registrations are an error +// if ( parameter.getMode() == ParameterMode.REF_CURSOR ) { +// throw new HibernateException( "PostgreSQL supports only one REF_CURSOR parameter, but multiple were registered" ); +// } +// +// for ( int ignored : parameter.getSqlTypes() ) { +// buffer.append( sep ).append( "?" ); +// sep = ","; +// } +// } +// +// return buffer.append( ")}" ).toString(); } @Override @@ -80,30 +80,32 @@ public class PostgresCallableStatementSupport implements CallableStatementSuppor String procedureName, CallableStatement statement, ParameterStrategy parameterStrategy, - List> parameterRegistrations, + ParameterMetadataImplementor parameterMetadata, SharedSessionContractImplementor session) { - // prepare parameters - int i = 1; + throw new NotYetImplementedFor6Exception( getClass() ); - try { - for ( ParameterRegistrationImplementor parameter : parameterRegistrations ) { - if ( parameter.getMode() == ParameterMode.REF_CURSOR ) { - statement.registerOutParameter( i, Types.OTHER ); - i++; - - } - else { - parameter.prepare( statement, i ); - i += parameter.getSqlTypes().length; - } - } - } - catch (SQLException e) { - throw session.getJdbcServices().getSqlExceptionHelper().convert( - e, - "Error registering CallableStatement parameters", - procedureName - ); - } +// // prepare parameters +// int i = 1; +// +// try { +// for ( ParameterRegistrationImplementor parameter : parameterRegistrations ) { +// if ( parameter.getMode() == ParameterMode.REF_CURSOR ) { +// statement.registerOutParameter( i, Types.OTHER ); +// i++; +// +// } +// else { +// parameter.prepare( statement, i ); +// i += parameter.getSqlTypes().length; +// } +// } +// } +// catch (SQLException e) { +// throw session.getJdbcServices().getSqlExceptionHelper().convert( +// e, +// "Error registering CallableStatement parameters", +// procedureName +// ); +// } } } diff --git a/hibernate-core/src/main/java/org/hibernate/procedure/internal/StandardCallableStatementSupport.java b/hibernate-core/src/main/java/org/hibernate/procedure/internal/StandardCallableStatementSupport.java index 9137121878..630c1ce700 100644 --- a/hibernate-core/src/main/java/org/hibernate/procedure/internal/StandardCallableStatementSupport.java +++ b/hibernate-core/src/main/java/org/hibernate/procedure/internal/StandardCallableStatementSupport.java @@ -7,16 +7,19 @@ package org.hibernate.procedure.internal; import java.sql.CallableStatement; -import java.sql.SQLException; -import java.util.List; +import java.util.function.Consumer; import javax.persistence.ParameterMode; +import org.hibernate.NotYetImplementedFor6Exception; import org.hibernate.QueryException; import org.hibernate.dialect.Dialect; import org.hibernate.engine.spi.SharedSessionContractImplementor; import org.hibernate.procedure.spi.CallableStatementSupport; -import org.hibernate.procedure.spi.ParameterRegistrationImplementor; import org.hibernate.procedure.spi.ParameterStrategy; +import org.hibernate.procedure.spi.ProcedureParameterImplementor; +import org.hibernate.query.spi.ParameterMetadataImplementor; +import org.hibernate.query.spi.QueryParameterImplementor; +import org.hibernate.sql.exec.spi.JdbcCall; /** * Standard implementation of CallableStatementSupport @@ -41,34 +44,49 @@ public class StandardCallableStatementSupport implements CallableStatementSuppor } @Override - public String renderCallableStatement( + public JdbcCall interpretCall( String procedureName, - ParameterStrategy parameterStrategy, - List> parameterRegistrations, + FunctionReturnImpl functionReturn, + ParameterMetadataImplementor parameterMetadata, + ProcedureParamBindings paramBindings, SharedSessionContractImplementor session) { final StringBuilder buffer = new StringBuilder().append( "{call " ) .append( procedureName ) .append( "(" ); - String sep = ""; - for ( ParameterRegistrationImplementor parameter : parameterRegistrations ) { - if ( parameter == null ) { - throw new QueryException( "Parameter registrations had gaps" ); - } - if ( parameter.getMode() == ParameterMode.REF_CURSOR ) { - verifyRefCursorSupport( session.getJdbcServices().getJdbcEnvironment().getDialect() ); - buffer.append( sep ).append( "?" ); - sep = ","; - } - else { - for ( int i = 0; i < parameter.getSqlTypes().length; i++ ) { - buffer.append( sep ).append( "?" ); - sep = ","; + parameterMetadata.visitParameters( + new Consumer>() { + String sep = ""; + + @Override + public void accept(QueryParameterImplementor param) { + if ( param == null ) { + throw new QueryException( "Parameter registrations had gaps" ); + } + + final ProcedureParameterImplementor parameter = (ProcedureParameterImplementor) param; + + if ( parameter.getMode() == ParameterMode.REF_CURSOR ) { + verifyRefCursorSupport( session.getJdbcServices().getJdbcEnvironment().getDialect() ); + buffer.append( sep ).append( "?" ); + sep = ","; + } + else { + final int jdbcTypeCount = parameter.getHibernateType().getJdbcTypeCount( + session.getFactory().getTypeConfiguration() + ); + + for ( int i = 0; i < jdbcTypeCount; i++ ) { + buffer.append( sep ).append( "?" ); + sep = ","; + } + } + } } - } - } + ); - return buffer.append( ")}" ).toString(); + throw new NotYetImplementedFor6Exception( getClass() ); +// return buffer.append( ")}" ).toString(); } private void verifyRefCursorSupport(Dialect dialect) { @@ -82,28 +100,32 @@ public class StandardCallableStatementSupport implements CallableStatementSuppor String procedureName, CallableStatement statement, ParameterStrategy parameterStrategy, - List> parameterRegistrations, + ParameterMetadataImplementor parameterMetadata, SharedSessionContractImplementor session) { - // prepare parameters - int i = 1; + throw new NotYetImplementedFor6Exception( getClass() ); - try { - for ( ParameterRegistrationImplementor parameter : parameterRegistrations ) { - parameter.prepare( statement, i ); - if ( parameter.getMode() == ParameterMode.REF_CURSOR ) { - i++; - } - else { - i += parameter.getSqlTypes().length; - } - } - } - catch (SQLException e) { - throw session.getJdbcServices().getSqlExceptionHelper().convert( - e, - "Error registering CallableStatement parameters", - procedureName - ); - } +// final AtomicInteger count = new AtomicInteger( 1 ); +// +// try { +// parameterMetadata.visitParameters( +// param -> { +// final ProcedureParameterImplementor parameter = (ProcedureParameterImplementor) param; +// parameter.prepare( statement, count.get() ); +// if ( parameter.getMode() == ParameterMode.REF_CURSOR ) { +// i++; +// } +// else { +// i += parameter.getSqlTypes().length; +// } +// } +// ); +// } +// catch (SQLException e) { +// throw session.getJdbcServices().getSqlExceptionHelper().convert( +// e, +// "Error registering CallableStatement parameters", +// procedureName +// ); +// } } } diff --git a/hibernate-core/src/main/java/org/hibernate/query/internal/AbstractProducedQuery.java b/hibernate-core/src/main/java/org/hibernate/query/internal/AbstractProducedQuery.java index 4167da6c3f..51049bff3f 100644 --- a/hibernate-core/src/main/java/org/hibernate/query/internal/AbstractProducedQuery.java +++ b/hibernate-core/src/main/java/org/hibernate/query/internal/AbstractProducedQuery.java @@ -11,14 +11,11 @@ import java.time.Instant; import java.time.LocalDateTime; import java.time.OffsetDateTime; import java.time.ZonedDateTime; -import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Collection; -import java.util.Collections; import java.util.Date; import java.util.HashMap; -import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Optional; @@ -34,53 +31,47 @@ import javax.persistence.LockModeType; import javax.persistence.NoResultException; import javax.persistence.Parameter; import javax.persistence.TemporalType; -import javax.persistence.TransactionRequiredException; import org.hibernate.CacheMode; -import org.hibernate.Filter; import org.hibernate.FlushMode; import org.hibernate.HibernateException; import org.hibernate.LockMode; import org.hibernate.LockOptions; import org.hibernate.NonUniqueResultException; +import org.hibernate.NotYetImplementedFor6Exception; import org.hibernate.PropertyNotFoundException; import org.hibernate.QueryParameterException; import org.hibernate.ScrollMode; import org.hibernate.TypeMismatchException; import org.hibernate.engine.query.spi.EntityGraphQueryHint; -import org.hibernate.engine.query.spi.HQLQueryPlan; import org.hibernate.engine.spi.ExceptionConverter; +import org.hibernate.engine.spi.QueryParameters; import org.hibernate.engine.spi.RowSelection; import org.hibernate.engine.spi.SharedSessionContractImplementor; -import org.hibernate.engine.spi.TypedValue; import org.hibernate.graph.GraphSemantic; import org.hibernate.graph.RootGraph; import org.hibernate.graph.spi.RootGraphImplementor; -import org.hibernate.hql.internal.QueryExecutionRequestException; -import org.hibernate.internal.EmptyScrollableResults; import org.hibernate.internal.EntityManagerMessageLogger; import org.hibernate.internal.HEMLogging; -import org.hibernate.internal.util.collections.ArrayHelper; import org.hibernate.jpa.QueryHints; -import org.hibernate.jpa.TypedParameterValue; -import org.hibernate.graph.internal.RootGraphImpl; -import org.hibernate.jpa.internal.util.CacheModeHelper; import org.hibernate.jpa.internal.util.ConfigurationHelper; import org.hibernate.jpa.internal.util.FlushModeTypeHelper; import org.hibernate.jpa.internal.util.LockModeTypeHelper; +import org.hibernate.metamodel.model.domain.AllowableParameterType; import org.hibernate.property.access.spi.BuiltInPropertyAccessStrategies; import org.hibernate.property.access.spi.Getter; import org.hibernate.property.access.spi.PropertyAccess; import org.hibernate.query.ParameterMetadata; import org.hibernate.query.Query; import org.hibernate.query.QueryParameter; +import org.hibernate.query.TypedParameterValue; +import org.hibernate.query.spi.MutableQueryOptions; import org.hibernate.query.spi.QueryImplementor; import org.hibernate.query.spi.QueryParameterBinding; import org.hibernate.query.spi.QueryParameterBindings; -import org.hibernate.query.spi.QueryParameterListBinding; +import org.hibernate.query.spi.QueryParameterImplementor; import org.hibernate.query.spi.ScrollableResultsImplementor; import org.hibernate.transform.ResultTransformer; -import org.hibernate.type.Type; import org.jboss.logging.Logger; @@ -113,20 +104,8 @@ public abstract class AbstractProducedQuery implements QueryImplementor { private final SharedSessionContractImplementor producer; private final ParameterMetadata parameterMetadata; - private FlushMode flushMode; - private CacheStoreMode cacheStoreMode; - private CacheRetrieveMode cacheRetrieveMode; - private boolean cacheable; - private String cacheRegion; - private Boolean readOnly; - - private LockOptions lockOptions = new LockOptions(); - - private String comment; - private final List dbHints = new ArrayList<>(); - private ResultTransformer resultTransformer; - private RowSelection queryOptions = new RowSelection(); + private MutableQueryOptions queryOptions = new QueryOptionsImpl(); private EntityGraphQueryHint entityGraphQueryHint; @@ -143,79 +122,74 @@ public abstract class AbstractProducedQuery implements QueryImplementor { this.parameterMetadata = parameterMetadata; } + @Override - public SharedSessionContractImplementor getProducer() { - return producer; + public MutableQueryOptions getQueryOptions() { + return queryOptions; } + @Override public FlushMode getHibernateFlushMode() { - return flushMode; + return getQueryOptions().getFlushMode(); } @Override @SuppressWarnings("unchecked") public QueryImplementor setHibernateFlushMode(FlushMode flushMode) { - this.flushMode = flushMode; + getQueryOptions().setFlushMode( flushMode ); return this; } - @Override - public QueryImplementor setFlushMode(FlushMode flushMode) { - return setHibernateFlushMode( flushMode ); - } - @Override public FlushModeType getFlushMode() { - getProducer().checkOpen(); - return ( flushMode == null ? - getProducer().getFlushMode() : - FlushModeTypeHelper.getFlushModeType( flushMode ) - ); + getSession().checkOpen(); + return getHibernateFlushMode() == null + ? getSession().getFlushMode() + : FlushModeTypeHelper.getFlushModeType( getHibernateFlushMode() ); } @Override @SuppressWarnings("unchecked") public QueryImplementor setFlushMode(FlushModeType flushModeType) { - getProducer().checkOpen(); + getSession().checkOpen(); setHibernateFlushMode( FlushModeTypeHelper.getFlushMode( flushModeType ) ); return this; } @Override public CacheMode getCacheMode() { - return CacheModeHelper.interpretCacheMode( cacheStoreMode, cacheRetrieveMode ); + return getQueryOptions().getCacheMode(); } @Override @SuppressWarnings("unchecked") public QueryImplementor setCacheMode(CacheMode cacheMode) { - this.cacheStoreMode = CacheModeHelper.interpretCacheStoreMode( cacheMode ); - this.cacheRetrieveMode = CacheModeHelper.interpretCacheRetrieveMode( cacheMode ); + getQueryOptions().setCacheMode( cacheMode ); return this; } @Override public boolean isCacheable() { - return cacheable; + return getQueryOptions().isResultCachingEnabled(); } @Override @SuppressWarnings("unchecked") public QueryImplementor setCacheable(boolean cacheable) { - this.cacheable = cacheable; + getQueryOptions().setResultCachingEnabled( cacheable ); return this; } @Override public String getCacheRegion() { - return cacheRegion; + return getQueryOptions().getResultCacheRegionName(); } @Override @SuppressWarnings("unchecked") public QueryImplementor setCacheRegion(String cacheRegion) { - this.cacheRegion = cacheRegion; + getQueryOptions().setResultCacheRegionName( cacheRegion ); return this; } @@ -245,70 +219,69 @@ public abstract class AbstractProducedQuery implements QueryImplementor { @Override public boolean isReadOnly() { - return ( readOnly == null ? - producer.getPersistenceContextInternal().isDefaultReadOnly() : - readOnly - ); + return getQueryOptions().isReadOnly() == null + ? getSession().isDefaultReadOnly() + : getQueryOptions().isReadOnly(); } @Override @SuppressWarnings("unchecked") public QueryImplementor setReadOnly(boolean readOnly) { - this.readOnly = readOnly; + getQueryOptions().setReadOnly( readOnly ); return this; } @Override public LockOptions getLockOptions() { - return lockOptions; + return getQueryOptions().getLockOptions(); } @Override @SuppressWarnings("unchecked") public QueryImplementor setLockOptions(LockOptions lockOptions) { - this.lockOptions.setLockMode( lockOptions.getLockMode() ); - this.lockOptions.setScope( lockOptions.getScope() ); - this.lockOptions.setTimeOut( lockOptions.getTimeOut() ); - this.lockOptions.setFollowOnLocking( lockOptions.getFollowOnLocking() ); + getQueryOptions().getLockOptions().setLockMode( lockOptions.getLockMode() ); + getQueryOptions().getLockOptions().setScope( lockOptions.getScope() ); + getQueryOptions().getLockOptions().setTimeOut( lockOptions.getTimeOut() ); + getQueryOptions().getLockOptions().setFollowOnLocking( lockOptions.getFollowOnLocking() ); return this; } @Override @SuppressWarnings("unchecked") public QueryImplementor setLockMode(String alias, LockMode lockMode) { - lockOptions.setAliasSpecificLockMode( alias, lockMode ); + getQueryOptions().getLockOptions().setAliasSpecificLockMode( alias, lockMode ); return this; } @Override @SuppressWarnings("unchecked") public QueryImplementor setLockMode(LockModeType lockModeType) { - getProducer().checkOpen(); + getSession().checkOpen(); if ( !LockModeType.NONE.equals( lockModeType ) ) { if ( !isSelect() ) { throw new IllegalStateException( "Illegal attempt to set lock mode on a non-SELECT query" ); } } - lockOptions.setLockMode( LockModeTypeHelper.getLockMode( lockModeType ) ); + getQueryOptions().getLockOptions().setLockMode( LockModeTypeHelper.getLockMode( lockModeType ) ); return this; } @Override public String getComment() { - return comment; + return getQueryOptions().getComment(); } @Override @SuppressWarnings("unchecked") public QueryImplementor setComment(String comment) { - this.comment = comment; + getQueryOptions().setComment( comment ); return this; } @Override @SuppressWarnings("unchecked") public QueryImplementor addQueryHint(String hint) { - this.dbHints.add( hint ); + getQueryOptions().addDatabaseHint( hint ); return this; } @@ -317,11 +290,6 @@ public abstract class AbstractProducedQuery implements QueryImplementor { return parameterMetadata; } - @Override - public String[] getNamedParameters() { - return ArrayHelper.toStringArray( getParameterMetadata().getNamedParameterNames() ); - } - @Override public QueryImplementor setParameter(Parameter param, Instant value, TemporalType temporalType) { locateBinding( param ).setBindValue( value, temporalType ); @@ -390,7 +358,7 @@ public abstract class AbstractProducedQuery implements QueryImplementor { @Override public QueryImplementor setParameter(int position, OffsetDateTime value, TemporalType temporalType) { - final QueryParameterBinding binding = getQueryParameterBindings().getBinding( + final QueryParameterBinding binding = getQueryParameterBindings().getBinding( getParameterMetadata().getQueryParameter( position ) ); @@ -402,20 +370,20 @@ public abstract class AbstractProducedQuery implements QueryImplementor { @Override @SuppressWarnings("unchecked") public

QueryImplementor setParameter(QueryParameter

parameter, P value) { - getQueryParameterBindings().getBinding( (QueryParameter) parameter ).setBindValue( value ); + getQueryParameterBindings().getBinding( parameter ).setBindValue( value ); return this; } @SuppressWarnings("unchecked") private

QueryParameterBinding

locateBinding(Parameter

parameter) { - if ( parameter instanceof QueryParameter ) { - return getQueryParameterBindings().getBinding( (QueryParameter) parameter ); + if ( parameter instanceof QueryParameterImplementor ) { + return getQueryParameterBindings().getBinding( (QueryParameterImplementor) parameter ); } else if ( parameter.getName() != null ) { - return getQueryParameterBindings().getBinding( parameter.getName() ); + return (QueryParameterBinding) getQueryParameterBindings().getBinding( parameter.getName() ); } else if ( parameter.getPosition() != null ) { - return getQueryParameterBindings().getBinding( parameter.getPosition() ); + return (QueryParameterBinding) getQueryParameterBindings().getBinding( parameter.getPosition() ); } throw getExceptionConverter().convert( @@ -424,22 +392,25 @@ public abstract class AbstractProducedQuery implements QueryImplementor { } private

QueryParameterBinding

locateBinding(String name) { - return getQueryParameterBindings().getBinding( name ); + //noinspection unchecked + return (QueryParameterBinding) getQueryParameterBindings().getBinding( name ); } private

QueryParameterBinding

locateBinding(int position) { - return getQueryParameterBindings().getBinding( position ); + //noinspection unchecked + return (QueryParameterBinding) getQueryParameterBindings().getBinding( position ); } @Override @SuppressWarnings("unchecked") public

QueryImplementor setParameter(Parameter

parameter, P value) { - getProducer().checkOpen(); + getSession().checkOpen(); if ( value instanceof TypedParameterValue ) { - setParameter( parameter, ( (TypedParameterValue) value ).getValue(), ( (TypedParameterValue) value ).getType() ); - } - else if ( value instanceof Collection && !isRegisteredAsBasicType( value.getClass() ) ) { - locateListBinding( parameter ).setBindValues( (Collection) value ); + setParameter( + parameter, + ( (TypedParameterValue) value ).getValue(), + ( (TypedParameterValue) value ).getType() + ); } else { locateBinding( parameter ).setBindValue( value ); @@ -449,34 +420,22 @@ public abstract class AbstractProducedQuery implements QueryImplementor { } @SuppressWarnings("unchecked") - private

void setParameter(Parameter

parameter, Object value, Type type) { + private

void setParameter(Parameter

parameter, Object value, AllowableParameterType type) { if ( parameter instanceof QueryParameter ) { setParameter( (QueryParameter) parameter, value, type ); } else if ( value == null ) { locateBinding( parameter ).setBindValue( null, type ); } - else if ( value instanceof Collection && !isRegisteredAsBasicType( value.getClass() ) ) { - locateListBinding( parameter ).setBindValues( (Collection) value, type ); - } else { locateBinding( parameter ).setBindValue( (P) value, type ); } } - private QueryParameterListBinding locateListBinding(Parameter parameter) { - if ( parameter instanceof QueryParameter ) { - return getQueryParameterBindings().getQueryParameterListBinding( (QueryParameter) parameter ); - } - else { - return getQueryParameterBindings().getQueryParameterListBinding( parameter.getName() ); - } - } - @Override @SuppressWarnings("unchecked") public QueryImplementor setParameter(String name, Object value) { - getProducer().checkOpen(); + getSession().checkOpen(); if ( value instanceof TypedParameterValue ) { final TypedParameterValue typedValueWrapper = (TypedParameterValue) value; setParameter( name, typedValueWrapper.getValue(), typedValueWrapper.getType() ); @@ -494,13 +453,13 @@ public abstract class AbstractProducedQuery implements QueryImplementor { @Override @SuppressWarnings("unchecked") public QueryImplementor setParameter(int position, Object value) { - getProducer().checkOpen(); + getSession().checkOpen(); if ( value instanceof TypedParameterValue ) { final TypedParameterValue typedParameterValue = (TypedParameterValue) value; setParameter( position, typedParameterValue.getValue(), typedParameterValue.getType() ); } else if ( value instanceof Collection && !isRegisteredAsBasicType( value.getClass() ) ) { - setParameterList( getParameterMetadata().getQueryParameter( position ), (Collection) value ); + setParameterList( position, (Collection) value ); } else { getQueryParameterBindings().getBinding( position ).setBindValue( value ); @@ -510,21 +469,21 @@ public abstract class AbstractProducedQuery implements QueryImplementor { @Override @SuppressWarnings("unchecked") - public

QueryImplementor setParameter(QueryParameter

parameter, P value, Type type) { + public

QueryImplementor setParameter(QueryParameter

parameter, P value, AllowableParameterType type) { getQueryParameterBindings().getBinding( parameter ).setBindValue( value, type ); return this; } @Override @SuppressWarnings("unchecked") - public QueryImplementor setParameter(String name, Object value, Type type) { + public QueryImplementor setParameter(String name, Object value, AllowableParameterType type) { getQueryParameterBindings().getBinding( name ).setBindValue( value, type ); return this; } @Override @SuppressWarnings("unchecked") - public QueryImplementor setParameter(int position, Object value, Type type) { + public QueryImplementor setParameter(int position, Object value, AllowableParameterType type) { getQueryParameterBindings().getBinding( position ).setBindValue( value, type ); return this; } @@ -551,72 +510,71 @@ public abstract class AbstractProducedQuery implements QueryImplementor { } @Override - @SuppressWarnings("unchecked") public

QueryImplementor setParameterList(QueryParameter

parameter, Collection

values) { - getQueryParameterBindings().getQueryParameterListBinding( parameter ).setBindValues( values ); + getQueryParameterBindings().getBinding( parameter ).setBindValues( values ); return this; } @Override @SuppressWarnings("unchecked") public QueryImplementor setParameterList(String name, Collection values) { - getQueryParameterBindings().getQueryParameterListBinding( name ).setBindValues( values ); + getQueryParameterBindings().getBinding( name ).setBindValues( values ); return this; } @Override @SuppressWarnings("unchecked") public QueryImplementor setParameterList(int position, Collection values) { - getQueryParameterBindings().getQueryParameterListBinding( position ).setBindValues( values ); + getQueryParameterBindings().getBinding( position ).setBindValues( values ); return this; } @Override @SuppressWarnings("unchecked") - public QueryImplementor setParameterList(String name, Collection values, Type type) { - getQueryParameterBindings().getQueryParameterListBinding( name ).setBindValues( values, type ); + public QueryImplementor setParameterList(String name, Collection values, AllowableParameterType type) { + getQueryParameterBindings().getBinding( name ).setBindValues( values, type ); return this; } @Override @SuppressWarnings("unchecked") - public QueryImplementor setParameterList(int position, Collection values, Type type) { - getQueryParameterBindings().getQueryParameterListBinding( position ).setBindValues( values, type ); + public QueryImplementor setParameterList(int position, Collection values, AllowableParameterType type) { + getQueryParameterBindings().getBinding( position ).setBindValues( values, type ); return this; } @Override @SuppressWarnings("unchecked") - public QueryImplementor setParameterList(String name, Object[] values, Type type) { - getQueryParameterBindings().getQueryParameterListBinding( name ).setBindValues( Arrays.asList( values ), type ); + public QueryImplementor setParameterList(String name, Object[] values, AllowableParameterType type) { + getQueryParameterBindings().getBinding( name ).setBindValues( Arrays.asList( values ), type ); return this; } @Override @SuppressWarnings("unchecked") - public QueryImplementor setParameterList(int position, Object[] values, Type type) { - getQueryParameterBindings().getQueryParameterListBinding( position ).setBindValues( Arrays.asList( values ), type ); + public QueryImplementor setParameterList(int position, Object[] values, AllowableParameterType type) { + getQueryParameterBindings().getBinding( position ).setBindValues( Arrays.asList( values ), type ); return this; } @Override @SuppressWarnings("unchecked") public QueryImplementor setParameterList(String name, Object[] values) { - getQueryParameterBindings().getQueryParameterListBinding( name ).setBindValues( Arrays.asList( values ) ); + getQueryParameterBindings().getBinding( name ).setBindValues( Arrays.asList( values ) ); return this; } @Override @SuppressWarnings("unchecked") public QueryImplementor setParameterList(int position, Object[] values) { - getQueryParameterBindings().getQueryParameterListBinding( position ).setBindValues( Arrays.asList( values ) ); + getQueryParameterBindings().getBinding( position ).setBindValues( Arrays.asList( values ) ); return this; } @Override @SuppressWarnings("unchecked") public QueryImplementor setParameter(Parameter param, Calendar value, TemporalType temporalType) { - getProducer().checkOpen(); + getSession().checkOpen(); getQueryParameterBindings().getBinding( (QueryParameter) param ).setBindValue( value, temporalType ); return this; } @@ -624,7 +582,7 @@ public abstract class AbstractProducedQuery implements QueryImplementor { @Override @SuppressWarnings("unchecked") public QueryImplementor setParameter(Parameter param, Date value, TemporalType temporalType) { - getProducer().checkOpen(); + getSession().checkOpen(); getQueryParameterBindings().getBinding( (QueryParameter) param ).setBindValue( value, temporalType ); return this; } @@ -632,7 +590,7 @@ public abstract class AbstractProducedQuery implements QueryImplementor { @Override @SuppressWarnings("unchecked") public QueryImplementor setParameter(String name, Calendar value, TemporalType temporalType) { - getProducer().checkOpen(); + getSession().checkOpen(); getQueryParameterBindings().getBinding( name ).setBindValue( value, temporalType ); return this; } @@ -640,7 +598,7 @@ public abstract class AbstractProducedQuery implements QueryImplementor { @Override @SuppressWarnings("unchecked") public QueryImplementor setParameter(String name, Date value, TemporalType temporalType) { - getProducer().checkOpen(); + getSession().checkOpen(); getQueryParameterBindings().getBinding( name ).setBindValue( value, temporalType ); return this; } @@ -648,7 +606,7 @@ public abstract class AbstractProducedQuery implements QueryImplementor { @Override @SuppressWarnings("unchecked") public QueryImplementor setParameter(int position, Calendar value, TemporalType temporalType) { - getProducer().checkOpen(); + getSession().checkOpen(); getQueryParameterBindings().getBinding( position ).setBindValue( value, temporalType ); return this; } @@ -656,20 +614,21 @@ public abstract class AbstractProducedQuery implements QueryImplementor { @Override @SuppressWarnings("unchecked") public QueryImplementor setParameter(int position, Date value, TemporalType temporalType) { - getProducer().checkOpen(); + getSession().checkOpen(); getQueryParameterBindings().getBinding( position ).setBindValue( value, temporalType ); return this; } @Override public Set> getParameters() { - getProducer().checkOpen( false ); - return getParameterMetadata().collectAllParametersJpa(); + getSession().checkOpen( false ); + //noinspection unchecked + return (Set) getParameterMetadata().getRegistrations(); } @Override public QueryParameter getParameter(String name) { - getProducer().checkOpen( false ); + getSession().checkOpen( false ); try { return getParameterMetadata().getQueryParameter( name ); } @@ -681,7 +640,7 @@ public abstract class AbstractProducedQuery implements QueryImplementor { @Override @SuppressWarnings("unchecked") public QueryParameter getParameter(String name, Class type) { - getProducer().checkOpen( false ); + getSession().checkOpen( false ); try { final QueryParameter parameter = getParameterMetadata().getQueryParameter( name ); if ( !parameter.getParameterType().isAssignableFrom( type ) ) { @@ -700,18 +659,9 @@ public abstract class AbstractProducedQuery implements QueryImplementor { @Override public QueryParameter getParameter(int position) { - getProducer().checkOpen( false ); + getSession().checkOpen( false ); try { - if ( getParameterMetadata().getPositionalParameterCount() == 0 ) { - try { - return getParameterMetadata().getQueryParameter( Integer.toString( position ) ); - } - catch (HibernateException e) { - throw new QueryParameterException( "could not locate parameter at position [" + position + "]" ); - } - } - // fallback to ordinal lookup - return getParameterMetadata().getQueryParameter( position ); + return parameterMetadata.getQueryParameter( position ); } catch (HibernateException e) { throw getExceptionConverter().convert( e ); @@ -721,7 +671,7 @@ public abstract class AbstractProducedQuery implements QueryImplementor { @Override @SuppressWarnings("unchecked") public QueryParameter getParameter(int position, Class type) { - getProducer().checkOpen( false ); + getSession().checkOpen( false ); try { final QueryParameter parameter = getParameterMetadata().getQueryParameter( position ); if ( !parameter.getParameterType().isAssignableFrom( type ) ) { @@ -740,15 +690,15 @@ public abstract class AbstractProducedQuery implements QueryImplementor { @Override public boolean isBound(Parameter parameter) { - getProducer().checkOpen(); - return getQueryParameterBindings().isBound( (QueryParameter) parameter ); + getSession().checkOpen(); + return getQueryParameterBindings().getBinding( (QueryParameterImplementor) parameter ).isBound(); } @Override public T getParameterValue(Parameter parameter) { LOGGER.tracef( "#getParameterValue(%s)", parameter ); - getProducer().checkOpen( false ); + getSession().checkOpen( false ); if ( !getParameterMetadata().containsReference( (QueryParameter) parameter ) ) { throw new IllegalArgumentException( "Parameter reference [" + parameter + "] did not come from this query" ); @@ -764,7 +714,7 @@ public abstract class AbstractProducedQuery implements QueryImplementor { @Override public Object getParameterValue(String name) { - getProducer().checkOpen( false ); + getSession().checkOpen( false ); final QueryParameterBinding binding; try { @@ -783,7 +733,7 @@ public abstract class AbstractProducedQuery implements QueryImplementor { @Override public Object getParameterValue(int position) { - getProducer().checkOpen( false ); + getSession().checkOpen( false ); final QueryParameterBinding binding; try { @@ -803,42 +753,46 @@ public abstract class AbstractProducedQuery implements QueryImplementor { @Override @SuppressWarnings("unchecked") public QueryImplementor setProperties(Object bean) { - Class clazz = bean.getClass(); - String[] params = getNamedParameters(); - for ( String namedParam : params ) { - try { - final PropertyAccess propertyAccess = BuiltInPropertyAccessStrategies.BASIC.getStrategy().buildPropertyAccess( - clazz, - namedParam - ); - final Getter getter = propertyAccess.getGetter(); - final Class retType = getter.getReturnType(); - final Object object = getter.get( bean ); - if ( Collection.class.isAssignableFrom( retType ) ) { - setParameterList( namedParam, (Collection) object ); + final Class clazz = bean.getClass(); + parameterMetadata.visitRegistrations( + queryParameter -> { + final String parameterName = queryParameter.getName(); + if ( parameterName != null ) { + try { + final PropertyAccess propertyAccess = BuiltInPropertyAccessStrategies.BASIC.getStrategy().buildPropertyAccess( + clazz, + parameterName + ); + final Getter getter = propertyAccess.getGetter(); + final Class retType = getter.getReturnType(); + final Object object = getter.get( bean ); + if ( Collection.class.isAssignableFrom( retType ) ) { + setParameterList( parameterName, (Collection) object ); + } + else if ( retType.isArray() ) { + setParameterList( parameterName, (Object[]) object ); + } + else { + setParameter( parameterName, object, determineType( parameterName, retType ) ); + } + } + catch (PropertyNotFoundException e) { + // ignore + } + } } - else if ( retType.isArray() ) { - setParameterList( namedParam, (Object[]) object ); - } - else { - Type type = determineType( namedParam, retType ); - setParameter( namedParam, object, type ); - } - } - catch (PropertyNotFoundException pnfe) { - // ignore - } - } + ); + return this; } - protected Type determineType(String namedParam, Class retType) { - Type type = getQueryParameterBindings().getBinding( namedParam ).getBindType(); + protected AllowableParameterType determineType(String namedParam, Class retType) { + AllowableParameterType type = getQueryParameterBindings().getBinding( namedParam ).getBindType(); if ( type == null ) { type = getParameterMetadata().getQueryParameter( namedParam ).getHibernateType(); } if ( type == null ) { - type = getProducer().getFactory().resolveParameterBindType( retType ); + type = getSession().getFactory().resolveParameterBindType( retType ); } return type; } @@ -846,27 +800,33 @@ public abstract class AbstractProducedQuery implements QueryImplementor { @Override @SuppressWarnings("unchecked") public QueryImplementor setProperties(Map map) { - final String[] namedParameterNames = getNamedParameters(); - for ( String paramName : namedParameterNames ) { - final Object object = map.get( paramName ); - if ( object == null ) { - if ( map.containsKey( paramName ) ) { - setParameter( paramName, null, determineType( paramName, null ) ); + parameterMetadata.visitRegistrations( + queryParameter -> { + final String parameterName = queryParameter.getName(); + if ( parameterName != null ) { + final Object value = map.get( parameterName ); + + if ( value == null ) { + if ( map.containsKey( parameterName ) ) { + setParameter( parameterName, null, determineType( parameterName, null ) ); + } + } + else { + Class retType = value.getClass(); + if ( Collection.class.isAssignableFrom( retType ) ) { + setParameterList( parameterName, (Collection) value ); + } + else if ( retType.isArray() ) { + setParameterList( parameterName, (Object[]) value ); + } + else { + setParameter( parameterName, value, determineType( parameterName, retType ) ); + } + } + } } - } - else { - Class retType = object.getClass(); - if ( Collection.class.isAssignableFrom( retType ) ) { - setParameterList( paramName, (Collection) object ); - } - else if ( retType.isArray() ) { - setParameterList( paramName, (Object[]) object ); - } - else { - setParameter( paramName, object, determineType( paramName, retType ) ); - } - } - } + ); + return this; } @@ -877,14 +837,9 @@ public abstract class AbstractProducedQuery implements QueryImplementor { return this; } - @Override - public RowSelection getQueryOptions() { - return queryOptions; - } - @Override public int getMaxResults() { - getProducer().checkOpen(); + getSession().checkOpen(); // to be JPA compliant this method returns an int - specifically the "magic number" Integer.MAX_VALUE defined by the spec. // For access to the Integer (for checking), use #getQueryOptions#getMaxRows instead return queryOptions.getMaxRows() == null ? Integer.MAX_VALUE : queryOptions.getMaxRows(); @@ -893,20 +848,20 @@ public abstract class AbstractProducedQuery implements QueryImplementor { @Override @SuppressWarnings("unchecked") public QueryImplementor setMaxResults(int maxResult) { - getProducer().checkOpen(); + getSession().checkOpen(); if ( maxResult < 0 ) { throw new IllegalArgumentException( "max-results cannot be negative" ); } else { - queryOptions.setMaxRows( maxResult ); + queryOptions.getLimit().setMaxRows( maxResult ); } return this; } @Override public int getFirstResult() { - getProducer().checkOpen(); + getSession().checkOpen(); // to be JPA compliant this method returns an int - specifically the "magic number" 0 (ZERO) defined by the spec. // For access to the Integer (for checking), use #getQueryOptions#getFirstRow instead return queryOptions.getFirstRow() == null ? 0 : queryOptions.getFirstRow(); @@ -915,11 +870,11 @@ public abstract class AbstractProducedQuery implements QueryImplementor { @Override @SuppressWarnings("unchecked") public QueryImplementor setFirstResult(int startPosition) { - getProducer().checkOpen(); + getSession().checkOpen(); if ( startPosition < 0 ) { throw new IllegalArgumentException( "first-result value cannot be negative : " + startPosition ); } - queryOptions.setFirstRow( startPosition ); + queryOptions.getLimit().setFirstRow( startPosition ); return this; } @@ -932,7 +887,7 @@ public abstract class AbstractProducedQuery implements QueryImplementor { public Map getHints() { // Technically this should rollback, but that's insane :) // If the TCK ever adds a check for this, we may need to change this behavior - getProducer().checkOpen( false ); + getSession().checkOpen( false ); final Map hints = new HashMap<>(); collectBaselineHints( hints ); @@ -975,10 +930,11 @@ public abstract class AbstractProducedQuery implements QueryImplementor { putIfNotNull( hints, HINT_FETCH_SIZE, queryOptions.getFetchSize() ); putIfNotNull( hints, HINT_FLUSH_MODE, getHibernateFlushMode() ); - if ( cacheStoreMode != null || cacheRetrieveMode != null ) { - putIfNotNull( hints, HINT_CACHE_MODE, CacheModeHelper.interpretCacheMode( cacheStoreMode, cacheRetrieveMode ) ); - putIfNotNull( hints, JPA_SHARED_CACHE_RETRIEVE_MODE, cacheRetrieveMode ); - putIfNotNull( hints, JPA_SHARED_CACHE_STORE_MODE, cacheStoreMode ); + final CacheMode cacheMode = getQueryOptions().getCacheMode(); + if ( cacheMode != null ) { + hints.put( HINT_CACHE_MODE, cacheMode ); + hints.put( JPA_SHARED_CACHE_RETRIEVE_MODE, cacheMode.getJpaRetrieveMode() ); + hints.put( JPA_SHARED_CACHE_STORE_MODE, cacheMode.getJpaStoreMode() ); } if ( isCacheable() ) { @@ -991,7 +947,7 @@ public abstract class AbstractProducedQuery implements QueryImplementor { } if ( entityGraphQueryHint != null ) { - hints.put( entityGraphQueryHint.getHintName(), entityGraphQueryHint.getOriginEntityGraph() ); + hints.put( entityGraphQueryHint.getSemantic().getJpaHintName(), entityGraphQueryHint.getGraph() ); } } @@ -1013,7 +969,7 @@ public abstract class AbstractProducedQuery implements QueryImplementor { @Override @SuppressWarnings("unchecked") public QueryImplementor setHint(String hintName, Object value) { - getProducer().checkOpen( true ); + getSession().checkOpen( true ); boolean applied = false; try { if ( HINT_TIMEOUT.equals( hintName ) ) { @@ -1080,7 +1036,6 @@ public abstract class AbstractProducedQuery implements QueryImplementor { else if ( HINT_FETCHGRAPH.equals( hintName ) || HINT_LOADGRAPH.equals( hintName ) ) { if ( value instanceof RootGraph ) { applyGraph( (RootGraph) value, GraphSemantic.fromJpaHintName( hintName ) ); - applyEntityGraphQueryHint( new EntityGraphQueryHint( hintName, (RootGraphImpl) value ) ); } else { MSG_LOGGER.warnf( "The %s hint was set, but the value was not an EntityGraph!", hintName ); @@ -1113,12 +1068,12 @@ public abstract class AbstractProducedQuery implements QueryImplementor { } protected boolean applyJpaCacheRetrieveMode(CacheRetrieveMode mode) { - this.cacheRetrieveMode = mode; + getQueryOptions().setCacheRetrieveMode( mode ); return true; } - protected boolean applyJpaCacheStoreMode(CacheStoreMode storeMode) { - this.cacheStoreMode = storeMode; + protected boolean applyJpaCacheStoreMode(CacheStoreMode mode) { + getQueryOptions().setCacheStoreMode( mode ); return true; } @@ -1236,7 +1191,7 @@ public abstract class AbstractProducedQuery implements QueryImplementor { * @return {@code true} if the hint was "applied" */ protected boolean applyFlushModeHint(FlushMode flushMode) { - setFlushMode( flushMode ); + setHibernateFlushMode( flushMode ); return true; } @@ -1281,7 +1236,7 @@ public abstract class AbstractProducedQuery implements QueryImplementor { throw new IllegalStateException( "Semantic was non-null, but graph was null" ); } - applyEntityGraphQueryHint( new EntityGraphQueryHint( (RootGraphImplementor) graph, semantic ) ); + applyGraph( (RootGraphImplementor) graph, semantic ); } return this; @@ -1329,18 +1284,18 @@ public abstract class AbstractProducedQuery implements QueryImplementor { @Override public LockModeType getLockMode() { - getProducer().checkOpen( false ); + getSession().checkOpen( false ); if ( !isSelect() ) { throw new IllegalStateException( "Illegal attempt to get lock mode on a non-SELECT query" ); } - return LockModeTypeHelper.getLockModeType( lockOptions.getLockMode() ); + return LockModeTypeHelper.getLockModeType( getQueryOptions().getLockOptions().getLockMode() ); } @Override @SuppressWarnings("unchecked") public T unwrap(Class cls) { - if ( cls.isInstance( getProducer() ) ) { - return (T) getProducer(); + if ( cls.isInstance( getSession() ) ) { + return (T) getSession(); } if ( cls.isInstance( getParameterMetadata() ) ) { return (T) getParameterMetadata(); @@ -1362,7 +1317,7 @@ public abstract class AbstractProducedQuery implements QueryImplementor { entityGraphHintedQueryPlan = null; } else { - final SharedSessionContractImplementor producer = getProducer(); + final SharedSessionContractImplementor producer = getSession(); entityGraphHintedQueryPlan = new HQLQueryPlan( hql, false, @@ -1372,16 +1327,10 @@ public abstract class AbstractProducedQuery implements QueryImplementor { ); } - QueryParameters queryParameters = new QueryParameters( - getQueryParameterBindings(), + final QueryParameters queryParameters = new QueryParameters( + getQueryParameterBindings(), getLockOptions(), queryOptions, - true, - isReadOnly(), - cacheable, - cacheRegion, - comment, - dbHints, null, optionalObject, optionalEntityName, @@ -1396,23 +1345,9 @@ public abstract class AbstractProducedQuery implements QueryImplementor { } public QueryParameters getQueryParameters() { - final String expandedQuery = getQueryParameterBindings().expandListValuedParameters( getQueryString(), getProducer() ); - return makeQueryParametersForExecution( expandedQuery ); - } - - @SuppressWarnings("deprecation") - protected Type[] getPositionalParameterTypes() { - return getQueryParameterBindings().collectPositionalBindTypes(); - } - - @SuppressWarnings("deprecation") - protected Object[] getPositionalParameterValues() { - return getQueryParameterBindings().collectPositionalBindValues(); - } - - @SuppressWarnings("deprecation") - protected Map getNamedParameterMap() { - return getQueryParameterBindings().collectNamedParameterBindings(); + throw new NotYetImplementedFor6Exception( getClass() ); +// final String expandedQuery = getQueryParameterBindings().expandListValuedParameters( getQueryString(), getSession() ); +// return makeQueryParametersForExecution( expandedQuery ); } private FlushMode sessionFlushMode; @@ -1420,59 +1355,37 @@ public abstract class AbstractProducedQuery implements QueryImplementor { protected void beforeQuery() { if ( optionalId == null ) { - getQueryParameterBindings().verifyParametersBound( isCallable() ); + getQueryParameterBindings().validate(); } assert sessionFlushMode == null; assert sessionCacheMode == null; + final FlushMode flushMode = getQueryOptions().getFlushMode(); if ( flushMode != null ) { - sessionFlushMode = getProducer().getHibernateFlushMode(); - getProducer().setHibernateFlushMode( flushMode ); - } - final CacheMode effectiveCacheMode = CacheModeHelper.effectiveCacheMode( cacheStoreMode, cacheRetrieveMode ); - if ( effectiveCacheMode != null ) { - sessionCacheMode = getProducer().getCacheMode(); - getProducer().setCacheMode( effectiveCacheMode ); + sessionFlushMode = getSession().getHibernateFlushMode(); + getSession().setHibernateFlushMode( flushMode ); } + + final CacheMode effectiveCacheMode = CacheMode.fromJpaModes( queryOptions.getCacheRetrieveMode(), queryOptions.getCacheStoreMode() ); + sessionCacheMode = getSession().getCacheMode(); + getSession().setCacheMode( effectiveCacheMode ); } protected void afterQuery() { if ( sessionFlushMode != null ) { - getProducer().setHibernateFlushMode( sessionFlushMode ); + getSession().setHibernateFlushMode( sessionFlushMode ); sessionFlushMode = null; } if ( sessionCacheMode != null ) { - getProducer().setCacheMode( sessionCacheMode ); + getSession().setCacheMode( sessionCacheMode ); sessionCacheMode = null; } } - @Override - public Iterator iterate() { - beforeQuery(); - try { - return doIterate(); - } - finally { - afterQuery(); - } - } - - @SuppressWarnings("unchecked") - protected Iterator doIterate() { - if (getMaxResults() == 0){ - return Collections.emptyIterator(); - } - return getProducer().iterate( - getQueryParameterBindings().expandListValuedParameters( getQueryString(), getProducer() ), - getQueryParameters() - ); - } - @Override public ScrollableResultsImplementor scroll() { - return scroll( getProducer().getJdbcServices().getJdbcEnvironment().getDialect().defaultScrollMode() ); + return scroll( getSession().getJdbcServices().getJdbcEnvironment().getDialect().defaultScrollMode() ); } @Override @@ -1487,13 +1400,16 @@ public abstract class AbstractProducedQuery implements QueryImplementor { } protected ScrollableResultsImplementor doScroll(ScrollMode scrollMode) { - if (getMaxResults() == 0){ - return EmptyScrollableResults.INSTANCE; - } - final String query = getQueryParameterBindings().expandListValuedParameters( getQueryString(), getProducer() ); - QueryParameters queryParameters = makeQueryParametersForExecution( query ); - queryParameters.setScrollMode( scrollMode ); - return getProducer().scroll( query, queryParameters ); + throw new NotYetImplementedFor6Exception( getClass() ); + +// if ( getMaxResults() == 0 ) { +// return EmptyScrollableResults.INSTANCE; +// } +// +// final String query = getQueryParameterBindings().expandListValuedParameters( getQueryString(), getSession() ); +// QueryParameters queryParameters = makeQueryParametersForExecution( query ); +// queryParameters.setScrollMode( scrollMode ); +// return getSession().scroll( query, queryParameters ); } @Override @@ -1524,9 +1440,6 @@ public abstract class AbstractProducedQuery implements QueryImplementor { try { return doList(); } - catch (QueryExecutionRequestException he) { - throw new IllegalStateException( he ); - } catch (TypeMismatchException e) { throw new IllegalArgumentException( e ); } @@ -1544,20 +1457,22 @@ public abstract class AbstractProducedQuery implements QueryImplementor { @SuppressWarnings("unchecked") protected List doList() { - if ( getMaxResults() == 0 ) { - return Collections.EMPTY_LIST; - } - if ( lockOptions.getLockMode() != null && lockOptions.getLockMode() != LockMode.NONE ) { - if ( !getProducer().isTransactionInProgress() ) { - throw new TransactionRequiredException( "no transaction is in progress" ); - } - } + throw new NotYetImplementedFor6Exception( getClass() ); - final String expandedQuery = getQueryParameterBindings().expandListValuedParameters( getQueryString(), getProducer() ); - return getProducer().list( - expandedQuery, - makeQueryParametersForExecution( expandedQuery ) - ); +// if ( getMaxResults() == 0 ) { +// return Collections.EMPTY_LIST; +// } +// if ( lockOptions.getLockMode() != null && lockOptions.getLockMode() != LockMode.NONE ) { +// if ( !getSession().isTransactionInProgress() ) { +// throw new TransactionRequiredException( "no transaction is in progress" ); +// } +// } +// +// final String expandedQuery = getQueryParameterBindings().expandListValuedParameters( getQueryString(), getSession() ); +// return getSession().list( +// expandedQuery, +// makeQueryParametersForExecution( expandedQuery ) +// ); } protected abstract QueryParameterBindings getQueryParameterBindings(); @@ -1597,15 +1512,12 @@ public abstract class AbstractProducedQuery implements QueryImplementor { @Override public int executeUpdate() throws HibernateException { - getProducer().checkTransactionNeededForUpdateOperation( "Executing an update/delete query" ); + getSession().checkTransactionNeededForUpdateOperation( "Executing an update/delete query" ); beforeQuery(); try { return doExecuteUpdate(); } - catch ( QueryExecutionRequestException e) { - throw new IllegalStateException( e ); - } catch( TypeMismatchException e ) { throw new IllegalArgumentException( e ); } @@ -1618,18 +1530,20 @@ public abstract class AbstractProducedQuery implements QueryImplementor { } protected int doExecuteUpdate() { - final String expandedQuery = getQueryParameterBindings().expandListValuedParameters( getQueryString(), getProducer() ); - return getProducer().executeUpdate( - expandedQuery, - makeQueryParametersForExecution( expandedQuery ) - ); + throw new NotYetImplementedFor6Exception( getClass() ); + +// final String expandedQuery = getQueryParameterBindings().expandListValuedParameters( getQueryString(), getSession() ); +// return getSession().executeUpdate( +// expandedQuery, +// makeQueryParametersForExecution( expandedQuery ) +// ); } protected String resolveEntityName(Object val) { if ( val == null ) { throw new IllegalArgumentException( "entity for parameter binding cannot be null" ); } - return getProducer().bestGuessEntityName( val ); + return getSession().bestGuessEntityName( val ); } @Override @@ -1647,27 +1561,12 @@ public abstract class AbstractProducedQuery implements QueryImplementor { this.optionalObject = optionalObject; } - @Override - @SuppressWarnings("unchecked") - public Type determineProperBooleanType(String name, Object value, Type defaultType) { - final QueryParameterBinding binding = getQueryParameterBindings().getBinding( name ); - return binding.getBindType() != null - ? binding.getBindType() - : defaultType; - } - - @Override - public Type determineProperBooleanType(int position, Object value, Type defaultType) { - final QueryParameterBinding binding = getQueryParameterBindings().getBinding( position ); - return binding.getBindType() != null - ? binding.getBindType() - : defaultType; - } - private boolean isSelect() { - return getProducer().getFactory().getQueryInterpretationCache() - .getHQLQueryPlan( getQueryString(), false, Collections.emptyMap() ) - .isSelect(); + throw new NotYetImplementedFor6Exception( getClass() ); + +// return getSession().getFactory().getQueryInterpretationCache() +// .getHQLQueryPlan( getQueryString(), false, Collections.emptyMap() ) +// .isSelect(); } protected ExceptionConverter getExceptionConverter(){ diff --git a/hibernate-core/src/main/java/org/hibernate/query/internal/QueryOptionsImpl.java b/hibernate-core/src/main/java/org/hibernate/query/internal/QueryOptionsImpl.java index d837832ee5..502f25b521 100644 --- a/hibernate-core/src/main/java/org/hibernate/query/internal/QueryOptionsImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/query/internal/QueryOptionsImpl.java @@ -9,8 +9,9 @@ package org.hibernate.query.internal; import java.util.ArrayList; import java.util.Collections; import java.util.List; +import javax.persistence.CacheRetrieveMode; +import javax.persistence.CacheStoreMode; -import org.hibernate.CacheMode; import org.hibernate.FlushMode; import org.hibernate.LockOptions; import org.hibernate.graph.GraphSemantic; @@ -34,7 +35,8 @@ public class QueryOptionsImpl implements MutableQueryOptions, AppliedGraph { private final Limit limit = new Limit(); private final LockOptions lockOptions = new LockOptions(); private Integer fetchSize; - private CacheMode cacheMode; + private CacheRetrieveMode cacheRetrieveMode; + private CacheStoreMode cacheStoreMode; private Boolean resultCachingEnabled; private String resultCacheRegionName; private Boolean readOnlyEnabled; @@ -115,15 +117,31 @@ public class QueryOptionsImpl implements MutableQueryOptions, AppliedGraph { } @Override - public CacheMode getCacheMode() { - if ( cacheMode == null ) { - return CacheMode.IGNORE; + public CacheRetrieveMode getCacheRetrieveMode() { + if ( cacheRetrieveMode == null ) { + return CacheRetrieveMode.BYPASS; } - return cacheMode; + + return cacheRetrieveMode; } - public void setCacheMode(CacheMode cacheMode) { - this.cacheMode = cacheMode; + @Override + public CacheStoreMode getCacheStoreMode() { + if ( cacheStoreMode == null ) { + return CacheStoreMode.BYPASS; + } + + return cacheStoreMode; + } + + @Override + public void setCacheRetrieveMode(CacheRetrieveMode retrieveMode) { + this.cacheRetrieveMode = retrieveMode; + } + + @Override + public void setCacheStoreMode(CacheStoreMode storeMode) { + this.cacheStoreMode = storeMode; } @Override diff --git a/hibernate-core/src/main/java/org/hibernate/query/internal/QueryParameterBindingsImpl.java b/hibernate-core/src/main/java/org/hibernate/query/internal/QueryParameterBindingsImpl.java index e340dfad14..cab8f25504 100644 --- a/hibernate-core/src/main/java/org/hibernate/query/internal/QueryParameterBindingsImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/query/internal/QueryParameterBindingsImpl.java @@ -6,44 +6,21 @@ */ package org.hibernate.query.internal; -import java.util.Collection; -import java.util.Comparator; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; import java.util.Map; -import java.util.Set; -import java.util.TreeMap; import java.util.function.BiConsumer; -import java.util.stream.Collectors; -import javax.persistence.Parameter; -import org.hibernate.HibernateException; import org.hibernate.Incubating; import org.hibernate.QueryException; import org.hibernate.QueryParameterException; -import org.hibernate.dialect.Dialect; -import org.hibernate.engine.jdbc.spi.JdbcServices; -import org.hibernate.engine.query.spi.NamedParameterDescriptor; -import org.hibernate.engine.query.spi.OrdinalParameterDescriptor; import org.hibernate.engine.spi.SessionFactoryImplementor; -import org.hibernate.engine.spi.SharedSessionContractImplementor; -import org.hibernate.engine.spi.TypedValue; import org.hibernate.internal.CoreLogging; import org.hibernate.internal.CoreMessageLogger; -import org.hibernate.internal.util.MathHelper; -import org.hibernate.internal.util.StringHelper; -import org.hibernate.internal.util.collections.ArrayHelper; import org.hibernate.internal.util.collections.CollectionHelper; -import org.hibernate.query.ParameterMetadata; import org.hibernate.query.QueryParameter; import org.hibernate.query.spi.ParameterMetadataImplementor; import org.hibernate.query.spi.QueryParameterBinding; import org.hibernate.query.spi.QueryParameterBindings; import org.hibernate.query.spi.QueryParameterImplementor; -import org.hibernate.query.spi.QueryParameterListBinding; -import org.hibernate.type.SerializableType; -import org.hibernate.type.Type; /** * Manages the group of QueryParameterBinding for a particular query. @@ -56,7 +33,7 @@ public class QueryParameterBindingsImpl implements QueryParameterBindings { private static final CoreMessageLogger log = CoreLogging.messageLogger( QueryParameterBindingsImpl.class ); private final SessionFactoryImplementor sessionFactory; - private final ParameterMetadataImplementor> parameterMetadata; + private final ParameterMetadataImplementor parameterMetadata; private final boolean queryParametersValidationEnabled; private final int jdbcStyleOrdinalCountBase; @@ -133,7 +110,7 @@ public class QueryParameterBindingsImpl implements QueryParameterBindings { } @Override - public QueryParameterBinding getBinding(QueryParameterImplementor parameter) { + public

QueryParameterBinding

getBinding(QueryParameterImplementor

parameter) { if ( parameterBindingMap == null ) { return null; } @@ -154,13 +131,15 @@ public class QueryParameterBindingsImpl implements QueryParameterBindings { } @Override - public QueryParameterBinding getBinding(int position) { - return getBinding( parameterMetadata.getQueryParameter( position ) ); + public

QueryParameterBinding

getBinding(int position) { + //noinspection unchecked + return (QueryParameterBinding

) getBinding( parameterMetadata.getQueryParameter( position ) ); } @Override - public QueryParameterBinding getBinding(String name) { - return getBinding( parameterMetadata.getQueryParameter( name ) ); + public

QueryParameterBinding

getBinding(String name) { + //noinspection unchecked + return (QueryParameterBinding

) getBinding( parameterMetadata.getQueryParameter( name ) ); } @Override diff --git a/hibernate-core/src/main/java/org/hibernate/query/spi/MutableQueryOptions.java b/hibernate-core/src/main/java/org/hibernate/query/spi/MutableQueryOptions.java index 25c98e798c..8f543877e8 100644 --- a/hibernate-core/src/main/java/org/hibernate/query/spi/MutableQueryOptions.java +++ b/hibernate-core/src/main/java/org/hibernate/query/spi/MutableQueryOptions.java @@ -6,6 +6,9 @@ */ package org.hibernate.query.spi; +import javax.persistence.CacheRetrieveMode; +import javax.persistence.CacheStoreMode; + import org.hibernate.CacheMode; import org.hibernate.FlushMode; import org.hibernate.query.ResultListTransformer; @@ -20,10 +23,23 @@ public interface MutableQueryOptions extends QueryOptions { */ void setFlushMode(FlushMode flushMode); + /** + * Corollary to {@link #getCacheRetrieveMode} + */ + void setCacheRetrieveMode(CacheRetrieveMode retrieveMode); + + /** + * Corollary to {@link #getCacheStoreMode()} + */ + void setCacheStoreMode(CacheStoreMode storeMode); + /** * Corollary to {@link #getCacheMode()} */ - void setCacheMode(CacheMode cacheMode); + default void setCacheMode(CacheMode cacheMode) { + setCacheRetrieveMode( cacheMode.getJpaRetrieveMode() ); + setCacheStoreMode( cacheMode.getJpaStoreMode() ); + } /** * Corollary to {@link #isResultCachingEnabled()} diff --git a/hibernate-core/src/main/java/org/hibernate/query/spi/QueryEngine.java b/hibernate-core/src/main/java/org/hibernate/query/spi/QueryEngine.java index 169116f2f5..13cead45b6 100644 --- a/hibernate-core/src/main/java/org/hibernate/query/spi/QueryEngine.java +++ b/hibernate-core/src/main/java/org/hibernate/query/spi/QueryEngine.java @@ -66,6 +66,7 @@ public class QueryEngine { Map properties, NamedQueryRepository namedQueryRepository) { this.namedQueryRepository = namedQueryRepository; + // todo (6.0) : allow SemanticQueryProducer to be pluggable (see legacy `QueryTranslatorFactoryInitiator`) this.semanticQueryProducer = new SemanticQueryProducerImpl( sqmCreationContext, sqmCreationOptions ); this.criteriaBuilder = new SqmCriteriaNodeBuilder( this, diff --git a/hibernate-core/src/main/java/org/hibernate/query/spi/QueryOptions.java b/hibernate-core/src/main/java/org/hibernate/query/spi/QueryOptions.java index d7c51f12a0..f765b1f426 100644 --- a/hibernate-core/src/main/java/org/hibernate/query/spi/QueryOptions.java +++ b/hibernate-core/src/main/java/org/hibernate/query/spi/QueryOptions.java @@ -10,9 +10,13 @@ import java.sql.Statement; import java.util.Collections; import java.util.List; +import javax.persistence.CacheRetrieveMode; +import javax.persistence.CacheStoreMode; + import org.hibernate.CacheMode; import org.hibernate.FlushMode; import org.hibernate.LockOptions; +import org.hibernate.annotations.Cache; import org.hibernate.graph.spi.AppliedGraph; import org.hibernate.query.Limit; import org.hibernate.query.ResultListTransformer; @@ -71,10 +75,26 @@ public interface QueryOptions { Boolean isResultCachingEnabled(); /** - * The cache-mode to be used for the query. No effect unless - * {@link #isResultCachingEnabled} returns {@code true} + * Controls whether query results are read from the cache. + * No effect unless {@link #isResultCachingEnabled} returns + * {@code true} + * + * @see CacheMode */ - CacheMode getCacheMode(); + CacheRetrieveMode getCacheRetrieveMode(); + + /** + * Controls whether query results are put into the cache. + * No effect unless {@link #isResultCachingEnabled} returns + * {@code true} + * + * @see CacheMode + */ + CacheStoreMode getCacheStoreMode(); + + default CacheMode getCacheMode() { + return CacheMode.fromJpaModes( getCacheRetrieveMode(), getCacheStoreMode() ); + } /** * The query cache region in which the results should be cached. No @@ -207,6 +227,16 @@ public interface QueryOptions { return null; } + @Override + public CacheRetrieveMode getCacheRetrieveMode() { + return CacheRetrieveMode.BYPASS; + } + + @Override + public CacheStoreMode getCacheStoreMode() { + return CacheStoreMode.BYPASS; + } + @Override public CacheMode getCacheMode() { return CacheMode.IGNORE; diff --git a/hibernate-core/src/main/java/org/hibernate/query/spi/QueryParameterBindings.java b/hibernate-core/src/main/java/org/hibernate/query/spi/QueryParameterBindings.java index 889c373742..a4995f0b4c 100644 --- a/hibernate-core/src/main/java/org/hibernate/query/spi/QueryParameterBindings.java +++ b/hibernate-core/src/main/java/org/hibernate/query/spi/QueryParameterBindings.java @@ -11,6 +11,7 @@ import java.util.function.BiConsumer; import org.hibernate.Incubating; import org.hibernate.NotYetImplementedFor6Exception; import org.hibernate.cache.spi.QueryKey; +import org.hibernate.query.QueryParameter; /** * Manages all the parameter bindings for a particular query. @@ -38,7 +39,18 @@ public interface QueryParameterBindings { * * @return The binding, or {@code null} if not yet bound */ - QueryParameterBinding getBinding(QueryParameterImplementor parameter); + default

QueryParameterBinding

getBinding(QueryParameter

parameter) { + return getBinding( (QueryParameterImplementor

) parameter ); + } + + /** + * Access to the binding via QueryParameter reference + * + * @param parameter The QueryParameter reference + * + * @return The binding, or {@code null} if not yet bound + */ +

QueryParameterBinding

getBinding(QueryParameterImplementor

parameter); /** * Access to the binding via name @@ -47,7 +59,7 @@ public interface QueryParameterBindings { * * @return The binding, or {@code null} if not yet bound */ - QueryParameterBinding getBinding(String name); +

QueryParameterBinding

getBinding(String name); /** * Access to the binding via position @@ -56,7 +68,7 @@ public interface QueryParameterBindings { * * @return The binding, or {@code null} if not yet bound */ - QueryParameterBinding getBinding(int position); +

QueryParameterBinding

getBinding(int position); /** * Validate the bindings. Called just before execution diff --git a/hibernate-core/src/main/java/org/hibernate/query/spi/QueryParameterListBinding.java b/hibernate-core/src/main/java/org/hibernate/query/spi/QueryParameterListBinding.java index 75bcd535d4..60f3d3aa7b 100644 --- a/hibernate-core/src/main/java/org/hibernate/query/spi/QueryParameterListBinding.java +++ b/hibernate-core/src/main/java/org/hibernate/query/spi/QueryParameterListBinding.java @@ -10,6 +10,7 @@ import java.util.Collection; import javax.persistence.TemporalType; import org.hibernate.Incubating; +import org.hibernate.metamodel.model.domain.AllowableParameterType; import org.hibernate.query.internal.QueryParameterBindingsImpl; import org.hibernate.type.Type; @@ -36,7 +37,7 @@ public interface QueryParameterListBinding { * @param values The bind values * @param clarifiedType The explicit Type to use */ - void setBindValues(Collection values, Type clarifiedType); + void setBindValues(Collection values, AllowableParameterType clarifiedType); /**Sets the parameter binding value using the explicit TemporalType in regards to the individual values. * diff --git a/hibernate-core/src/main/java/org/hibernate/query/sqm/consume/internal/SqmConsumeHelper.java b/hibernate-core/src/main/java/org/hibernate/query/sqm/consume/internal/SqmConsumeHelper.java deleted file mode 100644 index 795527b002..0000000000 --- a/hibernate-core/src/main/java/org/hibernate/query/sqm/consume/internal/SqmConsumeHelper.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Hibernate, Relational Persistence for Idiomatic Java - * - * License: GNU Lesser General Public License (LGPL), version 2.1 or later - * See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html - */ -package org.hibernate.query.sqm.consume.internal; - -import java.util.Collections; -import java.util.IdentityHashMap; -import java.util.List; -import java.util.Map; - -import org.hibernate.query.spi.QueryParameterImplementor; -import org.hibernate.query.sqm.internal.DomainParameterXref; -import org.hibernate.query.sqm.tree.expression.SqmParameter; -import org.hibernate.sql.ast.produce.sqm.spi.JdbcParameterBySqmParameterAccess; -import org.hibernate.sql.exec.spi.JdbcParameter; - -/** - * @author Steve Ebersole - */ -public class SqmConsumeHelper { - private SqmConsumeHelper() { - } - - public static Map, Map>> generateJdbcParamsXref( - DomainParameterXref domainParameterXref, - JdbcParameterBySqmParameterAccess jdbcParameterBySqmParameterAccess) { - if ( domainParameterXref == null || !domainParameterXref.hasParameters() ) { - return Collections.emptyMap(); - } - - final Map, Map>> result = new IdentityHashMap<>(); - - for ( Map.Entry, List> entry : - domainParameterXref.getSqmParamByQueryParam().entrySet() ) { - final QueryParameterImplementor queryParam = entry.getKey(); - final List sqmParams = entry.getValue(); - - final Map> sqmParamMap = result.computeIfAbsent( - queryParam, - qp -> new IdentityHashMap<>() - ); - - for ( SqmParameter sqmParam : sqmParams ) { - sqmParamMap.put( sqmParam, jdbcParameterBySqmParameterAccess.getJdbcParamsBySqmParam().get( sqmParam ) ); - result.put( queryParam, sqmParamMap ); - - final List expansions = domainParameterXref.getExpansions( sqmParam ); - if ( ! expansions.isEmpty() ) { - for ( SqmParameter expansion : expansions ) { - sqmParamMap.put( expansion, jdbcParameterBySqmParameterAccess.getJdbcParamsBySqmParam().get( expansion ) ); - result.put( queryParam, sqmParamMap ); - } - } - } - } - - return result; - } -} diff --git a/hibernate-core/src/main/java/org/hibernate/query/sqm/consume/spi/BaseSqmToSqlAstConverter.java b/hibernate-core/src/main/java/org/hibernate/query/sqm/consume/spi/BaseSqmToSqlAstConverter.java deleted file mode 100644 index 3823683bdb..0000000000 --- a/hibernate-core/src/main/java/org/hibernate/query/sqm/consume/spi/BaseSqmToSqlAstConverter.java +++ /dev/null @@ -1,1018 +0,0 @@ -/* - * Hibernate, Relational Persistence for Idiomatic Java - * - * License: GNU Lesser General Public License (LGPL), version 2.1 or later - * See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html - */ -package org.hibernate.query.sqm.consume.spi; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.IdentityHashMap; -import java.util.List; -import java.util.Map; -import java.util.function.Consumer; - -import org.hibernate.AssertionFailure; -import org.hibernate.LockMode; -import org.hibernate.NotYetImplementedFor6Exception; -import org.hibernate.engine.spi.LoadQueryInfluencers; -import org.hibernate.graph.spi.GraphImplementor; -import org.hibernate.internal.util.NullnessHelper; -import org.hibernate.internal.util.collections.Stack; -import org.hibernate.internal.util.collections.StandardStack; -import org.hibernate.metamodel.model.domain.AllowableParameterType; -import org.hibernate.query.BinaryArithmeticOperator; -import org.hibernate.query.UnaryArithmeticOperator; -import org.hibernate.query.internal.QueryHelper; -import org.hibernate.query.spi.QueryOptions; -import org.hibernate.query.spi.QueryParameterBinding; -import org.hibernate.query.spi.QueryParameterBindings; -import org.hibernate.query.spi.QueryParameterImplementor; -import org.hibernate.query.sqm.internal.DomainParameterXref; -import org.hibernate.query.sqm.tree.delete.SqmDeleteStatement; -import org.hibernate.query.sqm.tree.domain.SqmBasicValuedSimplePath; -import org.hibernate.query.sqm.tree.domain.SqmEmbeddedValuedSimplePath; -import org.hibernate.query.sqm.tree.domain.SqmEntityValuedSimplePath; -import org.hibernate.query.sqm.tree.domain.SqmPluralValuedSimplePath; -import org.hibernate.query.sqm.tree.expression.SqmBinaryArithmetic; -import org.hibernate.query.sqm.tree.expression.SqmCaseSearched; -import org.hibernate.query.sqm.tree.expression.SqmCaseSimple; -import org.hibernate.query.sqm.tree.expression.SqmCriteriaParameter; -import org.hibernate.query.sqm.tree.expression.SqmExpression; -import org.hibernate.query.sqm.tree.expression.SqmLiteral; -import org.hibernate.query.sqm.tree.expression.SqmNamedParameter; -import org.hibernate.query.sqm.tree.expression.SqmParameter; -import org.hibernate.query.sqm.tree.expression.SqmPositionalParameter; -import org.hibernate.query.sqm.tree.expression.SqmTuple; -import org.hibernate.query.sqm.tree.expression.SqmUnaryOperation; -import org.hibernate.query.sqm.tree.expression.function.SqmCastTarget; -import org.hibernate.query.sqm.tree.expression.function.SqmDistinct; -import org.hibernate.query.sqm.tree.expression.function.SqmExtractUnit; -import org.hibernate.query.sqm.tree.expression.function.SqmStar; -import org.hibernate.query.sqm.tree.expression.function.SqmTrimSpecification; -import org.hibernate.query.sqm.tree.from.SqmAttributeJoin; -import org.hibernate.query.sqm.tree.from.SqmCrossJoin; -import org.hibernate.query.sqm.tree.from.SqmEntityJoin; -import org.hibernate.query.sqm.tree.from.SqmFromClause; -import org.hibernate.query.sqm.tree.from.SqmRoot; -import org.hibernate.query.sqm.tree.insert.SqmInsertSelectStatement; -import org.hibernate.query.sqm.tree.predicate.SqmLikePredicate; -import org.hibernate.query.sqm.tree.predicate.SqmNegatedPredicate; -import org.hibernate.query.sqm.tree.predicate.SqmNullnessPredicate; -import org.hibernate.query.sqm.tree.predicate.SqmAndPredicate; -import org.hibernate.query.sqm.tree.predicate.SqmBetweenPredicate; -import org.hibernate.query.sqm.tree.predicate.SqmComparisonPredicate; -import org.hibernate.query.sqm.tree.predicate.SqmGroupedPredicate; -import org.hibernate.query.sqm.tree.predicate.SqmInListPredicate; -import org.hibernate.query.sqm.tree.predicate.SqmInSubQueryPredicate; -import org.hibernate.query.sqm.tree.predicate.SqmOrPredicate; -import org.hibernate.query.sqm.tree.predicate.SqmWhereClause; -import org.hibernate.query.sqm.tree.select.SqmOrderByClause; -import org.hibernate.query.sqm.tree.select.SqmQuerySpec; -import org.hibernate.query.sqm.tree.select.SqmSelectClause; -import org.hibernate.query.sqm.tree.select.SqmSelectStatement; -import org.hibernate.query.sqm.tree.select.SqmSortSpecification; -import org.hibernate.query.sqm.tree.select.SqmSubQuery; -import org.hibernate.query.sqm.tree.update.SqmUpdateStatement; -import org.hibernate.sql.ast.Clause; -import org.hibernate.sql.ast.JoinType; -import org.hibernate.sql.ast.spi.FromClauseAccess; -import org.hibernate.sql.ast.spi.SqlAliasBaseManager; -import org.hibernate.sql.ast.spi.SqlAstCreationContext; -import org.hibernate.query.sqm.tree.expression.function.SqmFunction; -import org.hibernate.sql.ast.spi.SqlAstProcessingState; -import org.hibernate.sql.ast.spi.SqlExpressionResolver; -import org.hibernate.sql.ast.tree.expression.BinaryArithmeticExpression; -import org.hibernate.sql.ast.tree.expression.Expression; -import org.hibernate.sql.ast.tree.expression.SqlTuple; -import org.hibernate.sql.ast.tree.predicate.Junction; -import org.hibernate.sql.ast.tree.predicate.Predicate; -import org.hibernate.sql.ast.tree.select.QuerySpec; -import org.hibernate.sql.ast.tree.select.SelectClause; -import org.hibernate.sql.ast.tree.select.SelectStatement; -import org.hibernate.sql.ast.tree.select.SortSpecification; -import org.hibernate.sql.exec.spi.JdbcParameter; -import org.hibernate.sql.exec.spi.JdbcParameters; -import org.hibernate.sql.results.spi.Fetch; -import org.hibernate.sql.results.spi.FetchParent; -import org.hibernate.type.StandardBasicTypes; - -import org.jboss.logging.Logger; - -import static org.hibernate.query.BinaryArithmeticOperator.ADD; -import static org.hibernate.query.BinaryArithmeticOperator.DIVIDE; -import static org.hibernate.query.BinaryArithmeticOperator.MULTIPLY; -import static org.hibernate.query.BinaryArithmeticOperator.QUOT; -import static org.hibernate.query.BinaryArithmeticOperator.SUBTRACT; - -/** - * @author Steve Ebersole - */ -public abstract class BaseSqmToSqlAstConverter - extends BaseSemanticQueryWalker - implements SqmToSqlAstConverter, JdbcParameterBySqmParameterAccess { - - private static final Logger log = Logger.getLogger( BaseSqmToSqlAstConverter.class ); - - protected enum Shallowness { - NONE, - CTOR, - FUNCTION, - SUBQUERY - } - - private final SqlAstCreationContext creationContext; - private final QueryOptions queryOptions; - private final DomainParameterXref domainParameterXref; - private final QueryParameterBindings domainParameterBindings; - private final LoadQueryInfluencers loadQueryInfluencers; - private final Callback callback; - - private final SqlAliasBaseManager sqlAliasBaseManager = new SqlAliasBaseManager(); - - private final FromClauseIndex fromClauseIndex = new FromClauseIndex(); - - private final Stack processingStateStack = new StandardStack<>(); - - private final Stack currentClauseStack = new StandardStack<>(); - private final Stack shallownessStack = new StandardStack<>( Shallowness.NONE ); - - public BaseSqmToSqlAstConverter( - SqlAstCreationContext creationContext, - QueryOptions queryOptions, - DomainParameterXref domainParameterXref, - QueryParameterBindings domainParameterBindings, - LoadQueryInfluencers loadQueryInfluencers, - Callback callback) { - super( creationContext.getServiceRegistry() ); - this.creationContext = creationContext; - this.queryOptions = queryOptions; - this.domainParameterXref = domainParameterXref; - this.domainParameterBindings = domainParameterBindings; - this.loadQueryInfluencers = loadQueryInfluencers; - this.callback = callback; - } - - protected Stack getProcessingStateStack() { - return processingStateStack; - } - - - // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - // SqlAstCreationState - - @Override - public SqlAstCreationContext getCreationContext() { - return creationContext; - } - - @Override - public SqlAstProcessingState getCurrentProcessingState() { - return processingStateStack.getCurrent(); - } - - @Override - public SqlExpressionResolver getSqlExpressionResolver() { - return getCurrentProcessingState().getSqlExpressionResolver(); - } - - @Override - public FromClauseAccess getFromClauseAccess() { - return fromClauseIndex; - } - - @Override - public SqlAliasBaseManager getSqlAliasBaseManager() { - return sqlAliasBaseManager; - } - - @Override - public LockMode determineLockMode(String identificationVariable) { - return queryOptions.getLockOptions().getEffectiveLockMode( identificationVariable ); - } - - @Override - public List visitFetches(FetchParent fetchParent) { - return Collections.emptyList(); - } - - private QuerySpec currentQuerySpec() { - return ( (SqlAstQuerySpecProcessingState) processingStateStack.getCurrent() ).getInflightQuerySpec(); - } - - public QueryOptions getQueryOptions() { - return queryOptions; - } - - protected FromClauseIndex getFromClauseIndex() { - return fromClauseIndex; - } - - protected Stack getCurrentClauseStack() { - return currentClauseStack; - } - - protected void primeStack(Stack stack, T initialValue) { - verifyCanBePrimed( stack ); - stack.push( initialValue ); - } - - private static void verifyCanBePrimed(Stack stack) { - if ( !stack.isEmpty() ) { - throw new IllegalStateException( "Cannot prime an already populated Stack" ); - } - } - - - - // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - // Statements - - @Override - public Object visitUpdateStatement(SqmUpdateStatement statement) { - throw new AssertionFailure( "UpdateStatement not supported" ); - } - - @Override - public Object visitDeleteStatement(SqmDeleteStatement statement) { - throw new AssertionFailure( "DeleteStatement not supported" ); - } - - @Override - public Object visitInsertSelectStatement(SqmInsertSelectStatement statement) { - throw new AssertionFailure( "InsertStatement not supported" ); - } - - @Override - public SelectStatement visitSelectStatement(SqmSelectStatement statement) { - throw new AssertionFailure( "SelectStatement not supported" ); - } - - - @Override - public QuerySpec visitQuerySpec(SqmQuerySpec sqmQuerySpec) { - final QuerySpec sqlQuerySpec = new QuerySpec( processingStateStack.isEmpty() ); - - processingStateStack.push( - new SqlAstQuerySpecProcessingStateImpl( - sqlQuerySpec, - processingStateStack.getCurrent(), - this, - currentClauseStack::getCurrent, - () -> (expression) -> {}, - () -> sqlQuerySpec.getSelectClause()::addSqlSelection - ) - ); - - try { - // we want to visit the from-clause first - visitFromClause( sqmQuerySpec.getFromClause() ); - - final SqmSelectClause selectClause = sqmQuerySpec.getSelectClause(); - if ( selectClause != null ) { - visitSelectClause( selectClause ); - } - - final SqmWhereClause whereClause = sqmQuerySpec.getWhereClause(); - if ( whereClause != null && whereClause.getPredicate() != null ) { - currentClauseStack.push( Clause.WHERE ); - try { - sqlQuerySpec.setWhereClauseRestrictions( - (Predicate) whereClause.getPredicate().accept( this ) - ); - } - finally { - currentClauseStack.pop(); - } - } - - // todo : group-by - // todo : having - - if ( sqmQuerySpec.getOrderByClause() != null ) { - currentClauseStack.push( Clause.ORDER ); - try { - for ( SqmSortSpecification sortSpecification : sqmQuerySpec.getOrderByClause().getSortSpecifications() ) { - sqlQuerySpec.addSortSpecification( visitSortSpecification( sortSpecification ) ); - } - } - finally { - currentClauseStack.pop(); - } - } - - sqlQuerySpec.setLimitClauseExpression( visitLimitExpression( sqmQuerySpec.getLimitExpression() ) ); - sqlQuerySpec.setOffsetClauseExpression( visitOffsetExpression( sqmQuerySpec.getOffsetExpression() ) ); - - return sqlQuerySpec; - } - finally { - processingStateStack.pop(); - } - } - - @Override - public Void visitOrderByClause(SqmOrderByClause orderByClause) { - super.visitOrderByClause( orderByClause ); - return null; - } - - @Override - public SortSpecification visitSortSpecification(SqmSortSpecification sortSpecification) { - return new SortSpecification( - toSqlExpression( sortSpecification.getSortExpression().accept( this ) ), - sortSpecification.getCollation(), - sortSpecification.getSortOrder() - ); - } - - @Override - public Expression visitOffsetExpression(SqmExpression expression) { - if ( expression == null ) { - return null; - } - - currentClauseStack.push( Clause.OFFSET ); - try { - return (Expression) expression.accept( this ); - } - finally { - currentClauseStack.pop(); - } - } - - @Override - public Expression visitLimitExpression(SqmExpression expression) { - if ( expression == null ) { - return null; - } - - currentClauseStack.push( Clause.LIMIT ); - try { - return (Expression) expression.accept( this ); - } - finally { - currentClauseStack.pop(); - } - } - - - @Override - public Void visitFromClause(SqmFromClause sqmFromClause) { - currentClauseStack.push( Clause.FROM ); - - try { - sqmFromClause.visitRoots( - sqmRoot -> { - final NavigableReference rootReference = visitRootPath( sqmRoot ); - assert rootReference instanceof TableGroup; - currentQuerySpec().getFromClause().addRoot( (TableGroup) rootReference ); - } - ); - } - finally { - currentClauseStack.pop(); - } - return null; - } - - - @Override - public NavigableReference visitRootPath(SqmRoot sqmRoot) { - log.tracef( "Starting resolution of SqmRoot [%s] to TableGroup", sqmRoot ); - - if ( fromClauseIndex.isResolved( sqmRoot ) ) { - final TableGroup resolvedTableGroup = fromClauseIndex.findTableGroup( sqmRoot.getNavigablePath() ); - log.tracef( "SqmRoot [%s] resolved to existing TableGroup [%s]", sqmRoot, resolvedTableGroup ); - return resolvedTableGroup; - } - - final EntityTypeDescriptor entityDescriptor = sqmRoot.getReferencedPathSource().getEntityDescriptor(); - final TableGroup group = entityDescriptor.createRootTableGroup( - sqmRoot.getNavigablePath(), - sqmRoot.getExplicitAlias(), - JoinType.INNER, - LockMode.NONE, - this - ); - - fromClauseIndex.register( sqmRoot, group ); - - log.tracef( "Resolved SqmRoot [%s] to new TableGroup [%s]", sqmRoot, group ); - - sqmRoot.visitSqmJoins( - sqmJoin -> { - final TableGroupJoin tableGroupJoin = (TableGroupJoin) sqmJoin.accept( this ); - if ( tableGroupJoin != null ) { - group.addTableGroupJoin( tableGroupJoin ); - } - } - ); - - return group; - } - - @Override - public TableGroupJoin visitQualifiedAttributeJoin(SqmAttributeJoin sqmJoin) { - final TableGroup lhsTableGroup = fromClauseIndex.findTableGroup( sqmJoin.getLhs().getNavigablePath() ); - - final NavigableContainer joinedNavigable = sqmJoin.sqmAs( NavigableContainer.class ); - if ( joinedNavigable instanceof EmbeddedValuedNavigable ) { - // register the LHS TableGroup as the embedded's TableGroup - fromClauseIndex.registerTableGroup( sqmJoin.getNavigablePath(), lhsTableGroup ); - - // we also still want to process its joins, adding them to the LHS TableGroup - sqmJoin.visitSqmJoins( - sqmJoinJoin -> { - final TableGroupJoin tableGroupJoin = (TableGroupJoin) sqmJoinJoin.accept( this ); - if ( tableGroupJoin != null ) { - lhsTableGroup.addTableGroupJoin( tableGroupJoin ); - } - } - ); - - return null; - } - - final TableGroupJoin tableJoinJoin = fromClauseIndex.findTableGroupJoin( sqmJoin.getNavigablePath() ); - if ( tableJoinJoin != null ) { - return tableJoinJoin; - } - - final TableGroupJoinProducer joinProducer = joinedNavigable.as( TableGroupJoinProducer.class ); - - final TableGroupJoin tableGroupJoin = joinProducer.createTableGroupJoin( - sqmJoin.getNavigablePath(), - fromClauseIndex.getTableGroup( sqmJoin.getLhs().getNavigablePath() ), - sqmJoin.getExplicitAlias(), - sqmJoin.getSqmJoinType().getCorrespondingSqlJoinType(), - LockMode.NONE, - this - ); - - fromClauseIndex.register( sqmJoin, tableGroupJoin ); - lhsTableGroup.addTableGroupJoin( tableGroupJoin ); - - // add any additional join restrictions - if ( sqmJoin.getJoinPredicate() != null ) { - currentQuerySpec().addRestriction( - (Predicate) sqmJoin.getJoinPredicate().accept( this ) - ); - } - - - return tableGroupJoin; - } - - @Override - public TableGroup visitCrossJoin(SqmCrossJoin sqmJoin) { - final EntityTypeDescriptor entityMetadata = sqmJoin.getReferencedPathSource().getEntityDescriptor(); - final TableGroup group = entityMetadata.createRootTableGroup( - sqmJoin.getNavigablePath(), - sqmJoin.getExplicitAlias(), - JoinType.INNER, - LockMode.NONE, - this - ); - - fromClauseIndex.register( sqmJoin, group ); - - sqmJoin.visitSqmJoins( - sqmJoinJoin -> { - final TableGroupJoin tableGroupJoin = (TableGroupJoin) sqmJoinJoin.accept( this ); - if ( tableGroupJoin != null ) { - group.addTableGroupJoin( tableGroupJoin ); - } - } - ); - - return new TableGroupJoin( JoinType.CROSS, group, null ).getJoinedGroup(); - } - - @Override - public Object visitQualifiedEntityJoin(SqmEntityJoin joinedFromElement) { - throw new NotYetImplementedFor6Exception(); - } - - @Override - public SelectClause visitSelectClause(SqmSelectClause selectClause) { - currentClauseStack.push( Clause.SELECT ); - shallownessStack.push( SqmSelectToSqlAstConverter.Shallowness.SUBQUERY ); - try { - super.visitSelectClause( selectClause ); - - currentQuerySpec().getSelectClause().makeDistinct( selectClause.isDistinct() ); - return currentQuerySpec().getSelectClause(); - } - finally { - shallownessStack.pop(); - currentClauseStack.pop(); - } - } - - @Override - public BasicValuedNavigableReference visitBasicValuedPath(SqmBasicValuedSimplePath path) { - return new BasicValuedNavigableReference( - path.getNavigablePath(), - path.getReferencedPathSource(), - this - ); - } - - @Override - public EmbeddableValuedNavigableReference visitEmbeddableValuedPath(SqmEmbeddedValuedSimplePath path) { - return new EmbeddableValuedNavigableReference( - path.getNavigablePath(), - path.getReferencedPathSource(), - determineLockMode( path.getExplicitAlias() ), - this - ); - } - - @Override - public Object visitEntityValuedPath(SqmEntityValuedSimplePath path) { - return new EntityValuedNavigableReference( - path.getNavigablePath(), - path.getReferencedPathSource(), - determineLockMode( path.getExplicitAlias() ), - this - ); - } - - @Override - public Object visitPluralValuedPath(SqmPluralValuedSimplePath path) { - throw new NotYetImplementedFor6Exception(); - } - - - // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - // Expressions - - @Override - public Object visitLiteral(SqmLiteral literal) { - return new QueryLiteral( - literal.getLiteralValue(), - literal.getNodeType().getSqlExpressableType( creationContext.getDomainModel().getTypeConfiguration() ), - getCurrentClauseStack().getCurrent() - ); - } - - @Override - public Object visitTuple(SqmTuple sqmTuple) { - throw new NotYetImplementedFor6Exception(); - } - - private final Map> jdbcParamsBySqmParam = new IdentityHashMap<>(); - private final JdbcParameters jdbcParameters = new JdbcParametersImpl(); - - @Override - public Map> getJdbcParamsBySqmParam() { - return jdbcParamsBySqmParam; - } - - @Override - public Expression visitNamedParameterExpression(SqmNamedParameter expression) { - return consumeSqmParameter( expression ); - } - - private Expression consumeSqmParameter(SqmParameter sqmParameter) { - final List jdbcParametersForSqm = new ArrayList<>(); - - if ( jdbcParamsBySqmParam.containsKey( sqmParameter ) ) { - // this is a "correction" in the case where a Criteria - assert sqmParameter instanceof SqmCriteriaParameter; - final SqmParameter copy = sqmParameter.copy(); - domainParameterXref.addCriteriaAdjustment( - domainParameterXref.getQueryParameter( sqmParameter ), - (SqmCriteriaParameter) sqmParameter, - copy - ); - - sqmParameter = copy; - } - - resolveSqmParameter( sqmParameter, jdbcParametersForSqm::add ); - - jdbcParameters.addParameters( jdbcParametersForSqm ); - jdbcParamsBySqmParam.put( sqmParameter, jdbcParametersForSqm ); - - if ( jdbcParametersForSqm.size() > 1 ) { - //noinspection unchecked - return new SqlTuple( (List) jdbcParametersForSqm ); - } - else { - return jdbcParametersForSqm.get( 0 ); - } - } - - private void resolveSqmParameter(SqmParameter expression, Consumer jdbcParameterConsumer) { - AllowableParameterType expressableType = expression.getNodeType(); - - if ( expressableType == null ) { - final QueryParameterImplementor queryParameter = domainParameterXref.getQueryParameter( expression ); - final QueryParameterBinding binding = domainParameterBindings.getBinding( queryParameter ); - expressableType = getCreationContext().getDomainModel().resolveQueryParameterType( - NullnessHelper.coalesce( - binding.getBindType(), - queryParameter.getHibernateType(), - expression.getAnticipatedType() - ).getJavaType() - ); - - if ( expressableType == null ) { - log.debugf( "Could not determine ExpressableType for parameter [%s], falling back to Object-handling", expression ); - expressableType = StandardBasicTypes.OBJECT_TYPE; - } - - expression.applyInferableType( expressableType ); - } - - expressableType.visitJdbcTypes( - type -> { - final StandardJdbcParameterImpl jdbcParameter = new StandardJdbcParameterImpl( - jdbcParameters.getJdbcParameters().size(), - type, - currentClauseStack.getCurrent(), - getCreationContext().getDomainModel().getTypeConfiguration() - ); - jdbcParameterConsumer.accept( jdbcParameter ); - }, - currentClauseStack.getCurrent(), - getCreationContext().getDomainModel().getTypeConfiguration() - ); - } - - @Override - public Object visitPositionalParameterExpression(SqmPositionalParameter expression) { - return consumeSqmParameter( expression ); - } - - @Override - public Object visitCriteriaParameter(SqmCriteriaParameter expression) { - return consumeSqmParameter( expression ); - } - - - @Override - public Object visitFunction(SqmFunction sqmFunction) { - shallownessStack.push( Shallowness.FUNCTION ); - try { - return sqmFunction.convertToSqlAst( this ); - } - finally { - shallownessStack.pop(); - } - } - - @Override - public Object visitTrimSpecification(SqmTrimSpecification specification) { - shallownessStack.push( Shallowness.FUNCTION ); - try { - return new TrimSpecification( - specification.getSpecification() - ); - } - finally { - shallownessStack.pop(); - } - } - - @Override - public Object visitCastTarget(SqmCastTarget target) { - shallownessStack.push( Shallowness.FUNCTION ); - try { - return new CastTarget( - target.getType().getSqlExpressableType() - ); - } - finally { - shallownessStack.pop(); - } - } - - @Override - public Object visitExtractUnit(SqmExtractUnit unit) { - shallownessStack.push( Shallowness.FUNCTION ); - try { - return new ExtractUnit( - unit.getUnitName(), - unit.getType().getSqlExpressableType() - ); - } - finally { - shallownessStack.pop(); - } - } - - @Override - public Object visitDistinct(SqmDistinct distinct) { - return new Distinct( toSqlExpression( distinct.getExpression().accept(this) ) ); - } - - @Override - public Object visitStar(SqmStar sqmStar) { - return new Star(); - } - - @Override - public Object visitUnaryOperationExpression(SqmUnaryOperation expression) { - shallownessStack.push( Shallowness.NONE ); - - try { - return new UnaryOperation( - interpret( expression.getOperation() ), - toSqlExpression( expression.getOperand().accept( this ) ), - expression.getNodeType().getSqlExpressableType() - - ); - } - finally { - shallownessStack.pop(); - } - } - - private UnaryArithmeticOperator interpret(UnaryArithmeticOperator operator) { - return operator; - } - - @Override - public Expression visitBinaryArithmeticExpression(SqmBinaryArithmetic expression) { - shallownessStack.push( Shallowness.NONE ); - - try { - return new BinaryArithmeticExpression( - toSqlExpression( expression.getLeftHandOperand().accept( this ) ), - interpret( expression.getOperator() ), - toSqlExpression( expression.getRightHandOperand().accept( this ) ), - expression.getNodeType().getSqlExpressableType() - ); - } - finally { - shallownessStack.pop(); - } - } - - private BinaryArithmeticOperator interpret(BinaryArithmeticOperator operator) { - switch ( operator ) { - case ADD: { - return ADD; - } - case SUBTRACT: { - return SUBTRACT; - } - case MULTIPLY: { - return MULTIPLY; - } - case DIVIDE: { - return DIVIDE; - } - case QUOT: { - return QUOT; - } - } - - throw new IllegalStateException( "Unexpected BinaryArithmeticOperator : " + operator ); - } - - @Override - public Object visitSubQueryExpression(SqmSubQuery sqmSubQuery) { - final QuerySpec subQuerySpec = visitQuerySpec( sqmSubQuery.getQuerySpec() ); - - final ExpressableType expressableType = sqmSubQuery.getNodeType(); - - return new SubQuery( - subQuerySpec, - expressableType instanceof BasicValuedExpressableType - ? ( (BasicValuedExpressableType) expressableType ).getSqlExpressableType( getCreationContext().getDomainModel().getTypeConfiguration() ) - : null, - expressableType - ); - } - - @Override - public CaseSimpleExpression visitSimpleCaseExpression(SqmCaseSimple expression) { - final CaseSimpleExpression result = new CaseSimpleExpression( - expression.getNodeType().getSqlExpressableType(), - toSqlExpression( expression.getFixture().accept( this ) ) - ); - - for ( SqmCaseSimple.WhenFragment whenFragment : expression.getWhenFragments() ) { - result.when( - toSqlExpression( whenFragment.getCheckValue().accept( this ) ), - toSqlExpression( whenFragment.getResult().accept( this ) ) - ); - } - - result.otherwise( toSqlExpression( expression.getOtherwise().accept( this ) ) ); - - return result; - } - - @Override - public CaseSearchedExpression visitSearchedCaseExpression(SqmCaseSearched expression) { - final CaseSearchedExpression result = new CaseSearchedExpression( - ( (BasicValuedExpressableType) expression.getNodeType() ).getSqlExpressableType() - ); - - for ( SqmCaseSearched.WhenFragment whenFragment : expression.getWhenFragments() ) { - result.when( - (Predicate) whenFragment.getPredicate().accept( this ), - toSqlExpression( whenFragment.getResult().accept( this ) ) - ); - } - - result.otherwise( toSqlExpression( expression.getOtherwise().accept( this ) ) ); - - return result; - } - -// @Override -// public Object visitPluralAttributeElementBinding(PluralAttributeElementBinding binding) { -// final TableGroup resolvedTableGroup = fromClauseIndex.findResolvedTableGroup( binding.getFromElement() ); -// -// return getCurrentDomainReferenceExpressionBuilder().buildPluralAttributeElementReferenceExpression( -// binding, -// resolvedTableGroup, -// PersisterHelper.convert( binding.getNavigablePath() ) -// ); -// } - - - // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - // Predicates - - - @Override - public GroupedPredicate visitGroupedPredicate(SqmGroupedPredicate predicate) { - return new GroupedPredicate ( (Predicate ) predicate.getSubPredicate().accept( this ) ); - } - - @Override - public Junction visitAndPredicate(SqmAndPredicate predicate) { - final Junction conjunction = new Junction( Junction.Nature.CONJUNCTION ); - conjunction.add( (Predicate) predicate.getLeftHandPredicate().accept( this ) ); - conjunction.add( (Predicate) predicate.getRightHandPredicate().accept( this ) ); - return conjunction; - } - - @Override - public Junction visitOrPredicate(SqmOrPredicate predicate) { - final Junction disjunction = new Junction( Junction.Nature.DISJUNCTION ); - disjunction.add( (Predicate) predicate.getLeftHandPredicate().accept( this ) ); - disjunction.add( (Predicate) predicate.getRightHandPredicate().accept( this ) ); - return disjunction; - } - - @Override - public NegatedPredicate visitNegatedPredicate(SqmNegatedPredicate predicate) { - return new NegatedPredicate( - (Predicate) predicate.getWrappedPredicate().accept( this ) - ); - } - - @Override - public ComparisonPredicate visitComparisonPredicate(SqmComparisonPredicate predicate) { - final Expression lhs = toSqlExpression( predicate.getLeftHandExpression().accept( this ) ); - final Expression rhs = toSqlExpression( predicate.getRightHandExpression().accept( this ) ); - - return new ComparisonPredicate( - lhs, - interpret( predicate.getSqmOperator() ), - rhs - ); - } - - private Expression toSqlExpression(Object value) { - if ( value instanceof SqmExpressionInterpretation ) { - return ( (SqmExpressionInterpretation) value ).toSqlExpression( this ); - } - - // any other special cases? - - return (Expression) value; - } - - private ComparisonOperator interpret(ComparisonOperator operator) { - switch ( operator ) { - case EQUAL: { - return ComparisonOperator.EQUAL; - } - case NOT_EQUAL: { - return ComparisonOperator.NOT_EQUAL; - } - case GREATER_THAN_OR_EQUAL: { - return ComparisonOperator.GREATER_THAN_OR_EQUAL; - } - case GREATER_THAN: { - return ComparisonOperator.GREATER_THAN; - } - case LESS_THAN_OR_EQUAL: { - return ComparisonOperator.LESS_THAN_OR_EQUAL; - } - case LESS_THAN: { - return ComparisonOperator.LESS_THAN; - } - } - - throw new IllegalStateException( "Unexpected RelationalPredicate Type : " + operator ); - } - - @Override - public BetweenPredicate visitBetweenPredicate(SqmBetweenPredicate predicate) { - final Expression expression = toSqlExpression( predicate.getExpression().accept( this ) ); - final Expression lowerBound = toSqlExpression( predicate.getLowerBound().accept( this ) ); - final Expression upperBound = toSqlExpression( predicate.getUpperBound().accept( this ) ); - - return new BetweenPredicate( - expression, - lowerBound, - upperBound, - predicate.isNegated() - ); - } - - @Override - public LikePredicate visitLikePredicate(SqmLikePredicate predicate) { - final Expression escapeExpression = predicate.getEscapeCharacter() == null - ? null - : toSqlExpression( predicate.getEscapeCharacter().accept( this ) ); - - return new LikePredicate( - toSqlExpression( predicate.getMatchExpression().accept( this ) ), - toSqlExpression( predicate.getPattern().accept( this ) ), - escapeExpression, - predicate.isNegated() - ); - } - - @Override - public NullnessPredicate visitIsNullPredicate(SqmNullnessPredicate predicate) { - return new NullnessPredicate( - toSqlExpression( predicate.getExpression().accept( this ) ), - predicate.isNegated() - ); - } - - @Override - public InListPredicate visitInListPredicate(SqmInListPredicate predicate) { - // special case: - // if there is just a single element and it is an SqmParameter - // and the corresponding QueryParameter binding is multi-valued... - // lets expand the SQL AST for each bind value - if ( predicate.getListExpressions().size() == 1 ) { - final SqmExpression sqmExpression = predicate.getListExpressions().get( 0 ); - if ( sqmExpression instanceof SqmParameter ) { - final SqmParameter sqmParameter = (SqmParameter) sqmExpression; - final QueryParameterImplementor domainParam = domainParameterXref.getQueryParameter( sqmParameter ); - final QueryParameterBinding domainParamBinding = domainParameterBindings.getBinding( domainParam ); - - if ( domainParamBinding.isMultiValued() ) { - final InListPredicate inListPredicate = new InListPredicate( - toSqlExpression( predicate.getTestExpression().accept( this ) ) - ); - - boolean first = true; - for ( Object bindValue : domainParamBinding.getBindValues() ) { - final SqmParameter sqmParamToConsume; - // for each bind value do the following: - // 1) create a pseudo-SqmParameter (though re-use the original for the first value) - if ( first ) { - sqmParamToConsume = sqmParameter; - first = false; - } - else { - sqmParamToConsume = sqmParameter.copy(); - domainParameterXref.addExpansion( domainParam, sqmParameter, sqmParamToConsume ); - } - - inListPredicate.addExpression( consumeSqmParameter( sqmParamToConsume ) ); - } - - return inListPredicate; - } - } - } - - - final InListPredicate inPredicate = new InListPredicate( - toSqlExpression( predicate.getTestExpression().accept( this ) ), - predicate.isNegated() - ); - - for ( SqmExpression expression : predicate.getListExpressions() ) { - inPredicate.addExpression( toSqlExpression( expression.accept( this ) ) ); - } - - return inPredicate; - } - - @Override - public InSubQueryPredicate visitInSubQueryPredicate(SqmInSubQueryPredicate predicate) { - return new InSubQueryPredicate( - toSqlExpression( predicate.getTestExpression().accept( this ) ), - (QuerySpec) predicate.getSubQueryExpression().accept( this ), - predicate.isNegated() - ); - } -} diff --git a/hibernate-core/src/main/java/org/hibernate/query/sqm/consume/spi/SqmExpressionInterpretation.java b/hibernate-core/src/main/java/org/hibernate/query/sqm/consume/spi/SqmExpressionInterpretation.java deleted file mode 100644 index 58c6285855..0000000000 --- a/hibernate-core/src/main/java/org/hibernate/query/sqm/consume/spi/SqmExpressionInterpretation.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Hibernate, Relational Persistence for Idiomatic Java - * - * License: GNU Lesser General Public License (LGPL), version 2.1 or later - * See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html - */ -package org.hibernate.query.sqm.consume.spi; - -import org.hibernate.sql.ast.spi.SqlAstCreationState; -import org.hibernate.sql.ast.tree.expression.Expression; -import org.hibernate.sql.results.spi.DomainResultProducer; - -/** - * The interpretation of an SqmExpression as part of the SQM -> SQL conversion. - * - * Allows multi-column navigable references to be used anywhere a (SqlExpression) - * can be. The trick is to properly define methods on this interface for how the - * thing should be rendered into the SQL AST. Access to the domain type descriptor - * also allows consumers to find out information about the - * - * @author Steve Ebersole - */ -public interface SqmExpressionInterpretation extends DomainResultProducer { - ExpressableType getExpressableType(); - - default Expression toSqlExpression(SqlAstCreationState sqlAstCreationState) { - return (Expression) this; - } -} diff --git a/hibernate-core/src/main/java/org/hibernate/query/sqm/internal/ConcreteSqmSelectQueryPlan.java b/hibernate-core/src/main/java/org/hibernate/query/sqm/internal/ConcreteSqmSelectQueryPlan.java index 545f15bd9e..1805a75163 100644 --- a/hibernate-core/src/main/java/org/hibernate/query/sqm/internal/ConcreteSqmSelectQueryPlan.java +++ b/hibernate-core/src/main/java/org/hibernate/query/sqm/internal/ConcreteSqmSelectQueryPlan.java @@ -12,35 +12,26 @@ import java.util.Map; import javax.persistence.Tuple; import javax.persistence.TupleElement; +import org.hibernate.NotYetImplementedFor6Exception; import org.hibernate.ScrollMode; -import org.hibernate.internal.util.collections.streams.StingArrayCollector; +import org.hibernate.internal.util.streams.StingArrayCollector; import org.hibernate.query.IllegalQueryOperationException; -import org.hibernate.query.JpaTupleTransformer; -import org.hibernate.query.internal.QueryHelper; import org.hibernate.query.spi.QueryOptions; import org.hibernate.query.spi.QueryParameterImplementor; import org.hibernate.query.spi.ScrollableResultsImplementor; import org.hibernate.query.spi.SelectQueryPlan; -import org.hibernate.query.sqm.consume.internal.SqmConsumeHelper; import org.hibernate.query.sqm.tree.expression.SqmParameter; import org.hibernate.query.sqm.tree.select.SqmSelectStatement; import org.hibernate.query.sqm.tree.select.SqmSelection; -import org.hibernate.sql.ast.consume.spi.SqlAstSelectToJdbcSelectConverter; -import org.hibernate.sql.ast.produce.metamodel.spi.ExpressableType; -import org.hibernate.sql.ast.produce.spi.SqlAstSelectDescriptor; -import org.hibernate.sql.ast.produce.sqm.spi.SqmSelectInterpretation; -import org.hibernate.sql.ast.produce.sqm.spi.SqmSelectToSqlAstConverter; -import org.hibernate.sql.exec.internal.JdbcSelectExecutorStandardImpl; +import org.hibernate.sql.exec.spi.ExecutionContext; +import org.hibernate.sql.exec.spi.JdbcParameter; +import org.hibernate.sql.exec.spi.JdbcSelect; import org.hibernate.sql.results.internal.RowTransformerJpaTupleImpl; import org.hibernate.sql.results.internal.RowTransformerPassThruImpl; import org.hibernate.sql.results.internal.RowTransformerSingularReturnImpl; import org.hibernate.sql.results.internal.RowTransformerTupleTransformerAdapter; -import org.hibernate.sql.exec.internal.TupleElementImpl; -import org.hibernate.sql.exec.spi.ExecutionContext; -import org.hibernate.sql.exec.spi.JdbcParameter; -import org.hibernate.sql.exec.spi.JdbcParameterBindings; -import org.hibernate.sql.exec.spi.JdbcSelect; -import org.hibernate.sql.exec.spi.RowTransformer; +import org.hibernate.sql.results.internal.TupleElementImpl; +import org.hibernate.sql.results.spi.RowTransformer; /** * Standard Hibernate implementation of SelectQueryPlan for SQM-backed @@ -111,12 +102,6 @@ public class ConcreteSqmSelectQueryPlan implements SelectQueryPlan { return (RowTransformer) new RowTransformerJpaTupleImpl( tupleElementList ); } - // there can be a TupleTransformer IF it is a JpaTupleBuilder, - // otherwise this is considered an error - if ( queryOptions.getTupleTransformer() instanceof JpaTupleTransformer ) { - return makeRowTransformerTupleTransformerAdapter( sqm, queryOptions ); - } - throw new IllegalArgumentException( "Illegal combination of Tuple resultType and (non-JpaTupleBuilder) TupleTransformer : " + queryOptions.getTupleTransformer() @@ -155,85 +140,88 @@ public class ConcreteSqmSelectQueryPlan implements SelectQueryPlan { @Override @SuppressWarnings("unchecked") public List performList(ExecutionContext executionContext) { - if ( jdbcSelect == null ) { - final SqmSelectToSqlAstConverter sqmConverter = getSqmSelectToSqlAstConverter( executionContext ); - final SqmSelectInterpretation interpretation = sqmConverter.interpret( sqm ); - jdbcSelect = SqlAstSelectToJdbcSelectConverter.interpret( - interpretation, - executionContext.getSession().getSessionFactory() - ); + throw new NotYetImplementedFor6Exception( getClass() ); - this.jdbcParamsXref = SqmConsumeHelper.generateJdbcParamsXref( domainParameterXref, interpretation ); - } - - final JdbcParameterBindings jdbcParameterBindings = QueryHelper.createJdbcParameterBindings( - executionContext.getDomainParameterBindingContext().getQueryParameterBindings(), - domainParameterXref, - jdbcParamsXref, - executionContext.getSession() - ); - - try { - // todo (6.0) : make these executors resolvable to allow plugging in custom ones. - // Dialect? - return JdbcSelectExecutorStandardImpl.INSTANCE.list( - jdbcSelect, - jdbcParameterBindings, - executionContext, - rowTransformer - ); - } - finally { - domainParameterXref.clearExpansions(); - } +// if ( jdbcSelect == null ) { +// final SqmSelectToSqlAstConverter sqmConverter = getSqmSelectToSqlAstConverter( executionContext ); +// final SqmSelectInterpretation interpretation = sqmConverter.interpret( sqm ); +// jdbcSelect = SqlAstSelectToJdbcSelectConverter.interpret( +// interpretation, +// executionContext.getSession().getSessionFactory() +// ); +// +// this.jdbcParamsXref = SqmConsumeHelper.generateJdbcParamsXref( domainParameterXref, interpretation ); +// } +// +// final JdbcParameterBindings jdbcParameterBindings = QueryHelper.createJdbcParameterBindings( +// executionContext.getDomainParameterBindingContext().getQueryParameterBindings(), +// domainParameterXref, +// jdbcParamsXref, +// executionContext.getSession() +// ); +// +// try { +// // todo (6.0) : make these executors resolvable to allow plugging in custom ones. +// // Dialect? +// return JdbcSelectExecutorStandardImpl.INSTANCE.list( +// jdbcSelect, +// jdbcParameterBindings, +// executionContext, +// rowTransformer +// ); +// } +// finally { +// domainParameterXref.clearExpansions(); +// } } - private SqmSelectToSqlAstConverter getSqmSelectToSqlAstConverter(ExecutionContext executionContext) { - // todo (6.0) : for cases where we have no "load query influencers" we could use a cached SQL AST - return new SqmSelectToSqlAstConverter( - executionContext.getQueryOptions(), - domainParameterXref, - executionContext.getDomainParameterBindingContext().getQueryParameterBindings(), - executionContext.getLoadQueryInfluencers(), - afterLoadAction -> {}, - executionContext.getSession().getFactory() - ); - } +// private SqmSelectToSqlAstConverter getSqmSelectToSqlAstConverter(ExecutionContext executionContext) { +// // todo (6.0) : for cases where we have no "load query influencers" we could use a cached SQL AST +// return new SqmSelectToSqlAstConverter( +// executionContext.getQueryOptions(), +// domainParameterXref, +// executionContext.getDomainParameterBindingContext().getQueryParameterBindings(), +// executionContext.getLoadQueryInfluencers(), +// afterLoadAction -> {}, +// executionContext.getSession().getFactory() +// ); +// } @Override @SuppressWarnings("unchecked") public ScrollableResultsImplementor performScroll(ScrollMode scrollMode, ExecutionContext executionContext) { + throw new NotYetImplementedFor6Exception( getClass() ); - final SqmSelectToSqlAstConverter sqmConverter = getSqmSelectToSqlAstConverter( executionContext ); - - final SqmSelectInterpretation interpretation = sqmConverter.interpret( sqm ); - - final JdbcSelect jdbcSelect = SqlAstSelectToJdbcSelectConverter.interpret( - interpretation, - executionContext.getSession().getSessionFactory() - ); - - final Map, Map>> jdbcParamsXref = - SqmConsumeHelper.generateJdbcParamsXref( domainParameterXref, sqmConverter ); - - final JdbcParameterBindings jdbcParameterBindings = QueryHelper.createJdbcParameterBindings( - executionContext.getDomainParameterBindingContext().getQueryParameterBindings(), - domainParameterXref, - jdbcParamsXref, - executionContext.getSession() - ); - - try { - return JdbcSelectExecutorStandardImpl.INSTANCE.scroll( - jdbcSelect, - scrollMode, - jdbcParameterBindings, - executionContext, - rowTransformer - ); - } - finally { - domainParameterXref.clearExpansions(); - } +// final SqmSelectToSqlAstConverter sqmConverter = getSqmSelectToSqlAstConverter( executionContext ); +// +// final SqmSelectInterpretation interpretation = sqmConverter.interpret( sqm ); +// +// final JdbcSelect jdbcSelect = SqlAstSelectToJdbcSelectConverter.interpret( +// interpretation, +// executionContext.getSession().getSessionFactory() +// ); +// +// final Map, Map>> jdbcParamsXref = +// SqmConsumeHelper.generateJdbcParamsXref( domainParameterXref, sqmConverter ); +// +// final JdbcParameterBindings jdbcParameterBindings = QueryHelper.createJdbcParameterBindings( +// executionContext.getDomainParameterBindingContext().getQueryParameterBindings(), +// domainParameterXref, +// jdbcParamsXref, +// executionContext.getSession() +// ); +// +// try { +// return JdbcSelectExecutorStandardImpl.INSTANCE.scroll( +// jdbcSelect, +// scrollMode, +// jdbcParameterBindings, +// executionContext, +// rowTransformer +// ); +// } +// finally { +// domainParameterXref.clearExpansions(); +// } } } diff --git a/hibernate-core/src/main/java/org/hibernate/query/sqm/internal/SimpleDeleteQueryPlan.java b/hibernate-core/src/main/java/org/hibernate/query/sqm/internal/SimpleDeleteQueryPlan.java index 59096f9ae9..d2a4754938 100644 --- a/hibernate-core/src/main/java/org/hibernate/query/sqm/internal/SimpleDeleteQueryPlan.java +++ b/hibernate-core/src/main/java/org/hibernate/query/sqm/internal/SimpleDeleteQueryPlan.java @@ -6,16 +6,18 @@ */ package org.hibernate.query.sqm.internal; +import org.hibernate.NotYetImplementedFor6Exception; import org.hibernate.query.spi.NonSelectQueryPlan; import org.hibernate.query.sqm.tree.delete.SqmDeleteStatement; -import org.hibernate.sql.ast.consume.spi.SqlDeleteToJdbcDeleteConverter; -import org.hibernate.sql.ast.produce.sqm.spi.SqmDeleteInterpretation; -import org.hibernate.sql.ast.produce.sqm.spi.SqmDeleteToSqlAstConverterSimple; -import org.hibernate.sql.exec.internal.JdbcMutationExecutorImpl; import org.hibernate.sql.exec.spi.ExecutionContext; -import org.hibernate.sql.exec.spi.JdbcMutation; - -import static org.hibernate.query.internal.QueryHelper.buildJdbcParameterBindings; +//import org.hibernate.sql.ast.consume.spi.SqlDeleteToJdbcDeleteConverter; +//import org.hibernate.sql.ast.produce.sqm.spi.SqmDeleteInterpretation; +//import org.hibernate.sql.ast.produce.sqm.spi.SqmDeleteToSqlAstConverterSimple; +//import org.hibernate.sql.exec.internal.JdbcMutationExecutorImpl; +//import org.hibernate.sql.exec.spi.ExecutionContext; +//import org.hibernate.sql.exec.spi.JdbcMutation; +// +//import static org.hibernate.query.internal.QueryHelper.buildJdbcParameterBindings; /** * @author Steve Ebersole @@ -33,27 +35,28 @@ public class SimpleDeleteQueryPlan implements NonSelectQueryPlan { @Override public int executeUpdate(ExecutionContext executionContext) { - final SqmDeleteInterpretation sqmInterpretation = SqmDeleteToSqlAstConverterSimple.interpret( - sqmStatement, - executionContext.getQueryOptions(), - domainParameterXref, - executionContext.getDomainParameterBindingContext().getQueryParameterBindings(), - executionContext.getSession() - ); - - // the converter should enforce this, simple assertion here - assert sqmInterpretation.getSqlDeletes().size() == 1; - - final JdbcMutation jdbcDelete = SqlDeleteToJdbcDeleteConverter.interpret( - sqmInterpretation.getSqlDeletes().get( 0 ), - executionContext.getSession().getSessionFactory() - ); - - - return JdbcMutationExecutorImpl.WITH_AFTER_STATEMENT_CALL.execute( - jdbcDelete, - buildJdbcParameterBindings( sqmStatement, sqmInterpretation, executionContext ), - executionContext - ); + throw new NotYetImplementedFor6Exception( getClass() ); +// final SqmDeleteInterpretation sqmInterpretation = SqmDeleteToSqlAstConverterSimple.interpret( +// sqmStatement, +// executionContext.getQueryOptions(), +// domainParameterXref, +// executionContext.getDomainParameterBindingContext().getQueryParameterBindings(), +// executionContext.getSession() +// ); +// +// // the converter should enforce this, simple assertion here +// assert sqmInterpretation.getSqlDeletes().size() == 1; +// +// final JdbcMutation jdbcDelete = SqlDeleteToJdbcDeleteConverter.interpret( +// sqmInterpretation.getSqlDeletes().get( 0 ), +// executionContext.getSession().getSessionFactory() +// ); +// +// +// return JdbcMutationExecutorImpl.WITH_AFTER_STATEMENT_CALL.execute( +// jdbcDelete, +// buildJdbcParameterBindings( sqmStatement, sqmInterpretation, executionContext ), +// executionContext +// ); } } diff --git a/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/internal/SqmIdSelectGenerator.java b/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/internal/SqmIdSelectGenerator.java deleted file mode 100644 index 15f481c103..0000000000 --- a/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/internal/SqmIdSelectGenerator.java +++ /dev/null @@ -1,132 +0,0 @@ -/* - * Hibernate, Relational Persistence for Idiomatic Java - * - * License: GNU Lesser General Public License (LGPL), version 2.1 or later - * See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html - */ -package org.hibernate.query.sqm.mutation.internal; - -import org.hibernate.engine.spi.SessionFactoryImplementor; -import org.hibernate.internal.util.collections.Stack; -import org.hibernate.internal.util.collections.StandardStack; -import org.hibernate.metamodel.model.mapping.EntityTypeDescriptor; -import org.hibernate.query.sqm.NodeBuilder; -import org.hibernate.query.sqm.produce.spi.SqmCreationProcessingState; -import org.hibernate.query.sqm.produce.spi.SqmQuerySpecCreationProcessingState; -import org.hibernate.query.sqm.produce.spi.ImplicitAliasGenerator; -import org.hibernate.query.sqm.produce.spi.SqmCreationContext; -import org.hibernate.query.sqm.produce.spi.SqmCreationOptions; -import org.hibernate.query.sqm.produce.spi.SqmCreationState; -import org.hibernate.query.sqm.tree.SqmDeleteOrUpdateStatement; -import org.hibernate.query.sqm.tree.from.SqmFromClause; -import org.hibernate.query.sqm.tree.from.SqmRoot; -import org.hibernate.query.sqm.tree.predicate.SqmWhereClause; -import org.hibernate.query.sqm.tree.select.SqmQuerySpec; -import org.hibernate.query.sqm.tree.select.SqmSelectClause; -import org.hibernate.query.sqm.tree.select.SqmSelection; - -import org.jboss.logging.Logger; - -/** - * Helper used to generate the SELECT for selection of an entity's - * identifier, here specifically intended to be used as the SELECT - * portion of a multi-table SQM mutation - * - * @author Steve Ebersole - */ -public class SqmIdSelectGenerator { - private static final Logger log = Logger.getLogger( SqmIdSelectGenerator.class ); - - public static SqmQuerySpec generateSqmEntityIdSelect( - SqmDeleteOrUpdateStatement sqmStatement, - SessionFactoryImplementor sessionFactory) { - final SqmIdSelectGenerator generator = new SqmIdSelectGenerator( sqmStatement, sessionFactory ); - - return generator.process(); - } - - private final SqmDeleteOrUpdateStatement sourceSqmStatement; - private final EntityTypeDescriptor entityDescriptor; - private final SqmCreationContext creationContext; - - private final NodeBuilder nodeBuilder; - - public SqmIdSelectGenerator( - SqmDeleteOrUpdateStatement sourceSqmStatement, - SqmCreationContext creationContext) { - this.sourceSqmStatement = sourceSqmStatement; - this.entityDescriptor = sourceSqmStatement.getTarget().getReferencedPathSource(); - this.creationContext = creationContext; - - this.nodeBuilder = creationContext.getQueryEngine().getCriteriaBuilder(); - } - - private SqmQuerySpec process() { - final SqmQuerySpec sqmQuerySpec = new SqmQuerySpec( nodeBuilder ); - - final SqmFromClause sqmFromClause = new SqmFromClause(); - sqmQuerySpec.setFromClause( sqmFromClause ); - - final SqmRoot sqmRoot = new SqmRoot<>( entityDescriptor, null, nodeBuilder ); - sqmFromClause.addRoot( sqmRoot ); - - final SqmSelectClause sqmSelectClause = new SqmSelectClause( true, nodeBuilder ); - sqmQuerySpec.setSelectClause( sqmSelectClause ); - applySelections( sqmSelectClause, sqmRoot ); - - if ( sourceSqmStatement.getWhereClause() != null ) { - sqmQuerySpec.setWhereClause( - new SqmWhereClause( - sourceSqmStatement.getWhereClause().getPredicate(), - nodeBuilder - ) - ); - } - - return sqmQuerySpec; - } - - private void applySelections(SqmSelectClause sqmSelectClause, SqmRoot sqmRoot) { - final Stack processingStateStack = new StandardStack<>(); - - final SqmCreationState sqmCreationState = new SqmCreationState() { - @Override - public SqmCreationContext getCreationContext() { - return creationContext; - } - - @Override - public SqmCreationOptions getCreationOptions() { - return () -> false; - } - - @Override - public Stack getProcessingStateStack() { - return processingStateStack; - } - - @Override - public String generateUniqueIdentifier() { - return null; - } - - @Override - public ImplicitAliasGenerator getImplicitAliasGenerator() { - return null; - } - - @Override - public SqmQuerySpecCreationProcessingState getCurrentQuerySpecProcessingState() { - return (SqmQuerySpecCreationProcessingState) processingStateStack.getCurrent(); - } - }; - - sqmSelectClause.addSelection( - new SqmSelection( - entityDescriptor.getIdentifierDescriptor().createSqmExpression( sqmRoot, sqmCreationState ), - nodeBuilder - ) - ); - } - -} diff --git a/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/internal/SqmMutationStrategyHelper.java b/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/internal/SqmMutationStrategyHelper.java deleted file mode 100644 index 92b8dab482..0000000000 --- a/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/internal/SqmMutationStrategyHelper.java +++ /dev/null @@ -1,267 +0,0 @@ -/* - * Hibernate, Relational Persistence for Idiomatic Java - * - * License: GNU Lesser General Public License (LGPL), version 2.1 or later - * See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html - */ -package org.hibernate.query.sqm.mutation.internal; - -import java.util.List; - -import org.hibernate.boot.model.domain.EntityMappingHierarchy; -import org.hibernate.boot.spi.SessionFactoryOptions; -import org.hibernate.engine.jdbc.spi.JdbcServices; -import org.hibernate.metamodel.model.mapping.spi.EntityHierarchy; -import org.hibernate.metamodel.model.mapping.spi.EntityIdentifier; -import org.hibernate.query.internal.QueryHelper; -import org.hibernate.query.sqm.consume.internal.SqmConsumeHelper; -import org.hibernate.query.sqm.internal.DomainParameterXref; -import org.hibernate.query.sqm.mutation.spi.DeleteHandler; -import org.hibernate.query.sqm.mutation.spi.HandlerCreationContext; -import org.hibernate.query.sqm.mutation.spi.SqmMutationStrategy; -import org.hibernate.query.sqm.mutation.spi.UpdateHandler; -import org.hibernate.query.sqm.tree.SqmDeleteOrUpdateStatement; -import org.hibernate.query.sqm.tree.delete.SqmDeleteStatement; -import org.hibernate.query.sqm.tree.expression.SqmExpression; -import org.hibernate.query.sqm.tree.domain.SqmNavigableReference; -import org.hibernate.query.sqm.tree.predicate.SqmBetweenPredicate; -import org.hibernate.query.sqm.tree.predicate.SqmGroupedPredicate; -import org.hibernate.query.sqm.tree.predicate.SqmInListPredicate; -import org.hibernate.query.sqm.tree.predicate.SqmComparisonPredicate; -import org.hibernate.query.sqm.tree.predicate.SqmJunctivePredicate; -import org.hibernate.query.sqm.tree.predicate.SqmPredicate; -import org.hibernate.query.sqm.tree.select.SqmQuerySpec; -import org.hibernate.query.sqm.tree.select.SqmSelectStatement; -import org.hibernate.query.sqm.tree.update.SqmUpdateStatement; -import org.hibernate.service.ServiceRegistry; -import org.hibernate.sql.ast.consume.spi.SqlAstSelectToJdbcSelectConverter; -import org.hibernate.sql.ast.produce.sqm.spi.SqmSelectInterpretation; -import org.hibernate.sql.ast.produce.sqm.spi.SqmSelectToSqlAstConverter; -import org.hibernate.sql.exec.internal.JdbcSelectExecutorStandardImpl; -import org.hibernate.sql.exec.spi.ExecutionContext; -import org.hibernate.sql.exec.spi.JdbcSelect; - -/** - * @author Steve Ebersole - */ -public class SqmMutationStrategyHelper { - /** - * Singleton access - */ - public static final SqmMutationStrategyHelper INSTANCE = new SqmMutationStrategyHelper(); - - private SqmMutationStrategyHelper() { - } - - /** - * Standard resolution of SqmMutationStrategy to use for a given - * entity hierarchy. - */ - public static SqmMutationStrategy resolveStrategy( - EntityMappingHierarchy bootHierarchyDescriptor, - EntityHierarchy entityHierarchy, - SessionFactoryOptions options, - ServiceRegistry serviceRegistry) { - // todo (6.0) : Planned support for per-entity config - - if ( options.getSqmMutationStrategy() != null ) { - return options.getSqmMutationStrategy(); - } - - return serviceRegistry.getService( JdbcServices.class ) - .getJdbcEnvironment() - .getDialect() - .getFallbackSqmMutationStrategy( entityHierarchy ); - } - - /** - * Specialized "Supplier" or "tri Function" for creating the - * fallback handler if the query matches no "special cases" - */ - public interface FallbackDeleteHandlerCreator { - DeleteHandler create( - SqmDeleteStatement sqmDelete, - DomainParameterXref domainParameterXref, - HandlerCreationContext creationContext); - } - - /** - * Standard DeleteHandler resolution applying "special case" resolution - */ - public static DeleteHandler resolveDeleteHandler( - SqmDeleteStatement sqmDelete, - DomainParameterXref domainParameterXref, - HandlerCreationContext creationContext, - FallbackDeleteHandlerCreator fallbackCreator) { - if ( sqmDelete.getWhereClause() == null ) { - // special case : unrestricted - // -> delete all rows, no need to use the id table - } - else { - // if the predicate contains refers to any non-id Navigable, we will need to use the id table - if ( ! hasNonIdReferences( sqmDelete.getWhereClause().getPredicate() ) ) { - // special case : not restricted on non-id Navigable reference - // -> we can apply the original restriction to the individual - // - // todo (6.0) : technically non-id references where the reference is mapped to the primary table - // can also be handled by this special case. Really the special case condition is "has - // any non-id references to Navigables not mapped to the primary table of the container" - } - } - - // otherwise, use the fallback.... - return fallbackCreator.create( sqmDelete, domainParameterXref, creationContext ); - } - - /** - * Specialized "Supplier" or "tri Function" for creating the - * fallback handler if the query mmatches no "special cases" - */ - public interface FallbackUpdateHandlerCreator { - UpdateHandler create( - SqmUpdateStatement sqmUpdate, - DomainParameterXref domainParameterXref, - HandlerCreationContext creationContext); - } - - /** - * Standard UpdateHandler resolution applying "special case" resolution - */ - public static UpdateHandler resolveUpdateHandler( - SqmUpdateStatement sqmUpdate, - DomainParameterXref domainParameterXref, - HandlerCreationContext creationContext, - FallbackUpdateHandlerCreator fallbackCreator) { - if ( sqmUpdate.getWhereClause() == null ) { - // special case : unrestricted - // -> delete all rows, no need to use the id table - } - else { - // see if the predicate contains any non-id Navigable references - if ( ! hasNonIdReferences( sqmUpdate.getWhereClause().getPredicate() ) ) { - // special case : not restricted on non-id Navigable reference - // -> we can apply the original restriction to the individual updates without needing to use the id-table - // - // todo (6.0) : technically non-id references where the reference is mapped to the primary table - // can also be handled by this special case. Really the special case condition is "has - // any non-id references to Navigables not mapped to the primary table of the container" - } - } - - // todo (6.0) : implement the above special cases - - // otherwise, use the fallback.... - return fallbackCreator.create( sqmUpdate, domainParameterXref, creationContext ); - } - - /** - * Does the given `predicate` "non-identifier Navigable references"? - * - * @see #isNonIdentifierReference - */ - @SuppressWarnings("WeakerAccess") - public static boolean hasNonIdReferences(SqmPredicate predicate) { - if ( predicate instanceof SqmGroupedPredicate ) { - return hasNonIdReferences( ( (SqmGroupedPredicate) predicate ).getSubPredicate() ); - } - - if ( predicate instanceof SqmJunctivePredicate ) { - return hasNonIdReferences( ( (SqmJunctivePredicate) predicate ).getLeftHandPredicate() ) - && hasNonIdReferences( ( (SqmJunctivePredicate) predicate ).getRightHandPredicate() ); - } - - if ( predicate instanceof SqmComparisonPredicate ) { - final SqmExpression lhs = ( (SqmComparisonPredicate) predicate ).getLeftHandExpression(); - final SqmExpression rhs = ( (SqmComparisonPredicate) predicate ).getRightHandExpression(); - - return isNonIdentifierReference( lhs ) || isNonIdentifierReference( rhs ); - } - - if ( predicate instanceof SqmInListPredicate ) { - final SqmInListPredicate inPredicate = (SqmInListPredicate) predicate; - if ( isNonIdentifierReference( inPredicate.getTestExpression() ) ) { - return true; - } - - for ( SqmExpression listExpression : inPredicate.getListExpressions() ) { - if ( isNonIdentifierReference( listExpression ) ) { - return true; - } - } - - return false; - } - - if ( predicate instanceof SqmBetweenPredicate ) { - final SqmBetweenPredicate betweenPredicate = (SqmBetweenPredicate) predicate; - return isNonIdentifierReference( betweenPredicate.getExpression() ) - || isNonIdentifierReference( betweenPredicate.getLowerBound() ) - || isNonIdentifierReference( betweenPredicate.getUpperBound() ); - } - - return false; - } - - /** - * Is the given `expression` a `SqmNavigableReference` that is also a reference - * to a non-`EntityIdentifier` `Navigable`? - * - * @see SqmNavigableReference - * @see EntityIdentifier - */ - @SuppressWarnings("WeakerAccess") - public static boolean isNonIdentifierReference(SqmExpression expression) { - if ( expression instanceof SqmNavigableReference ) { - return ! EntityIdentifier.class.isInstance( expression ); - } - - return false; - } - - /** - * Centralized selection of ids matching the restriction of the DELETE - * or UPDATE SQM query - */ - public static List selectMatchingIds( - DomainParameterXref domainParameterXref, - SqmDeleteOrUpdateStatement sqmDeleteStatement, - ExecutionContext executionContext) { - final SqmQuerySpec sqmIdSelectQuerySpec = SqmIdSelectGenerator.generateSqmEntityIdSelect( - sqmDeleteStatement, - executionContext.getSession().getSessionFactory() - ); - - final SqmSelectToSqlAstConverter sqmConverter = new SqmSelectToSqlAstConverter( - executionContext.getQueryOptions(), - domainParameterXref, - executionContext.getDomainParameterBindingContext().getQueryParameterBindings(), - executionContext.getLoadQueryInfluencers(), - executionContext.getCallback(), - executionContext.getSession().getSessionFactory() - ); - - final SqmSelectStatement sqmIdSelect = new SqmSelectStatement( - executionContext.getSession().getFactory().getQueryEngine().getCriteriaBuilder() - ); - - sqmIdSelect.setQuerySpec( sqmIdSelectQuerySpec ); - - final SqmSelectInterpretation sqmSelectInterpretation = sqmConverter.interpret( sqmIdSelect ); - - final JdbcSelect jdbcSelect = SqlAstSelectToJdbcSelectConverter.interpret( - sqmSelectInterpretation, - executionContext.getSession().getSessionFactory() - ); - - return JdbcSelectExecutorStandardImpl.INSTANCE.list( - jdbcSelect, - QueryHelper.buildJdbcParameterBindings( - domainParameterXref, - SqmConsumeHelper.generateJdbcParamsXref( domainParameterXref, sqmConverter ), - executionContext - ), - executionContext, - row -> row[0] - ); - } -} diff --git a/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/AbstractMutationHandler.java b/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/AbstractMutationHandler.java index afd640ba91..f02ed5af4f 100644 --- a/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/AbstractMutationHandler.java +++ b/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/AbstractMutationHandler.java @@ -6,7 +6,7 @@ */ package org.hibernate.query.sqm.mutation.spi; -import org.hibernate.metamodel.model.mapping.EntityTypeDescriptor; +import org.hibernate.persister.entity.EntityPersister; import org.hibernate.query.sqm.tree.SqmDeleteOrUpdateStatement; /** @@ -27,8 +27,13 @@ public abstract class AbstractMutationHandler implements Handler { return sqmDeleteOrUpdateStatement; } - public EntityTypeDescriptor getEntityDescriptor() { - return sqmDeleteOrUpdateStatement.getTarget().getReferencedPathSource(); + public EntityPersister getEntityDescriptor() { + final String entityName = sqmDeleteOrUpdateStatement.getTarget() + .getReferencedPathSource() + .getHibernateEntityName(); + + return creationContext.getSessionFactory().getMetamodel().getEntityDescriptor( entityName ); + } public HandlerCreationContext getCreationContext() { diff --git a/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/SqmMutationStrategy.java b/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/SqmMutationStrategy.java index da289b687b..444c588b94 100644 --- a/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/SqmMutationStrategy.java +++ b/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/SqmMutationStrategy.java @@ -10,7 +10,6 @@ import org.hibernate.Metamodel; import org.hibernate.boot.spi.SessionFactoryOptions; import org.hibernate.engine.jdbc.connections.spi.JdbcConnectionAccess; import org.hibernate.query.sqm.internal.DomainParameterXref; -import org.hibernate.query.sqm.mutation.internal.SqmMutationStrategyHelper; import org.hibernate.query.sqm.tree.delete.SqmDeleteStatement; import org.hibernate.query.sqm.tree.update.SqmUpdateStatement; diff --git a/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/cte/AbstractCteMutationHandler.java b/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/cte/AbstractCteMutationHandler.java deleted file mode 100644 index 33db147f5f..0000000000 --- a/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/cte/AbstractCteMutationHandler.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Hibernate, Relational Persistence for Idiomatic Java - * - * License: GNU Lesser General Public License (LGPL), version 2.1 or later - * See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html - */ -package org.hibernate.query.sqm.mutation.spi.cte; - -import org.hibernate.query.sqm.internal.DomainParameterXref; -import org.hibernate.query.sqm.mutation.spi.AbstractMutationHandler; -import org.hibernate.query.sqm.mutation.spi.HandlerCreationContext; -import org.hibernate.query.sqm.tree.SqmDeleteOrUpdateStatement; - -/** - * Defines how identifier values are selected from the updatable/deletable tables. - * - * @author Evandro Pires da Silva - * @author Vlad Mihalcea - * @author Steve Ebersole - */ -public abstract class AbstractCteMutationHandler extends AbstractMutationHandler { - private final DomainParameterXref domainParameterXref; - private final CteBasedMutationStrategy strategy; - - public AbstractCteMutationHandler( - SqmDeleteOrUpdateStatement sqmStatement, - DomainParameterXref domainParameterXref, - CteBasedMutationStrategy strategy, - HandlerCreationContext creationContext) { - super( sqmStatement, creationContext ); - this.domainParameterXref = domainParameterXref; - - this.strategy = strategy; - } - - public DomainParameterXref getDomainParameterXref() { - return domainParameterXref; - } - - public CteBasedMutationStrategy getStrategy() { - return strategy; - } -} diff --git a/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/cte/CteBasedMutationStrategy.java b/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/cte/CteBasedMutationStrategy.java deleted file mode 100644 index a7128001d2..0000000000 --- a/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/cte/CteBasedMutationStrategy.java +++ /dev/null @@ -1,165 +0,0 @@ -/* - * Hibernate, Relational Persistence for Idiomatic Java - * - * License: GNU Lesser General Public License (LGPL), version 2.1 or later - * See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html - */ -package org.hibernate.query.sqm.mutation.spi.cte; - -import java.util.Locale; - -import org.hibernate.dialect.Dialect; -import org.hibernate.engine.jdbc.spi.JdbcServices; -import org.hibernate.metamodel.model.mapping.EntityTypeDescriptor; -import org.hibernate.query.sqm.internal.DomainParameterXref; -import org.hibernate.query.sqm.mutation.spi.DeleteHandler; -import org.hibernate.query.sqm.mutation.spi.HandlerCreationContext; -import org.hibernate.query.sqm.mutation.spi.SqmMutationStrategy; -import org.hibernate.query.sqm.mutation.spi.UpdateHandler; -import org.hibernate.query.sqm.tree.SqmDeleteOrUpdateStatement; -import org.hibernate.query.sqm.tree.delete.SqmDeleteStatement; -import org.hibernate.query.sqm.tree.update.SqmUpdateStatement; - -/** - * @asciidoc - * - * {@link SqmMutationStrategy} - * implementation using CTE (SQL's Common Table Expression) approach to perform - * the update/delete. E.g. (using delete): - * - * ```` - * with cte_id (id) as ( - * select - * id - * from ( - * values - * (?), - * (?), - * (?) - * (?) - * ) - * ) - * delete - * from - * Person - * where - * ( id ) in ( - * select id - * from cte_id - * ) - * ```` - * - * todo (6.0) : why not: - * - * ```` - * with cte_id (id) as ( - * select id - * from Person p - * where ... - * ) - * delete from Contact - * where (id) in ( - * select id - * from cte_id - * ) - * - * with cte_id (id) as ( - * select id - * from Person p - * where ... - * ) - * delete from Person - * where (id) in ( - * select id - * from cte_id - * ) - * ```` - * - * @author Evandro Pires da Silva - * @author Vlad Mihalcea - * @author Steve Ebersole - */ -public class CteBasedMutationStrategy implements SqmMutationStrategy { - public static final String ID_CTE = "id_cte"; - - private final EntityTypeDescriptor entityDescriptor; - - private final CteTable cteTable; - - public CteBasedMutationStrategy(EntityTypeDescriptor entityDescriptor) { - this.entityDescriptor = entityDescriptor; - - final Dialect dialect = entityDescriptor.getTypeConfiguration() - .getSessionFactory() - .getServiceRegistry() - .getService( JdbcServices.class ) - .getJdbcEnvironment() - .getDialect(); - - if ( !dialect.supportsNonQueryWithCTE() ) { - throw new UnsupportedOperationException( - getClass().getSimpleName() + - " can only be used with Dialects that support CTE that can take UPDATE or DELETE statements as well" - ); - } - - if ( !dialect.supportsValuesList() ) { - throw new UnsupportedOperationException( - getClass().getSimpleName() + - " can only be used with Dialects that support VALUES lists" - ); - } - - if ( !dialect.supportsRowValueConstructorSyntaxInInList() ) { - throw new UnsupportedOperationException( - getClass().getSimpleName() + - " can only be used with Dialects that support IN clause row-value expressions (for composite identifiers)" - ); - } - - this.cteTable = new CteTable( entityDescriptor ); - } - - public EntityTypeDescriptor getEntityDescriptor() { - return entityDescriptor; - } - - public CteTable getCteTable() { - return cteTable; - } - - @Override - public UpdateHandler buildUpdateHandler( - SqmUpdateStatement sqmStatement, - DomainParameterXref domainParameterXref, - HandlerCreationContext creationContext) { - checkMatch( sqmStatement ); - - return new CteUpdateHandlerImpl( sqmStatement, domainParameterXref, this, creationContext ); - } - - private void checkMatch(SqmDeleteOrUpdateStatement sqmStatement) { - final EntityTypeDescriptor targetEntity = sqmStatement.getTarget().getReferencedPathSource(); - if ( targetEntity != entityDescriptor && ! entityDescriptor.isSubclassTypeName( targetEntity.getEntityName() ) ) { - throw new IllegalArgumentException( - String.format( - Locale.ROOT, - "Target of query [%s] did not match configured entity [%s]", - targetEntity, - entityDescriptor - ) - ); - } - - } - - @Override - public DeleteHandler buildDeleteHandler( - SqmDeleteStatement sqmStatement, - DomainParameterXref domainParameterXref, - HandlerCreationContext creationContext) { - checkMatch( sqmStatement ); - - return new CteDeleteHandlerImpl( sqmStatement, domainParameterXref, this, creationContext ); - } -} diff --git a/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/cte/CteDeleteHandlerImpl.java b/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/cte/CteDeleteHandlerImpl.java deleted file mode 100644 index abc3b6527c..0000000000 --- a/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/cte/CteDeleteHandlerImpl.java +++ /dev/null @@ -1,193 +0,0 @@ -/* - * Hibernate, Relational Persistence for Idiomatic Java - * - * License: GNU Lesser General Public License (LGPL), version 2.1 or later - * See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html - */ -package org.hibernate.query.sqm.mutation.spi.cte; - -import java.util.ArrayList; -import java.util.List; - -import org.hibernate.metamodel.model.mapping.PersistentCollectionDescriptor; -import org.hibernate.metamodel.model.mapping.spi.PluralPersistentAttribute; -import org.hibernate.metamodel.model.relational.spi.Column; -import org.hibernate.metamodel.model.relational.spi.Table; -import org.hibernate.query.sqm.internal.DomainParameterXref; -import org.hibernate.query.sqm.mutation.internal.SqmMutationStrategyHelper; -import org.hibernate.query.sqm.mutation.spi.DeleteHandler; -import org.hibernate.query.sqm.mutation.spi.HandlerCreationContext; -import org.hibernate.query.sqm.tree.delete.SqmDeleteStatement; -import org.hibernate.sql.ast.consume.spi.SqlDeleteToJdbcDeleteConverter; -import org.hibernate.sql.ast.tree.CteStatement; -import org.hibernate.sql.ast.tree.delete.DeleteStatement; -import org.hibernate.sql.ast.tree.expression.Expression; -import org.hibernate.sql.ast.tree.expression.SqlTuple; -import org.hibernate.sql.ast.tree.from.TableReference; -import org.hibernate.sql.ast.tree.predicate.InSubQueryPredicate; -import org.hibernate.sql.ast.tree.select.QuerySpec; -import org.hibernate.sql.exec.internal.JdbcParameterBindingsImpl; -import org.hibernate.sql.exec.spi.ExecutionContext; -import org.hibernate.sql.exec.spi.JdbcDelete; -import org.hibernate.sql.exec.spi.JdbcMutationExecutor; -import org.hibernate.sql.exec.spi.JdbcParameterBindings; - -/** - * Bulk-id delete handler that uses CTE and VALUES lists. - * - * @author Evandro Pires da Silva - * @author Vlad Mihalcea - * @author Steve Ebersole - */ -@SuppressWarnings("WeakerAccess") -public class CteDeleteHandlerImpl extends AbstractCteMutationHandler implements DeleteHandler { - protected CteDeleteHandlerImpl( - SqmDeleteStatement sqmDeleteStatement, - DomainParameterXref domainParameterXref, - CteBasedMutationStrategy strategy, - HandlerCreationContext creationContext) { - super( sqmDeleteStatement, domainParameterXref, strategy, creationContext ); - } - - @Override - public SqmDeleteStatement getSqmDeleteOrUpdateStatement() { - return (SqmDeleteStatement) super.getSqmDeleteOrUpdateStatement(); - } - - @Override - public int execute(ExecutionContext executionContext) { - final List ids = selectMatchingIds( executionContext ); - - final QuerySpec cteQuerySpec = getStrategy().getCteTable().createCteSubQuery( executionContext ); - - final JdbcParameterBindings jdbcParameterBindings = new JdbcParameterBindingsImpl(); - final QuerySpec cteDefinitionQuerySpec = getStrategy().getCteTable().createCteDefinition( - ids, - jdbcParameterBindings, - executionContext - ); - - // for every table to be deleted, create the CteStatement and execute it - - - getEntityDescriptor().visitAttributes( - attribute -> { - final PluralPersistentAttribute pluralAttribute = (PluralPersistentAttribute) attribute; - final PersistentCollectionDescriptor collectionDescriptor = pluralAttribute.getCollectionDescriptor(); - - if ( collectionDescriptor.getSeparateCollectionTable() != null ) { - // this collection has a separate collection table, meaning it is one of: - // 1) element-collection - // 2) many-to-many - // 3) one-to many using a dedicated join-table - // - // in all of these cases, we should clean up the matching rows in the - // collection table - - executeDelete( - cteDefinitionQuerySpec, - collectionDescriptor.getSeparateCollectionTable(), - collectionDescriptor.getCollectionKeyDescriptor().getJoinForeignKey().getColumnMappings().getReferringColumns(), - cteQuerySpec, - jdbcParameterBindings, - executionContext - ); - } - }, - attribute -> attribute instanceof PluralPersistentAttribute - ); - - getEntityDescriptor().getHierarchy().visitConstraintOrderedTables( - (table,columns) -> executeDelete( - cteDefinitionQuerySpec, - table, - columns, - cteQuerySpec, - jdbcParameterBindings, - executionContext - ) - ); - - return ids.size(); - } - - private List selectMatchingIds(ExecutionContext executionContext) { - return SqmMutationStrategyHelper.selectMatchingIds( - getDomainParameterXref(), - getSqmDeleteOrUpdateStatement(), - executionContext - ); - } - - protected void executeDelete( - QuerySpec cteDefinition, - Table targetTable, - List columnsToMatch, - QuerySpec cteSubQuery, - JdbcParameterBindings jdbcParameterBindings, - ExecutionContext executionContext) { - final CteStatement cteStatement = generateCteStatement( - cteDefinition, - targetTable, - columnsToMatch, - cteSubQuery, - executionContext - ); - final JdbcDelete jdbcDelete = SqlDeleteToJdbcDeleteConverter.interpret( - cteStatement, - executionContext.getSession().getSessionFactory() - ); - - final JdbcMutationExecutor executor = JdbcMutationExecutor.WITH_AFTER_STATEMENT_CALL; - executor.execute( - jdbcDelete, - jdbcParameterBindings, - executionContext, - (rows, preparedStatement) -> {} - ); - } - - protected CteStatement generateCteStatement( - QuerySpec cteDefinition, - Table targetTable, - List columnsToMatch, - QuerySpec cteSubQuery, - @SuppressWarnings("unused") ExecutionContext executionContext) { - return new CteStatement( - cteDefinition, - CteBasedMutationStrategy.ID_CTE, - getStrategy().getCteTable(), - generateCteConsumer( targetTable, columnsToMatch, cteSubQuery ) - ); - } - - private DeleteStatement generateCteConsumer(Table targetTable, List columnsToMatch, QuerySpec cteSubQuery) { - final TableReference targetTableReference = new TableReference( - targetTable, - null, - false - ); - - final Expression columnsToMatchExpression; - - if ( columnsToMatch.size() == 1 ) { - columnsToMatchExpression = targetTableReference.resolveColumnReference( columnsToMatch.get( 0 ) ); - } - else { - final List columnsToMatchExpressions = new ArrayList<>(); - for ( Column toMatch : columnsToMatch ) { - columnsToMatchExpressions.add( targetTableReference.resolveColumnReference( toMatch ) ); - } - columnsToMatchExpression = new SqlTuple( columnsToMatchExpressions, getEntityDescriptor().getIdType() ); - } - - return new DeleteStatement( - targetTableReference, - new InSubQueryPredicate( - columnsToMatchExpression, - cteSubQuery, - false - ) - ); - } -} diff --git a/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/cte/CteTable.java b/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/cte/CteTable.java deleted file mode 100644 index af59a9928e..0000000000 --- a/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/cte/CteTable.java +++ /dev/null @@ -1,201 +0,0 @@ -/* - * Hibernate, Relational Persistence for Idiomatic Java - * - * License: GNU Lesser General Public License (LGPL), version 2.1 or later - * See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html - */ -package org.hibernate.query.sqm.mutation.spi.cte; - -import java.util.Collections; -import java.util.List; -import java.util.UUID; - -import org.hibernate.LockMode; -import org.hibernate.dialect.Dialect; -import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment; -import org.hibernate.internal.util.StringHelper; -import org.hibernate.metamodel.model.mapping.EntityTypeDescriptor; -import org.hibernate.metamodel.model.mapping.spi.Writeable; -import org.hibernate.metamodel.model.relational.spi.AbstractTable; -import org.hibernate.metamodel.model.relational.spi.Column; -import org.hibernate.metamodel.model.relational.spi.DerivedTable; -import org.hibernate.metamodel.model.relational.spi.PhysicalColumn; -import org.hibernate.query.NavigablePath; -import org.hibernate.sql.SqlExpressableType; -import org.hibernate.sql.ast.Clause; -import org.hibernate.sql.ast.tree.from.StandardTableGroup; -import org.hibernate.sql.ast.tree.from.TableReference; -import org.hibernate.sql.ast.tree.select.QuerySpec; -import org.hibernate.sql.exec.internal.StandardJdbcParameterImpl; -import org.hibernate.sql.exec.spi.ExecutionContext; -import org.hibernate.sql.exec.spi.JdbcParameterBinding; -import org.hibernate.sql.exec.spi.JdbcParameterBindings; -import org.hibernate.sql.results.internal.SqlSelectionImpl; - -/** - * Adaption of the CTE expression as a {@link org.hibernate.metamodel.model.relational.spi.Table} - * to be used in SQL AST - * - * @author Steve Ebersole - */ -public class CteTable extends AbstractTable { - private final EntityTypeDescriptor entityDescriptor; - - public CteTable(EntityTypeDescriptor entityDescriptor) { - super( UUID.randomUUID(), false ); - this.entityDescriptor = entityDescriptor; - - for ( Column column : (List) entityDescriptor.getIdentifierDescriptor().getColumns() ) { - final CteTableColumn cteTableColumn = new CteTableColumn( - this, - (PhysicalColumn) column, - entityDescriptor.getTypeConfiguration() - ); - - addColumn( cteTableColumn ); - } - } - - @Override - public String getTableExpression() { - return CteBasedMutationStrategy.ID_CTE; - } - - @Override - public String render(Dialect dialect, JdbcEnvironment jdbcEnvironment) { - return getTableExpression(); - } - - @Override - public boolean isExportable() { - return false; - } - - @Override - public String toLoggableFragment() { - return getTableExpression(); - } - - public QuerySpec createCteDefinition( - List matchingIds, - JdbcParameterBindings jdbcParameterBindings, - ExecutionContext executionContext) { - final QuerySpec querySpec = new QuerySpec( false ); - - final TableReference tableValueConstructorReference = createCteDefinitionTableValueCtor( - matchingIds, - jdbcParameterBindings, - executionContext - ); - final StandardTableGroup tableValueCtorGroup = new StandardTableGroup( - new NavigablePath( entityDescriptor.getIdentifierDescriptor().getNavigableRole().getFullPath() ), - entityDescriptor.getIdentifierDescriptor(), - LockMode.NONE, - tableValueConstructorReference, - Collections.emptyList() - ); - querySpec.getFromClause().addRoot( tableValueCtorGroup ); - - applySelections( querySpec, tableValueConstructorReference ); - - return querySpec; - } - - private TableReference createCteDefinitionTableValueCtor( - List matchingIds, - JdbcParameterBindings jdbcParameterBindings, - ExecutionContext executionContext) { - // use `DerivedTable` as the TableValueConstructor - // so its `#expression` would be something like `values ( (a1, b1), (a2, b2), ... )` - - final int numberOfColumns = getColumns().size(); - - final StringBuilder tableValueCtorExpressionBuffer = new StringBuilder( "values(" ); - String rowSeparator = ""; - int idProcessedCount = 0; - for ( Object matchingId : matchingIds ) { - tableValueCtorExpressionBuffer.append( rowSeparator ); - - tableValueCtorExpressionBuffer.append( '(' ); - StringHelper.repeat( "?", numberOfColumns, ",", tableValueCtorExpressionBuffer ); - tableValueCtorExpressionBuffer.append( ')' ); - - final int currentIdPosition = idProcessedCount; - - entityDescriptor.getIdentifierDescriptor().dehydrate( - matchingId, - new Writeable.JdbcValueCollector() { - int currentColumnPosition = 0; - - @Override - public void collect( - Object jdbcValue, - SqlExpressableType type, - Column boundColumn) { - jdbcParameterBindings.addBinding( - new StandardJdbcParameterImpl( - currentIdPosition + currentColumnPosition++, - type, - // it is effectively the where-clause - Clause.WHERE, - executionContext.getSession().getFactory().getTypeConfiguration() - ), - new JdbcParameterBinding() { - @Override - public SqlExpressableType getBindType() { - return type; - } - - @Override - public Object getBindValue() { - return jdbcValue; - } - } - ); - } - }, - Clause.WHERE, - executionContext.getSession() - ); - - - rowSeparator = ", "; - idProcessedCount++; - } - tableValueCtorExpressionBuffer.append( ')' ); - - final DerivedTable derivedTable = new DerivedTable( null, tableValueCtorExpressionBuffer.toString(), true ); - - return new TableReference( - derivedTable, - CteBasedMutationStrategy.ID_CTE, - false - ); - } - - public QuerySpec createCteSubQuery(ExecutionContext executionContext) { - final QuerySpec querySpec = new QuerySpec( false ); - - final CteTableReference cteTableReference = new CteTableReference( this, executionContext ); - final CteTableGroup cteTableGroup = new CteTableGroup( entityDescriptor, cteTableReference ); - querySpec.getFromClause().addRoot( cteTableGroup ); - - applySelections( querySpec, cteTableReference ); - - return querySpec; - } - - private void applySelections(QuerySpec querySpec, TableReference tableReference) { - int i = 0; - for ( Column column : getColumns() ) { - querySpec.getSelectClause().addSqlSelection( - new SqlSelectionImpl( - i + 1, - i, - tableReference.resolveColumnReference( column ), - column.getExpressableType() - ) - ); - } - } -} diff --git a/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/cte/CteTableColumn.java b/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/cte/CteTableColumn.java deleted file mode 100644 index ae6357a370..0000000000 --- a/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/cte/CteTableColumn.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Hibernate, Relational Persistence for Idiomatic Java - * - * License: GNU Lesser General Public License (LGPL), version 2.1 or later - * See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html - */ -package org.hibernate.query.sqm.mutation.spi.cte; - -import org.hibernate.metamodel.model.relational.spi.PhysicalColumn; -import org.hibernate.naming.Identifier; -import org.hibernate.type.spi.TypeConfiguration; - -/** - * Adapts a CTE "column name" to the {@link org.hibernate.metamodel.model.relational.spi.Column} - * hierarchy for use inSQL AST - * - * @author Steve Ebersole - */ -@SuppressWarnings("WeakerAccess") -public class CteTableColumn extends PhysicalColumn { - public CteTableColumn( - CteTable table, - PhysicalColumn sourceColumn, - TypeConfiguration typeConfiguration) { - super( - table, - Identifier.toIdentifier( "cte_" + sourceColumn.getName().render() ), - () -> sourceColumn.getExpressableType().getSqlTypeDescriptor(), - () -> sourceColumn.getExpressableType().getJavaTypeDescriptor(), - null, - null, - false, - true, - typeConfiguration - ); - } -} diff --git a/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/cte/CteTableGroup.java b/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/cte/CteTableGroup.java deleted file mode 100644 index f2d38de27b..0000000000 --- a/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/cte/CteTableGroup.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Hibernate, Relational Persistence for Idiomatic Java - * - * License: GNU Lesser General Public License (LGPL), version 2.1 or later - * See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html - */ -package org.hibernate.query.sqm.mutation.spi.cte; - -import java.util.Collections; -import java.util.List; -import java.util.function.Consumer; - -import org.hibernate.LockMode; -import org.hibernate.metamodel.model.mapping.EntityTypeDescriptor; -import org.hibernate.metamodel.model.relational.spi.Column; -import org.hibernate.query.NavigablePath; -import org.hibernate.sql.ast.consume.spi.SqlAppender; -import org.hibernate.sql.ast.spi.SqlAstWalker; -import org.hibernate.sql.ast.tree.from.AbstractTableGroup; -import org.hibernate.sql.ast.tree.from.TableReferenceJoin; - -/** - * Wraps a {@link CteTableReference} and adapts it to - * {@link org.hibernate.sql.ast.tree.from.TableGroup} for use in SQL AST - * - * @author Steve Ebersole - */ -@SuppressWarnings("WeakerAccess") -public class CteTableGroup extends AbstractTableGroup { - private final CteTableReference cteTableReference; - - public CteTableGroup(EntityTypeDescriptor entityDescriptor, CteTableReference cteTableReference) { - super( - new NavigablePath( entityDescriptor.getEntityName() ), - entityDescriptor, - LockMode.NONE - ); - this.cteTableReference = cteTableReference; - } - - @Override - public void render(SqlAppender sqlAppender, SqlAstWalker walker) { - sqlAppender.appendSql( cteTableReference.getTable().getTableExpression() ); - } - - @Override - public void applyAffectedTableNames(Consumer nameCollector) { - nameCollector.accept( cteTableReference.getTable().getTableExpression() ); - } - - @Override - public CteTableReference getPrimaryTableReference() { - return cteTableReference; - } - - @Override - public List getTableReferenceJoins() { - return Collections.emptyList(); - } - - @Override - public Column resolveColumn(String columnName) { - return cteTableReference.resolveColumn( columnName ); - } -} diff --git a/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/cte/CteTableReference.java b/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/cte/CteTableReference.java deleted file mode 100644 index 5d3a02b40c..0000000000 --- a/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/cte/CteTableReference.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Hibernate, Relational Persistence for Idiomatic Java - * - * License: GNU Lesser General Public License (LGPL), version 2.1 or later - * See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html - */ -package org.hibernate.query.sqm.mutation.spi.cte; - -import org.hibernate.sql.ast.tree.from.TableReference; -import org.hibernate.sql.exec.spi.ExecutionContext; - -/** - * @author Steve Ebersole - */ -@SuppressWarnings("WeakerAccess") -public class CteTableReference extends TableReference { - public CteTableReference( - CteTable cteTable, @SuppressWarnings("unused") ExecutionContext executionContext) { - super( - cteTable, - null, - false - ); - } - - @Override - public CteTable getTable() { - return (CteTable) super.getTable(); - } -} diff --git a/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/cte/CteUpdateHandlerImpl.java b/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/cte/CteUpdateHandlerImpl.java deleted file mode 100644 index c40750a608..0000000000 --- a/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/cte/CteUpdateHandlerImpl.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Hibernate, Relational Persistence for Idiomatic Java - * - * License: GNU Lesser General Public License (LGPL), version 2.1 or later - * See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html - */ -package org.hibernate.query.sqm.mutation.spi.cte; - -import org.hibernate.NotYetImplementedFor6Exception; -import org.hibernate.query.sqm.internal.DomainParameterXref; -import org.hibernate.query.sqm.mutation.spi.HandlerCreationContext; -import org.hibernate.query.sqm.mutation.spi.UpdateHandler; -import org.hibernate.query.sqm.tree.update.SqmUpdateStatement; -import org.hibernate.sql.exec.spi.ExecutionContext; - -/** - * - * @author Evandro Pires da Silva - * @author Vlad Mihalcea - * @author Steve Ebersole - */ -public class CteUpdateHandlerImpl - extends AbstractCteMutationHandler - implements UpdateHandler { - - public CteUpdateHandlerImpl( - SqmUpdateStatement sqmStatement, - DomainParameterXref domainParameterXref, - CteBasedMutationStrategy strategy, - HandlerCreationContext creationContext) { - super( sqmStatement, domainParameterXref, strategy, creationContext ); - } - - @Override - public int execute(ExecutionContext executionContext) { - throw new NotYetImplementedFor6Exception(); - } -} diff --git a/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/cte/package-info.java b/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/cte/package-info.java deleted file mode 100644 index 58780327d0..0000000000 --- a/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/cte/package-info.java +++ /dev/null @@ -1,13 +0,0 @@ -/* - * Hibernate, Relational Persistence for Idiomatic Java - * - * License: GNU Lesser General Public License (LGPL), version 2.1 or later - * See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html - */ - -/** - * Support for {@link org.hibernate.query.sqm.mutation.spi.SqmMutationStrategy} - * implementations that use CTE (SQL's Common Table Expression) approach to perform - * the update/delete - */ -package org.hibernate.query.sqm.mutation.spi.cte; diff --git a/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/idtable/AbstractTableBasedHandler.java b/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/idtable/AbstractTableBasedHandler.java deleted file mode 100644 index 78771f950e..0000000000 --- a/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/idtable/AbstractTableBasedHandler.java +++ /dev/null @@ -1,291 +0,0 @@ -/* - * Hibernate, Relational Persistence for Idiomatic Java - * - * License: GNU Lesser General Public License (LGPL), version 2.1 or later - * See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html - */ -package org.hibernate.query.sqm.mutation.spi.idtable; - -import org.hibernate.query.internal.QueryHelper; -import org.hibernate.query.spi.ComparisonOperator; -import org.hibernate.query.sqm.internal.DomainParameterXref; -import org.hibernate.query.sqm.mutation.internal.SqmIdSelectGenerator; -import org.hibernate.query.sqm.mutation.spi.AbstractMutationHandler; -import org.hibernate.query.sqm.mutation.spi.Handler; -import org.hibernate.query.sqm.mutation.spi.HandlerCreationContext; -import org.hibernate.query.sqm.produce.internal.SqmTreePrinter; -import org.hibernate.query.sqm.tree.SqmDeleteOrUpdateStatement; -import org.hibernate.query.sqm.tree.expression.SqmLiteral; -import org.hibernate.query.sqm.tree.select.SqmQuerySpec; -import org.hibernate.query.sqm.tree.select.SqmSelectStatement; -import org.hibernate.query.sqm.tree.select.SqmSelection; -import org.hibernate.sql.ast.Clause; -import org.hibernate.sql.ast.consume.spi.SqlInsertSelectToJdbcInsertSelectConverter; -import org.hibernate.sql.ast.produce.sqm.spi.SqmSelectInterpretation; -import org.hibernate.sql.ast.produce.sqm.spi.SqmSelectToSqlAstConverter; -import org.hibernate.sql.ast.tree.expression.LiteralParameter; -import org.hibernate.sql.ast.tree.insert.InsertSelectStatement; -import org.hibernate.sql.ast.tree.predicate.ComparisonPredicate; -import org.hibernate.sql.ast.tree.select.QuerySpec; -import org.hibernate.sql.exec.spi.ExecutionContext; -import org.hibernate.sql.exec.spi.JdbcInsertSelect; -import org.hibernate.sql.exec.spi.JdbcMutationExecutor; -import org.hibernate.sql.exec.spi.JdbcParameterBindings; -import org.hibernate.sql.results.internal.SqlSelectionImpl; -import org.hibernate.type.spi.StandardSpiBasicTypes; - -import org.jboss.logging.Logger; - -/** - * Support for {@link Handler} implementations - * - * @author Steve Ebersole - */ -public abstract class AbstractTableBasedHandler extends AbstractMutationHandler { - private static final Logger log = Logger.getLogger( AbstractTableBasedHandler.class ); - - private final IdTable idTableInfo; - private final SessionUidSupport sessionUidSupport; - private final BeforeUseAction beforeUseAction; - private final AfterUseAction afterUseAction; - private final IdTableHelper tableHelper; - private final DomainParameterXref domainParameterXref; - - - public AbstractTableBasedHandler( - SqmDeleteOrUpdateStatement sqmDeleteOrUpdateStatement, - IdTable idTableInfo, - SessionUidSupport sessionUidSupport, - BeforeUseAction beforeUseAction, - AfterUseAction afterUseAction, - IdTableHelper idTableHelper, - DomainParameterXref domainParameterXref, - HandlerCreationContext creationContext) { - super( sqmDeleteOrUpdateStatement, creationContext ); - this.idTableInfo = idTableInfo; - this.sessionUidSupport = sessionUidSupport; - this.beforeUseAction = beforeUseAction; - this.afterUseAction = afterUseAction; - - this.tableHelper = idTableHelper; - this.domainParameterXref = domainParameterXref; - } - - public IdTable getIdTableInfo() { - return idTableInfo; - } - - public DomainParameterXref getDomainParameterXref() { - return domainParameterXref; - } - - public SessionUidSupport getSessionUidSupport() { - return sessionUidSupport; - } - - @Override - public int execute(ExecutionContext executionContext) { - - // In general: - // 1) prepare for use - this is completely a subclass hook - // 2) perform execution - // 3) release after use - again, completely a subclass hook - - beforeExecution( executionContext ); - - try { - return performExecution( executionContext ); - } - finally { - afterExecution( executionContext ); - } - } - - /** - * Allow subclasses a chance to perform any preliminary work they need - * to perform prior to execution - * @param executionContext - */ - protected void beforeExecution(ExecutionContext executionContext) { - } - - /** - * Allow subclasses a chance to perform any clean-up work they need - * to perform after execution - * @param executionContext - */ - protected void afterExecution(ExecutionContext executionContext) { - } - - protected int performExecution(ExecutionContext executionContext) { - performBeforeUseActions( executionContext ); - - try { - // 1) save the matching ids into the id table - final int affectedRowCount = saveMatchingIdsIntoIdTable( executionContext ); - - // 2) perform the actual individual update or deletes, using - // inclusion in the id-table as restriction - performMutations( executionContext ); - - return affectedRowCount; - } - finally { - performAfterUseActions( executionContext ); - } - } - - private void performBeforeUseActions(ExecutionContext executionContext) { - if ( beforeUseAction == BeforeUseAction.CREATE ) { - tableHelper.createIdTable( executionContext.getSession() ); - } - } - - private void performAfterUseActions(ExecutionContext executionContext) { - if ( afterUseAction == AfterUseAction.DROP ) { - tableHelper.dropIdTable( executionContext.getSession() ); - } - else if ( afterUseAction == AfterUseAction.CLEAN ) { - tableHelper.cleanIdTableRows( executionContext.getSession() ); - } - } - - protected int saveMatchingIdsIntoIdTable(ExecutionContext executionContext) { - final SqmQuerySpec sqmIdSelectQuerySpec = SqmIdSelectGenerator.generateSqmEntityIdSelect( - getSqmDeleteOrUpdateStatement(), - executionContext.getSession().getSessionFactory() - ); - - if ( sessionUidSupport.needsSessionUidColumn() ) { - // we need to insert the uid into the id-table to properly identify the rows later - sqmIdSelectQuerySpec.getSelectClause().addSelection( - new SqmSelection( - generateSessionUidLiteralExpression( executionContext ), - executionContext.getSession().getFactory().getNodeBuilder() - ) - ); - } - - final SqmSelectStatement sqmIdSelect = new SqmSelectStatement( - executionContext.getSession().getFactory().getNodeBuilder() - ); - - sqmIdSelect.setQuerySpec( sqmIdSelectQuerySpec ); - - SqmTreePrinter.logTree( sqmIdSelect ); - - final SqmSelectToSqlAstConverter sqmConverter = new SqmSelectToSqlAstConverter( - executionContext.getQueryOptions(), - domainParameterXref, - executionContext.getDomainParameterBindingContext().getQueryParameterBindings(), - executionContext.getLoadQueryInfluencers(), - afterLoadAction -> {}, - executionContext.getSession().getSessionFactory() - ); - - final SqmSelectInterpretation sqlAstInterpretation = sqmConverter.interpret( sqmIdSelect ); - - final QuerySpec entityIdSelect = sqlAstInterpretation.getSqlAstStatement().getQuerySpec(); - - final InsertSelectStatement idTableInsertSelect = generateIdTableInsertSelect( - idTableInfo, - entityIdSelect - ); - - final JdbcInsertSelect insertSelectCall = SqlInsertSelectToJdbcInsertSelectConverter.interpret( - idTableInsertSelect, - executionContext.getSession().getSessionFactory() - ); - - final JdbcParameterBindings jdbcParameterBindings = QueryHelper.buildJdbcParameterBindings( - sqmIdSelect, sqlAstInterpretation, executionContext - ); - - return JdbcMutationExecutor.NO_AFTER_STATEMENT_CALL.execute( - insertSelectCall, - jdbcParameterBindings, - executionContext - ); - } - - private SqmLiteral generateSessionUidLiteralExpression(ExecutionContext executionContext) { - return new SqmLiteral<>( - sessionUidSupport.extractUid( executionContext.getSession() ), - StandardSpiBasicTypes.STRING, - executionContext.getSession().getFactory().getNodeBuilder() - ); - } - - public QuerySpec createIdTableSubQuery(ExecutionContext executionContext) { - final QuerySpec querySpec = new QuerySpec( false ); - - final IdTableReference idTableReference = new IdTableReference( getIdTableInfo() ); - final IdTableGroup cteTableGroup = new IdTableGroup( getIdTableInfo().getEntityDescriptor(), idTableReference ); - querySpec.getFromClause().addRoot( cteTableGroup ); - - applySelections( querySpec, idTableReference, executionContext ); - applyRestrictions( querySpec, idTableReference, executionContext ); - - return querySpec; - } - - private void applySelections( - QuerySpec querySpec, - IdTableReference tableReference, - ExecutionContext executionContext) { - int i = 0; - for ( IdTableColumn column : tableReference.getTable().getIdTableColumns() ) { - if ( column != tableReference.getTable().getSessionUidColumn() ) { - querySpec.getSelectClause().addSqlSelection( - new SqlSelectionImpl( - i + 1, - i, - tableReference.resolveColumnReference( column ), - column.getSqlTypeDescriptor().getSqlExpressableType( - column.getJavaTypeDescriptor(), - executionContext.getSession().getFactory().getTypeConfiguration() - ) - ) - ); - } - } - - return ; - } - - private void applyRestrictions( - QuerySpec querySpec, - IdTableReference idTableReference, - ExecutionContext executionContext) { - if ( sessionUidSupport.needsSessionUidColumn() ) { - querySpec.addRestriction( - new ComparisonPredicate( - idTableReference.resolveColumnReference( idTableReference.getTable().getSessionUidColumn() ), - ComparisonOperator.EQUAL, - new LiteralParameter( - sessionUidSupport.extractUid( executionContext.getSession() ), - StandardSpiBasicTypes.STRING.getSqlExpressableType(), - Clause.WHERE, - executionContext.getSession().getFactory().getTypeConfiguration() - ) - ) - ); - - } - } - - private InsertSelectStatement generateIdTableInsertSelect( - IdTable idTableInfo, - QuerySpec entityIdSelect) { - final InsertSelectStatement insertSelect = new InsertSelectStatement(); - insertSelect.setTargetTable( new IdTableReference( idTableInfo ) ); - insertSelect.setSourceSelectStatement( entityIdSelect ); - - // target columns should already be aligned, there should be no need to define them explicitly - // via InsertSelectStatement#addTargetColumnReferences - - return insertSelect; - } - - protected abstract void performMutations(ExecutionContext executionContext); -} diff --git a/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/idtable/AbstractTableBasedMutationStrategy.java b/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/idtable/AbstractTableBasedMutationStrategy.java deleted file mode 100644 index 31d6e46828..0000000000 --- a/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/idtable/AbstractTableBasedMutationStrategy.java +++ /dev/null @@ -1,276 +0,0 @@ -/* - * Hibernate, Relational Persistence for Idiomatic Java - * - * License: GNU Lesser General Public License (LGPL), version 2.1 or later - * See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html - */ -package org.hibernate.query.sqm.mutation.spi.idtable; - -import java.util.HashMap; -import java.util.Locale; -import java.util.Map; - -import org.hibernate.Metamodel; -import org.hibernate.boot.spi.SessionFactoryOptions; -import org.hibernate.engine.jdbc.connections.spi.JdbcConnectionAccess; -import org.hibernate.metamodel.model.mapping.EntityTypeDescriptor; -import org.hibernate.metamodel.model.relational.spi.PhysicalTable; -import org.hibernate.naming.Identifier; -import org.hibernate.naming.QualifiedTableName; -import org.hibernate.query.sqm.internal.DomainParameterXref; -import org.hibernate.query.sqm.mutation.internal.SqmMutationStrategyHelper; -import org.hibernate.query.sqm.mutation.spi.DeleteHandler; -import org.hibernate.query.sqm.mutation.spi.HandlerCreationContext; -import org.hibernate.query.sqm.mutation.spi.SqmMutationStrategy; -import org.hibernate.query.sqm.mutation.spi.UpdateHandler; -import org.hibernate.query.sqm.tree.delete.SqmDeleteStatement; -import org.hibernate.query.sqm.tree.update.SqmUpdateStatement; - -/** - * @author Steve Ebersole - */ -public abstract class AbstractTableBasedMutationStrategy implements SqmMutationStrategy { - private final Map idTableInfoMap = new HashMap<>(); - - protected abstract IdTableSupport getIdTableSupport(); - - @Override - public void prepare( - Metamodel runtimeMetadata, - SessionFactoryOptions sessionFactoryOptions, - JdbcConnectionAccess connectionAccess) { - runtimeMetadata.visitEntityDescriptors( - entityDescriptor -> generateIdTableDefinition( - entityDescriptor, - sessionFactoryOptions, - connectionAccess - ) - ); - } - - protected IdTable getIdTableInfo(EntityTypeDescriptor entityDescriptor) { - return idTableInfoMap.get( entityDescriptor ); - } - - protected IdTable generateIdTableDefinition( - EntityTypeDescriptor entityDescriptor, - SessionFactoryOptions sessionFactoryOptions, - JdbcConnectionAccess connectionAccess) { - final IdTable idTable = new IdTable( - entityDescriptor, - determineIdTableName( entityDescriptor, sessionFactoryOptions ) - ); - - entityDescriptor.getPrimaryTable().getPrimaryKey().getColumns().forEach( - column -> idTable.addColumn( new IdTableColumn( idTable, column ) ) - ); - - if ( getSessionUidSupport() != null && getSessionUidSupport().needsSessionUidColumn() ) { - getSessionUidSupport().addColumn( idTable ); - } - - idTableInfoMap.put( entityDescriptor, idTable ); - - return idTable; - } - - protected QualifiedTableName determineIdTableName( - EntityTypeDescriptor entityDescriptor, - SessionFactoryOptions sessionFactoryOptions) { - - final Identifier entityTableCatalog = entityDescriptor.getPrimaryTable() instanceof PhysicalTable - ? ( (PhysicalTable) entityDescriptor.getPrimaryTable() ).getCatalogName() - : null; - final Identifier entityTableSchema = entityDescriptor.getPrimaryTable() instanceof PhysicalTable - ? ( (PhysicalTable) entityDescriptor.getPrimaryTable() ).getSchemaName() - : null; - - final Identifier catalogToUse; - final Identifier schemaToUse; - - switch ( getNamespaceHandling() ) { - case USE_NONE: { - catalogToUse = null; - schemaToUse = null; - break; - } - case USE_ENTITY_TABLE_NAMESPACE: { - catalogToUse = entityTableCatalog; - schemaToUse = entityTableSchema; - break; - } - case PREFER_SETTINGS: { - final Identifier configuredCatalog = getConfiguredCatalog(); - final Identifier configuredSchema = getConfiguredSchema(); - - // todo (6.0) : if no setting use default (null) or entity namespace? - - catalogToUse = configuredCatalog == null ? entityTableCatalog : configuredCatalog; - schemaToUse = configuredSchema == null ? entityTableSchema : configuredSchema; - break; - } - default: { - throw new IllegalArgumentException( - String.format( - Locale.ROOT, - "Unknown NamespaceHandling value [%s] - expecting %s, %s or %s", - getNamespaceHandling().name(), - NamespaceHandling.USE_NONE.name(), - NamespaceHandling.USE_ENTITY_TABLE_NAMESPACE.name(), - NamespaceHandling.PREFER_SETTINGS.name() - ) - ); - } - } - - return new QualifiedTableName( - catalogToUse, - schemaToUse, - getIdTableSupport().determineIdTableName( - entityDescriptor, - sessionFactoryOptions - ) - ); - - } - - protected Identifier getConfiguredCatalog() { - // by default, none - return null; - } - - protected Identifier getConfiguredSchema() { - // by default, none - return null; - } - - protected NamespaceHandling getNamespaceHandling() { - // by default use the entity table's namespace - return NamespaceHandling.USE_ENTITY_TABLE_NAMESPACE; - } - - public enum NamespaceHandling { - USE_NONE, - USE_ENTITY_TABLE_NAMESPACE, - PREFER_SETTINGS - } - - protected SessionUidSupport getSessionUidSupport() { - // by default none - return null; - } - - public BeforeUseAction getBeforeUseAction() { - // by default none - return null; - } - - public AfterUseAction getAfterUseAction() { - // by default none - return null; - } - - public IdTableManagementTransactionality getTableManagementTransactionality() { - // by default none - return null; - } - - @Override - public void release(Metamodel runtimeMetadata, JdbcConnectionAccess connectionAccess) { - idTableInfoMap.clear(); - } - - @Override - public UpdateHandler buildUpdateHandler( - SqmUpdateStatement sqmUpdateStatement, - DomainParameterXref domainParameterXref, - HandlerCreationContext creationContext) { - return SqmMutationStrategyHelper.resolveUpdateHandler( - sqmUpdateStatement, - domainParameterXref, - creationContext, - this::buildFallbackUpdateHandler - ); - } - - private UpdateHandler buildFallbackUpdateHandler( - SqmUpdateStatement sqmUpdateStatement, - DomainParameterXref domainParameterXref, - HandlerCreationContext creationContext) { - final EntityTypeDescriptor entityDescriptor = sqmUpdateStatement.getTarget() - .getReferencedPathSource() - .getEntityDescriptor(); - - final TableBasedUpdateHandlerImpl.Builder builder = new TableBasedUpdateHandlerImpl.Builder( - sqmUpdateStatement, - idTableInfoMap.get( entityDescriptor ), - getIdTableSupport() - ); - - if ( getBeforeUseAction() != null ) { - builder.setBeforeUseAction( getBeforeUseAction() ); - } - - if ( getAfterUseAction() != null ) { - builder.setAfterUseAction( getAfterUseAction() ); - } - - if ( getTableManagementTransactionality() != null ) { - builder.setTransactionality( getTableManagementTransactionality() ); - } - - final SessionUidSupport sessionUidSupport = getSessionUidSupport(); - if ( sessionUidSupport != null ) { - builder.setSessionUidSupport( sessionUidSupport ); - } - - return builder.build( domainParameterXref, creationContext ); - } - - @Override - public DeleteHandler buildDeleteHandler( - SqmDeleteStatement sqmDelete, - DomainParameterXref domainParameterXref, - HandlerCreationContext creationContext) { - return SqmMutationStrategyHelper.resolveDeleteHandler( - sqmDelete, - domainParameterXref, - creationContext, - this::buildFallbackDeleteHandler - ); - } - - private DeleteHandler buildFallbackDeleteHandler( - SqmDeleteStatement sqmDelete, - DomainParameterXref domainParameterXref, - HandlerCreationContext creationContext) { - final EntityTypeDescriptor entityDescriptor = sqmDelete.getTarget() - .getReferencedPathSource() - .getEntityDescriptor(); - final TableBasedDeleteHandlerImpl.Builder builder = new TableBasedDeleteHandlerImpl.Builder( - sqmDelete, - idTableInfoMap.get( entityDescriptor ), - getIdTableSupport() - ); - - if ( getBeforeUseAction() != null ) { - builder.setBeforeUseAction( getBeforeUseAction() ); - } - - if ( getAfterUseAction() != null ) { - builder.setAfterUseAction( getAfterUseAction() ); - } - - if ( getTableManagementTransactionality() != null ) { - builder.setTransactionality( getTableManagementTransactionality() ); - } - - final SessionUidSupport sessionUidSupport = getSessionUidSupport(); - if ( sessionUidSupport != null ) { - builder.setSessionUidSupport( sessionUidSupport ); - } - - return builder.build( creationContext, domainParameterXref ); - } - -} diff --git a/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/idtable/GlobalTempTableExporter.java b/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/idtable/GlobalTempTableExporter.java deleted file mode 100644 index 23945d8d08..0000000000 --- a/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/idtable/GlobalTempTableExporter.java +++ /dev/null @@ -1,17 +0,0 @@ -/* - * Hibernate, Relational Persistence for Idiomatic Java - * - * License: GNU Lesser General Public License (LGPL), version 2.1 or later - * See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html - */ -package org.hibernate.query.sqm.mutation.spi.idtable; - -/** - * @author Steve Ebersole - */ -public class GlobalTempTableExporter extends IdTableExporterImpl { - @Override - protected String getCreateCommand() { - return "create global temporary table"; - } -} diff --git a/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/idtable/GlobalTemporaryTableStrategy.java b/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/idtable/GlobalTemporaryTableStrategy.java deleted file mode 100644 index f38087e65c..0000000000 --- a/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/idtable/GlobalTemporaryTableStrategy.java +++ /dev/null @@ -1,154 +0,0 @@ -/* - * Hibernate, Relational Persistence for Idiomatic Java - * - * License: GNU Lesser General Public License (LGPL), version 2.1 or later - * See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html - */ -package org.hibernate.query.sqm.mutation.spi.idtable; - -import java.util.ArrayList; -import java.util.List; - -import org.hibernate.Metamodel; -import org.hibernate.boot.registry.StandardServiceRegistry; -import org.hibernate.boot.spi.SessionFactoryOptions; -import org.hibernate.engine.config.spi.ConfigurationService; -import org.hibernate.engine.config.spi.StandardConverters; -import org.hibernate.engine.jdbc.connections.spi.JdbcConnectionAccess; -import org.hibernate.engine.jdbc.spi.JdbcServices; -import org.hibernate.metamodel.model.mapping.EntityTypeDescriptor; -import org.hibernate.tool.schema.spi.Exporter; - -/** - * Strategy based on ANSI SQL's definition of a "global temporary table". - * - * @author Steve Ebersole - */ -public class GlobalTemporaryTableStrategy - extends AbstractTableBasedMutationStrategy { - public static final String DROP_ID_TABLES = "hibernate.hql.bulk_id_strategy.global_temporary.drop_tables"; - - public static final String SHORT_NAME = "global_temporary"; - private final IdTableSupport idTableSupport; - - private IdTableManagementTransactionality transactionality; - private List idTableHelpers; - - public GlobalTemporaryTableStrategy() { - this( generateStandardExporter() ); - } - - private static Exporter generateStandardExporter() { - return new GlobalTempTableExporter(); - } - - public GlobalTemporaryTableStrategy(Exporter exporter) { - this( new StandardIdTableSupport( exporter ) ); - } - - public GlobalTemporaryTableStrategy(IdTableSupport idTableSupport) { - this.idTableSupport = idTableSupport; - } - - @Override - protected IdTableSupport getIdTableSupport() { - return idTableSupport; - } - - @Override - protected NamespaceHandling getNamespaceHandling() { - return NamespaceHandling.USE_NONE; - } - - @Override - public void prepare( - Metamodel runtimeMetadata, - SessionFactoryOptions sessionFactoryOptions, - JdbcConnectionAccess connectionAccess) { - - final StandardServiceRegistry serviceRegistry = sessionFactoryOptions.getServiceRegistry(); - final ConfigurationService configService = serviceRegistry.getService( ConfigurationService.class ); - final boolean dropIdTables = configService.getSetting( - DROP_ID_TABLES, - StandardConverters.BOOLEAN, - false - ); - - // todo (6.0) : this could also be handled via the - if ( dropIdTables ) { - // trigger #generateIdTableDefinition to keep around the IdTableHelper for drops - idTableHelpers = new ArrayList<>(); - } - - // see if the user explicitly requested specific transactionality via settings... - switch ( sessionFactoryOptions.getTempTableDdlTransactionHandling() ) { - case ISOLATE: { - transactionality = IdTableManagementTransactionality.ISOLATE; - break; - } - case ISOLATE_AND_TRANSACT: { - transactionality = IdTableManagementTransactionality.ISOLATE_AND_TRANSACT; - break; - } - default: { - // nothing to do - null will be handled properly by super - } - } - - super.prepare( runtimeMetadata, sessionFactoryOptions, connectionAccess ); - } - - @Override - protected IdTable generateIdTableDefinition( - EntityTypeDescriptor entityDescriptor, - SessionFactoryOptions sessionFactoryOptions, - JdbcConnectionAccess connectionAccess) { - final IdTable idTable = super.generateIdTableDefinition( - entityDescriptor, - sessionFactoryOptions, - connectionAccess - ); - - final IdTableHelper idTableHelper = new IdTableHelper( - idTable, - getIdTableSupport(), - transactionality, - sessionFactoryOptions.getServiceRegistry().getService( JdbcServices.class ) - ); - - idTableHelper.createIdTable( connectionAccess ); - - if ( idTableHelpers != null ) { - idTableHelpers.add( idTableHelper ); - } - - return idTable; - } - - @Override - public BeforeUseAction getBeforeUseAction() { - return BeforeUseAction.NONE; - } - - @Override - public AfterUseAction getAfterUseAction() { - return AfterUseAction.CLEAN; - } - - @Override - public IdTableManagementTransactionality getTableManagementTransactionality() { - return transactionality; - } - - @Override - public void release(Metamodel runtimeMetadata, JdbcConnectionAccess connectionAccess) { - if ( idTableHelpers != null ) { - for ( IdTableHelper idTableHelper : idTableHelpers ) { - idTableHelper.dropIdTable( connectionAccess ); - } - } - - super.release( runtimeMetadata, connectionAccess ); - } - -} diff --git a/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/idtable/IdTable.java b/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/idtable/IdTable.java deleted file mode 100644 index 163a38035b..0000000000 --- a/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/idtable/IdTable.java +++ /dev/null @@ -1,197 +0,0 @@ -/* - * Hibernate, Relational Persistence for Idiomatic Java - * - * License: GNU Lesser General Public License (LGPL), version 2.1 or later - * See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html - */ -package org.hibernate.query.sqm.mutation.spi.idtable; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.List; -import java.util.UUID; - -import org.hibernate.boot.model.relational.InitCommand; -import org.hibernate.dialect.Dialect; -import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment; -import org.hibernate.metamodel.model.mapping.EntityTypeDescriptor; -import org.hibernate.metamodel.model.relational.spi.ExportableTable; -import org.hibernate.metamodel.model.relational.spi.ForeignKey; -import org.hibernate.metamodel.model.relational.spi.Index; -import org.hibernate.metamodel.model.relational.spi.PrimaryKey; -import org.hibernate.metamodel.model.relational.spi.UniqueKey; -import org.hibernate.naming.Identifier; -import org.hibernate.naming.QualifiedTableName; - -/** - * @author Steve Ebersole - */ -public class IdTable implements ExportableTable { - private final EntityTypeDescriptor entityDescriptor; - private final QualifiedTableName qualifiedName; - - private final UUID uuid = UUID.randomUUID(); - - private IdTableSessionUidColumn sessionUidColumn; - private final List columns = new ArrayList<>(); - - public IdTable( - EntityTypeDescriptor entityDescriptor, - QualifiedTableName physicalQualifiedName) { - this.entityDescriptor = entityDescriptor; - this.qualifiedName = physicalQualifiedName; - } - - public EntityTypeDescriptor getEntityDescriptor() { - return entityDescriptor; - } - - public List getIdTableColumns() { - return columns; - } - - public IdTableSessionUidColumn getSessionUidColumn() { - return sessionUidColumn; - } - - - // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - // Table - - @Override - public String getTableExpression() { - return getQualifiedTableName().getTableName().getText(); - } - - @Override - public String render(Dialect dialect, JdbcEnvironment jdbcEnvironment) { - return jdbcEnvironment.getQualifiedObjectNameFormatter().format( getQualifiedTableName(), dialect ); - } - - @Override - @SuppressWarnings("unchecked") - public Collection getColumns() { - return columns; - } - - - @Override - public IdTableColumn getColumn(String name) { - for ( IdTableColumn column : columns ) { - if ( column.getName().getText().equalsIgnoreCase( name ) ) { - return column; - } - } - - return null; - } - - public void addColumn(IdTableColumn column) { - columns.add( column ); - if ( column instanceof IdTableSessionUidColumn ) { - this.sessionUidColumn = (IdTableSessionUidColumn) column; - } - } - - @Override - public UUID getUid() { - return uuid; - } - - @Override - public PrimaryKey getPrimaryKey() { - return null; - } - - @Override - public boolean hasPrimaryKey() { - return false; - } - - @Override - public boolean isAbstract() { - return false; - } - - @Override - public Collection getForeignKeys() { - return Collections.emptyList(); - } - - - // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - // ExportableTable - - @Override - public boolean isExportable() { - return true; - } - - @Override - public Identifier getCatalogName() { - return getQualifiedTableName().getCatalogName(); - } - - @Override - public Identifier getSchemaName() { - return getQualifiedTableName().getSchemaName(); - } - - @Override - public Identifier getTableName() { - return getQualifiedTableName().getTableName(); - } - - @Override - public QualifiedTableName getQualifiedTableName() { - return qualifiedName; - } - - @Override - @SuppressWarnings("unchecked") - public Collection getPhysicalColumns() { - return columns; - } - - @Override - public Collection getUniqueKeys() { - return Collections.emptyList(); - } - - @Override - public List getCheckConstraints() { - return Collections.emptyList(); - } - - @Override - public Collection getIndexes() { - return Collections.emptyList(); - } - - @Override - public boolean isPrimaryKeyIdentity() { - return false; - } - - @Override - public Collection getInitCommands() { - return Collections.emptyList(); - } - - @Override - public String toLoggableFragment() { - return getTableExpression(); - } - - @Override - public String getExportIdentifier() { - return getQualifiedTableName().render(); - } - - @Override - public String getComment() { - return "Table used to temporarily hold id values for the entity " + entityDescriptor.getEntityName(); - } - -} diff --git a/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/idtable/IdTableColumn.java b/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/idtable/IdTableColumn.java deleted file mode 100644 index a87617bc33..0000000000 --- a/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/idtable/IdTableColumn.java +++ /dev/null @@ -1,88 +0,0 @@ -/* - * Hibernate, Relational Persistence for Idiomatic Java - * - * License: GNU Lesser General Public License (LGPL), version 2.1 or later - * See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html - */ -package org.hibernate.query.sqm.mutation.spi.idtable; - -import org.hibernate.dialect.Dialect; -import org.hibernate.engine.jdbc.env.internal.QualifiedObjectNameFormatterStandardImpl; -import org.hibernate.metamodel.model.relational.spi.PhysicalColumn; -import org.hibernate.naming.Identifier; -import org.hibernate.type.descriptor.java.spi.BasicJavaDescriptor; -import org.hibernate.type.descriptor.sql.spi.SqlTypeDescriptor; -import org.hibernate.type.spi.TypeConfiguration; - -/** - * A column in a IdTable. As the column exists in the - * IdTable, we know a few things about it inherently, such as: - * - * the column is part of the PK for the IdTable - * therefore, the column is non-nullable - * - * @author Steve Ebersole - */ -public class IdTableColumn extends PhysicalColumn { - public IdTableColumn( - IdTable containingTable, - Identifier columnName, - SqlTypeDescriptor sqlTypeDescriptor, - BasicJavaDescriptor javaTypeDescriptor, - String defaultValue, - String sqlTypeDefinition, - TypeConfiguration typeConfiguration) { - super( - containingTable, - columnName, - () -> sqlTypeDescriptor, - () -> javaTypeDescriptor, - defaultValue, - sqlTypeDefinition, - false, - false, - typeConfiguration - ); - } - - public IdTableColumn(IdTable idTable,PhysicalColumn entityIdPkColumn) { - super( - idTable, - entityIdPkColumn.getName(), - entityIdPkColumn.getSqlTypeDescriptorAccess(), - entityIdPkColumn.getJavaTypeDescriptorAccess(), - entityIdPkColumn.getDefaultValue(), - entityIdPkColumn.getSqlTypeName(), - false, - false, - entityIdPkColumn.getTypeConfiguration() - ); - } - - @Override - public IdTable getSourceTable() { - return (IdTable) super.getSourceTable(); - } - - @Override - public String render(String qualifier) { - final Dialect dialect = getSourceTable().getEntityDescriptor() - .getTypeConfiguration() - .getSessionFactory() - .getJdbcServices() - .getDialect(); - - final String base = getName().render( dialect ); - if ( qualifier == null ) { - return base; - } - else { - return qualifier + '.' + base; - } - } - - @Override - public String render() { - return getName().render(); - } -} diff --git a/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/idtable/IdTableExporterImpl.java b/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/idtable/IdTableExporterImpl.java deleted file mode 100644 index c6c3201bb2..0000000000 --- a/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/idtable/IdTableExporterImpl.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Hibernate, Relational Persistence for Idiomatic Java - * - * License: GNU Lesser General Public License (LGPL), version 2.1 or later - * See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html - */ -package org.hibernate.query.sqm.mutation.spi.idtable; - -import org.hibernate.dialect.Dialect; -import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment; -import org.hibernate.engine.jdbc.spi.JdbcServices; -import org.hibernate.tool.schema.spi.Exporter; - -/** - * @author Steve Ebersole - */ -public class IdTableExporterImpl implements Exporter { - protected String getCreateCommand() { - return "create table"; - } - - protected String getCreateOptions() { - return null; - } - - protected String getDropCommand() { - return "drop table"; - } - - protected String getTruncateIdTableCommand(){ - return "delete from"; - } - - @Override - public String[] getSqlCreateStrings(IdTable exportable, JdbcServices jdbcServices) { - final JdbcEnvironment jdbcEnvironment = jdbcServices.getJdbcEnvironment(); - final Dialect dialect = jdbcEnvironment.getDialect(); - - final StringBuilder buffer = new StringBuilder( getCreateCommand() ).append( ' ' ); - buffer.append( determineIdTableNameForCreate( exportable, jdbcServices ) ); - buffer.append( '(' ); - - boolean firstPass = true; - for ( IdTableColumn column : exportable.getIdTableColumns() ) { - if ( firstPass ) { - firstPass = false; - } - else { - buffer.append( ", " ); - } - - buffer.append( column.getName().render( dialect ) ).append( ' ' ); - buffer.append( column.getSqlTypeName() ); - // id values cannot be null - buffer.append( " not null" ); - } - - buffer.append( ") " ); - - final String createOptions = getCreateOptions(); - if ( createOptions != null ) { - buffer.append( createOptions ); - } - - return new String[] { buffer.toString() }; - } - - protected String determineIdTableNameForCreate(IdTable exportable, JdbcServices jdbcServices) { - return determineIdTableName( exportable, jdbcServices ); - } - - protected String determineIdTableName(IdTable exportable, JdbcServices jdbcServices) { - final JdbcEnvironment jdbcEnvironment = jdbcServices.getJdbcEnvironment(); - final Dialect dialect = jdbcEnvironment.getDialect(); - return jdbcEnvironment.getQualifiedObjectNameFormatter() - .format( exportable.getQualifiedTableName(), dialect ); - } - - @Override - public String[] getSqlDropStrings(IdTable exportable, JdbcServices jdbcServices) { - return new String[] { - getDropCommand() + ' ' + determineIdTableNameForDrop( exportable, jdbcServices ) - }; - } - - private String determineIdTableNameForDrop(IdTable exportable, JdbcServices jdbcServices) { - return determineIdTableName( exportable, jdbcServices ); - } -} diff --git a/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/idtable/IdTableGroup.java b/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/idtable/IdTableGroup.java deleted file mode 100644 index 94754c244a..0000000000 --- a/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/idtable/IdTableGroup.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Hibernate, Relational Persistence for Idiomatic Java - * - * License: GNU Lesser General Public License (LGPL), version 2.1 or later - * See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html - */ -package org.hibernate.query.sqm.mutation.spi.idtable; - -import java.util.Collections; -import java.util.List; -import java.util.function.Consumer; - -import org.hibernate.LockMode; -import org.hibernate.metamodel.model.mapping.EntityTypeDescriptor; -import org.hibernate.metamodel.model.relational.spi.Column; -import org.hibernate.query.NavigablePath; -import org.hibernate.sql.ast.consume.spi.SqlAppender; -import org.hibernate.sql.ast.spi.SqlAstWalker; -import org.hibernate.sql.ast.tree.from.AbstractTableGroup; -import org.hibernate.sql.ast.tree.from.TableReferenceJoin; - -/** - * Wraps a {@link IdTableReference} and adapts it to - * {@link org.hibernate.sql.ast.tree.from.TableGroup} for use in SQL AST - * - * @author Steve Ebersole - */ -@SuppressWarnings("WeakerAccess") -public class IdTableGroup extends AbstractTableGroup { - private final IdTableReference idTableReference; - - public IdTableGroup(EntityTypeDescriptor entityDescriptor, IdTableReference idTableReference) { - super( - new NavigablePath( entityDescriptor.getEntityName() ), - entityDescriptor, - LockMode.NONE - ); - this.idTableReference = idTableReference; - } - - @Override - public void render(SqlAppender sqlAppender, SqlAstWalker walker) { - sqlAppender.appendSql( idTableReference.getTable().getTableExpression() ); - } - - @Override - public void applyAffectedTableNames(Consumer nameCollector) { - nameCollector.accept( idTableReference.getTable().getTableExpression() ); - } - - @Override - public IdTableReference getPrimaryTableReference() { - return idTableReference; - } - - @Override - public List getTableReferenceJoins() { - return Collections.emptyList(); - } - - @Override - public Column resolveColumn(String columnName) { - return idTableReference.resolveColumn( columnName ); - } -} diff --git a/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/idtable/IdTableHelper.java b/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/idtable/IdTableHelper.java deleted file mode 100644 index d7729fae2d..0000000000 --- a/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/idtable/IdTableHelper.java +++ /dev/null @@ -1,312 +0,0 @@ -/* - * Hibernate, Relational Persistence for Idiomatic Java - * - * License: GNU Lesser General Public License (LGPL), version 2.1 or later - * See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html - */ -package org.hibernate.query.sqm.mutation.spi.idtable; - -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.SQLException; -import java.sql.SQLWarning; -import java.sql.Statement; - -import org.hibernate.engine.jdbc.connections.spi.JdbcConnectionAccess; -import org.hibernate.engine.jdbc.internal.FormatStyle; -import org.hibernate.engine.jdbc.spi.JdbcServices; -import org.hibernate.engine.jdbc.spi.SqlExceptionHelper; -import org.hibernate.engine.jdbc.spi.SqlStatementLogger; -import org.hibernate.engine.spi.SharedSessionContractImplementor; -import org.hibernate.internal.CoreLogging; -import org.hibernate.internal.CoreMessageLogger; -import org.hibernate.jdbc.AbstractWork; - -/** - * @author Steve Ebersole - */ -public class IdTableHelper { - private final static CoreMessageLogger log = CoreLogging.messageLogger(IdTableHelper.class ); - - private final IdTable idTableInfo; - private final IdTableSupport idTableSupport; - private final IdTableManagementTransactionality transactionality; - private final JdbcServices jdbcServices; - - private final String[] creationCommands; - private final String[] dropCommands; - - public IdTableHelper( - IdTable idTableInfo, - IdTableSupport idTableSupport, - IdTableManagementTransactionality transactionality, - JdbcServices jdbcServices) { - this.idTableInfo = idTableInfo; - this.idTableSupport = idTableSupport; - if ( idTableSupport.geIdTableManagementTransactionality() != null ) { - this.transactionality = idTableSupport.geIdTableManagementTransactionality(); - } - else { - this.transactionality = transactionality; - } - this.jdbcServices = jdbcServices; - - this.creationCommands = generateIdTableCreationCommands( idTableInfo, idTableSupport, jdbcServices ); - this.dropCommands = generateIdTableDropCommands( idTableInfo, idTableSupport, jdbcServices ); - } - - private static String[] generateIdTableCreationCommands( - IdTable idTableInfo, - IdTableSupport idTableSupport, - JdbcServices jdbcServices) { - return idTableSupport.getIdTableExporter().getSqlCreateStrings( idTableInfo, jdbcServices ); - } - - private static String[] generateIdTableDropCommands( - IdTable idTableInfo, - IdTableSupport idTableSupport, - JdbcServices jdbcServices) { - return idTableSupport.getIdTableExporter().getSqlDropStrings( idTableInfo, jdbcServices ); - } - - // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - // Creation - - private class IdTableCreationWork extends AbstractWork { - @Override - public void execute(Connection connection) { - try { - Statement statement = connection.createStatement(); - for ( String creationCommand : creationCommands ) { - try { - logStatement( creationCommand ); - statement.executeUpdate( creationCommand ); - jdbcServices.getSqlExceptionHelper() - .handleAndClearWarnings( statement, WARNING_HANDLER ); - } - catch( SQLException e ) { - log.debugf( - "unable to create id table [%s]; `%s` failed : %s", - idTableInfo.getQualifiedTableName().render(), - creationCommand, - e.getMessage() - ); - } - finally { - try { - statement.close(); - } - catch( Throwable ignore ) { - // ignore - } - } - - } - } - catch( Exception e ) { - log.debugf( "Error creating id table(s) : %s", e.getMessage() ); - } - } - - } - - public void createIdTable(SharedSessionContractImplementor session) { - executeWork( new IdTableCreationWork(), session ); - } - - private void executeWork(AbstractWork work, SharedSessionContractImplementor session) { - if ( transactionality == IdTableManagementTransactionality.NONE ) { - // simply execute the work using a Connection obtained from JdbcConnectionAccess - // - // NOTE : we do not (potentially) release the Connection here - // via LogicalConnectionImplementor#afterStatement because - // for sure we will be immediately using it again to - // populate the id table and use it... - - try { - work.execute( session.getJdbcCoordinator().getLogicalConnection().getPhysicalConnection() ); - } - catch (SQLException e) { - log.error( "Unable to use JDBC Connection to create perform id table management", e ); - } - } - else { - session.getTransactionCoordinator() - .createIsolationDelegate() - .delegateWork( work, transactionality == IdTableManagementTransactionality.ISOLATE_AND_TRANSACT ); - } - - } - - public void createIdTable(JdbcConnectionAccess jdbcConnectionAccess) { - // Don't really know all the codes required to adequately decipher returned jdbc exceptions here. - // simply allow the failure to be eaten and the subsequent insert-selects/deletes should fail - final IdTableCreationWork work = new IdTableCreationWork(); - - if ( transactionality != IdTableManagementTransactionality.NONE ) { - log.debugf( "IdTableManagementTransactionality#%s was requested but not supported, skipping transactionality" ); - } - - // simply execute the work using a Connection obtained from JdbcConnectionAccess - try { - final Connection connection = jdbcConnectionAccess.obtainConnection(); - - try { - work.execute( connection ); - } - finally { - try { - jdbcConnectionAccess.releaseConnection( connection ); - } - catch (SQLException ignore) { - } - } - } - catch (SQLException e) { - throw jdbcServices.getSqlExceptionHelper() - .convert( e, "Unable to obtain JDBC Connection for id-table [" + idTableInfo.getQualifiedTableName().render() + "]" ); - } - } - - - // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - // Drop - - - public void dropIdTable(SharedSessionContractImplementor session) { - final IdTableDropWork work = new IdTableDropWork(); - if ( transactionality == IdTableManagementTransactionality.NONE ) { - final Connection connection = session.getJdbcCoordinator() - .getLogicalConnection() - .getPhysicalConnection(); - - work.execute( connection ); - - session.getJdbcCoordinator().afterStatementExecution(); - } - else { - session.getTransactionCoordinator() - .createIsolationDelegate() - .delegateWork( work, transactionality == IdTableManagementTransactionality.ISOLATE_AND_TRANSACT ); - } - } - - - public void dropIdTable(JdbcConnectionAccess jdbcConnectionAccess) { - if ( transactionality != IdTableManagementTransactionality.NONE ) { - log.debugf( "IdTableManagementTransactionality#%s was requested but not supported, skipping transactionality" ); - } - - final IdTableDropWork work = new IdTableDropWork(); - - // simply execute the work using a Connection obtained from JdbcConnectionAccess - try { - final Connection connection = jdbcConnectionAccess.obtainConnection(); - - try { - work.execute( connection ); - } - finally { - try { - jdbcConnectionAccess.releaseConnection( connection ); - } - catch (SQLException ignore) { - } - } - } - catch (SQLException e) { - throw jdbcServices.getSqlExceptionHelper() - .convert( e, "Unable to obtain JDBC Connection for id-table [" + idTableInfo.getQualifiedTableName().render() + "]" ); - } - } - - private class IdTableDropWork extends AbstractWork { - @Override - public void execute(Connection connection) { - try { - - final Statement statement = connection.createStatement(); - - for ( String dropCommand : dropCommands ) { - try { - logStatement( dropCommand ); - statement.executeUpdate( dropCommand ); - jdbcServices.getSqlExceptionHelper() - .handleAndClearWarnings( statement, WARNING_HANDLER ); - } - finally { - try { - statement.close(); - } - catch( Throwable ignore ) { - // ignore - } - } - } - } - catch( Exception e ) { - log.warn( "unable to drop temporary id table afterQuery use [" + e.getMessage() + "]" ); - } - } - } - - - // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - // Clean - - public void cleanIdTableRows(SharedSessionContractImplementor session) { - final JdbcServices jdbcServices = session.getJdbcServices(); - - // todo (6.0) : need to account for session uid if support is enabled. - - PreparedStatement ps = null; - try { - final String tableName = jdbcServices.getJdbcEnvironment() - .getQualifiedObjectNameFormatter() - .format( idTableInfo.getQualifiedTableName(), jdbcServices.getJdbcEnvironment().getDialect() ); - - final String sql = ((IdTableExporterImpl)this.idTableSupport.getIdTableExporter()).getTruncateIdTableCommand() + " " + tableName; - ps = session.getJdbcCoordinator().getStatementPreparer().prepareStatement( sql, false ); - session.getJdbcCoordinator().getResultSetReturn().executeUpdate( ps ); - } - catch( Throwable t ) { - log.unableToCleanupTemporaryIdTable(t); - } - finally { - if ( ps != null ) { - try { - session.getJdbcCoordinator().getLogicalConnection().getResourceRegistry().release( ps ); - } - catch( Throwable ignore ) { - // ignore - } - } - } - } - - - // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - // Misc - - private static SqlExceptionHelper.WarningHandler WARNING_HANDLER = new SqlExceptionHelper.WarningHandlerLoggingSupport() { - public boolean doProcess() { - return log.isDebugEnabled(); - } - - public void prepare(SQLWarning warning) { - log.warningsCreatingTempTable( warning ); - } - - @Override - protected void logWarning(String description, String message) { - log.debug( description ); - log.debug( message ); - } - }; - - - private void logStatement(String sql) { - final SqlStatementLogger statementLogger = jdbcServices.getSqlStatementLogger(); - statementLogger.logStatement( sql, FormatStyle.BASIC.getFormatter() ); - } -} diff --git a/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/idtable/IdTableManagementTransactionality.java b/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/idtable/IdTableManagementTransactionality.java deleted file mode 100644 index f7062c7367..0000000000 --- a/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/idtable/IdTableManagementTransactionality.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Hibernate, Relational Persistence for Idiomatic Java - * - * License: GNU Lesser General Public License (LGPL), version 2.1 or later - * See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html - */ -package org.hibernate.query.sqm.mutation.spi.idtable; - -/** - * @author Steve Ebersole - */ -public enum IdTableManagementTransactionality { - /** - * No handling of transactions is needed - */ - NONE, - /** - * Execution of the DDL must be isolated from any ongoing transaction. Isolation - * is needed when the database implicitly commints any active transaction when - * DDL is performed. - */ - ISOLATE, - /** - * As with {@link #ISOLATE} the execution of the DDL must be isolated from any ongoing transaction. - * However, here the "isolation" will also be transacted. Some databases require that the DDL - * happen within a transaction. This value covers such cases. - */ - ISOLATE_AND_TRANSACT -} diff --git a/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/idtable/IdTableReference.java b/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/idtable/IdTableReference.java deleted file mode 100644 index 8e25d33831..0000000000 --- a/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/idtable/IdTableReference.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Hibernate, Relational Persistence for Idiomatic Java - * - * License: GNU Lesser General Public License (LGPL), version 2.1 or later - * See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html - */ -package org.hibernate.query.sqm.mutation.spi.idtable; - -import java.util.Locale; - -import org.hibernate.metamodel.model.relational.spi.Column; -import org.hibernate.metamodel.model.relational.spi.Table; -import org.hibernate.sql.ast.tree.expression.ColumnReference; -import org.hibernate.sql.ast.tree.from.TableReference; - -/** - * @author Steve Ebersole - */ -public class IdTableReference extends TableReference { - public IdTableReference(IdTable table) { - super( table, null, false ); - } - - @Override - public IdTable getTable() { - return (IdTable) super.getTable(); - } - - @Override - public IdTableReference locateTableReference(Table table) { - if ( ! IdTable.class.isInstance( table ) ) { - throw new IllegalArgumentException( - String.format( - Locale.ROOT, - "Expecting Table passed to %s#locateTableReference to be of type %s, but found %s ", - getClass().getName(), - IdTable.class.getName(), - table - ) - ); - } - - return (IdTableReference) super.locateTableReference( table ); - } - - @Override - public ColumnReference resolveColumnReference(Column column) { - if ( ! IdTableColumn.class.isInstance( column ) ) { - throw new IllegalArgumentException( - String.format( - Locale.ROOT, - "Expecting Column passed to %s#resolveColumnReference to be of type %s, but found %s ", - getClass().getName(), - IdTableColumn.class.getName(), - column - ) - ); - } - - return super.resolveColumnReference( column ); - } -} diff --git a/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/idtable/IdTableSessionUidColumn.java b/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/idtable/IdTableSessionUidColumn.java deleted file mode 100644 index 7846618681..0000000000 --- a/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/idtable/IdTableSessionUidColumn.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Hibernate, Relational Persistence for Idiomatic Java - * - * License: GNU Lesser General Public License (LGPL), version 2.1 or later - * See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html - */ -package org.hibernate.query.sqm.mutation.spi.idtable; - -import org.hibernate.naming.Identifier; -import org.hibernate.type.descriptor.java.internal.StringJavaDescriptor; -import org.hibernate.type.descriptor.sql.spi.VarcharSqlDescriptor; -import org.hibernate.type.spi.TypeConfiguration; - -/** - * @author Steve Ebersole - */ -public class IdTableSessionUidColumn extends IdTableColumn { - public IdTableSessionUidColumn( - IdTable containingTable, - String defaultValue, - String sqlTypeDefinition, - TypeConfiguration typeConfiguration) { - super( - containingTable, - Identifier.toIdentifier( SessionUidSupport.SESSION_ID_COLUMN_NAME ), - VarcharSqlDescriptor.INSTANCE, - StringJavaDescriptor.INSTANCE, - defaultValue, - sqlTypeDefinition, - typeConfiguration - ); - } -} diff --git a/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/idtable/IdTableSupport.java b/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/idtable/IdTableSupport.java deleted file mode 100644 index 3c023e469a..0000000000 --- a/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/idtable/IdTableSupport.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Hibernate, Relational Persistence for Idiomatic Java - * - * License: GNU Lesser General Public License (LGPL), version 2.1 or later - * See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html - */ -package org.hibernate.query.sqm.mutation.spi.idtable; - -import org.hibernate.boot.spi.SessionFactoryOptions; -import org.hibernate.metamodel.model.mapping.EntityTypeDescriptor; -import org.hibernate.naming.Identifier; -import org.hibernate.tool.schema.spi.Exporter; - -/** - * Defines environment's support for id-tables. Generally this comes from - * Dialect. - * - * todo (6.0) : get rid of this contract - the strategy can handle this on its own - * this is a left-over from porting pre-6.0 support - * - * @author Steve Ebersole - */ -public interface IdTableSupport { - /** - * Determine the name to use for the id-table. - */ - Identifier determineIdTableName(EntityTypeDescriptor entityDescriptor, SessionFactoryOptions sessionFactoryOptions); - - Exporter getIdTableExporter(); - - default IdTableManagementTransactionality geIdTableManagementTransactionality(){ - return null; - } -} diff --git a/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/idtable/LocalTempTableExporter.java b/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/idtable/LocalTempTableExporter.java deleted file mode 100644 index f8a8316dc1..0000000000 --- a/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/idtable/LocalTempTableExporter.java +++ /dev/null @@ -1,17 +0,0 @@ -/* - * Hibernate, Relational Persistence for Idiomatic Java - * - * License: GNU Lesser General Public License (LGPL), version 2.1 or later - * See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html - */ -package org.hibernate.query.sqm.mutation.spi.idtable; - -/** - * @author Steve Ebersole - */ -public class LocalTempTableExporter extends IdTableExporterImpl { - @Override - protected String getCreateCommand() { - return "create local temporary table"; - } -} diff --git a/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/idtable/LocalTemporaryTableStrategy.java b/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/idtable/LocalTemporaryTableStrategy.java deleted file mode 100644 index 7fe1cb8483..0000000000 --- a/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/idtable/LocalTemporaryTableStrategy.java +++ /dev/null @@ -1,103 +0,0 @@ -/* - * Hibernate, Relational Persistence for Idiomatic Java - * - * License: GNU Lesser General Public License (LGPL), version 2.1 or later - * See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html - */ -package org.hibernate.query.sqm.mutation.spi.idtable; - -import org.hibernate.Metamodel; -import org.hibernate.boot.spi.SessionFactoryOptions; -import org.hibernate.engine.jdbc.connections.spi.JdbcConnectionAccess; -import org.hibernate.tool.schema.spi.Exporter; - -/** - * Strategy based on ANSI SQL's definition of a "local temporary table" (local to each db session). - * - * @author Steve Ebersole - */ -public class LocalTemporaryTableStrategy extends AbstractTableBasedMutationStrategy { - public static final String SHORT_NAME = "local_temporary"; - - private final IdTableSupport idTableSupport; - private IdTableManagementTransactionality transactionality; - - public LocalTemporaryTableStrategy() { - this( generateStandardIdTableSupport() ); - } - - private static StandardIdTableSupport generateStandardIdTableSupport() { - return new StandardIdTableSupport( generateStandardExporter() ); - } - - private static Exporter generateStandardExporter() { - return new IdTableExporterImpl() { - @Override - protected String getCreateCommand() { - return "create local temporary table"; - } - }; - } - - public LocalTemporaryTableStrategy(IdTableSupport idTableSupport) { - this( idTableSupport, null ); - } - - public LocalTemporaryTableStrategy(IdTableManagementTransactionality transactionality) { - this( generateStandardIdTableSupport(), transactionality ); - } - - public LocalTemporaryTableStrategy(IdTableSupport idTableSupport, IdTableManagementTransactionality transactionality) { - this.idTableSupport = idTableSupport; - this.transactionality = transactionality; - } - - @Override - protected IdTableSupport getIdTableSupport() { - return idTableSupport; - } - - @Override - public BeforeUseAction getBeforeUseAction() { - return BeforeUseAction.CREATE; - } - - @Override - public AfterUseAction getAfterUseAction() { - return AfterUseAction.DROP; - } - - @Override - public IdTableManagementTransactionality getTableManagementTransactionality() { - return transactionality; - } - - @Override - public void prepare( - Metamodel runtimeMetadata, - SessionFactoryOptions sessionFactoryOptions, - JdbcConnectionAccess connectionAccess) { - super.prepare( runtimeMetadata, sessionFactoryOptions, connectionAccess ); - - if ( transactionality == null ) { - // see if the user explicitly requested one via settings... - switch ( sessionFactoryOptions.getTempTableDdlTransactionHandling() ) { - case ISOLATE: { - transactionality = IdTableManagementTransactionality.ISOLATE; - } - case ISOLATE_AND_TRANSACT: { - transactionality = IdTableManagementTransactionality.ISOLATE_AND_TRANSACT; - } - default: { - // nothing to do - null will be handled properly by super - } - } - } - } - - @Override - protected NamespaceHandling getNamespaceHandling() { - // by default local temp tables will use no namespace - return NamespaceHandling.USE_NONE; - } -} diff --git a/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/idtable/PersistentTableSessionUidSupport.java b/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/idtable/PersistentTableSessionUidSupport.java deleted file mode 100644 index e35fb48a6d..0000000000 --- a/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/idtable/PersistentTableSessionUidSupport.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Hibernate, Relational Persistence for Idiomatic Java - * - * License: GNU Lesser General Public License (LGPL), version 2.1 or later - * See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html - */ -package org.hibernate.query.sqm.mutation.spi.idtable; - -import org.hibernate.engine.spi.SharedSessionContractImplementor; - -/** - * @author Steve Ebersole - */ -public class PersistentTableSessionUidSupport implements SessionUidSupport { - @Override - public boolean needsSessionUidColumn() { - return true; - } - - @Override - public void addColumn(IdTable idTable) { - idTable.addColumn( - new IdTableSessionUidColumn( - idTable, - null, - "CHAR(36)", - null - ) - ); - } - - @Override - public String extractUid(SharedSessionContractImplementor session) { - return session.getSessionIdentifier().toString(); - } -} diff --git a/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/idtable/PersistentTableStrategy.java b/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/idtable/PersistentTableStrategy.java deleted file mode 100644 index df744937f2..0000000000 --- a/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/idtable/PersistentTableStrategy.java +++ /dev/null @@ -1,183 +0,0 @@ -/* - * Hibernate, Relational Persistence for Idiomatic Java - * - * License: GNU Lesser General Public License (LGPL), version 2.1 or later - * See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html - */ -package org.hibernate.query.sqm.mutation.spi.idtable; - -import java.util.ArrayList; -import java.util.List; - -import org.hibernate.Metamodel; -import org.hibernate.boot.spi.SessionFactoryOptions; -import org.hibernate.cfg.AvailableSettings; -import org.hibernate.engine.config.spi.ConfigurationService; -import org.hibernate.engine.config.spi.StandardConverters; -import org.hibernate.engine.jdbc.connections.spi.JdbcConnectionAccess; -import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment; -import org.hibernate.engine.jdbc.spi.JdbcServices; -import org.hibernate.metamodel.model.mapping.EntityTypeDescriptor; -import org.hibernate.naming.Identifier; -import org.hibernate.service.ServiceRegistry; -import org.hibernate.tool.schema.spi.Exporter; - -/** - * This is a strategy that mimics temporary tables for databases which do not support - * temporary tables. It follows a pattern similar to the ANSI SQL definition of global - * temporary table using a "session id" column to segment rows from the various sessions. - * - * @author Steve Ebersole - */ -public class PersistentTableStrategy - extends AbstractTableBasedMutationStrategy { - - public static final String SHORT_NAME = "persistent"; - - public static final String DROP_ID_TABLES = "hibernate.hql.bulk_id_strategy.persistent.drop_tables"; - - public static final String SCHEMA = "hibernate.hql.bulk_id_strategy.persistent.schema"; - public static final String CATALOG = "hibernate.hql.bulk_id_strategy.persistent.catalog"; - - private final SessionUidSupport sessionUidSupport = new PersistentTableSessionUidSupport(); - - private final IdTableSupport idTableSupport; - - private Identifier configuredCatalog; - private Identifier configuredSchema; - - private List idTableHelpers; - - public PersistentTableStrategy(Exporter exporter) { - this( new StandardIdTableSupport( exporter ) ); - } - - public PersistentTableStrategy(IdTableSupport idTableSupport) { - this.idTableSupport = idTableSupport; - } - - @Override - protected SessionUidSupport getSessionUidSupport() { - return sessionUidSupport; - } - - @Override - protected IdTableSupport getIdTableSupport() { - return idTableSupport; - } - - @Override - public AfterUseAction getAfterUseAction() { - return AfterUseAction.CLEAN; - } - - @Override - public void prepare( - Metamodel runtimeMetadata, - SessionFactoryOptions sessionFactoryOptions, - JdbcConnectionAccess connectionAccess) { - final ServiceRegistry serviceRegistry = sessionFactoryOptions.getServiceRegistry(); - final JdbcEnvironment jdbcEnvironment = serviceRegistry.getService( JdbcEnvironment.class ); - final ConfigurationService configService = serviceRegistry.getService( ConfigurationService.class ); - - final String catalogName = configService.getSetting( - CATALOG, - StandardConverters.STRING, - configService.getSetting( AvailableSettings.DEFAULT_CATALOG, StandardConverters.STRING ) - ); - final String schemaName = configService.getSetting( - SCHEMA, - StandardConverters.STRING, - configService.getSetting( AvailableSettings.DEFAULT_SCHEMA, StandardConverters.STRING ) - ); - - this.configuredCatalog = jdbcEnvironment.getIdentifierHelper().toIdentifier( catalogName ); - this.configuredSchema = jdbcEnvironment.getIdentifierHelper().toIdentifier( schemaName ); - - final boolean dropIdTables = configService.getSetting( - DROP_ID_TABLES, - StandardConverters.BOOLEAN, - false - ); - - - if ( dropIdTables ) { - // trigger #generateIdTableDefinition to keep around the IdTableHelper for drops - idTableHelpers = new ArrayList<>(); - } - - super.prepare( runtimeMetadata, sessionFactoryOptions, connectionAccess ); - } - - @Override - protected IdTable generateIdTableDefinition( - EntityTypeDescriptor entityDescriptor, - SessionFactoryOptions sessionFactoryOptions, - JdbcConnectionAccess connectionAccess) { - final IdTable idTable = super.generateIdTableDefinition( - entityDescriptor, - sessionFactoryOptions, - connectionAccess - ); - - // see if the user explicitly requested specific transactionality via settings... - final IdTableManagementTransactionality transactionality; - - switch ( sessionFactoryOptions.getTempTableDdlTransactionHandling() ) { - case ISOLATE: { - transactionality = IdTableManagementTransactionality.ISOLATE; - break; - } - case ISOLATE_AND_TRANSACT: { - transactionality = IdTableManagementTransactionality.ISOLATE_AND_TRANSACT; - break; - } - default: { - transactionality = IdTableManagementTransactionality.NONE; - } - } - - final IdTableHelper idTableHelper = new IdTableHelper( - idTable, - getIdTableSupport(), - transactionality, - sessionFactoryOptions.getServiceRegistry().getService( JdbcServices.class ) - ); - - idTableHelper.createIdTable( connectionAccess ); - - if ( idTableHelpers != null ) { - idTableHelpers.add( idTableHelper ); - } - - return idTable; - } - - @Override - protected NamespaceHandling getNamespaceHandling() { - return NamespaceHandling.PREFER_SETTINGS; - } - - @Override - protected Identifier getConfiguredCatalog() { - return configuredCatalog; - } - - @Override - protected Identifier getConfiguredSchema() { - return configuredSchema; - } - - @Override - public void release( - Metamodel runtimeMetadata, - JdbcConnectionAccess connectionAccess) { - if ( idTableHelpers != null ) { - for ( IdTableHelper idTableHelper : idTableHelpers ) { - idTableHelper.dropIdTable( connectionAccess ); - } - } - - super.release( runtimeMetadata, connectionAccess ); - } -} diff --git a/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/idtable/SessionUidSupport.java b/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/idtable/SessionUidSupport.java deleted file mode 100644 index d75ca99c95..0000000000 --- a/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/idtable/SessionUidSupport.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Hibernate, Relational Persistence for Idiomatic Java - * - * License: GNU Lesser General Public License (LGPL), version 2.1 or later - * See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html - */ -package org.hibernate.query.sqm.mutation.spi.idtable; - -import org.hibernate.engine.spi.SharedSessionContractImplementor; - -/** - * Hook for strategies which need to add a column in the underlying id table - * to hold a "Session uid". - * - * @author Steve Ebersole - */ -public interface SessionUidSupport { - String SESSION_ID_COLUMN_NAME = "hib_sess_id"; - - /** - * Singleton access - */ - SessionUidSupport NONE = new SessionUidSupport() { - - @Override - public boolean needsSessionUidColumn() { - return false; - } - - @Override - public void addColumn(IdTable idTable) { - } - - @Override - public String extractUid(SharedSessionContractImplementor session) { - return null; - } - }; - - boolean needsSessionUidColumn(); - - /** - * Get the column used to store the session uid in the id table - */ - void addColumn(IdTable idTable); - - /** - * Given a session, extract the corresponding uid - */ - String extractUid(SharedSessionContractImplementor session); -} diff --git a/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/idtable/StandardIdTableSupport.java b/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/idtable/StandardIdTableSupport.java deleted file mode 100644 index 365e79feac..0000000000 --- a/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/idtable/StandardIdTableSupport.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Hibernate, Relational Persistence for Idiomatic Java - * - * License: GNU Lesser General Public License (LGPL), version 2.1 or later - * See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html - */ -package org.hibernate.query.sqm.mutation.spi.idtable; - -import org.hibernate.boot.spi.SessionFactoryOptions; -import org.hibernate.metamodel.model.mapping.EntityTypeDescriptor; -import org.hibernate.metamodel.model.relational.spi.PhysicalTable; -import org.hibernate.naming.Identifier; -import org.hibernate.tool.schema.spi.Exporter; - -/** - * @author Steve Ebersole - */ -public class StandardIdTableSupport implements IdTableSupport { - private final Exporter idTableExporter; - private IdTableManagementTransactionality tableManagementTransactionality; - - public StandardIdTableSupport(Exporter idTableExporter) { - this.idTableExporter = idTableExporter; - } - - public StandardIdTableSupport(Exporter idTableExporter, IdTableManagementTransactionality tableManagementTransactionality) { - this(idTableExporter); - this.tableManagementTransactionality = tableManagementTransactionality; - } - - @Override - public Identifier determineIdTableName(EntityTypeDescriptor entityDescriptor, SessionFactoryOptions sessionFactoryOptions) { - return determineIdTableName( entityDescriptor ); - } - - protected Identifier determineIdTableName(EntityTypeDescriptor entityDescriptor) { - final Identifier idTableNameBase = determineIdTableNameBase( entityDescriptor ); - return determineIdTableName( idTableNameBase ); - } - - private Identifier determineIdTableNameBase(EntityTypeDescriptor entityDescriptor) { - if ( entityDescriptor.getPrimaryTable() instanceof PhysicalTable ) { - return ( (PhysicalTable) entityDescriptor.getPrimaryTable() ).getTableName(); - } - else { - return Identifier.toIdentifier( entityDescriptor.getJpaEntityName() ); - } - } - - protected Identifier determineIdTableName(Identifier baseName) { - return new Identifier( "HT_" + baseName.getText(), false ); - } - - @Override - public Exporter getIdTableExporter() { - return idTableExporter; - } - - @Override - public IdTableManagementTransactionality geIdTableManagementTransactionality() { - return tableManagementTransactionality; - } -} diff --git a/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/idtable/TableBasedDeleteHandlerImpl.java b/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/idtable/TableBasedDeleteHandlerImpl.java deleted file mode 100644 index 6bd3209cc3..0000000000 --- a/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/idtable/TableBasedDeleteHandlerImpl.java +++ /dev/null @@ -1,204 +0,0 @@ -/* - * Hibernate, Relational Persistence for Idiomatic Java - * - * License: GNU Lesser General Public License (LGPL), version 2.1 or later - * See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html - */ -package org.hibernate.query.sqm.mutation.spi.idtable; - -import java.util.Collections; -import java.util.List; -import java.util.Set; - -import org.hibernate.dialect.Dialect; -import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment; -import org.hibernate.metamodel.model.relational.spi.JoinedTableBinding; -import org.hibernate.metamodel.model.relational.spi.PhysicalColumn; -import org.hibernate.metamodel.model.relational.spi.Table; -import org.hibernate.query.sqm.internal.DomainParameterXref; -import org.hibernate.query.sqm.mutation.spi.DeleteHandler; -import org.hibernate.query.sqm.mutation.spi.HandlerCreationContext; -import org.hibernate.query.sqm.tree.delete.SqmDeleteStatement; -import org.hibernate.sql.ast.consume.spi.SqlAstSelectToJdbcSelectConverter; -import org.hibernate.sql.ast.tree.select.QuerySpec; -import org.hibernate.sql.exec.spi.ExecutionContext; -import org.hibernate.sql.exec.spi.JdbcDelete; -import org.hibernate.sql.exec.spi.JdbcMutationExecutor; -import org.hibernate.sql.exec.spi.JdbcParameterBinder; -import org.hibernate.sql.exec.spi.JdbcParameterBindings; -import org.hibernate.type.spi.StandardSpiBasicTypes; - -/** -* @author Steve Ebersole -*/ -public class TableBasedDeleteHandlerImpl - extends AbstractTableBasedHandler - implements DeleteHandler { - - private TableBasedDeleteHandlerImpl( - SqmDeleteStatement sqmDeleteStatement, - IdTable idTableInfo, - IdTableSupport idTableSupport, - SessionUidSupport sessionUidSupport, - BeforeUseAction beforeUseAction, - AfterUseAction afterUseAction, - IdTableManagementTransactionality transactionality, - DomainParameterXref domainParameterXref, - HandlerCreationContext creationContext) { - super( - sqmDeleteStatement, - idTableInfo, - sessionUidSupport, - beforeUseAction, - afterUseAction, - new IdTableHelper( - idTableInfo, - idTableSupport, - transactionality, - creationContext.getSessionFactory().getJdbcServices() - ), - domainParameterXref, - creationContext - ); - } - - @Override - public SqmDeleteStatement getSqmDeleteOrUpdateStatement() { - return (SqmDeleteStatement) super.getSqmDeleteOrUpdateStatement(); - } - - @Override - protected void performMutations(ExecutionContext executionContext) { - final QuerySpec idTableSelectSubQuerySpec = createIdTableSubQuery( - executionContext - ); - - String idTableSelectSubQuery = SqlAstSelectToJdbcSelectConverter.interpret( - idTableSelectSubQuerySpec, - executionContext.getSession().getSessionFactory() - ).getSql(); - - for ( JoinedTableBinding joinedTable : getEntityDescriptor().getSecondaryTableBindings() ) { - deleteFrom( joinedTable.getReferringTable(), idTableSelectSubQuery, executionContext ); - } - - deleteFrom( getEntityDescriptor().getPrimaryTable(), idTableSelectSubQuery, executionContext ); - } - - private void deleteFrom(Table table, String idTableSelectSubQuery, ExecutionContext executionContext) { - final Dialect dialect = executionContext.getSession().getSessionFactory().getJdbcServices().getDialect(); - final JdbcEnvironment jdbcEnvironment = executionContext.getSession().getSessionFactory().getJdbcServices().getJdbcEnvironment(); - final StringBuilder sqlBuffer = new StringBuilder( ); - sqlBuffer.append( "delete from " ) - .append( table.render( dialect, jdbcEnvironment ) ) - .append( " where " ); - - if ( table.getPrimaryKey().getColumns().size() == 1 ) { - sqlBuffer.append( table.getPrimaryKey().getColumns().get( 0 ).getName().render( dialect ) ) - .append( " in " ); - } - else { - sqlBuffer.append( "(" ); - boolean firstPass = true; - for ( PhysicalColumn physicalColumn : table.getPrimaryKey().getColumns() ) { - if ( firstPass ) { - firstPass = false; - } - else { - sqlBuffer.append( "," ); - } - sqlBuffer.append( physicalColumn.getName().render( dialect ) ); - } - sqlBuffer.append( ") in " ); - } - - sqlBuffer.append( idTableSelectSubQuery ); - - final String deleteStatement = sqlBuffer.toString(); - - JdbcMutationExecutor.NO_AFTER_STATEMENT_CALL.execute( - new JdbcDelete() { - @Override - public String getSql() { - return deleteStatement; - } - - @Override - public List getParameterBinders() { - if ( getSessionUidSupport().needsSessionUidColumn() ) { - return Collections.singletonList( - (statement, startPosition, jdbcParameterBindings, executionContext1) -> { - statement.setString( - startPosition, - getSessionUidSupport().extractUid( executionContext.getSession() ) - ); - return 1; - } - ); - } - - return Collections.emptyList(); - } - - @Override - public Set getAffectedTableNames() { - return Collections.singleton( table.getTableExpression() ); - } - }, - JdbcParameterBindings.NO_BINDINGS, - executionContext - ); - } - - public static class Builder { - private final SqmDeleteStatement sqmStatement; - private final IdTable idTableInfo; - private final IdTableSupport idTableSupport; - - private SessionUidSupport sessionUidSupport = SessionUidSupport.NONE; - private BeforeUseAction beforeUseAction = BeforeUseAction.NONE; - private AfterUseAction afterUseAction = AfterUseAction.NONE; - private IdTableManagementTransactionality transactionality = IdTableManagementTransactionality.NONE; - - public Builder( - SqmDeleteStatement sqmStatement, - IdTable idTableInfo, - IdTableSupport idTableSupport) { - this.sqmStatement = sqmStatement; - this.idTableInfo = idTableInfo; - this.idTableSupport = idTableSupport; - } - - public void setSessionUidSupport(SessionUidSupport sessionUidSupport) { - this.sessionUidSupport = sessionUidSupport; - } - - public void setBeforeUseAction(BeforeUseAction beforeUseAction) { - this.beforeUseAction = beforeUseAction; - } - - public void setAfterUseAction(AfterUseAction afterUseAction) { - this.afterUseAction = afterUseAction; - } - - public void setTransactionality(IdTableManagementTransactionality transactionality) { - this.transactionality = transactionality; - } - - public TableBasedDeleteHandlerImpl build( - HandlerCreationContext creationContext, - DomainParameterXref domainParameterXref) { - return new TableBasedDeleteHandlerImpl( - sqmStatement, - idTableInfo, - idTableSupport, - sessionUidSupport, - beforeUseAction, - afterUseAction, - transactionality, - domainParameterXref, - creationContext - ); - } - } -} diff --git a/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/idtable/TableBasedUpdateHandlerImpl.java b/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/idtable/TableBasedUpdateHandlerImpl.java deleted file mode 100644 index 0239187e8b..0000000000 --- a/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/idtable/TableBasedUpdateHandlerImpl.java +++ /dev/null @@ -1,150 +0,0 @@ -/* - * Hibernate, Relational Persistence for Idiomatic Java - * - * License: GNU Lesser General Public License (LGPL), version 2.1 or later - * See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html - */ -package org.hibernate.query.sqm.mutation.spi.idtable; - -import org.hibernate.query.spi.QueryParameterBindings; -import org.hibernate.query.sqm.internal.DomainParameterXref; -import org.hibernate.query.sqm.mutation.spi.HandlerCreationContext; -import org.hibernate.query.sqm.mutation.spi.UpdateHandler; -import org.hibernate.query.sqm.tree.SqmDeleteOrUpdateStatement; -import org.hibernate.query.sqm.tree.update.SqmUpdateStatement; -import org.hibernate.sql.ast.consume.spi.UpdateToJdbcUpdateConverter; -import org.hibernate.sql.ast.produce.sqm.spi.SqmUpdateInterpretation; -import org.hibernate.sql.ast.produce.sqm.spi.SqmUpdateToSqlAstConverterMultiTable; -import org.hibernate.sql.ast.tree.select.QuerySpec; -import org.hibernate.sql.ast.tree.update.UpdateStatement; -import org.hibernate.sql.exec.spi.ExecutionContext; -import org.hibernate.sql.exec.spi.JdbcMutationExecutor; -import org.hibernate.sql.exec.spi.JdbcParameterBindings; -import org.hibernate.sql.exec.spi.JdbcUpdate; - -/** -* @author Steve Ebersole -*/ -public class TableBasedUpdateHandlerImpl - extends AbstractTableBasedHandler - implements UpdateHandler { - private TableBasedUpdateHandlerImpl( - SqmDeleteOrUpdateStatement sqmDeleteOrUpdateStatement, - IdTable idTableInfo, - IdTableSupport idTableSupport, - SessionUidSupport sessionUidSupport, - BeforeUseAction beforeUseAction, - AfterUseAction afterUseAction, - IdTableManagementTransactionality transactionality, - DomainParameterXref domainParameterXref, - HandlerCreationContext creationContext) { - super( - sqmDeleteOrUpdateStatement, - idTableInfo, - sessionUidSupport, - beforeUseAction, - afterUseAction, - new IdTableHelper( - idTableInfo, - idTableSupport, - transactionality, - creationContext.getSessionFactory().getJdbcServices() - ), - domainParameterXref, - creationContext - ); - } - - @Override - public SqmUpdateStatement getSqmDeleteOrUpdateStatement() { - return (SqmUpdateStatement) super.getSqmDeleteOrUpdateStatement(); - } - - @Override - protected void performMutations(ExecutionContext executionContext) { - boolean hasNoSecondaryTables = getSqmDeleteOrUpdateStatement().getTarget() - .getReferencedPathSource() - .getEntityDescriptor() - .getSecondaryTableBindings() - .isEmpty(); - - final QuerySpec idTableSelectSubQuerySpec = createIdTableSubQuery( executionContext ); - - final SqmUpdateInterpretation interpretation = SqmUpdateToSqlAstConverterMultiTable.interpret( - getSqmDeleteOrUpdateStatement(), - idTableSelectSubQuerySpec, - executionContext.getQueryOptions(), - DomainParameterXref.empty(), - QueryParameterBindings.NO_PARAM_BINDINGS, - executionContext.getSession().getFactory() - ); - - for ( UpdateStatement sqlUpdateAst : interpretation.getSqlUpdates() ) { - // convert each SQL AST UpdateStatement into a JdbcUpdate operation - // and execute it - - final JdbcUpdate jdbcUpdate = UpdateToJdbcUpdateConverter.createJdbcUpdate( - sqlUpdateAst, - executionContext.getSession().getSessionFactory() - ); - - JdbcMutationExecutor.NO_AFTER_STATEMENT_CALL.execute( - jdbcUpdate, - JdbcParameterBindings.NO_BINDINGS, - executionContext - ); - } - } - - public static class Builder { - private final SqmDeleteOrUpdateStatement sqmStatement; - private final IdTable idTableInfo; - private final IdTableSupport idTableSupport; - - private SessionUidSupport sessionUidSupport = SessionUidSupport.NONE; - private BeforeUseAction beforeUseAction = BeforeUseAction.NONE; - private AfterUseAction afterUseAction = AfterUseAction.NONE; - private IdTableManagementTransactionality transactionality = IdTableManagementTransactionality.NONE; - - public Builder( - SqmUpdateStatement sqmStatement, - IdTable idTableInfo, - IdTableSupport idTableSupport) { - this.sqmStatement = sqmStatement; - this.idTableInfo = idTableInfo; - this.idTableSupport = idTableSupport; - } - - public void setSessionUidSupport(SessionUidSupport sessionUidSupport) { - this.sessionUidSupport = sessionUidSupport; - } - - public void setBeforeUseAction(BeforeUseAction beforeUseAction) { - this.beforeUseAction = beforeUseAction; - } - - public void setAfterUseAction(AfterUseAction afterUseAction) { - this.afterUseAction = afterUseAction; - } - - public void setTransactionality(IdTableManagementTransactionality transactionality) { - this.transactionality = transactionality; - } - - public TableBasedUpdateHandlerImpl build( - DomainParameterXref domainParameterXref, - HandlerCreationContext creationContext) { - return new TableBasedUpdateHandlerImpl( - sqmStatement, - idTableInfo, - idTableSupport, - sessionUidSupport, - beforeUseAction, - afterUseAction, - transactionality, - domainParameterXref, - creationContext - ); - } - } -} diff --git a/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/idtable/package-info.java b/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/idtable/package-info.java deleted file mode 100644 index 0f68f705bf..0000000000 --- a/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/idtable/package-info.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Hibernate, Relational Persistence for Idiomatic Java - * - * License: GNU Lesser General Public License (LGPL), version 2.1 or later - * See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html - */ - -/** - * Support for {@link org.hibernate.query.sqm.mutation.spi.SqmMutationStrategy} - * implementations that are backed by an "id table" used to temporarily store the ids of - * entities matching the update/delete restrictions. - * - * General execution processing via both - * {@link org.hibernate.query.sqm.mutation.spi.UpdateHandler} and - * {@link org.hibernate.query.sqm.mutation.spi.DeleteHandler} - * follows the same steps:
    - *
  1. - * (possibly) create the id-table - *
  2. - *
  3. - * perform the INSERT-SELECT to populate the id-table with ids of - * entities matching the restriction specified on the SQM - * update or delete query being handled - *
  4. - *
  5. - * for each entity table perform the physical update or delete as - * indicated by the SQM delete or update query - *
  6. - *
  7. - * (possibly) delete the id-table rows - should probably just always - * do that first (unless we just created the table in step 1) - *
  8. - *
  9. - * (possibly) drop the id-table - *
  10. - *
- * - * todo (6.0) : do 1 and 5 really ever happen today? - * I guess the id-table has to be created there if the table - * is a local temp table - maybe in that case it also needs to - * be manually dropped - * + - * Any other cases? - * + - * Note that generally speaking the id-table is created and dropped - * at the Strategy level during - * {@link org.hibernate.query.sqm.mutation.spi.SqmMutationStrategy#prepare} - * and {@link org.hibernate.query.sqm.mutation.spi.SqmMutationStrategy#release} - */ -package org.hibernate.query.sqm.mutation.spi.idtable; diff --git a/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/inline/AbstractInlineHandler.java b/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/inline/AbstractInlineHandler.java deleted file mode 100644 index c197abb0a4..0000000000 --- a/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/inline/AbstractInlineHandler.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Hibernate, Relational Persistence for Idiomatic Java - * - * License: GNU Lesser General Public License (LGPL), version 2.1 or later - * See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html - */ -package org.hibernate.query.sqm.mutation.spi.inline; - -import java.util.List; - -import org.hibernate.metamodel.model.mapping.EntityTypeDescriptor; -import org.hibernate.query.sqm.internal.DomainParameterXref; -import org.hibernate.query.sqm.mutation.internal.SqmMutationStrategyHelper; -import org.hibernate.query.sqm.mutation.spi.Handler; -import org.hibernate.query.sqm.mutation.spi.HandlerCreationContext; -import org.hibernate.query.sqm.tree.SqmDeleteOrUpdateStatement; -import org.hibernate.sql.exec.spi.ExecutionContext; - -/** - * @author Steve Ebersole - */ -public abstract class AbstractInlineHandler implements Handler { - private final SqmDeleteOrUpdateStatement sqmStatement; - private final DomainParameterXref domainParameterXref; - private final HandlerCreationContext creationContext; - - public AbstractInlineHandler( - SqmDeleteOrUpdateStatement sqmStatement, - DomainParameterXref domainParameterXref, - HandlerCreationContext creationContext) { - this.sqmStatement = sqmStatement; - this.domainParameterXref = domainParameterXref; - this.creationContext = creationContext; - } - - protected EntityTypeDescriptor getEntityDescriptor() { - return sqmStatement.getTarget().getReferencedPathSource(); - } - - public SqmDeleteOrUpdateStatement getSqmStatement() { - return sqmStatement; - } - - public DomainParameterXref getDomainParameterXref() { - return domainParameterXref; - } - - protected List selectMatchingIds(ExecutionContext executionContext) { - return SqmMutationStrategyHelper.selectMatchingIds( domainParameterXref, sqmStatement, executionContext ); - } - -} diff --git a/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/inline/InlineDeleteHandler.java b/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/inline/InlineDeleteHandler.java deleted file mode 100644 index b547372689..0000000000 --- a/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/inline/InlineDeleteHandler.java +++ /dev/null @@ -1,169 +0,0 @@ -/* - * Hibernate, Relational Persistence for Idiomatic Java - * - * License: GNU Lesser General Public License (LGPL), version 2.1 or later - * See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html - */ -package org.hibernate.query.sqm.mutation.spi.inline; - -import java.util.List; - -import org.hibernate.internal.util.collections.CollectionHelper; -import org.hibernate.metamodel.model.mapping.spi.Navigable; -import org.hibernate.metamodel.model.mapping.PersistentCollectionDescriptor; -import org.hibernate.metamodel.model.mapping.spi.PluralPersistentAttribute; -import org.hibernate.metamodel.model.relational.spi.Column; -import org.hibernate.metamodel.model.relational.spi.Table; -import org.hibernate.query.sqm.internal.DomainParameterXref; -import org.hibernate.query.sqm.mutation.internal.SqmMutationStrategyHelper; -import org.hibernate.query.sqm.mutation.spi.DeleteHandler; -import org.hibernate.query.sqm.mutation.spi.HandlerCreationContext; -import org.hibernate.query.sqm.tree.delete.SqmDeleteStatement; -import org.hibernate.sql.ast.Clause; -import org.hibernate.sql.ast.consume.spi.SqlDeleteToJdbcDeleteConverter; -import org.hibernate.sql.ast.tree.delete.DeleteStatement; -import org.hibernate.sql.ast.tree.expression.Expression; -import org.hibernate.sql.ast.tree.expression.QueryLiteral; -import org.hibernate.sql.ast.tree.expression.SqlTuple; -import org.hibernate.sql.ast.tree.from.TableReference; -import org.hibernate.sql.ast.tree.predicate.InListPredicate; -import org.hibernate.sql.ast.tree.predicate.Predicate; -import org.hibernate.sql.exec.spi.ExecutionContext; -import org.hibernate.sql.exec.spi.JdbcDelete; -import org.hibernate.sql.exec.spi.JdbcMutationExecutor; -import org.hibernate.sql.exec.spi.JdbcParameterBindings; - -/** - * @author Steve Ebersole - */ -public class InlineDeleteHandler extends AbstractInlineHandler implements DeleteHandler { - public InlineDeleteHandler( - SqmDeleteStatement sqmDeleteStatement, - DomainParameterXref domainParameterXref, - HandlerCreationContext creationContext) { - super( sqmDeleteStatement, domainParameterXref, creationContext ); - } - - @Override - public int execute(ExecutionContext executionContext) { - final List ids = SqmMutationStrategyHelper.selectMatchingIds( getDomainParameterXref(), getSqmStatement(), executionContext ); - - getEntityDescriptor().visitAttributes( - attribute -> { - final PluralPersistentAttribute pluralAttribute = (PluralPersistentAttribute) attribute; - final PersistentCollectionDescriptor collectionDescriptor = pluralAttribute.getCollectionDescriptor(); - - if ( collectionDescriptor.getSeparateCollectionTable() != null ) { - // this collection has a separate collection table, meaning it is one of: - // 1) element-collection - // 2) many-to-many - // 3) one-to many using a dedicated join-table - // - // in all of these cases, we should clean up the matching rows in the - // collection table - - executeDelete( - collectionDescriptor.getSeparateCollectionTable(), - ids, - collectionDescriptor.getCollectionKeyDescriptor().getJoinForeignKey().getColumnMappings().getTargetColumns(), - collectionDescriptor.getCollectionKeyDescriptor(), - executionContext - ); - } - }, - attribute -> attribute instanceof PluralPersistentAttribute - ); - - getEntityDescriptor().getHierarchy().visitConstraintOrderedTables( - (table,columns) -> executeDelete( - table, - ids, - columns, - getEntityDescriptor().getIdentifierDescriptor(), - executionContext - ) - ); - - - return ids.size(); - } - - private void executeDelete( - Table table, - List ids, - List columns, - Navigable navigable, - ExecutionContext executionContext) { - final TableReference tableReference = new TableReference( table, null, false ); - - final Predicate idRestriction = generateRestrictionValuesList( tableReference, ids, columns , navigable, executionContext ); - - final DeleteStatement deleteStatement = new DeleteStatement( tableReference, idRestriction ); - - final JdbcDelete jdbcDelete = SqlDeleteToJdbcDeleteConverter.interpret( - deleteStatement, - executionContext.getSession().getSessionFactory() - ); - - final JdbcMutationExecutor executor = JdbcMutationExecutor.WITH_AFTER_STATEMENT_CALL; - executor.execute( - jdbcDelete, - JdbcParameterBindings.NO_BINDINGS, - executionContext, - (rows, preparedStatement) -> {} - ); - } - - private Predicate generateRestrictionValuesList( - TableReference tableReference, - List ids, - List columns, - Navigable navigable, - ExecutionContext executionContext) { - if ( ids.isEmpty() ) { - return null; - } - - final InListPredicate restriction; - if ( columns.size() > 1 ) { - final List keyColumnReferences = CollectionHelper.arrayList( columns.size() ); - - for ( Column column : columns ) { - keyColumnReferences.add( - tableReference.resolveColumnReference( column ) ) - ; - } - - restriction = new InListPredicate( new SqlTuple( keyColumnReferences, navigable ) ); - } - else { - restriction = new InListPredicate( - tableReference.resolveColumnReference( columns.get( 0 ) ) - ); - } - - final List valueListElementExpressions = CollectionHelper.arrayList( columns.size() ); - - for ( Object id : ids ) { - valueListElementExpressions.clear(); - - navigable.dehydrate( - navigable.unresolve( id, executionContext.getSession() ), - (jdbcValue, type, boundColumn) -> { - valueListElementExpressions.add( new QueryLiteral( jdbcValue, type, Clause.WHERE ) ); - }, - Clause.WHERE, - executionContext.getSession() - ); - - if ( columns.size() > 1 ) { - restriction.addExpression( new SqlTuple( valueListElementExpressions, navigable ) ); - } - else { - restriction.addExpression( valueListElementExpressions.get( 0 ) ); - } - } - - return restriction; - } -} diff --git a/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/inline/InlineMutationStrategy.java b/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/inline/InlineMutationStrategy.java deleted file mode 100644 index 8766cd2f23..0000000000 --- a/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/inline/InlineMutationStrategy.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Hibernate, Relational Persistence for Idiomatic Java - * - * License: GNU Lesser General Public License (LGPL), version 2.1 or later - * See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html - */ -package org.hibernate.query.sqm.mutation.spi.inline; - -import org.hibernate.query.sqm.internal.DomainParameterXref; -import org.hibernate.query.sqm.mutation.spi.DeleteHandler; -import org.hibernate.query.sqm.mutation.spi.HandlerCreationContext; -import org.hibernate.query.sqm.mutation.spi.SqmMutationStrategy; -import org.hibernate.query.sqm.mutation.spi.UpdateHandler; -import org.hibernate.query.sqm.tree.delete.SqmDeleteStatement; -import org.hibernate.query.sqm.tree.update.SqmUpdateStatement; - -/** - * @asciidoc - * - * {@link SqmMutationStrategy} - * implementation first selecting all matching ids back into memory and then - * using those matching ids to update/delete against each table. - * - * ```` - * select id - * from Person p - * where ... - * - * delete from Contact - * where ( id ) in ( 1, 2, 3, ...) - * - * delete from Person - * where ( id ) in ( 1, 2, 3, ...) - * ```` - * - * @author Vlad Mihalcea - * @author Steve Ebersole - */ -public class InlineMutationStrategy implements SqmMutationStrategy { - @Override - public UpdateHandler buildUpdateHandler( - SqmUpdateStatement sqmUpdateStatement, - DomainParameterXref domainParameterXref, HandlerCreationContext creationContext) { - return null; - } - - @Override - public DeleteHandler buildDeleteHandler( - SqmDeleteStatement sqmDeleteStatement, - DomainParameterXref domainParameterXref, - HandlerCreationContext creationContext) { - return new InlineDeleteHandler( sqmDeleteStatement, domainParameterXref, creationContext ); - } -} diff --git a/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/inline/package-info.java b/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/inline/package-info.java deleted file mode 100644 index a20400833f..0000000000 --- a/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/inline/package-info.java +++ /dev/null @@ -1,13 +0,0 @@ -/* - * Hibernate, Relational Persistence for Idiomatic Java - * - * License: GNU Lesser General Public License (LGPL), version 2.1 or later - * See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html - */ - -/** - * Support for {@link org.hibernate.query.sqm.mutation.spi.SqmMutationStrategy} - * implementations that first selecting all matching ids back into memory and then using - * those matching ids to update/delete against each table. - */ -package org.hibernate.query.sqm.mutation.spi.inline; diff --git a/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/simple/SimpleDeleteHandler.java b/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/simple/SimpleDeleteHandler.java deleted file mode 100644 index 2af3455e0b..0000000000 --- a/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/simple/SimpleDeleteHandler.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Hibernate, Relational Persistence for Idiomatic Java - * - * License: GNU Lesser General Public License (LGPL), version 2.1 or later - * See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html - */ -package org.hibernate.query.sqm.mutation.spi.simple; - -import java.util.Collections; - -import org.hibernate.query.internal.QueryHelper; -import org.hibernate.query.sqm.consume.internal.SqmConsumeHelper; -import org.hibernate.query.sqm.internal.DomainParameterXref; -import org.hibernate.query.sqm.mutation.spi.AbstractMutationHandler; -import org.hibernate.query.sqm.mutation.spi.DeleteHandler; -import org.hibernate.query.sqm.mutation.spi.HandlerCreationContext; -import org.hibernate.query.sqm.tree.delete.SqmDeleteStatement; -import org.hibernate.sql.ast.consume.spi.SqlDeleteToJdbcDeleteConverter; -import org.hibernate.sql.ast.produce.internal.SqlAstDeleteDescriptorImpl; -import org.hibernate.sql.ast.produce.sqm.spi.SqmDeleteToSqlAstConverterSimple; -import org.hibernate.sql.ast.tree.delete.DeleteStatement; -import org.hibernate.sql.exec.internal.JdbcMutationExecutorImpl; -import org.hibernate.sql.exec.spi.ExecutionContext; -import org.hibernate.sql.exec.spi.JdbcMutation; -import org.hibernate.sql.exec.spi.JdbcParameterBindings; - -/** - * @author Steve Ebersole - */ -public class SimpleDeleteHandler extends AbstractMutationHandler implements DeleteHandler { - private final DomainParameterXref domainParameterXref; - - @SuppressWarnings("WeakerAccess") - protected SimpleDeleteHandler( - SqmDeleteStatement sqmStatement, - DomainParameterXref domainParameterXref, - HandlerCreationContext creationContext) { - super( sqmStatement, creationContext ); - this.domainParameterXref = domainParameterXref; - } - - @Override - public SqmDeleteStatement getSqmDeleteOrUpdateStatement() { - return (SqmDeleteStatement) super.getSqmDeleteOrUpdateStatement(); - } - - @Override - public int execute(ExecutionContext executionContext) { - final SqmDeleteToSqlAstConverterSimple sqmConverter = new SqmDeleteToSqlAstConverterSimple( - executionContext.getQueryOptions(), - domainParameterXref, - executionContext.getDomainParameterBindingContext().getQueryParameterBindings(), - executionContext.getSession() - ); - - final DeleteStatement deleteStatement = sqmConverter.visitDeleteStatement( getSqmDeleteOrUpdateStatement() ); - - //noinspection unchecked - final JdbcParameterBindings jdbcParameterBindings = QueryHelper.createJdbcParameterBindings( - executionContext.getDomainParameterBindingContext().getQueryParameterBindings(), - domainParameterXref, - SqmConsumeHelper.generateJdbcParamsXref( domainParameterXref, sqmConverter ), - executionContext.getSession() - ); - - final JdbcMutation jdbcDelete = SqlDeleteToJdbcDeleteConverter.interpret( - new SqlAstDeleteDescriptorImpl( - deleteStatement, - Collections.singleton( - deleteStatement.getTargetTable().getTable().getTableExpression() - ) - ), - executionContext.getSession().getSessionFactory() - ); - - return JdbcMutationExecutorImpl.WITH_AFTER_STATEMENT_CALL.execute( - jdbcDelete, - jdbcParameterBindings, - executionContext - ); - } -} diff --git a/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/simple/SimpleSqmMutationStrategy.java b/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/simple/SimpleSqmMutationStrategy.java deleted file mode 100644 index 26698a0ca8..0000000000 --- a/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/simple/SimpleSqmMutationStrategy.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Hibernate, Relational Persistence for Idiomatic Java - * - * License: GNU Lesser General Public License (LGPL), version 2.1 or later - * See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html - */ -package org.hibernate.query.sqm.mutation.spi.simple; - -import org.hibernate.query.sqm.internal.DomainParameterXref; -import org.hibernate.query.sqm.mutation.spi.AbstractMutationHandler; -import org.hibernate.query.sqm.mutation.spi.DeleteHandler; -import org.hibernate.query.sqm.mutation.spi.HandlerCreationContext; -import org.hibernate.query.sqm.mutation.spi.SqmMutationStrategy; -import org.hibernate.query.sqm.mutation.spi.UpdateHandler; -import org.hibernate.query.sqm.tree.delete.SqmDeleteStatement; -import org.hibernate.query.sqm.tree.update.SqmUpdateStatement; - -/** - * @author Steve Ebersole - */ -public class SimpleSqmMutationStrategy implements SqmMutationStrategy { - @Override - public UpdateHandler buildUpdateHandler( - SqmUpdateStatement sqmUpdateStatement, - DomainParameterXref domainParameterXref, - HandlerCreationContext creationContext) { - return new SimpleUpdateHandler( sqmUpdateStatement, domainParameterXref, creationContext ); - } - - @Override - public DeleteHandler buildDeleteHandler( - SqmDeleteStatement sqmDeleteStatement, - DomainParameterXref domainParameterXref, - HandlerCreationContext creationContext) { - return new SimpleDeleteHandler( sqmDeleteStatement, domainParameterXref, creationContext ); - } -} diff --git a/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/simple/SimpleUpdateHandler.java b/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/simple/SimpleUpdateHandler.java deleted file mode 100644 index 403840456a..0000000000 --- a/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/simple/SimpleUpdateHandler.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Hibernate, Relational Persistence for Idiomatic Java - * - * License: GNU Lesser General Public License (LGPL), version 2.1 or later - * See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html - */ -package org.hibernate.query.sqm.mutation.spi.simple; - -import org.hibernate.NotYetImplementedFor6Exception; -import org.hibernate.query.sqm.internal.DomainParameterXref; -import org.hibernate.query.sqm.mutation.spi.AbstractMutationHandler; -import org.hibernate.query.sqm.mutation.spi.HandlerCreationContext; -import org.hibernate.query.sqm.mutation.spi.UpdateHandler; -import org.hibernate.query.sqm.tree.update.SqmUpdateStatement; -import org.hibernate.sql.exec.spi.ExecutionContext; - -/** - * @author Steve Ebersole - */ -public class SimpleUpdateHandler extends AbstractMutationHandler implements UpdateHandler { - private final SqmUpdateStatement sqmStatement; - private final DomainParameterXref domainParameterXref; - - public SimpleUpdateHandler( - SqmUpdateStatement sqmStatement, - DomainParameterXref domainParameterXref, - HandlerCreationContext creationContext) { - super( sqmStatement, creationContext ); - this.sqmStatement = sqmStatement; - this.domainParameterXref = domainParameterXref; - } - - @Override - public int execute(ExecutionContext executionContext) { - throw new NotYetImplementedFor6Exception( ); - } -} diff --git a/hibernate-core/src/main/java/org/hibernate/query/sqm/produce/function/internal/PatternRenderer.java b/hibernate-core/src/main/java/org/hibernate/query/sqm/produce/function/internal/PatternRenderer.java index e2919995cc..ac87f923de 100644 --- a/hibernate-core/src/main/java/org/hibernate/query/sqm/produce/function/internal/PatternRenderer.java +++ b/hibernate-core/src/main/java/org/hibernate/query/sqm/produce/function/internal/PatternRenderer.java @@ -14,7 +14,7 @@ import java.util.Set; import org.hibernate.engine.spi.SessionFactoryImplementor; import org.hibernate.internal.CoreLogging; import org.hibernate.internal.CoreMessageLogger; -import org.hibernate.sql.ast.consume.spi.SqlAppender; +import org.hibernate.sql.ast.spi.SqlAppender; import org.hibernate.sql.ast.spi.SqlAstWalker; import org.hibernate.sql.ast.tree.SqlAstNode; diff --git a/hibernate-core/src/main/java/org/hibernate/query/sqm/produce/function/internal/SelfRenderingFunctionSqlAstExpression.java b/hibernate-core/src/main/java/org/hibernate/query/sqm/produce/function/internal/SelfRenderingFunctionSqlAstExpression.java deleted file mode 100644 index 3bacf1d105..0000000000 --- a/hibernate-core/src/main/java/org/hibernate/query/sqm/produce/function/internal/SelfRenderingFunctionSqlAstExpression.java +++ /dev/null @@ -1,121 +0,0 @@ -/* - * Hibernate, Relational Persistence for Idiomatic Java - * - * License: GNU Lesser General Public License (LGPL), version 2.1 or later - * See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html - */ -package org.hibernate.query.sqm.produce.function.internal; - -import java.util.ArrayList; -import java.util.List; - -import org.hibernate.engine.spi.SessionFactoryImplementor; -import org.hibernate.query.sqm.tree.SqmTypedNode; -import org.hibernate.query.sqm.tree.SqmVisitableNode; -import org.hibernate.sql.SqlExpressableType; -import org.hibernate.sql.ast.consume.spi.SelfRenderingExpression; -import org.hibernate.sql.ast.consume.spi.SqlAppender; -import org.hibernate.sql.ast.spi.SqlAstWalker; -import org.hibernate.sql.ast.produce.spi.SqlExpressable; -import org.hibernate.sql.ast.produce.sqm.spi.SqmExpressionInterpretation; -import org.hibernate.sql.ast.produce.sqm.spi.SqmToSqlAstConverter; -import org.hibernate.sql.ast.tree.SqlAstNode; -import org.hibernate.sql.results.internal.SqlSelectionImpl; -import org.hibernate.sql.results.internal.domain.basic.BasicResultImpl; -import org.hibernate.sql.results.spi.DomainResult; -import org.hibernate.sql.results.spi.DomainResultCreationState; -import org.hibernate.sql.results.spi.DomainResultProducer; -import org.hibernate.sql.results.spi.Selectable; -import org.hibernate.sql.ast.spi.SqlSelection; -import org.hibernate.type.descriptor.java.spi.BasicJavaDescriptor; -import org.hibernate.type.spi.TypeConfiguration; - -import static java.util.Collections.emptyList; - -/** - * Representation of a function call in the SQL AST for impls that know how to - * render themselves. - * - * @author Steve Ebersole - */ -public class SelfRenderingFunctionSqlAstExpression - implements SelfRenderingExpression, Selectable, SqlExpressable, DomainResultProducer { - private final SelfRenderingSqmFunction sqmExpression; - private final List sqlAstArguments; - private final SqlExpressableType type; - - SelfRenderingFunctionSqlAstExpression( - SelfRenderingSqmFunction sqmFunction, - SqmToSqlAstConverter walker) { - this.sqmExpression = sqmFunction; - this.sqlAstArguments = resolveSqlAstArguments( sqmFunction.getArguments(), walker ); - this.type = sqmFunction.getNodeType().getSqlExpressableType(); - } - - private static List resolveSqlAstArguments(List> sqmArguments, SqmToSqlAstConverter walker) { - if ( sqmArguments == null || sqmArguments.isEmpty() ) { - return emptyList(); - } - - final ArrayList sqlAstArguments = new ArrayList<>(); - for ( SqmTypedNode sqmArgument : sqmArguments ) { - sqlAstArguments.add( toSqlAstNode( ((SqmVisitableNode) sqmArgument).accept( walker ), walker ) ); - } - return sqlAstArguments; - } - - private static SqlAstNode toSqlAstNode(Object arg, SqmToSqlAstConverter walker) { - if (arg instanceof SqmExpressionInterpretation) { - return ( (SqmExpressionInterpretation) arg ).toSqlExpression( walker ); - } - return (SqlAstNode) arg; - } - - @Override - public SqlExpressableType getExpressableType() { - return type; - } - - @Override - public SqlExpressableType getType() { - return type; - } - - @Override - public SqlSelection createSqlSelection( - int jdbcPosition, - int valuesArrayPosition, - BasicJavaDescriptor javaTypeDescriptor, - TypeConfiguration typeConfiguration) { - return new SqlSelectionImpl( - jdbcPosition, - valuesArrayPosition, - this, - getExpressableType() - ); - } - - - @Override - public DomainResult createDomainResult( - String resultVariable, - DomainResultCreationState creationState) { - return new BasicResultImpl( - resultVariable, - creationState.getSqlExpressionResolver().resolveSqlSelection( - this, - getExpressableType().getJavaTypeDescriptor(), - creationState.getSqlAstCreationState().getCreationContext().getDomainModel().getTypeConfiguration() - ), - getExpressableType() - ); - } - - @Override - public void renderToSql( - SqlAppender sqlAppender, - SqlAstWalker walker, - SessionFactoryImplementor sessionFactory) { - sqmExpression.getRenderingSupport().render( sqlAppender, sqlAstArguments, walker, sessionFactory ); - } -} diff --git a/hibernate-core/src/main/java/org/hibernate/query/sqm/produce/function/internal/SelfRenderingSqmFunction.java b/hibernate-core/src/main/java/org/hibernate/query/sqm/produce/function/internal/SelfRenderingSqmFunction.java index ae69e07b56..a6af6802a6 100644 --- a/hibernate-core/src/main/java/org/hibernate/query/sqm/produce/function/internal/SelfRenderingSqmFunction.java +++ b/hibernate-core/src/main/java/org/hibernate/query/sqm/produce/function/internal/SelfRenderingSqmFunction.java @@ -6,15 +6,14 @@ */ package org.hibernate.query.sqm.produce.function.internal; +import java.util.List; + import org.hibernate.metamodel.model.domain.AllowableFunctionReturnType; import org.hibernate.query.sqm.NodeBuilder; import org.hibernate.query.sqm.produce.function.spi.SelfRenderingFunctionSupport; import org.hibernate.query.sqm.tree.SqmTypedNode; import org.hibernate.query.sqm.tree.expression.AbstractSqmExpression; import org.hibernate.query.sqm.tree.expression.function.SqmFunction; -import org.hibernate.sql.ast.produce.sqm.spi.SqmToSqlAstConverter; - -import java.util.List; /** * @author Steve Ebersole @@ -49,11 +48,6 @@ public class SelfRenderingSqmFunction extends AbstractSqmExpression implem return renderingSupport; } - @Override - public SelfRenderingFunctionSqlAstExpression convertToSqlAst(SqmToSqlAstConverter walker) { - return new SelfRenderingFunctionSqlAstExpression<>( this, walker ); - } - @Override public String getFunctionName() { return name; diff --git a/hibernate-core/src/main/java/org/hibernate/query/sqm/produce/function/spi/FunctionAsExpressionTemplate.java b/hibernate-core/src/main/java/org/hibernate/query/sqm/produce/function/spi/FunctionAsExpressionTemplate.java index 2c44be2cda..8cd7303d4c 100644 --- a/hibernate-core/src/main/java/org/hibernate/query/sqm/produce/function/spi/FunctionAsExpressionTemplate.java +++ b/hibernate-core/src/main/java/org/hibernate/query/sqm/produce/function/spi/FunctionAsExpressionTemplate.java @@ -14,7 +14,7 @@ import org.hibernate.query.spi.QueryEngine; import org.hibernate.query.sqm.produce.function.ArgumentsValidator; import org.hibernate.query.sqm.produce.function.FunctionReturnTypeResolver; import org.hibernate.query.sqm.tree.SqmTypedNode; -import org.hibernate.sql.ast.consume.spi.SqlAppender; +import org.hibernate.sql.ast.spi.SqlAppender; import org.hibernate.sql.ast.spi.SqlAstWalker; import org.hibernate.sql.ast.tree.SqlAstNode; diff --git a/hibernate-core/src/main/java/org/hibernate/query/sqm/produce/function/spi/NamedSqmFunctionTemplate.java b/hibernate-core/src/main/java/org/hibernate/query/sqm/produce/function/spi/NamedSqmFunctionTemplate.java index 2f59dee153..28a87274b3 100644 --- a/hibernate-core/src/main/java/org/hibernate/query/sqm/produce/function/spi/NamedSqmFunctionTemplate.java +++ b/hibernate-core/src/main/java/org/hibernate/query/sqm/produce/function/spi/NamedSqmFunctionTemplate.java @@ -12,7 +12,7 @@ import org.hibernate.query.spi.QueryEngine; import org.hibernate.query.sqm.produce.function.ArgumentsValidator; import org.hibernate.query.sqm.produce.function.FunctionReturnTypeResolver; import org.hibernate.query.sqm.tree.SqmTypedNode; -import org.hibernate.sql.ast.consume.spi.SqlAppender; +import org.hibernate.sql.ast.spi.SqlAppender; import org.hibernate.sql.ast.spi.SqlAstWalker; import org.hibernate.sql.ast.tree.SqlAstNode; diff --git a/hibernate-core/src/main/java/org/hibernate/query/sqm/produce/function/spi/PatternBasedSqmFunctionTemplate.java b/hibernate-core/src/main/java/org/hibernate/query/sqm/produce/function/spi/PatternBasedSqmFunctionTemplate.java index b9413c6bdb..cbc7e15328 100755 --- a/hibernate-core/src/main/java/org/hibernate/query/sqm/produce/function/spi/PatternBasedSqmFunctionTemplate.java +++ b/hibernate-core/src/main/java/org/hibernate/query/sqm/produce/function/spi/PatternBasedSqmFunctionTemplate.java @@ -14,7 +14,7 @@ import org.hibernate.query.sqm.produce.function.FunctionReturnTypeResolver; import org.hibernate.query.sqm.produce.function.StandardArgumentsValidators; import org.hibernate.query.sqm.produce.function.internal.PatternRenderer; import org.hibernate.query.sqm.tree.SqmTypedNode; -import org.hibernate.sql.ast.consume.spi.SqlAppender; +import org.hibernate.sql.ast.spi.SqlAppender; import org.hibernate.sql.ast.spi.SqlAstWalker; import org.hibernate.sql.ast.tree.SqlAstNode; diff --git a/hibernate-core/src/main/java/org/hibernate/query/sqm/produce/function/spi/SelfRenderingFunctionSupport.java b/hibernate-core/src/main/java/org/hibernate/query/sqm/produce/function/spi/SelfRenderingFunctionSupport.java index 3980380cca..085222b8bb 100644 --- a/hibernate-core/src/main/java/org/hibernate/query/sqm/produce/function/spi/SelfRenderingFunctionSupport.java +++ b/hibernate-core/src/main/java/org/hibernate/query/sqm/produce/function/spi/SelfRenderingFunctionSupport.java @@ -7,7 +7,7 @@ package org.hibernate.query.sqm.produce.function.spi; import org.hibernate.engine.spi.SessionFactoryImplementor; -import org.hibernate.sql.ast.consume.spi.SqlAppender; +import org.hibernate.sql.ast.spi.SqlAppender; import org.hibernate.sql.ast.spi.SqlAstWalker; import org.hibernate.sql.ast.tree.SqlAstNode; diff --git a/hibernate-core/src/main/java/org/hibernate/query/sqm/tree/expression/SqmUnaryOperation.java b/hibernate-core/src/main/java/org/hibernate/query/sqm/tree/expression/SqmUnaryOperation.java index 3a60fbc056..2011bb2370 100644 --- a/hibernate-core/src/main/java/org/hibernate/query/sqm/tree/expression/SqmUnaryOperation.java +++ b/hibernate-core/src/main/java/org/hibernate/query/sqm/tree/expression/SqmUnaryOperation.java @@ -7,8 +7,8 @@ package org.hibernate.query.sqm.tree.expression; import org.hibernate.query.UnaryArithmeticOperator; +import org.hibernate.query.sqm.SqmExpressable; import org.hibernate.query.sqm.consume.spi.SemanticQueryWalker; -import org.hibernate.sql.ast.produce.metamodel.spi.BasicValuedExpressableType; /** * @author Steve Ebersole @@ -20,13 +20,13 @@ public class SqmUnaryOperation extends AbstractSqmExpression { public SqmUnaryOperation( UnaryArithmeticOperator operation, SqmExpression operand) { - this( operation, operand, (BasicValuedExpressableType) operand.getNodeType() ); + this( operation, operand, operand.getNodeType() ); } public SqmUnaryOperation( UnaryArithmeticOperator operation, SqmExpression operand, - BasicValuedExpressableType inherentType) { + SqmExpressable inherentType) { super( inherentType, operand.nodeBuilder() ); this.operation = operation; this.operand = operand; @@ -40,11 +40,6 @@ public class SqmUnaryOperation extends AbstractSqmExpression { return operation; } - @Override - public BasicValuedExpressableType getNodeType() { - return (BasicValuedExpressableType) super.getNodeType(); - } - @Override public X accept(SemanticQueryWalker walker) { return walker.visitUnaryOperationExpression( this ); diff --git a/hibernate-core/src/main/java/org/hibernate/query/sqm/tree/expression/function/SqmFunction.java b/hibernate-core/src/main/java/org/hibernate/query/sqm/tree/expression/function/SqmFunction.java index b7b2d1605d..7b5fc8f334 100644 --- a/hibernate-core/src/main/java/org/hibernate/query/sqm/tree/expression/function/SqmFunction.java +++ b/hibernate-core/src/main/java/org/hibernate/query/sqm/tree/expression/function/SqmFunction.java @@ -9,9 +9,6 @@ package org.hibernate.query.sqm.tree.expression.function; import org.hibernate.query.criteria.JpaFunction; import org.hibernate.query.sqm.consume.spi.SemanticQueryWalker; import org.hibernate.query.sqm.tree.expression.SqmExpression; -import org.hibernate.sql.ast.produce.sqm.spi.SqmToSqlAstConverter; -import org.hibernate.sql.ast.tree.expression.Expression; -import org.hibernate.sql.results.spi.DomainResultProducer; /** * Contract for functions impls that would like to control the @@ -24,16 +21,16 @@ import org.hibernate.sql.results.spi.DomainResultProducer; * @author Steve Ebersole */ public interface SqmFunction extends SqmExpression, JpaFunction { - /** - * Generate the SQL AST form of the function as an expression. - * - * To be able to use this in the select-clause, the returned - * expression must also implement the - * {@link DomainResultProducer} - * contract - */ - Expression convertToSqlAst(SqmToSqlAstConverter walker); - +// /** +// * Generate the SQL AST form of the function as an expression. +// * +// * To be able to use this in the select-clause, the returned +// * expression must also implement the +// * {@link DomainResultProducer} +// * contract +// */ +// Expression convertToSqlAst(SqmToSqlAstConverter walker); +// @Override default X accept(SemanticQueryWalker walker) { return walker.visitFunction( this ); diff --git a/hibernate-core/src/main/java/org/hibernate/query/sqm/tree/expression/function/SqmStar.java b/hibernate-core/src/main/java/org/hibernate/query/sqm/tree/expression/function/SqmStar.java index 076123080e..6dd0f27d0f 100644 --- a/hibernate-core/src/main/java/org/hibernate/query/sqm/tree/expression/function/SqmStar.java +++ b/hibernate-core/src/main/java/org/hibernate/query/sqm/tree/expression/function/SqmStar.java @@ -8,11 +8,7 @@ package org.hibernate.query.sqm.tree.expression.function; import org.hibernate.query.sqm.NodeBuilder; import org.hibernate.query.sqm.consume.spi.SemanticQueryWalker; -import org.hibernate.query.sqm.tree.AbstractSqmNode; -import org.hibernate.query.sqm.tree.SqmTypedNode; -import org.hibernate.query.sqm.tree.SqmVisitableNode; import org.hibernate.query.sqm.tree.expression.AbstractSqmExpression; -import org.hibernate.sql.ast.produce.metamodel.spi.ExpressableType; /** * @author Gavin King diff --git a/hibernate-core/src/main/java/org/hibernate/result/internal/OutputsImpl.java b/hibernate-core/src/main/java/org/hibernate/result/internal/OutputsImpl.java index 197b4c95fc..f611b264b6 100644 --- a/hibernate-core/src/main/java/org/hibernate/result/internal/OutputsImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/result/internal/OutputsImpl.java @@ -16,6 +16,7 @@ import java.util.Set; import java.util.function.Supplier; import org.hibernate.JDBCException; +import org.hibernate.engine.spi.QueryParameters; import org.hibernate.engine.spi.SharedSessionContractImplementor; import org.hibernate.internal.CoreLogging; import org.hibernate.loader.EntityAliases; diff --git a/hibernate-core/src/main/java/org/hibernate/service/StandardServiceInitiators.java b/hibernate-core/src/main/java/org/hibernate/service/StandardServiceInitiators.java index b0ed1484ec..df7a891f3a 100644 --- a/hibernate-core/src/main/java/org/hibernate/service/StandardServiceInitiators.java +++ b/hibernate-core/src/main/java/org/hibernate/service/StandardServiceInitiators.java @@ -26,7 +26,6 @@ import org.hibernate.engine.jndi.internal.JndiServiceInitiator; import org.hibernate.engine.transaction.jta.platform.internal.JtaPlatformInitiator; import org.hibernate.engine.transaction.jta.platform.internal.JtaPlatformResolverInitiator; import org.hibernate.event.internal.EntityCopyObserverFactoryInitiator; -import org.hibernate.hql.internal.QueryTranslatorFactoryInitiator; import org.hibernate.id.factory.internal.MutableIdentifierGeneratorFactoryInitiator; import org.hibernate.jmx.internal.JmxServiceInitiator; import org.hibernate.persister.internal.PersisterClassResolverInitiator; @@ -74,7 +73,6 @@ public final class StandardServiceInitiators { serviceInitiators.add( JdbcServicesInitiator.INSTANCE ); serviceInitiators.add( RefCursorSupportInitiator.INSTANCE ); - serviceInitiators.add( QueryTranslatorFactoryInitiator.INSTANCE ); serviceInitiators.add( MutableIdentifierGeneratorFactoryInitiator.INSTANCE); serviceInitiators.add( JtaPlatformResolverInitiator.INSTANCE ); diff --git a/hibernate-core/src/main/java/org/hibernate/sql/Template.java b/hibernate-core/src/main/java/org/hibernate/sql/Template.java index 31c1d400ee..7256fe8d1d 100644 --- a/hibernate-core/src/main/java/org/hibernate/sql/Template.java +++ b/hibernate-core/src/main/java/org/hibernate/sql/Template.java @@ -17,14 +17,7 @@ import org.hibernate.HibernateException; import org.hibernate.dialect.Dialect; import org.hibernate.dialect.function.SQLFunction; import org.hibernate.dialect.function.SQLFunctionRegistry; -import org.hibernate.engine.spi.SessionFactoryImplementor; import org.hibernate.internal.util.StringHelper; -import org.hibernate.sql.ordering.antlr.ColumnMapper; -import org.hibernate.sql.ordering.antlr.OrderByAliasResolver; -import org.hibernate.sql.ordering.antlr.OrderByFragmentTranslator; -import org.hibernate.sql.ordering.antlr.OrderByTranslation; -import org.hibernate.sql.ordering.antlr.SqlValueReference; -import org.hibernate.sql.ordering.antlr.TranslationContext; /** * Parses SQL fragments specified in mapping documents @@ -628,102 +621,6 @@ public final class Template { return valueBuilder.toString().trim(); } - public static class NoOpColumnMapper implements ColumnMapper { - public static final NoOpColumnMapper INSTANCE = new NoOpColumnMapper(); - public SqlValueReference[] map(String reference) { -// return new String[] { reference }; - return null; - } - } - - /** - * Performs order-by template rendering without {@link ColumnMapper column mapping}. An ORDER BY template - * has all column references "qualified" with a placeholder identified by {@link Template#TEMPLATE} - * - * @param orderByFragment The order-by fragment to render. - * @param dialect The SQL dialect being used. - * @param functionRegistry The SQL function registry - * - * @return The rendered ORDER BY template. - * - * @deprecated Use {@link #translateOrderBy} instead - */ - @Deprecated - public static String renderOrderByStringTemplate( - String orderByFragment, - Dialect dialect, - SQLFunctionRegistry functionRegistry) { - return renderOrderByStringTemplate( - orderByFragment, - NoOpColumnMapper.INSTANCE, - null, - dialect, - functionRegistry - ); - } - - public static String renderOrderByStringTemplate( - String orderByFragment, - final ColumnMapper columnMapper, - final SessionFactoryImplementor sessionFactory, - final Dialect dialect, - final SQLFunctionRegistry functionRegistry) { - return translateOrderBy( - orderByFragment, - columnMapper, - sessionFactory, - dialect, - functionRegistry - ).injectAliases( LEGACY_ORDER_BY_ALIAS_RESOLVER ); - } - - public static final OrderByAliasResolver LEGACY_ORDER_BY_ALIAS_RESOLVER = new OrderByAliasResolver() { - @Override - public String resolveTableAlias(String columnReference) { - return TEMPLATE; - } - }; - - /** - * Performs order-by template rendering allowing {@link ColumnMapper column mapping}. An ORDER BY template - * has all column references "qualified" with a placeholder identified by {@link Template#TEMPLATE} which can later - * be used to easily inject the SQL alias. - * - * @param orderByFragment The order-by fragment to render. - * @param columnMapper The column mapping strategy to use. - * @param sessionFactory The session factory. - * @param dialect The SQL dialect being used. - * @param functionRegistry The SQL function registry - * - * @return The rendered ORDER BY template. - */ - public static OrderByTranslation translateOrderBy( - String orderByFragment, - final ColumnMapper columnMapper, - final SessionFactoryImplementor sessionFactory, - final Dialect dialect, - final SQLFunctionRegistry functionRegistry) { - TranslationContext context = new TranslationContext() { - public SessionFactoryImplementor getSessionFactory() { - return sessionFactory; - } - - public Dialect getDialect() { - return dialect; - } - - public SQLFunctionRegistry getSqlFunctionRegistry() { - return functionRegistry; - } - - public ColumnMapper getColumnMapper() { - return columnMapper; - } - }; - - return OrderByFragmentTranslator.translate( context, orderByFragment ); - } - private static boolean isNamedParameter(String token) { return token.startsWith( ":" ); } diff --git a/hibernate-core/src/main/java/org/hibernate/sql/ast/spi/SqlAstWalker.java b/hibernate-core/src/main/java/org/hibernate/sql/ast/spi/SqlAstWalker.java index 1e1f89f820..6746ace60b 100644 --- a/hibernate-core/src/main/java/org/hibernate/sql/ast/spi/SqlAstWalker.java +++ b/hibernate-core/src/main/java/org/hibernate/sql/ast/spi/SqlAstWalker.java @@ -16,6 +16,8 @@ import org.hibernate.sql.ast.tree.expression.SqlTuple; import org.hibernate.sql.ast.tree.from.FromClause; import org.hibernate.sql.ast.tree.from.TableGroup; import org.hibernate.sql.ast.tree.from.TableGroupJoin; +import org.hibernate.sql.ast.tree.from.TableReference; +import org.hibernate.sql.ast.tree.from.TableReferenceJoin; import org.hibernate.sql.ast.tree.predicate.BetweenPredicate; import org.hibernate.sql.ast.tree.predicate.ComparisonPredicate; import org.hibernate.sql.ast.tree.predicate.FilterPredicate; diff --git a/hibernate-core/src/main/java/org/hibernate/sql/ast/spi/SqlExpressionResolver.java b/hibernate-core/src/main/java/org/hibernate/sql/ast/spi/SqlExpressionResolver.java index 5570bc4dd0..8a47d8655f 100644 --- a/hibernate-core/src/main/java/org/hibernate/sql/ast/spi/SqlExpressionResolver.java +++ b/hibernate-core/src/main/java/org/hibernate/sql/ast/spi/SqlExpressionResolver.java @@ -28,25 +28,25 @@ import org.hibernate.type.spi.TypeConfiguration; * @author Steve Ebersole */ public interface SqlExpressionResolver { - /** - * Given a qualifier + a qualifiable SqlExpressable, resolve the - * (Sql)Expression reference. - */ - Expression resolveSqlExpression(ColumnReferenceQualifier qualifier, QualifiableSqlExpressable sqlSelectable); - - /** - * Given a SqlExpressable not needing to be qualified, resolve the - * (Sql)Expression reference. - */ - Expression resolveSqlExpression(NonQualifiableSqlExpressable sqlSelectable); - - /** - * Resolve the SqlSelection for the given expression - */ - SqlSelection resolveSqlSelection( - Expression expression, - JavaTypeDescriptor javaTypeDescriptor, - TypeConfiguration typeConfiguration); - - SqlSelection emptySqlSelection(); +// /** +// * Given a qualifier + a qualifiable SqlExpressable, resolve the +// * (Sql)Expression reference. +// */ +// Expression resolveSqlExpression(ColumnReferenceQualifier qualifier, QualifiableSqlExpressable sqlSelectable); +// +// /** +// * Given a SqlExpressable not needing to be qualified, resolve the +// * (Sql)Expression reference. +// */ +// Expression resolveSqlExpression(NonQualifiableSqlExpressable sqlSelectable); +// +// /** +// * Resolve the SqlSelection for the given expression +// */ +// SqlSelection resolveSqlSelection( +// Expression expression, +// JavaTypeDescriptor javaTypeDescriptor, +// TypeConfiguration typeConfiguration); +// +// SqlSelection emptySqlSelection(); } diff --git a/hibernate-core/src/main/java/org/hibernate/sql/ast/spi/SqlSelection.java b/hibernate-core/src/main/java/org/hibernate/sql/ast/spi/SqlSelection.java index ee25275aa6..3f2b9bdf66 100644 --- a/hibernate-core/src/main/java/org/hibernate/sql/ast/spi/SqlSelection.java +++ b/hibernate-core/src/main/java/org/hibernate/sql/ast/spi/SqlSelection.java @@ -10,6 +10,7 @@ import java.util.function.Consumer; import org.hibernate.engine.spi.SessionFactoryImplementor; import org.hibernate.sql.results.spi.JdbcValuesMappingDescriptor; +import org.hibernate.sql.results.spi.JdbcValuesMetadata; import org.hibernate.sql.results.spi.RowProcessingState; import org.hibernate.sql.results.spi.SqlSelectionGroupNode; import org.hibernate.type.descriptor.ValueExtractor; @@ -52,9 +53,7 @@ public interface SqlSelection extends SqlSelectionGroupNode { return getValuesArrayPosition() + 1; } - default void prepare( - JdbcValuesMappingDescriptor.JdbcValuesMetadata jdbcResultsMetadata, - SessionFactoryImplementor sessionFactory) { + default void prepare(JdbcValuesMetadata jdbcResultsMetadata, SessionFactoryImplementor sessionFactory) { // By default we have nothing to do. Here as a hook for NativeQuery mapping resolutions } diff --git a/hibernate-core/src/main/java/org/hibernate/sql/ast/tree/from/TableGroup.java b/hibernate-core/src/main/java/org/hibernate/sql/ast/tree/from/TableGroup.java index e87b09e3a6..e28d46ab11 100644 --- a/hibernate-core/src/main/java/org/hibernate/sql/ast/tree/from/TableGroup.java +++ b/hibernate-core/src/main/java/org/hibernate/sql/ast/tree/from/TableGroup.java @@ -27,7 +27,7 @@ import org.hibernate.sql.results.spi.DomainResultProducer; * * @author Steve Ebersole */ -public interface TableGroup extends SqlAstNode, DomainResultProducer, NavigableReference, ColumnReferenceQualifier { +public interface TableGroup extends SqlAstNode, DomainResultProducer { NavigablePath getNavigablePath(); ModelPart getModelPart(); diff --git a/hibernate-core/src/main/java/org/hibernate/sql/ast/tree/from/TableGroupJoin.java b/hibernate-core/src/main/java/org/hibernate/sql/ast/tree/from/TableGroupJoin.java index 7559602e2e..b8a8e12ff5 100644 --- a/hibernate-core/src/main/java/org/hibernate/sql/ast/tree/from/TableGroupJoin.java +++ b/hibernate-core/src/main/java/org/hibernate/sql/ast/tree/from/TableGroupJoin.java @@ -18,7 +18,7 @@ import org.hibernate.sql.results.spi.DomainResultProducer; /** * @author Steve Ebersole */ -public class TableGroupJoin implements SqlAstNode, DomainResultProducer, SqmExpressionInterpretation { +public class TableGroupJoin implements SqlAstNode, DomainResultProducer { private final NavigablePath navigablePath; private final JoinType joinType; private final TableGroup joinedGroup; @@ -52,16 +52,10 @@ public class TableGroupJoin implements SqlAstNode, DomainResultProducer, SqmExpr sqlTreeWalker.visitTableGroupJoin( this ); } - @Override public NavigablePath getNavigablePath() { return navigablePath; } - @Override - public Navigable getNavigable() { - return joinedGroup.getNavigable(); - } - @Override public DomainResult createDomainResult( int valuesArrayPosition, diff --git a/hibernate-core/src/main/java/org/hibernate/sql/ast/tree/from/TableGroupJoinProducer.java b/hibernate-core/src/main/java/org/hibernate/sql/ast/tree/from/TableGroupJoinProducer.java index 22373172de..5e3024b17f 100644 --- a/hibernate-core/src/main/java/org/hibernate/sql/ast/tree/from/TableGroupJoinProducer.java +++ b/hibernate-core/src/main/java/org/hibernate/sql/ast/tree/from/TableGroupJoinProducer.java @@ -9,6 +9,7 @@ package org.hibernate.sql.ast.tree.from; import org.hibernate.LockMode; import org.hibernate.query.NavigablePath; import org.hibernate.sql.ast.JoinType; +import org.hibernate.sql.ast.spi.SqlAstCreationState; import org.hibernate.sql.ast.tree.from.TableGroup; import org.hibernate.sql.ast.tree.from.TableGroupJoin; diff --git a/hibernate-core/src/main/java/org/hibernate/sql/ast/tree/from/TableReference.java b/hibernate-core/src/main/java/org/hibernate/sql/ast/tree/from/TableReference.java new file mode 100644 index 0000000000..d2fff66be6 --- /dev/null +++ b/hibernate-core/src/main/java/org/hibernate/sql/ast/tree/from/TableReference.java @@ -0,0 +1,116 @@ +/* + * Hibernate, Relational Persistence for Idiomatic Java + * + * License: GNU Lesser General Public License (LGPL), version 2.1 or later + * See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html + */ +package org.hibernate.sql.ast.tree.from; + +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; + +import org.hibernate.boot.model.naming.Identifier; +import org.hibernate.sql.ast.spi.SqlAstWalker; +import org.hibernate.sql.ast.tree.SqlAstNode; +import org.hibernate.sql.ast.tree.expression.ColumnReference; + +/** + * Represents a reference to a table (derived or physical) in a query's from clause. + * + * @author Steve Ebersole + */ +public class TableReference implements SqlAstNode { + private final String tableName; + private final String identificationVariable; + + private final boolean isOptional; + + private final Map columnReferenceResolutionMap = new HashMap<>(); + + public TableReference(String tableName, String identificationVariable, boolean isOptional) { + this.tableName = tableName; + this.identificationVariable = identificationVariable; + this.isOptional = isOptional; + } + + public String getTableName() { + return tableName; + } + + public String getIdentificationVariable() { + return identificationVariable; + } + + public boolean isOptional() { + return isOptional; + } + + @Override + public void accept(SqlAstWalker sqlTreeWalker) { + sqlTreeWalker.visitTableReference( this ); + } + +// @Override +// public TableReference locateTableReference(Table table) { +// if ( table.equals( getTableName() ) ) { +// return this; +// } +// return null; +// } +// +// @Override +// public ColumnReference resolveColumnReference(Column column) { +// final ColumnReference existing = columnReferenceResolutionMap.get( column ); +// if ( existing != null ) { +// return existing; +// } +// +// final ColumnReference columnReference = new ColumnReference( this, column ); +// columnReferenceResolutionMap.put( column, columnReference ); +// return columnReference; +// } +// +// @Override +// public ColumnReference resolveColumnReference(String columnName) { +// return resolveColumnReference( getTableName().getColumn( columnName ) ); +// } +// +// @Override +// public Column resolveColumn(String columnName) { +// return getTableName().getColumn( columnName ); +// } +// +// @Override +// public Expression qualify(QualifiableSqlExpressable sqlSelectable) { +// assert sqlSelectable instanceof Column; +// return resolveColumnReference( (Column) sqlSelectable ); +// } +// +// @Override +// public String toLoggableFragment() { +// return getTableName().toLoggableFragment() + "(" + getIdentificationVariable() + ')'; +// } + + @Override + public String toString() { + return getTableName() + "(" + getIdentificationVariable() + ')'; + } + + @Override + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( o == null || getClass() != o.getClass() ) { + return false; + } + TableReference that = (TableReference) o; + return Objects.equals( identificationVariable, that.identificationVariable ); + } + + @Override + public int hashCode() { + return Objects.hash( identificationVariable ); + } +} diff --git a/hibernate-core/src/main/java/org/hibernate/sql/ast/tree/from/TableReferenceContributor.java b/hibernate-core/src/main/java/org/hibernate/sql/ast/tree/from/TableReferenceContributor.java index 0482ee467e..1a3c63bf57 100644 --- a/hibernate-core/src/main/java/org/hibernate/sql/ast/tree/from/TableReferenceContributor.java +++ b/hibernate-core/src/main/java/org/hibernate/sql/ast/tree/from/TableReferenceContributor.java @@ -6,19 +6,19 @@ */ package org.hibernate.sql.ast.tree.from; -import org.hibernate.metamodel.model.mapping.spi.TableReferenceJoinCollector; import org.hibernate.sql.ast.JoinType; +import org.hibernate.sql.ast.spi.SqlAliasBase; /** * @author Steve Ebersole */ public interface TableReferenceContributor { - /** - * Apply the Tables mapped by this producer to the collector as TableReferences - */ - void applyTableReferenceJoins( - ColumnReferenceQualifier lhs, - JoinType joinType, - SqlAliasBase sqlAliasBase, - TableReferenceJoinCollector joinCollector); +// /** +// * Apply the Tables mapped by this producer to the collector as TableReferences +// */ +// void applyTableReferenceJoins( +// ColumnReferenceQualifier lhs, +// JoinType joinType, +// SqlAliasBase sqlAliasBase, +// TableReferenceJoinCollector joinCollector); } diff --git a/hibernate-core/src/main/java/org/hibernate/sql/ast/tree/from/TableReferenceJoin.java b/hibernate-core/src/main/java/org/hibernate/sql/ast/tree/from/TableReferenceJoin.java new file mode 100644 index 0000000000..f4a5e07fc1 --- /dev/null +++ b/hibernate-core/src/main/java/org/hibernate/sql/ast/tree/from/TableReferenceJoin.java @@ -0,0 +1,57 @@ +/* + * Hibernate, Relational Persistence for Idiomatic Java + * + * License: GNU Lesser General Public License (LGPL), version 2.1 or later + * See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html + */ +package org.hibernate.sql.ast.tree.from; + +import org.hibernate.sql.ast.JoinType; +import org.hibernate.sql.ast.spi.SqlAstWalker; +import org.hibernate.sql.ast.tree.SqlAstNode; +import org.hibernate.sql.ast.tree.predicate.Predicate; + +/** + * Represents a join to a {@link TableReference}; roughly equivalent to a SQL join. + * + * @author Steve Ebersole + */ +public class TableReferenceJoin implements SqlAstNode { + private final JoinType joinType; + private final TableReference joinedTableBinding; + private final Predicate predicate; + + public TableReferenceJoin(JoinType joinType, TableReference joinedTableBinding, Predicate predicate) { + this.joinType = joinType; + this.joinedTableBinding = joinedTableBinding; + this.predicate = predicate; + +// if ( joinType == JoinType.CROSS ) { +// if ( predicate != null ) { +// throw new IllegalJoinSpecificationException( "Cross join cannot include join predicate" ); +// } +// } + } + + public JoinType getJoinType() { + return joinType; + } + + public TableReference getJoinedTableReference() { + return joinedTableBinding; + } + + public Predicate getJoinPredicate() { + return predicate; + } + + @Override + public void accept(SqlAstWalker sqlTreeWalker) { + sqlTreeWalker.visitTableReferenceJoin( this ); + } + + @Override + public String toString() { + return getJoinType().getText() + " join " + getJoinedTableReference().toString(); + } +} diff --git a/hibernate-core/src/main/java/org/hibernate/sql/ast/tree/update/UpdateStatement.java b/hibernate-core/src/main/java/org/hibernate/sql/ast/tree/update/UpdateStatement.java index 028ff69138..875fe4c0a2 100644 --- a/hibernate-core/src/main/java/org/hibernate/sql/ast/tree/update/UpdateStatement.java +++ b/hibernate-core/src/main/java/org/hibernate/sql/ast/tree/update/UpdateStatement.java @@ -12,6 +12,7 @@ import java.util.List; import org.hibernate.sql.ast.spi.SqlAstTreeHelper; import org.hibernate.sql.ast.tree.MutationStatement; +import org.hibernate.sql.ast.tree.from.TableReference; import org.hibernate.sql.ast.tree.predicate.Predicate; import org.hibernate.sql.ast.tree.predicate.PredicateContainer; @@ -73,12 +74,12 @@ public class UpdateStatement implements MutationStatement { return this; } - public SqlAstUpdateDescriptor createUpdateDescriptor() { - return new SqlAstUpdateDescriptorImpl( - createUpdateAst(), - Collections.singleton( targetTableRef.getTable().getTableExpression() ) - ); - } +// public SqlAstUpdateDescriptor createUpdateDescriptor() { +// return new SqlAstUpdateDescriptorImpl( +// createUpdateAst(), +// Collections.singleton( targetTableRef.getTable().getTableExpression() ) +// ); +// } public UpdateStatement createUpdateAst() { if ( assignments == null || assignments.isEmpty() ) { diff --git a/hibernate-core/src/main/java/org/hibernate/sql/exec/spi/JdbcCall.java b/hibernate-core/src/main/java/org/hibernate/sql/exec/spi/JdbcCall.java index 31c8beee4f..be713935e0 100644 --- a/hibernate-core/src/main/java/org/hibernate/sql/exec/spi/JdbcCall.java +++ b/hibernate-core/src/main/java/org/hibernate/sql/exec/spi/JdbcCall.java @@ -12,27 +12,27 @@ import java.util.List; * @author Steve Ebersole */ public interface JdbcCall extends JdbcAnonBlock { - /** - * If the call is a function, returns the function return descriptor - */ - JdbcCallFunctionReturn getFunctionReturn(); - - /** - * Get the list of any parameter registrations we need to register - * against the generated CallableStatement - */ - List getParameterRegistrations(); - - /** - * Extractors for reading back any OUT/INOUT parameters. - * - * @apiNote Note that REF_CURSOR parameters should be handled via - * {@link #getCallRefCursorExtractors()} - */ - List getParameterExtractors(); - - /** - * Extractors for REF_CURSOR (ResultSet) parameters - */ - List getCallRefCursorExtractors(); +// /** +// * If the call is a function, returns the function return descriptor +// */ +// JdbcCallFunctionReturn getFunctionReturn(); +// +// /** +// * Get the list of any parameter registrations we need to register +// * against the generated CallableStatement +// */ +// List getParameterRegistrations(); +// +// /** +// * Extractors for reading back any OUT/INOUT parameters. +// * +// * @apiNote Note that REF_CURSOR parameters should be handled via +// * {@link #getCallRefCursorExtractors()} +// */ +// List getParameterExtractors(); +// +// /** +// * Extractors for REF_CURSOR (ResultSet) parameters +// */ +// List getCallRefCursorExtractors(); } diff --git a/hibernate-core/src/main/java/org/hibernate/sql/results/internal/JdbcValuesMappingProducerDefined.java b/hibernate-core/src/main/java/org/hibernate/sql/results/internal/JdbcValuesMappingProducerDefined.java index 8ccd3c4a48..45694a2e7c 100644 --- a/hibernate-core/src/main/java/org/hibernate/sql/results/internal/JdbcValuesMappingProducerDefined.java +++ b/hibernate-core/src/main/java/org/hibernate/sql/results/internal/JdbcValuesMappingProducerDefined.java @@ -9,12 +9,13 @@ package org.hibernate.sql.results.internal; import java.util.List; import java.util.Set; +import org.hibernate.NotYetImplementedFor6Exception; import org.hibernate.engine.spi.SessionFactoryImplementor; +import org.hibernate.sql.ast.spi.SqlSelection; import org.hibernate.sql.results.spi.DomainResult; import org.hibernate.sql.results.spi.JdbcValuesMapping; import org.hibernate.sql.results.spi.JdbcValuesMappingProducer; import org.hibernate.sql.results.spi.JdbcValuesMetadata; -import org.hibernate.sql.ast.spi.SqlSelection; /** * ResultSetMapping for handling selections for a {@link org.hibernate.query.NativeQuery} @@ -40,10 +41,12 @@ public class JdbcValuesMappingProducerDefined implements JdbcValuesMappingProduc JdbcValuesMetadata jdbcResultsMetadata, SessionFactoryImplementor sessionFactory) { - for ( SqlSelection sqlSelection : selections ) { - sqlSelection.prepare( jdbcResultsMetadata, sessionFactory ); - } + throw new NotYetImplementedFor6Exception( getClass() ); - return new StandardResultSetMapping( selections, domainResults ); +// for ( SqlSelection sqlSelection : selections ) { +// sqlSelection.prepare( jdbcResultsMetadata, sessionFactory ); +// } +// +// return new StandardResultSetMapping( selections, domainResults ); } } diff --git a/hibernate-core/src/main/java/org/hibernate/sql/results/internal/JdbcValuesMappingProducerLegacy.java b/hibernate-core/src/main/java/org/hibernate/sql/results/internal/JdbcValuesMappingProducerLegacy.java index 73ab0a55e8..1655ce95ab 100644 --- a/hibernate-core/src/main/java/org/hibernate/sql/results/internal/JdbcValuesMappingProducerLegacy.java +++ b/hibernate-core/src/main/java/org/hibernate/sql/results/internal/JdbcValuesMappingProducerLegacy.java @@ -6,30 +6,11 @@ */ package org.hibernate.sql.results.internal; -import java.util.List; -import java.util.Map; - import org.hibernate.NotYetImplementedFor6Exception; import org.hibernate.engine.spi.SessionFactoryImplementor; -import org.hibernate.metamodel.model.mapping.EntityTypeDescriptor; -import org.hibernate.metamodel.model.mapping.PersistentCollectionDescriptor; -import org.hibernate.query.NativeQuery; -import org.hibernate.query.sql.spi.ResultSetMappingDescriptor; -import org.hibernate.sql.ast.produce.spi.ColumnReferenceQualifier; -import org.hibernate.sql.ast.tree.from.TableReference; -import org.hibernate.sql.results.spi.CollectionResult; -import org.hibernate.sql.results.spi.DomainResult; -import org.hibernate.sql.results.spi.DynamicInstantiationResult; -import org.hibernate.sql.results.spi.EntityResult; -import org.hibernate.sql.results.spi.Fetch; -import org.hibernate.sql.results.spi.FetchParent; import org.hibernate.sql.results.spi.JdbcValuesMapping; import org.hibernate.sql.results.spi.JdbcValuesMappingProducer; import org.hibernate.sql.results.spi.JdbcValuesMetadata; -import org.hibernate.sql.results.spi.ResultSetMapping; -import org.hibernate.sql.results.spi.ScalarResult; -import org.hibernate.type.descriptor.java.spi.EntityJavaDescriptor; -import org.hibernate.type.descriptor.java.spi.JavaTypeDescriptor; import org.hibernate.type.spi.TypeConfiguration; /** @@ -45,35 +26,35 @@ import org.hibernate.type.spi.TypeConfiguration; public class JdbcValuesMappingProducerLegacy implements JdbcValuesMappingProducer { private final TypeConfiguration typeConfiguration; - private TableReference scalarTableReference; - - private List roots; - private List fetches; - private Map fetchParentsByAlias; +// private TableReference scalarTableReference; +// +// private List roots; +// private List fetches; +// private Map fetchParentsByAlias; public JdbcValuesMappingProducerLegacy(TypeConfiguration typeConfiguration) { this.typeConfiguration = typeConfiguration; } - public RootNodeScalar makeScalarRoot(String alias, JavaTypeDescriptor javaTypeDescriptor) { - throw new NotYetImplementedFor6Exception( getClass() ); - } - - public RootNodeDynamicInstantiation makeDynamicInstantiationRoot(String instantiationTarget) { - throw new NotYetImplementedFor6Exception( getClass() ); - } - - public RootNodeEntity makeEntityRoot(String entityName, String alias) { - throw new NotYetImplementedFor6Exception( getClass() ); - } - - public RootNodeCollection makeCollectionRoot(String collectionRole, String alias) { - throw new NotYetImplementedFor6Exception( getClass() ); - } - - public ResultFetchNode makeFetch(String parentAlias, String relativePath, String fetchAlias) { - throw new NotYetImplementedFor6Exception( getClass() ); - } +// public RootNodeScalar makeScalarRoot(String alias, JavaTypeDescriptor javaTypeDescriptor) { +// throw new NotYetImplementedFor6Exception( getClass() ); +// } +// +// public RootNodeDynamicInstantiation makeDynamicInstantiationRoot(String instantiationTarget) { +// throw new NotYetImplementedFor6Exception( getClass() ); +// } +// +// public RootNodeEntity makeEntityRoot(String entityName, String alias) { +// throw new NotYetImplementedFor6Exception( getClass() ); +// } +// +// public RootNodeCollection makeCollectionRoot(String collectionRole, String alias) { +// throw new NotYetImplementedFor6Exception( getClass() ); +// } +// +// public ResultFetchNode makeFetch(String parentAlias, String relativePath, String fetchAlias) { +// throw new NotYetImplementedFor6Exception( getClass() ); +// } // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -82,10 +63,11 @@ public class JdbcValuesMappingProducerLegacy implements JdbcValuesMappingProduce @Override public JdbcValuesMapping resolve( - JdbcValuesMetadata jdbcResultsMetadata, SessionFactoryImplementor sessionFactory) { - if ( roots == null || roots.isEmpty() ) { - - } + JdbcValuesMetadata jdbcResultsMetadata, + SessionFactoryImplementor sessionFactory) { +// if ( roots == null || roots.isEmpty() ) { +// +// } throw new NotYetImplementedFor6Exception( getClass() ); // final int columnCount = jdbcResultsMetadata.getColumnCount(); @@ -105,92 +87,92 @@ public class JdbcValuesMappingProducerLegacy implements JdbcValuesMappingProduce } - /** - * Simple unification interface for all returns from the various `#addXYZ` methods . - * Allows control over the "shape" of that particular part of the fetch graph. - * - * Some GraphNodes can be query results, while others simply describe a part - * of one of the results, while still others define fetches. - */ - public interface ResultNode extends ColumnReferenceQualifier { - JavaTypeDescriptor getJavaTypeDescriptor(); - } - - /** - * Allows access to further control how properties within a root or join - * fetch are mapped back from the result set. Generally used in composite - * value scenarios. - */ - public interface ReturnProperty extends ResultNode { - /** - * Add a column alias to this property mapping. - * - * @param columnAlias The column alias. - */ - void addColumnAlias(String columnAlias); - } - - - // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - // Specializations - - public interface ScalarNode extends ResultNode { - } - - public interface FetchParentNode extends ResultNode { - String getAlias(); - } - - - // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - // ResultRoot - - /** - * ResultNode which can be a query result - */ - public interface ResultRootNode extends ResultNode { - DomainResult makeQueryResult(); - } - - public interface RootNodeScalar extends ResultRootNode, ScalarNode { - @Override - ScalarResult makeQueryResult(); - } - - public interface RootNodeDynamicInstantiation extends ResultRootNode { - @Override - DynamicInstantiationResult makeQueryResult(); - } - - public interface RootNodeEntity extends ResultRootNode, FetchParentNode, NativeQuery.RootReturn { - EntityTypeDescriptor getEntityDescriptor(); - - @Override - default EntityJavaDescriptor getJavaTypeDescriptor() { - return getEntityDescriptor().getJavaTypeDescriptor(); - } - - @Override - EntityResult makeQueryResult(); - } - - public interface RootNodeCollection extends ResultRootNode, FetchParentNode { - PersistentCollectionDescriptor getCollectionDescriptor(); - - @Override - default JavaTypeDescriptor getJavaTypeDescriptor() { - return getCollectionDescriptor().getJavaTypeDescriptor(); - } - - @Override - CollectionResult makeQueryResult(); - } - - - // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - // FetchResult - - public interface ResultFetchNode extends ResultNode, FetchParentNode, NativeQuery.FetchReturn { - Fetch makeFetch(FetchParent parent); - } +// /** +// * Simple unification interface for all returns from the various `#addXYZ` methods . +// * Allows control over the "shape" of that particular part of the fetch graph. +// * +// * Some GraphNodes can be query results, while others simply describe a part +// * of one of the results, while still others define fetches. +// */ +// public interface ResultNode extends ColumnReferenceQualifier { +// JavaTypeDescriptor getJavaTypeDescriptor(); +// } +// +// /** +// * Allows access to further control how properties within a root or join +// * fetch are mapped back from the result set. Generally used in composite +// * value scenarios. +// */ +// public interface ReturnProperty extends ResultNode { +// /** +// * Add a column alias to this property mapping. +// * +// * @param columnAlias The column alias. +// */ +// void addColumnAlias(String columnAlias); +// } +// +// +// // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// // Specializations +// +// public interface ScalarNode extends ResultNode { +// } +// +// public interface FetchParentNode extends ResultNode { +// String getAlias(); +// } +// +// +// // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// // ResultRoot +// +// /** +// * ResultNode which can be a query result +// */ +// public interface ResultRootNode extends ResultNode { +// DomainResult makeQueryResult(); +// } +// +// public interface RootNodeScalar extends ResultRootNode, ScalarNode { +// @Override +// ScalarResult makeQueryResult(); +// } +// +// public interface RootNodeDynamicInstantiation extends ResultRootNode { +// @Override +// DynamicInstantiationResult makeQueryResult(); +// } +// +// public interface RootNodeEntity extends ResultRootNode, FetchParentNode, NativeQuery.RootReturn { +// EntityTypeDescriptor getEntityDescriptor(); +// +// @Override +// default EntityJavaDescriptor getJavaTypeDescriptor() { +// return getEntityDescriptor().getJavaTypeDescriptor(); +// } +// +// @Override +// EntityResult makeQueryResult(); +// } +// +// public interface RootNodeCollection extends ResultRootNode, FetchParentNode { +// PersistentCollectionDescriptor getCollectionDescriptor(); +// +// @Override +// default JavaTypeDescriptor getJavaTypeDescriptor() { +// return getCollectionDescriptor().getJavaTypeDescriptor(); +// } +// +// @Override +// CollectionResult makeQueryResult(); +// } +// +// +// // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// // FetchResult +// +// public interface ResultFetchNode extends ResultNode, FetchParentNode, NativeQuery.FetchReturn { +// Fetch makeFetch(FetchParent parent); +// } } diff --git a/hibernate-core/src/main/java/org/hibernate/sql/results/internal/JdbcValuesMappingProducerStandard.java b/hibernate-core/src/main/java/org/hibernate/sql/results/internal/JdbcValuesMappingProducerStandard.java index 533774e566..b33124dd54 100644 --- a/hibernate-core/src/main/java/org/hibernate/sql/results/internal/JdbcValuesMappingProducerStandard.java +++ b/hibernate-core/src/main/java/org/hibernate/sql/results/internal/JdbcValuesMappingProducerStandard.java @@ -10,12 +10,11 @@ import java.util.List; import java.util.Set; import org.hibernate.engine.spi.SessionFactoryImplementor; -import org.hibernate.sql.results.internal.StandardResultSetMapping; +import org.hibernate.sql.ast.spi.SqlSelection; import org.hibernate.sql.results.spi.DomainResult; import org.hibernate.sql.results.spi.JdbcValuesMapping; import org.hibernate.sql.results.spi.JdbcValuesMappingProducer; import org.hibernate.sql.results.spi.JdbcValuesMetadata; -import org.hibernate.sql.ast.spi.SqlSelection; /** * Hibernate's standard ResultSetMappingDescriptor implementation for cases @@ -31,7 +30,7 @@ public class JdbcValuesMappingProducerStandard implements JdbcValuesMappingProdu public JdbcValuesMappingProducerStandard(Set sqlSelections, List domainResults) { - resolvedMapping = new StandardResultSetMapping( sqlSelections, domainResults ); + resolvedMapping = new StandardJdbcValuesMapping( sqlSelections, domainResults ); } @Override diff --git a/hibernate-core/src/main/java/org/hibernate/sql/results/internal/JdbcValuesMappingProducerUndefined.java b/hibernate-core/src/main/java/org/hibernate/sql/results/internal/JdbcValuesMappingProducerUndefined.java index 65f3c58f4a..9d3d5410b2 100644 --- a/hibernate-core/src/main/java/org/hibernate/sql/results/internal/JdbcValuesMappingProducerUndefined.java +++ b/hibernate-core/src/main/java/org/hibernate/sql/results/internal/JdbcValuesMappingProducerUndefined.java @@ -6,22 +6,11 @@ */ package org.hibernate.sql.results.internal; -import java.util.HashSet; -import java.util.List; - +import org.hibernate.NotYetImplementedFor6Exception; import org.hibernate.engine.spi.SessionFactoryImplementor; -import org.hibernate.internal.util.collections.CollectionHelper; -import org.hibernate.sql.JdbcValueExtractor; -import org.hibernate.sql.ast.spi.SqlAstWalker; -import org.hibernate.sql.results.internal.StandardResultSetMapping; -import org.hibernate.sql.results.spi.DomainResult; import org.hibernate.sql.results.spi.JdbcValuesMapping; import org.hibernate.sql.results.spi.JdbcValuesMappingProducer; import org.hibernate.sql.results.spi.JdbcValuesMetadata; -import org.hibernate.sql.ast.spi.SqlSelection; -import org.hibernate.type.descriptor.java.JavaTypeDescriptor; -import org.hibernate.type.descriptor.sql.SqlTypeDescriptor; -import org.hibernate.type.spi.TypeConfiguration; import org.jboss.logging.Logger; @@ -38,41 +27,42 @@ public class JdbcValuesMappingProducerUndefined implements JdbcValuesMappingProd public static JdbcValuesMapping resolveStatic( JdbcValuesMetadata jdbcResultsMetadata, SessionFactoryImplementor sessionFactory) { - final int columnCount = jdbcResultsMetadata.getColumnCount(); - - final HashSet sqlSelections = new HashSet<>( columnCount ); - final List domainResults = CollectionHelper.arrayList( columnCount ); - - final TypeConfiguration typeConfiguration = sessionFactory.getMetamodel().getTypeConfiguration(); - - for ( int columnPosition = 0; columnPosition < columnCount; columnPosition++ ) { - final String columnName = jdbcResultsMetadata.resolveColumnName( columnPosition ); - log.tracef( "Discovering JDBC result column metadata [%s (%s)]", columnName, columnPosition ); - - final SqlTypeDescriptor sqlTypeDescriptor = jdbcResultsMetadata.resolveSqlTypeDescriptor( columnPosition ); - final JavaTypeDescriptor javaTypeDescriptor = sqlTypeDescriptor.getJdbcRecommendedJavaTypeMapping( typeConfiguration ); - - log.debugf( "Discovered JDBC result column metadata [%s (%s)] : %s, %s ", columnName, columnPosition, sqlTypeDescriptor, javaTypeDescriptor ); - - final SqlSelection sqlSelection = new SqlSelectionImpl( - columnPosition, - columnName, - javaTypeDescriptor, - sqlTypeDescriptor, - typeConfiguration - ); - sqlSelections.add( sqlSelection ); - - domainResults.add( - new ResolvedScalarDomainResult( - sqlSelection, - columnName, - javaTypeDescriptor - ) - ); - } - - return new StandardResultSetMapping( sqlSelections, domainResults ); + throw new NotYetImplementedFor6Exception( JdbcValuesMappingProducerUndefined.class ); +// final int columnCount = jdbcResultsMetadata.getColumnCount(); +// +// final HashSet sqlSelections = new HashSet<>( columnCount ); +// final List domainResults = CollectionHelper.arrayList( columnCount ); +// +// final TypeConfiguration typeConfiguration = sessionFactory.getMetamodel().getTypeConfiguration(); +// +// for ( int columnPosition = 0; columnPosition < columnCount; columnPosition++ ) { +// final String columnName = jdbcResultsMetadata.resolveColumnName( columnPosition ); +// log.tracef( "Discovering JDBC result column metadata [%s (%s)]", columnName, columnPosition ); +// +// final SqlTypeDescriptor sqlTypeDescriptor = jdbcResultsMetadata.resolveSqlTypeDescriptor( columnPosition ); +// final JavaTypeDescriptor javaTypeDescriptor = sqlTypeDescriptor.getJdbcRecommendedJavaTypeMapping( typeConfiguration ); +// +// log.debugf( "Discovered JDBC result column metadata [%s (%s)] : %s, %s ", columnName, columnPosition, sqlTypeDescriptor, javaTypeDescriptor ); +// +// final SqlSelection sqlSelection = new SqlSelectionImpl( +// columnPosition, +// columnName, +// javaTypeDescriptor, +// sqlTypeDescriptor, +// typeConfiguration +// ); +// sqlSelections.add( sqlSelection ); +// +// domainResults.add( +// new ResolvedScalarDomainResult( +// sqlSelection, +// columnName, +// javaTypeDescriptor +// ) +// ); +// } +// +// return new StandardResultSetMapping( sqlSelections, domainResults ); } @Override @@ -82,37 +72,37 @@ public class JdbcValuesMappingProducerUndefined implements JdbcValuesMappingProd return resolveStatic( jdbcResultsMetadata, sessionFactory ); } - private static class SqlSelectionImpl implements SqlSelection { - private final int valuesArrayPosition; - private JdbcValueExtractor jdbcValueExtractor; - - @SuppressWarnings("unchecked") - public SqlSelectionImpl( - int columnPosition, - String columnName, - JavaTypeDescriptor javaTypeDescriptor, - SqlTypeDescriptor sqlTypeDescriptor, - TypeConfiguration typeConfiguration) { - log.tracef( "Creating SqlSelection for auto-discovered column : %s (%s)", columnName, columnPosition ); - this.valuesArrayPosition = columnPosition - 1; - - this.jdbcValueExtractor = sqlTypeDescriptor.getSqlExpressableType( javaTypeDescriptor, typeConfiguration ) - .getJdbcValueExtractor(); - } - - @Override - public JdbcValueExtractor getJdbcValueExtractor() { - return jdbcValueExtractor; - } - - @Override - public int getValuesArrayPosition() { - return valuesArrayPosition; - } - - @Override - public void accept(SqlAstWalker interpreter) { - throw new UnsupportedOperationException(); - } - } +// private static class SqlSelectionImpl implements SqlSelection { +// private final int valuesArrayPosition; +// private JdbcValueExtractor jdbcValueExtractor; +// +// @SuppressWarnings("unchecked") +// public SqlSelectionImpl( +// int columnPosition, +// String columnName, +// JavaTypeDescriptor javaTypeDescriptor, +// SqlTypeDescriptor sqlTypeDescriptor, +// TypeConfiguration typeConfiguration) { +// log.tracef( "Creating SqlSelection for auto-discovered column : %s (%s)", columnName, columnPosition ); +// this.valuesArrayPosition = columnPosition - 1; +// +// this.jdbcValueExtractor = sqlTypeDescriptor.getSqlExpressableType( javaTypeDescriptor, typeConfiguration ) +// .getJdbcValueExtractor(); +// } +// +// @Override +// public JdbcValueExtractor getJdbcValueExtractor() { +// return jdbcValueExtractor; +// } +// +// @Override +// public int getValuesArrayPosition() { +// return valuesArrayPosition; +// } +// +// @Override +// public void accept(SqlAstWalker interpreter) { +// throw new UnsupportedOperationException(); +// } +// } } diff --git a/hibernate-core/src/main/java/org/hibernate/sql/results/internal/JdbcValuesSourceProcessingStateStandardImpl.java b/hibernate-core/src/main/java/org/hibernate/sql/results/internal/JdbcValuesSourceProcessingStateStandardImpl.java new file mode 100644 index 0000000000..246d2f4be6 --- /dev/null +++ b/hibernate-core/src/main/java/org/hibernate/sql/results/internal/JdbcValuesSourceProcessingStateStandardImpl.java @@ -0,0 +1,189 @@ +/* + * Hibernate, Relational Persistence for Idiomatic Java + * + * License: GNU Lesser General Public License (LGPL), version 2.1 or later + * See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html + */ +package org.hibernate.sql.results.internal; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.hibernate.engine.spi.CollectionKey; +import org.hibernate.engine.spi.EntityKey; +import org.hibernate.engine.spi.SharedSessionContractImplementor; +import org.hibernate.event.spi.EventSource; +import org.hibernate.event.spi.PostLoadEvent; +import org.hibernate.event.spi.PreLoadEvent; +import org.hibernate.graph.spi.AppliedGraph; +import org.hibernate.query.spi.QueryOptions; +import org.hibernate.sql.exec.spi.ExecutionContext; +import org.hibernate.sql.results.internal.domain.ArrayInitializer; +import org.hibernate.sql.results.spi.CollectionInitializer; +import org.hibernate.sql.results.spi.JdbcValuesSourceProcessingOptions; +import org.hibernate.sql.results.spi.JdbcValuesSourceProcessingState; +import org.hibernate.sql.results.spi.LoadingCollectionEntry; +import org.hibernate.sql.results.spi.LoadingEntityEntry; + +import org.jboss.logging.Logger; + +/** + * @author Steve Ebersole + */ +public class JdbcValuesSourceProcessingStateStandardImpl implements JdbcValuesSourceProcessingState { + private static final Logger log = Logger.getLogger( JdbcValuesSourceProcessingStateStandardImpl.class ); + + private final ExecutionContext executionContext; + private final JdbcValuesSourceProcessingOptions processingOptions; + + private Map loadingEntityMap; + private Map loadingCollectionMap; + private List arrayInitializers; + + private final PreLoadEvent preLoadEvent; + private final PostLoadEvent postLoadEvent; + + // todo (6.0) : "loading collections" as well? + + public JdbcValuesSourceProcessingStateStandardImpl( + ExecutionContext executionContext, + JdbcValuesSourceProcessingOptions processingOptions) { + this.executionContext = executionContext; + this.processingOptions = processingOptions; + + preLoadEvent = new PreLoadEvent( (EventSource) executionContext.getSession() ); + postLoadEvent = new PostLoadEvent( (EventSource) executionContext.getSession() ); + } + + @Override + public ExecutionContext getExecutionContext() { + return executionContext; + } + + @Override + public QueryOptions getQueryOptions() { + return executionContext.getQueryOptions(); + } + + @Override + public JdbcValuesSourceProcessingOptions getProcessingOptions() { + return processingOptions; + } + + @Override + public PreLoadEvent getPreLoadEvent() { + return preLoadEvent; + } + + @Override + public PostLoadEvent getPostLoadEvent() { + return postLoadEvent; + } + + @Override + public void registerLoadingEntity( + EntityKey entityKey, + LoadingEntityEntry loadingEntry) { + if ( loadingEntityMap == null ) { + loadingEntityMap = new HashMap<>(); + } + + loadingEntityMap.put( entityKey, loadingEntry ); + } + + @Override + public LoadingEntityEntry findLoadingEntityLocally(EntityKey entityKey) { + return loadingEntityMap == null ? null : loadingEntityMap.get( entityKey ); + } + + @Override + public LoadingCollectionEntry findLoadingCollectionLocally(CollectionKey key) { + if ( loadingCollectionMap == null ) { + return null; + } + + return loadingCollectionMap.get( key ); + } + + @Override + public void registerLoadingCollection(CollectionKey key, LoadingCollectionEntry loadingCollectionEntry) { + if ( loadingCollectionMap == null ) { + loadingCollectionMap = new HashMap<>(); + } + + loadingCollectionMap.put( key, loadingCollectionEntry ); + if ( loadingCollectionEntry.getInitializer() instanceof ArrayInitializer ) { + if ( arrayInitializers == null ) { + arrayInitializers = new ArrayList<>(); + } + arrayInitializers.add( loadingCollectionEntry.getInitializer() ); + } + } + + @Override + public SharedSessionContractImplementor getSession() { + return executionContext.getSession(); + } + + @Override + public void finishUp() { + try { + // for arrays, we should end the collection load beforeQuery resolving the entities, since the + // actual array instances are not instantiated during loading + finishLoadingArrays(); + + // now finish loading the entities (2-phase load) + performTwoPhaseLoad(); + + // now we can finalize loading collections + finishLoadingCollections(); + } + finally { + executionContext.getSession().getPersistenceContext().getLoadContexts().deregister( this ); + } + } + + private void finishLoadingArrays() { + if ( arrayInitializers != null ) { + for ( CollectionInitializer collectionInitializer : arrayInitializers ) { + collectionInitializer.endLoading( executionContext ); + } + } + } + + + private void performTwoPhaseLoad() { + if ( loadingEntityMap == null ) { + return; + } + + log.tracev( "Total objects hydrated: {0}", loadingEntityMap.size() ); + } + + @SuppressWarnings("SimplifiableIfStatement") + private boolean isReadOnly() { + if ( getQueryOptions().isReadOnly() != null ) { + return getQueryOptions().isReadOnly(); + } + + if ( executionContext.getSession() instanceof EventSource ) { + return executionContext.getSession().isDefaultReadOnly(); + } + + return false; + } + + + private void finishLoadingCollections() { + if ( loadingCollectionMap != null ) { + for ( LoadingCollectionEntry loadingCollectionEntry : loadingCollectionMap.values() ) { + loadingCollectionEntry.finishLoading( getExecutionContext() ); + } + + loadingCollectionMap.clear(); + } + } + +} diff --git a/hibernate-core/src/main/java/org/hibernate/sql/results/internal/RowTransformerJpaTupleImpl.java b/hibernate-core/src/main/java/org/hibernate/sql/results/internal/RowTransformerJpaTupleImpl.java index 4de41c4124..99dba17297 100644 --- a/hibernate-core/src/main/java/org/hibernate/sql/results/internal/RowTransformerJpaTupleImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/sql/results/internal/RowTransformerJpaTupleImpl.java @@ -11,7 +11,7 @@ import java.util.List; import javax.persistence.Tuple; import javax.persistence.TupleElement; -import org.hibernate.sql.exec.spi.RowTransformer; +import org.hibernate.sql.results.spi.RowTransformer; /** * RowTransformer generating a JPA {@link Tuple} diff --git a/hibernate-core/src/main/java/org/hibernate/sql/results/internal/RowTransformerPassThruImpl.java b/hibernate-core/src/main/java/org/hibernate/sql/results/internal/RowTransformerPassThruImpl.java index de1f5bb46f..41affa432e 100644 --- a/hibernate-core/src/main/java/org/hibernate/sql/results/internal/RowTransformerPassThruImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/sql/results/internal/RowTransformerPassThruImpl.java @@ -7,7 +7,7 @@ package org.hibernate.sql.results.internal; import org.hibernate.Incubating; -import org.hibernate.sql.exec.spi.RowTransformer; +import org.hibernate.sql.results.spi.RowTransformer; /** * Essentially a no-op transformer - simply passes the result through diff --git a/hibernate-core/src/main/java/org/hibernate/sql/results/internal/RowTransformerSingularReturnImpl.java b/hibernate-core/src/main/java/org/hibernate/sql/results/internal/RowTransformerSingularReturnImpl.java index a1af160760..e1cf495884 100644 --- a/hibernate-core/src/main/java/org/hibernate/sql/results/internal/RowTransformerSingularReturnImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/sql/results/internal/RowTransformerSingularReturnImpl.java @@ -7,7 +7,7 @@ package org.hibernate.sql.results.internal; -import org.hibernate.sql.exec.spi.RowTransformer; +import org.hibernate.sql.results.spi.RowTransformer; /** * @author Steve Ebersole diff --git a/hibernate-core/src/main/java/org/hibernate/sql/results/internal/StandardJdbcValuesMapping.java b/hibernate-core/src/main/java/org/hibernate/sql/results/internal/StandardJdbcValuesMapping.java new file mode 100644 index 0000000000..77879b850b --- /dev/null +++ b/hibernate-core/src/main/java/org/hibernate/sql/results/internal/StandardJdbcValuesMapping.java @@ -0,0 +1,62 @@ +/* + * Hibernate, Relational Persistence for Idiomatic Java + * + * License: GNU Lesser General Public License (LGPL), version 2.1 or later + * See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html + */ +package org.hibernate.sql.results.internal; + +import java.util.List; +import java.util.Set; +import java.util.function.Consumer; + +import org.hibernate.internal.util.collections.CollectionHelper; +import org.hibernate.sql.ast.spi.SqlSelection; +import org.hibernate.sql.results.spi.AssemblerCreationState; +import org.hibernate.sql.results.spi.DomainResult; +import org.hibernate.sql.results.spi.DomainResultAssembler; +import org.hibernate.sql.results.spi.Initializer; +import org.hibernate.sql.results.spi.JdbcValuesMapping; + +/** + * @author Steve Ebersole + */ +public class StandardJdbcValuesMapping implements JdbcValuesMapping { + private final Set sqlSelections; + private final List domainResults; + + public StandardJdbcValuesMapping( + Set sqlSelections, + List domainResults) { + this.sqlSelections = sqlSelections; + this.domainResults = domainResults; + } + + @Override + public Set getSqlSelections() { + return sqlSelections; + } + + @Override + public List getDomainResults() { + return domainResults; + } + + @Override + public List resolveAssemblers( + Consumer initializerConsumer, + AssemblerCreationState creationState) { + final List assemblers = CollectionHelper.arrayList( domainResults.size() ); + + for ( DomainResult domainResult : domainResults ) { + final DomainResultAssembler resultAssembler = domainResult.createResultAssembler( + initializerConsumer, + creationState + ); + + assemblers.add( resultAssembler ); + } + + return assemblers; + } +} diff --git a/hibernate-core/src/main/java/org/hibernate/sql/results/internal/TupleElementImpl.java b/hibernate-core/src/main/java/org/hibernate/sql/results/internal/TupleElementImpl.java new file mode 100644 index 0000000000..07ac64f935 --- /dev/null +++ b/hibernate-core/src/main/java/org/hibernate/sql/results/internal/TupleElementImpl.java @@ -0,0 +1,35 @@ +/* + * Hibernate, Relational Persistence for Idiomatic Java + * + * License: GNU Lesser General Public License (LGPL), version 2.1 or later + * See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html + */ + +package org.hibernate.sql.results.internal; + +import javax.persistence.TupleElement; + +/** + * Implementation of the JPA TupleElement contract + * + * @author Steve Ebersole + */ +public class TupleElementImpl implements TupleElement { + private final Class javaType; + private final String alias; + + public TupleElementImpl(Class javaType, String alias) { + this.javaType = javaType; + this.alias = alias; + } + + @Override + public Class getJavaType() { + return javaType; + } + + @Override + public String getAlias() { + return alias; + } +} diff --git a/hibernate-core/src/main/java/org/hibernate/sql/results/internal/TupleImpl.java b/hibernate-core/src/main/java/org/hibernate/sql/results/internal/TupleImpl.java new file mode 100644 index 0000000000..0ab5be6b75 --- /dev/null +++ b/hibernate-core/src/main/java/org/hibernate/sql/results/internal/TupleImpl.java @@ -0,0 +1,123 @@ +/* + * Hibernate, Relational Persistence for Idiomatic Java + * + * License: GNU Lesser General Public License (LGPL), version 2.1 or later + * See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html + */ + +package org.hibernate.sql.results.internal; + +import java.util.List; +import javax.persistence.TupleElement; + +import org.hibernate.query.JpaTuple; + +/** + * Implementation of the JPA Tuple contract + * + * @author Steve Ebersole + */ +public class TupleImpl implements JpaTuple { + private final List> tupleElements; + private final Object[] row; + + public TupleImpl(List> tupleElements, Object[] row) { + this.tupleElements = tupleElements; + this.row = row; + } + + @Override + @SuppressWarnings("unchecked") + public X get(TupleElement tupleElement) { + int index = tupleElements.indexOf( tupleElement ); + if ( index < 0 ) { + throw new IllegalArgumentException( + "Requested tuple element did not correspond to element in the result tuple" + ); + } + // index should be "in range" by nature of size check in ctor + return (X) row[index]; + } + + @Override + @SuppressWarnings("unchecked") + public X get(String alias, Class type) { + final Object untyped = get( alias ); + if ( untyped != null ) { + if ( !type.isInstance( untyped ) ) { + throw new IllegalArgumentException( + String.format( + "Requested tuple value [alias=%s, value=%s] cannot be assigned to requested type [%s]", + alias, + untyped, + type.getName() + ) + ); + } + } + return (X) untyped; + } + + @Override + public Object get(String alias) { + int index = -1; + if ( alias != null ) { + alias = alias.trim(); + if ( alias.length() > 0 ) { + int i = 0; + for ( TupleElement selection : tupleElements ) { + if ( alias.equals( selection.getAlias() ) ) { + index = i; + break; + } + i++; + } + } + } + if ( index < 0 ) { + throw new IllegalArgumentException( + "Given alias [" + alias + "] did not correspond to an element in the result tuple" + ); + } + // index should be "in range" by nature of size check in ctor + return row[index]; + } + + @Override + @SuppressWarnings("unchecked") + public X get(int i, Class type) { + final Object result = get( i ); + if ( result != null && !type.isInstance( result ) ) { + throw new IllegalArgumentException( + String.format( + "Requested tuple value [index=%s, realType=%s] cannot be assigned to requested type [%s]", + i, + result.getClass().getName(), + type.getName() + ) + ); + } + return (X) result; + } + + @Override + public Object get(int i) { + if ( i >= row.length ) { + throw new IllegalArgumentException( + "Given index [" + i + "] was outside the range of result tuple size [" + row.length + "] " + ); + } + return row[i]; + } + + @Override + public Object[] toArray() { + return row; + } + + @Override + @SuppressWarnings("unchecked") + public List> getElements() { + return tupleElements; + } +} diff --git a/hibernate-core/src/main/java/org/hibernate/sql/results/internal/domain/ArrayInitializer.java b/hibernate-core/src/main/java/org/hibernate/sql/results/internal/domain/ArrayInitializer.java new file mode 100644 index 0000000000..a771f04825 --- /dev/null +++ b/hibernate-core/src/main/java/org/hibernate/sql/results/internal/domain/ArrayInitializer.java @@ -0,0 +1,75 @@ +/* + * Hibernate, Relational Persistence for Idiomatic Java + * + * License: GNU Lesser General Public License (LGPL), version 2.1 or later + * See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html + */ +package org.hibernate.sql.results.internal.domain; + +import org.hibernate.NotYetImplementedFor6Exception; +import org.hibernate.collection.internal.PersistentArrayHolder; +import org.hibernate.persister.collection.CollectionPersister; +import org.hibernate.query.NavigablePath; +import org.hibernate.sql.results.spi.CollectionInitializer; + +/** + * @author Chris Cranford + */ +public class ArrayInitializer implements CollectionInitializer { + private final CollectionPersister arrayDescriptor; + private final NavigablePath navigablePath; +// private final DomainResultAssembler listIndexAssembler; +// private final DomainResultAssembler elementAssembler; + +// public ArrayInitializer( +// CollectionPersister arrayDescriptor, +// FetchParentAccess parentAccess, +// NavigablePath navigablePath, +// boolean selected, +// LockMode lockMode, +// DomainResultAssembler keyContainerAssembler, +// DomainResultAssembler keyCollectionAssembler, +// DomainResultAssembler listIndexAssembler, +// DomainResultAssembler elementAssembler) { +// super( arrayDescriptor, parentAccess, navigablePath, selected, lockMode, keyContainerAssembler, keyCollectionAssembler ); +// this.listIndexAssembler = listIndexAssembler; +// this.elementAssembler = elementAssembler; +// } + + public ArrayInitializer( + CollectionPersister arrayDescriptor, + NavigablePath navigablePath) { + this.arrayDescriptor = arrayDescriptor; + this.navigablePath = navigablePath; + } + + @Override + public CollectionPersister getInitializingCollectionDescriptor() { + return arrayDescriptor; + } + + @Override + public NavigablePath getNavigablePath() { + return navigablePath; + } + + @Override + public PersistentArrayHolder getCollectionInstance() { + throw new NotYetImplementedFor6Exception( getClass() ); + //return (PersistentArrayHolder) super.getCollectionInstance(); + } + +// @Override +// protected void readCollectionRow(RowProcessingState rowProcessingState) { +// int index = (int) listIndexAssembler.assemble( rowProcessingState ); +// if ( getCollectionDescriptor().getIndexDescriptor().getBaseIndex() != 0 ) { +// index -= getCollectionDescriptor().getIndexDescriptor().getBaseIndex(); +// } +// getCollectionInstance().load( index, elementAssembler.assemble( rowProcessingState ) ); +// } +// +// @Override +// public String toString() { +// return "ArrayInitializer{" + LoggingHelper.toLoggableString( getNavigablePath() ) + ")"; +// } +} diff --git a/hibernate-core/src/main/java/org/hibernate/sql/results/spi/CollectionInitializer.java b/hibernate-core/src/main/java/org/hibernate/sql/results/spi/CollectionInitializer.java new file mode 100644 index 0000000000..213d8d714a --- /dev/null +++ b/hibernate-core/src/main/java/org/hibernate/sql/results/spi/CollectionInitializer.java @@ -0,0 +1,34 @@ +/* + * Hibernate, Relational Persistence for Idiomatic Java + * + * License: GNU Lesser General Public License (LGPL), version 2.1 or later + * See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html + */ +package org.hibernate.sql.results.spi; + +import org.hibernate.collection.spi.PersistentCollection; +import org.hibernate.persister.collection.CollectionPersister; +import org.hibernate.sql.exec.spi.ExecutionContext; + +/** + * Initializer implementation for initializing collections (plural attributes) + * + * @author Steve Ebersole + */ +public interface CollectionInitializer extends Initializer { + CollectionPersister getInitializingCollectionDescriptor(); + + PersistentCollection getCollectionInstance(); + + @Override + default Object getInitializedInstance() { + return getCollectionInstance(); + } + + /** + * Lifecycle method called at the very end of the result values processing + */ + default void endLoading(ExecutionContext context) { + // by default - nothing to do + } +} diff --git a/hibernate-core/src/main/java/org/hibernate/sql/results/spi/CompositeInitializer.java b/hibernate-core/src/main/java/org/hibernate/sql/results/spi/CompositeInitializer.java new file mode 100644 index 0000000000..584b2b5441 --- /dev/null +++ b/hibernate-core/src/main/java/org/hibernate/sql/results/spi/CompositeInitializer.java @@ -0,0 +1,28 @@ +/* + * Hibernate, Relational Persistence for Idiomatic Java + * + * License: GNU Lesser General Public License (LGPL), version 2.1 or later + * See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html + */ +package org.hibernate.sql.results.spi; + +import org.hibernate.metamodel.model.mapping.spi.ValueMappingContainer; + +/** + * @author Steve Ebersole + */ +public interface CompositeInitializer extends Initializer, FetchParentAccess { + ValueMappingContainer getInitializingEmbeddedDescriptor(); + + Object getCompositeInstance(); + + @Override + default Object getInitializedInstance() { + return getCompositeInstance(); + } + + @Override + default Object getFetchParentInstance() { + return getCompositeInstance(); + } +} diff --git a/hibernate-core/src/main/java/org/hibernate/sql/results/spi/JdbcValuesMappingDescriptor.java b/hibernate-core/src/main/java/org/hibernate/sql/results/spi/JdbcValuesMappingDescriptor.java index 12b3854fd2..75d759830e 100644 --- a/hibernate-core/src/main/java/org/hibernate/sql/results/spi/JdbcValuesMappingDescriptor.java +++ b/hibernate-core/src/main/java/org/hibernate/sql/results/spi/JdbcValuesMappingDescriptor.java @@ -7,7 +7,6 @@ package org.hibernate.sql.results.spi; import org.hibernate.engine.spi.SessionFactoryImplementor; -import org.hibernate.type.descriptor.sql.SqlTypeDescriptor; /** * Descriptor for the mapping of a JDBC ResultSet providing @@ -37,35 +36,6 @@ public interface JdbcValuesMappingDescriptor { // Both `ResultSetMappingDescriptorDefined` and `ResultSetMappingDescriptorUndefined` could // definitely use better names - - /** - * Access to information about the underlying JDBC values - * such as type, position, column name, etc - */ - interface JdbcValuesMetadata { - /** - * Number of values in the underlying result - */ - int getColumnCount(); - - /** - * Position of a particular result value by name - */ - int resolveColumnPosition(String columnName); - - /** - * Name of a particular result value by position - */ - String resolveColumnName(int position); - - /** - * Descriptor of the JDBC/SQL type of a particular result value by - * position - */ - SqlTypeDescriptor resolveSqlTypeDescriptor(int position); - - } - /** * Resolve the selections (both at the JDBC and object level) for this * mapping. Acts as delayed access to this resolution process to support diff --git a/hibernate-core/src/main/java/org/hibernate/sql/results/spi/LoadContexts.java b/hibernate-core/src/main/java/org/hibernate/sql/results/spi/LoadContexts.java index d140a02a0d..edec8599d2 100644 --- a/hibernate-core/src/main/java/org/hibernate/sql/results/spi/LoadContexts.java +++ b/hibernate-core/src/main/java/org/hibernate/sql/results/spi/LoadContexts.java @@ -6,8 +6,6 @@ */ package org.hibernate.sql.results.spi; -import java.sql.ResultSet; - import org.hibernate.engine.spi.CollectionKey; import org.hibernate.engine.spi.EntityKey; import org.hibernate.engine.spi.PersistenceContext; @@ -17,11 +15,10 @@ import org.hibernate.internal.CoreMessageLogger; import org.hibernate.internal.util.collections.StandardStack; /** - * Maps {@link ResultSet result-sets} to specific contextual data related to processing that result set - *

- * Considering the JDBC-redesign work, would further like this contextual info not mapped separately, but available - * based on the result set being processed. This would also allow maintaining a single mapping as we could reliably - * get notification of the result-set closing... + * Maintains a Stack of processing state related to performing load operations. + * The state is defined by {@link JdbcValuesSourceProcessingState} which + * encapsulates the data to be processed by the load whether the data comes from + * a ResultSet or second-level cache hit. * * @author Steve Ebersole */ diff --git a/hibernate-core/src/main/java/org/hibernate/sql/results/spi/LoadingCollectionEntry.java b/hibernate-core/src/main/java/org/hibernate/sql/results/spi/LoadingCollectionEntry.java index da1e6d4ddb..67087249ee 100644 --- a/hibernate-core/src/main/java/org/hibernate/sql/results/spi/LoadingCollectionEntry.java +++ b/hibernate-core/src/main/java/org/hibernate/sql/results/spi/LoadingCollectionEntry.java @@ -10,8 +10,7 @@ import org.hibernate.collection.spi.PersistentCollection; import org.hibernate.engine.spi.CollectionEntry; import org.hibernate.engine.spi.PersistenceContext; import org.hibernate.engine.spi.SharedSessionContractImplementor; -import org.hibernate.metamodel.model.mapping.PersistentCollectionDescriptor; -import org.hibernate.metamodel.model.mapping.internal.PersistentArrayDescriptorImpl; +import org.hibernate.persister.collection.CollectionPersister; import org.hibernate.sql.exec.spi.ExecutionContext; /** @@ -20,13 +19,13 @@ import org.hibernate.sql.exec.spi.ExecutionContext; * @author Steve Ebersole */ public class LoadingCollectionEntry { - private final PersistentCollectionDescriptor collectionDescriptor; + private final CollectionPersister collectionDescriptor; private final CollectionInitializer initializer; private final Object key; private final PersistentCollection collectionInstance; public LoadingCollectionEntry( - PersistentCollectionDescriptor collectionDescriptor, + CollectionPersister collectionDescriptor, CollectionInitializer initializer, Object key, PersistentCollection collectionInstance) { @@ -35,11 +34,11 @@ public class LoadingCollectionEntry { this.key = key; this.collectionInstance = collectionInstance; - collectionInstance.beforeInitialize( -1, getCollectionDescriptor() ); + collectionInstance.beforeInitialize( getCollectionDescriptor(), -1 ); collectionInstance.beginRead(); } - public PersistentCollectionDescriptor getCollectionDescriptor() { + public CollectionPersister getCollectionDescriptor() { return collectionDescriptor; } @@ -68,12 +67,12 @@ public class LoadingCollectionEntry { final SharedSessionContractImplementor session = executionContext.getSession(); final PersistenceContext persistenceContext = session.getPersistenceContext(); + final CollectionPersister collectionDescriptor = getCollectionDescriptor(); CollectionEntry collectionEntry = persistenceContext.getCollectionEntry( collectionInstance ); - if ( collectionEntry == null ) { collectionEntry = persistenceContext.addInitializedCollection( - getCollectionDescriptor(), + collectionDescriptor, getCollectionInstance(), getKey() ); @@ -82,7 +81,7 @@ public class LoadingCollectionEntry { collectionEntry.postInitialize( collectionInstance ); } - if ( getCollectionDescriptor() instanceof PersistentArrayDescriptorImpl ) { + if ( collectionDescriptor.getCollectionType().hasHolder() ) { persistenceContext.addCollectionHolder( collectionInstance ); } diff --git a/hibernate-core/src/main/java/org/hibernate/tool/hbm2ddl/MultipleLinesSqlCommandExtractor.java b/hibernate-core/src/main/java/org/hibernate/tool/hbm2ddl/MultipleLinesSqlCommandExtractor.java index ebcaf917ef..92451a74b5 100644 --- a/hibernate-core/src/main/java/org/hibernate/tool/hbm2ddl/MultipleLinesSqlCommandExtractor.java +++ b/hibernate-core/src/main/java/org/hibernate/tool/hbm2ddl/MultipleLinesSqlCommandExtractor.java @@ -9,8 +9,12 @@ package org.hibernate.tool.hbm2ddl; import java.io.Reader; import java.util.List; -import org.hibernate.hql.internal.antlr.SqlStatementLexer; -import org.hibernate.hql.internal.antlr.SqlStatementParser; +import org.hibernate.tool.hbm2ddl.grammar.SqlStatementLexer; +import org.hibernate.tool.hbm2ddl.grammar.SqlStatementParser; + +import org.antlr.v4.runtime.CommonTokenStream; +import org.antlr.v4.runtime.UnbufferedCharStream; +import org.antlr.v4.runtime.tree.ParseTreeWalker; /** * Class responsible for extracting SQL statements from import script. Supports instructions/comments and quoted @@ -21,16 +25,18 @@ import org.hibernate.hql.internal.antlr.SqlStatementParser; public class MultipleLinesSqlCommandExtractor implements ImportSqlCommandExtractor { @Override public String[] extractCommands(Reader reader) { - final SqlStatementLexer lexer = new SqlStatementLexer( reader ); - final SqlStatementParser parser = new SqlStatementParser( lexer ); try { - parser.script(); // Parse script. - parser.throwExceptionIfErrorOccurred(); + final SqlStatementLexer lexer; + lexer = new SqlStatementLexer( new UnbufferedCharStream( reader ) ); + final SqlStatementParser parser = new SqlStatementParser( new CommonTokenStream( lexer ) ); + SqlStatementParserListenerImpl listener = new SqlStatementParserListenerImpl(); + ParseTreeWalker parseTreeWalker = new ParseTreeWalker(); + parseTreeWalker.walk( listener, parser.statements() ); + final List statements = listener.getStatements(); + return statements.toArray( new String[0] ); } - catch ( Exception e ) { + catch (Exception e) { throw new ImportScriptException( "Error during import script parsing.", e ); } - List statementList = parser.getStatementList(); - return statementList.toArray( new String[statementList.size()] ); } } diff --git a/hibernate-core/src/main/java/org/hibernate/tool/hbm2ddl/SqlStatementParserListenerImpl.java b/hibernate-core/src/main/java/org/hibernate/tool/hbm2ddl/SqlStatementParserListenerImpl.java new file mode 100644 index 0000000000..88fa27ea0a --- /dev/null +++ b/hibernate-core/src/main/java/org/hibernate/tool/hbm2ddl/SqlStatementParserListenerImpl.java @@ -0,0 +1,30 @@ +/* + * Hibernate, Relational Persistence for Idiomatic Java + * + * License: GNU Lesser General Public License (LGPL), version 2.1 or later + * See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html + */ +package org.hibernate.tool.hbm2ddl; + +import java.util.ArrayList; +import java.util.List; + +import org.hibernate.tool.hbm2ddl.grammar.SqlStatementParser; +import org.hibernate.tool.hbm2ddl.grammar.SqlStatementParserBaseListener; + +/** + * @author Andrea Boriero + */ +public class SqlStatementParserListenerImpl extends SqlStatementParserBaseListener { + private final List statements = new ArrayList<>(); + + @Override + public void exitStatement(SqlStatementParser.StatementContext ctx) { + super.exitStatement( ctx ); + statements.add( ctx.getText().replace( System.lineSeparator(), " " ).trim() ); + } + + public List getStatements(){ + return statements; + } +} diff --git a/hibernate-core/src/main/java/org/hibernate/tuple/DynamicMapInstantiator.java b/hibernate-core/src/main/java/org/hibernate/tuple/DynamicMapInstantiator.java index 8781e659cb..0f601bf475 100755 --- a/hibernate-core/src/main/java/org/hibernate/tuple/DynamicMapInstantiator.java +++ b/hibernate-core/src/main/java/org/hibernate/tuple/DynamicMapInstantiator.java @@ -13,7 +13,6 @@ import java.util.Map; import java.util.Set; import org.hibernate.mapping.PersistentClass; -import org.hibernate.metamodel.spi.Instantiator; public class DynamicMapInstantiator implements Instantiator { public static final String KEY = "$type$"; diff --git a/hibernate-core/src/main/java/org/hibernate/tuple/Instantiator.java b/hibernate-core/src/main/java/org/hibernate/tuple/Instantiator.java new file mode 100644 index 0000000000..fe6577562a --- /dev/null +++ b/hibernate-core/src/main/java/org/hibernate/tuple/Instantiator.java @@ -0,0 +1,44 @@ +/* + * Hibernate, Relational Persistence for Idiomatic Java + * + * License: GNU Lesser General Public License (LGPL), version 2.1 or later + * See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html + */ +package org.hibernate.tuple; + +import java.io.Serializable; + +/** + * Contract for implementors responsible for instantiating entity/component instances. + * + * @author Steve Ebersole + */ +public interface Instantiator extends Serializable { + + /** + * Perform the requested entity instantiation. + *

+ * This form is never called for component instantiation, only entity instantiation. + * + * @param id The id of the entity to be instantiated. + * @return An appropriately instantiated entity. + */ + Object instantiate(Serializable id); + + /** + * Perform the requested instantiation. + * + * @return The instantiated data structure. + */ + Object instantiate(); + + /** + * Performs check to see if the given object is an instance of the entity + * or component which this Instantiator instantiates. + * + * @param object The object to be checked. + * @return True is the object does represent an instance of the underlying + * entity/component. + */ + boolean isInstance(Object object); +} diff --git a/hibernate-core/src/main/java/org/hibernate/tuple/PojoInstantiator.java b/hibernate-core/src/main/java/org/hibernate/tuple/PojoInstantiator.java index 6a8a3c3093..67a441d636 100755 --- a/hibernate-core/src/main/java/org/hibernate/tuple/PojoInstantiator.java +++ b/hibernate-core/src/main/java/org/hibernate/tuple/PojoInstantiator.java @@ -13,13 +13,10 @@ import java.lang.reflect.Constructor; import org.hibernate.InstantiationException; import org.hibernate.PropertyNotFoundException; import org.hibernate.bytecode.spi.ReflectionOptimizer; -import org.hibernate.engine.spi.SharedSessionContractImplementor; import org.hibernate.internal.CoreLogging; import org.hibernate.internal.CoreMessageLogger; import org.hibernate.internal.util.ReflectHelper; import org.hibernate.mapping.Component; -import org.hibernate.metamodel.spi.Instantiator; - /** * Defines a POJO-based instantiator for use from the tuplizers. */ @@ -100,11 +97,6 @@ public class PojoInstantiator implements Instantiator, Serializable { return entity; } - @Override - public Object instantiate(SharedSessionContractImplementor session) { - return null; - } - public Object instantiate(Serializable id) { final boolean useEmbeddedIdentifierInstanceAsEntity = embeddedIdentifier && id != null && diff --git a/hibernate-core/src/main/java/org/hibernate/tuple/component/AbstractComponentTuplizer.java b/hibernate-core/src/main/java/org/hibernate/tuple/component/AbstractComponentTuplizer.java index a426da1f2f..d18b8bfe89 100644 --- a/hibernate-core/src/main/java/org/hibernate/tuple/component/AbstractComponentTuplizer.java +++ b/hibernate-core/src/main/java/org/hibernate/tuple/component/AbstractComponentTuplizer.java @@ -14,7 +14,7 @@ import org.hibernate.mapping.Component; import org.hibernate.mapping.Property; import org.hibernate.property.access.spi.Getter; import org.hibernate.property.access.spi.Setter; -import org.hibernate.metamodel.spi.Instantiator; +import org.hibernate.tuple.Instantiator; /** * Support for tuplizers relating to components. diff --git a/hibernate-core/src/main/java/org/hibernate/tuple/component/DynamicMapComponentTuplizer.java b/hibernate-core/src/main/java/org/hibernate/tuple/component/DynamicMapComponentTuplizer.java index 49414211d1..b1c012a95f 100644 --- a/hibernate-core/src/main/java/org/hibernate/tuple/component/DynamicMapComponentTuplizer.java +++ b/hibernate-core/src/main/java/org/hibernate/tuple/component/DynamicMapComponentTuplizer.java @@ -13,7 +13,7 @@ import org.hibernate.property.access.internal.PropertyAccessStrategyMapImpl; import org.hibernate.property.access.spi.Getter; import org.hibernate.property.access.spi.Setter; import org.hibernate.tuple.DynamicMapInstantiator; -import org.hibernate.metamodel.spi.Instantiator; +import org.hibernate.tuple.Instantiator; /** * A {@link ComponentTuplizer} specific to the dynamic-map entity mode. diff --git a/hibernate-core/src/main/java/org/hibernate/tuple/component/PojoComponentTuplizer.java b/hibernate-core/src/main/java/org/hibernate/tuple/component/PojoComponentTuplizer.java index 5c0c053e73..6c21250af3 100644 --- a/hibernate-core/src/main/java/org/hibernate/tuple/component/PojoComponentTuplizer.java +++ b/hibernate-core/src/main/java/org/hibernate/tuple/component/PojoComponentTuplizer.java @@ -22,7 +22,7 @@ import org.hibernate.property.access.internal.PropertyAccessStrategyBasicImpl; import org.hibernate.property.access.spi.Getter; import org.hibernate.property.access.spi.PropertyAccess; import org.hibernate.property.access.spi.Setter; -import org.hibernate.metamodel.spi.Instantiator; +import org.hibernate.tuple.Instantiator; import org.hibernate.tuple.PojoInstantiator; /** diff --git a/hibernate-core/src/main/java/org/hibernate/tuple/entity/AbstractEntityTuplizer.java b/hibernate-core/src/main/java/org/hibernate/tuple/entity/AbstractEntityTuplizer.java index 264ee53b67..30350665c4 100644 --- a/hibernate-core/src/main/java/org/hibernate/tuple/entity/AbstractEntityTuplizer.java +++ b/hibernate-core/src/main/java/org/hibernate/tuple/entity/AbstractEntityTuplizer.java @@ -34,7 +34,7 @@ import org.hibernate.property.access.spi.Getter; import org.hibernate.property.access.spi.Setter; import org.hibernate.proxy.HibernateProxy; import org.hibernate.proxy.ProxyFactory; -import org.hibernate.metamodel.spi.Instantiator; +import org.hibernate.tuple.Instantiator; import org.hibernate.tuple.NonIdentifierAttribute; import org.hibernate.type.AssociationType; import org.hibernate.type.ComponentType; diff --git a/hibernate-core/src/main/java/org/hibernate/tuple/entity/DynamicMapEntityTuplizer.java b/hibernate-core/src/main/java/org/hibernate/tuple/entity/DynamicMapEntityTuplizer.java index 705231e42d..e119bd0be9 100644 --- a/hibernate-core/src/main/java/org/hibernate/tuple/entity/DynamicMapEntityTuplizer.java +++ b/hibernate-core/src/main/java/org/hibernate/tuple/entity/DynamicMapEntityTuplizer.java @@ -23,7 +23,7 @@ import org.hibernate.property.access.spi.Setter; import org.hibernate.proxy.ProxyFactory; import org.hibernate.proxy.map.MapProxyFactory; import org.hibernate.tuple.DynamicMapInstantiator; -import org.hibernate.metamodel.spi.Instantiator; +import org.hibernate.tuple.Instantiator; /** * An {@link EntityTuplizer} specific to the dynamic-map entity mode. diff --git a/hibernate-core/src/main/java/org/hibernate/tuple/entity/PojoEntityInstantiator.java b/hibernate-core/src/main/java/org/hibernate/tuple/entity/PojoEntityInstantiator.java index 0910b6d9ae..d85187c4a3 100644 --- a/hibernate-core/src/main/java/org/hibernate/tuple/entity/PojoEntityInstantiator.java +++ b/hibernate-core/src/main/java/org/hibernate/tuple/entity/PojoEntityInstantiator.java @@ -6,12 +6,10 @@ */ package org.hibernate.tuple.entity; -import org.hibernate.PropertyNotFoundException; import org.hibernate.bytecode.enhance.spi.interceptor.LazyAttributeLoadingInterceptor; import org.hibernate.bytecode.spi.ReflectionOptimizer; import org.hibernate.engine.spi.PersistentAttributeInterceptable; import org.hibernate.engine.spi.PersistentAttributeInterceptor; -import org.hibernate.internal.util.ReflectHelper; import org.hibernate.mapping.PersistentClass; import org.hibernate.tuple.PojoInstantiator; diff --git a/hibernate-core/src/main/java/org/hibernate/tuple/entity/PojoEntityTuplizer.java b/hibernate-core/src/main/java/org/hibernate/tuple/entity/PojoEntityTuplizer.java index 140aaf4b26..57c61115c8 100644 --- a/hibernate-core/src/main/java/org/hibernate/tuple/entity/PojoEntityTuplizer.java +++ b/hibernate-core/src/main/java/org/hibernate/tuple/entity/PojoEntityTuplizer.java @@ -35,7 +35,7 @@ import org.hibernate.property.access.spi.Getter; import org.hibernate.property.access.spi.Setter; import org.hibernate.proxy.HibernateProxy; import org.hibernate.proxy.ProxyFactory; -import org.hibernate.metamodel.spi.Instantiator; +import org.hibernate.tuple.Instantiator; import org.hibernate.type.CompositeType; /** diff --git a/hibernate-core/src/test/java/org/hibernate/query/criteria/internal/AliasWithCriterionTest.java b/hibernate-core/src/test/java/org/hibernate/query/criteria/internal/AliasWithCriterionTest.java index 9d0074b9a9..5f2d35f06b 100644 --- a/hibernate-core/src/test/java/org/hibernate/query/criteria/internal/AliasWithCriterionTest.java +++ b/hibernate-core/src/test/java/org/hibernate/query/criteria/internal/AliasWithCriterionTest.java @@ -7,7 +7,6 @@ package org.hibernate.query.criteria.internal; import java.util.Date; -import java.util.List; import java.util.Set; import javax.persistence.Column; import javax.persistence.Entity; @@ -18,7 +17,6 @@ import javax.persistence.OneToMany; import javax.persistence.Temporal; import javax.persistence.TemporalType; -import org.hibernate.Criteria; import org.hibernate.criterion.CriteriaSpecification; import org.hibernate.criterion.Criterion; import org.hibernate.criterion.ProjectionList; diff --git a/hibernate-core/src/test/java/org/hibernate/test/annotations/cid/CompositeIdIdentityTest.java b/hibernate-core/src/test/java/org/hibernate/test/annotations/cid/CompositeIdIdentityTest.java index 9fb9037dcd..2d233f70e8 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/annotations/cid/CompositeIdIdentityTest.java +++ b/hibernate-core/src/test/java/org/hibernate/test/annotations/cid/CompositeIdIdentityTest.java @@ -7,9 +7,6 @@ package org.hibernate.test.annotations.cid; import java.io.Serializable; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; import javax.persistence.Column; import javax.persistence.Entity; @@ -19,13 +16,9 @@ import javax.persistence.Id; import javax.persistence.IdClass; import javax.persistence.Table; -import org.hibernate.Criteria; import org.hibernate.Query; -import org.hibernate.Session; -import org.hibernate.Transaction; import org.hibernate.criterion.Disjunction; import org.hibernate.criterion.Restrictions; -import org.hibernate.engine.spi.SessionImplementor; import org.hibernate.testing.DialectChecks; import org.hibernate.testing.FailureExpected; diff --git a/hibernate-core/src/test/java/org/hibernate/test/annotations/cid/CompositeIdTest.java b/hibernate-core/src/test/java/org/hibernate/test/annotations/cid/CompositeIdTest.java index 60df4307c5..a0538b3d30 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/annotations/cid/CompositeIdTest.java +++ b/hibernate-core/src/test/java/org/hibernate/test/annotations/cid/CompositeIdTest.java @@ -9,11 +9,9 @@ package org.hibernate.test.annotations.cid; import java.util.ArrayList; import java.util.Date; import java.util.List; -import java.util.Map; import org.junit.Test; -import org.hibernate.Criteria; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.Transaction; diff --git a/hibernate-core/src/test/java/org/hibernate/test/annotations/idmanytoone/IdManyToOneTest.java b/hibernate-core/src/test/java/org/hibernate/test/annotations/idmanytoone/IdManyToOneTest.java index 0c3ad6d545..a1ef198b3f 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/annotations/idmanytoone/IdManyToOneTest.java +++ b/hibernate-core/src/test/java/org/hibernate/test/annotations/idmanytoone/IdManyToOneTest.java @@ -6,7 +6,6 @@ */ package org.hibernate.test.annotations.idmanytoone; -import org.hibernate.Criteria; import org.hibernate.Session; import org.hibernate.Transaction; import org.hibernate.boot.model.naming.ImplicitNamingStrategyJpaCompliantImpl; diff --git a/hibernate-core/src/test/java/org/hibernate/test/annotations/join/JoinTest.java b/hibernate-core/src/test/java/org/hibernate/test/annotations/join/JoinTest.java index 6293249f33..c157c7b06b 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/annotations/join/JoinTest.java +++ b/hibernate-core/src/test/java/org/hibernate/test/annotations/join/JoinTest.java @@ -11,8 +11,6 @@ import java.util.ArrayList; import java.util.Date; import java.util.Locale; -import org.hibernate.Criteria; -import org.hibernate.HibernateException; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.Transaction; diff --git a/hibernate-core/src/test/java/org/hibernate/test/annotations/naturalid/ImmutableNaturalKeyLookupTest.java b/hibernate-core/src/test/java/org/hibernate/test/annotations/naturalid/ImmutableNaturalKeyLookupTest.java index 58ea046c3e..1afa0eeae2 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/annotations/naturalid/ImmutableNaturalKeyLookupTest.java +++ b/hibernate-core/src/test/java/org/hibernate/test/annotations/naturalid/ImmutableNaturalKeyLookupTest.java @@ -9,7 +9,6 @@ package org.hibernate.test.annotations.naturalid; import org.junit.Assert; import org.junit.Test; -import org.hibernate.Criteria; import org.hibernate.FetchMode; import org.hibernate.FlushMode; import org.hibernate.Session; diff --git a/hibernate-core/src/test/java/org/hibernate/test/annotations/naturalid/NaturalIdOnSingleManyToOneTest.java b/hibernate-core/src/test/java/org/hibernate/test/annotations/naturalid/NaturalIdOnSingleManyToOneTest.java index 1c1f8be165..91aac49d78 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/annotations/naturalid/NaturalIdOnSingleManyToOneTest.java +++ b/hibernate-core/src/test/java/org/hibernate/test/annotations/naturalid/NaturalIdOnSingleManyToOneTest.java @@ -8,12 +8,9 @@ package org.hibernate.test.annotations.naturalid; import java.util.List; -import org.jboss.logging.Logger; import org.junit.After; import org.junit.Test; -import org.hibernate.Criteria; -import org.hibernate.Hibernate; import org.hibernate.Session; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; diff --git a/hibernate-core/src/test/java/org/hibernate/test/annotations/onetomany/DefaultNullOrderingTest.java b/hibernate-core/src/test/java/org/hibernate/test/annotations/onetomany/DefaultNullOrderingTest.java index b255954e54..69077cd173 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/annotations/onetomany/DefaultNullOrderingTest.java +++ b/hibernate-core/src/test/java/org/hibernate/test/annotations/onetomany/DefaultNullOrderingTest.java @@ -13,7 +13,6 @@ import java.util.List; import org.junit.Assert; import org.junit.Test; -import org.hibernate.Criteria; import org.hibernate.Session; import org.hibernate.cfg.AvailableSettings; import org.hibernate.cfg.Configuration; diff --git a/hibernate-core/src/test/java/org/hibernate/test/annotations/onetomany/OrderByTest.java b/hibernate-core/src/test/java/org/hibernate/test/annotations/onetomany/OrderByTest.java index 8b22d32c70..02536b0979 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/annotations/onetomany/OrderByTest.java +++ b/hibernate-core/src/test/java/org/hibernate/test/annotations/onetomany/OrderByTest.java @@ -20,7 +20,6 @@ import java.util.Iterator; import java.util.List; import java.util.Map; -import org.hibernate.Criteria; import org.hibernate.Hibernate; import org.hibernate.NullPrecedence; import org.hibernate.Session; @@ -28,8 +27,6 @@ import org.hibernate.dialect.H2Dialect; import org.hibernate.dialect.MySQLDialect; import org.hibernate.dialect.Oracle8iDialect; import org.hibernate.dialect.SQLServer2008Dialect; -import org.hibernate.dialect.SQLServer2012Dialect; -import org.hibernate.dialect.SQLServerDialect; import org.hibernate.engine.spi.SessionImplementor; import org.hibernate.persister.collection.CollectionPersister; import org.hibernate.persister.collection.QueryableCollection; diff --git a/hibernate-core/src/test/java/org/hibernate/test/annotations/secondarytable/SecondaryTableSchemaTest.java b/hibernate-core/src/test/java/org/hibernate/test/annotations/secondarytable/SecondaryTableSchemaTest.java index 28de8472e6..79f37e3415 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/annotations/secondarytable/SecondaryTableSchemaTest.java +++ b/hibernate-core/src/test/java/org/hibernate/test/annotations/secondarytable/SecondaryTableSchemaTest.java @@ -7,33 +7,23 @@ package org.hibernate.test.annotations.secondarytable; import java.io.Serializable; -import java.net.URL; -import java.util.Iterator; import java.util.List; import java.util.Map; import javax.persistence.Column; import javax.persistence.Entity; -import javax.persistence.ForeignKey; -import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.PrimaryKeyJoinColumn; import javax.persistence.SecondaryTable; import javax.persistence.Table; -import org.hibernate.Criteria; import org.hibernate.annotations.DynamicUpdate; import org.hibernate.annotations.OptimisticLockType; import org.hibernate.annotations.OptimisticLocking; import org.hibernate.cfg.AvailableSettings; -import org.hibernate.cfg.Environment; -import org.hibernate.dialect.Dialect; import org.hibernate.dialect.H2Dialect; -import org.hibernate.engine.spi.SessionFactoryImplementor; import org.hibernate.jpa.test.BaseEntityManagerFunctionalTestCase; import org.hibernate.testing.RequiresDialect; -import org.hibernate.testing.transaction.TransactionUtil; -import org.hibernate.test.schemaupdate.foreignkeys.definition.AbstractForeignKeyDefinitionTest; import org.junit.Test; import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; diff --git a/hibernate-core/src/test/java/org/hibernate/test/annotations/tuplizer/DynamicComponentTuplizer.java b/hibernate-core/src/test/java/org/hibernate/test/annotations/tuplizer/DynamicComponentTuplizer.java index f7ab3cf289..79f3c31ea1 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/annotations/tuplizer/DynamicComponentTuplizer.java +++ b/hibernate-core/src/test/java/org/hibernate/test/annotations/tuplizer/DynamicComponentTuplizer.java @@ -8,7 +8,7 @@ //$Id$ package org.hibernate.test.annotations.tuplizer; import org.hibernate.mapping.Component; -import org.hibernate.metamodel.spi.Instantiator; +import org.hibernate.tuple.Instantiator; import org.hibernate.tuple.component.PojoComponentTuplizer; /** diff --git a/hibernate-core/src/test/java/org/hibernate/test/annotations/tuplizer/DynamicEntityTuplizer.java b/hibernate-core/src/test/java/org/hibernate/test/annotations/tuplizer/DynamicEntityTuplizer.java index 67b8fac473..9ecf824531 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/annotations/tuplizer/DynamicEntityTuplizer.java +++ b/hibernate-core/src/test/java/org/hibernate/test/annotations/tuplizer/DynamicEntityTuplizer.java @@ -10,7 +10,7 @@ import org.hibernate.mapping.PersistentClass; import org.hibernate.property.access.spi.Getter; import org.hibernate.property.access.spi.Setter; import org.hibernate.proxy.ProxyFactory; -import org.hibernate.metamodel.spi.Instantiator; +import org.hibernate.tuple.Instantiator; import org.hibernate.tuple.entity.EntityMetamodel; import org.hibernate.tuple.entity.PojoEntityTuplizer; diff --git a/hibernate-core/src/test/java/org/hibernate/test/annotations/tuplizer/DynamicInstantiator.java b/hibernate-core/src/test/java/org/hibernate/test/annotations/tuplizer/DynamicInstantiator.java index 563fc9cf9d..1c32910e38 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/annotations/tuplizer/DynamicInstantiator.java +++ b/hibernate-core/src/test/java/org/hibernate/test/annotations/tuplizer/DynamicInstantiator.java @@ -14,7 +14,7 @@ import java.lang.reflect.Proxy; import org.hibernate.HibernateException; import org.hibernate.internal.util.ReflectHelper; -import org.hibernate.metamodel.spi.Instantiator; +import org.hibernate.tuple.Instantiator; /** * @author Emmanuel Bernard diff --git a/hibernate-core/src/test/java/org/hibernate/test/annotations/tuplizer/bytebuddysubclass/MyEntityInstantiator.java b/hibernate-core/src/test/java/org/hibernate/test/annotations/tuplizer/bytebuddysubclass/MyEntityInstantiator.java index ed1163d073..b264ff6331 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/annotations/tuplizer/bytebuddysubclass/MyEntityInstantiator.java +++ b/hibernate-core/src/test/java/org/hibernate/test/annotations/tuplizer/bytebuddysubclass/MyEntityInstantiator.java @@ -9,7 +9,7 @@ package org.hibernate.test.annotations.tuplizer.bytebuddysubclass; import java.io.Serializable; import org.hibernate.mapping.PersistentClass; -import org.hibernate.metamodel.spi.Instantiator; +import org.hibernate.tuple.Instantiator; import net.bytebuddy.ByteBuddy; import net.bytebuddy.implementation.FixedValue; diff --git a/hibernate-core/src/test/java/org/hibernate/test/annotations/tuplizer/bytebuddysubclass/MyTuplizer.java b/hibernate-core/src/test/java/org/hibernate/test/annotations/tuplizer/bytebuddysubclass/MyTuplizer.java index e9241cfde0..971e32a170 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/annotations/tuplizer/bytebuddysubclass/MyTuplizer.java +++ b/hibernate-core/src/test/java/org/hibernate/test/annotations/tuplizer/bytebuddysubclass/MyTuplizer.java @@ -8,7 +8,7 @@ package org.hibernate.test.annotations.tuplizer.bytebuddysubclass; import org.hibernate.EntityNameResolver; import org.hibernate.mapping.PersistentClass; -import org.hibernate.metamodel.spi.Instantiator; +import org.hibernate.tuple.Instantiator; import org.hibernate.tuple.entity.EntityMetamodel; import org.hibernate.tuple.entity.PojoEntityTuplizer; diff --git a/hibernate-core/src/test/java/org/hibernate/test/cid/CompositeIdTest.java b/hibernate-core/src/test/java/org/hibernate/test/cid/CompositeIdTest.java index 9f9a96191f..f49b4f1a95 100755 --- a/hibernate-core/src/test/java/org/hibernate/test/cid/CompositeIdTest.java +++ b/hibernate-core/src/test/java/org/hibernate/test/cid/CompositeIdTest.java @@ -24,7 +24,6 @@ import org.hibernate.Session; import org.hibernate.Transaction; import org.hibernate.dialect.Oracle8iDialect; import org.hibernate.dialect.SQLServerDialect; -import org.hibernate.engine.query.spi.HQLQueryPlan; import org.hibernate.exception.SQLGrammarException; import org.hibernate.hql.spi.QueryTranslator; diff --git a/hibernate-core/src/test/java/org/hibernate/test/criteria/ComplexJoinAliasTest.java b/hibernate-core/src/test/java/org/hibernate/test/criteria/ComplexJoinAliasTest.java index 4af4610bae..1bf95d88d5 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/criteria/ComplexJoinAliasTest.java +++ b/hibernate-core/src/test/java/org/hibernate/test/criteria/ComplexJoinAliasTest.java @@ -10,7 +10,6 @@ import java.util.Arrays; import org.junit.Test; -import org.hibernate.Criteria; import org.hibernate.Session; import org.hibernate.criterion.Restrictions; import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; diff --git a/hibernate-core/src/test/java/org/hibernate/test/criteria/CriteriaAliasFetchTest.java b/hibernate-core/src/test/java/org/hibernate/test/criteria/CriteriaAliasFetchTest.java index f0da491dff..66eab367a3 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/criteria/CriteriaAliasFetchTest.java +++ b/hibernate-core/src/test/java/org/hibernate/test/criteria/CriteriaAliasFetchTest.java @@ -18,13 +18,11 @@ import javax.persistence.Id; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; -import org.hibernate.Criteria; import org.hibernate.FetchMode; import org.hibernate.boot.MetadataSources; import org.hibernate.criterion.CriteriaSpecification; import org.hibernate.testing.TestForIssue; import org.hibernate.testing.junit4.BaseNonConfigCoreFunctionalTestCase; -import org.junit.Assert; import org.junit.Test; /** diff --git a/hibernate-core/src/test/java/org/hibernate/test/criteria/CriteriaLockingTest.java b/hibernate-core/src/test/java/org/hibernate/test/criteria/CriteriaLockingTest.java index 8b5312efa5..ccb9288980 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/criteria/CriteriaLockingTest.java +++ b/hibernate-core/src/test/java/org/hibernate/test/criteria/CriteriaLockingTest.java @@ -6,7 +6,6 @@ */ package org.hibernate.test.criteria; -import org.hibernate.Criteria; import org.hibernate.LockMode; import org.hibernate.Session; import org.hibernate.Transaction; diff --git a/hibernate-core/src/test/java/org/hibernate/test/criteria/CriteriaOrderByTest.java b/hibernate-core/src/test/java/org/hibernate/test/criteria/CriteriaOrderByTest.java index e187b63937..0775092cb1 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/criteria/CriteriaOrderByTest.java +++ b/hibernate-core/src/test/java/org/hibernate/test/criteria/CriteriaOrderByTest.java @@ -6,7 +6,6 @@ */ package org.hibernate.test.criteria; -import org.hibernate.Criteria; import org.hibernate.Session; import org.hibernate.Transaction; import org.hibernate.criterion.Projections; diff --git a/hibernate-core/src/test/java/org/hibernate/test/criteria/CriteriaQueryTest.java b/hibernate-core/src/test/java/org/hibernate/test/criteria/CriteriaQueryTest.java index 46a980d4a8..9c80852157 100755 --- a/hibernate-core/src/test/java/org/hibernate/test/criteria/CriteriaQueryTest.java +++ b/hibernate-core/src/test/java/org/hibernate/test/criteria/CriteriaQueryTest.java @@ -17,7 +17,6 @@ import java.util.List; import java.util.Map; import java.util.Set; -import org.hibernate.Criteria; import org.hibernate.FetchMode; import org.hibernate.Hibernate; import org.hibernate.JDBCException; diff --git a/hibernate-core/src/test/java/org/hibernate/test/criteria/LongInElementsTest.java b/hibernate-core/src/test/java/org/hibernate/test/criteria/LongInElementsTest.java index 2fd5e935f9..b10670c3d5 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/criteria/LongInElementsTest.java +++ b/hibernate-core/src/test/java/org/hibernate/test/criteria/LongInElementsTest.java @@ -9,7 +9,6 @@ package org.hibernate.test.criteria; import java.util.ArrayList; import java.util.List; -import org.hibernate.Criteria; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.Transaction; diff --git a/hibernate-core/src/test/java/org/hibernate/test/criteria/OuterJoinCriteriaTest.java b/hibernate-core/src/test/java/org/hibernate/test/criteria/OuterJoinCriteriaTest.java index a4e2f65ccb..337b105aaf 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/criteria/OuterJoinCriteriaTest.java +++ b/hibernate-core/src/test/java/org/hibernate/test/criteria/OuterJoinCriteriaTest.java @@ -12,8 +12,6 @@ import java.util.Map; import org.junit.Test; -import org.hibernate.Criteria; -import org.hibernate.FetchMode; import org.hibernate.Session; import org.hibernate.criterion.CriteriaSpecification; import org.hibernate.criterion.Restrictions; diff --git a/hibernate-core/src/test/java/org/hibernate/test/criteria/limitexpression/LimitExpressionTest.java b/hibernate-core/src/test/java/org/hibernate/test/criteria/limitexpression/LimitExpressionTest.java index d178f39e4d..3916318328 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/criteria/limitexpression/LimitExpressionTest.java +++ b/hibernate-core/src/test/java/org/hibernate/test/criteria/limitexpression/LimitExpressionTest.java @@ -9,9 +9,6 @@ package org.hibernate.test.criteria.limitexpression; import java.util.Arrays; import java.util.List; -import org.hibernate.Criteria; -import org.hibernate.Session; -import org.hibernate.Transaction; import org.hibernate.criterion.Restrictions; import org.hibernate.testing.DialectChecks; @@ -20,7 +17,6 @@ import org.hibernate.testing.TestForIssue; import org.hibernate.testing.junit4.BaseNonConfigCoreFunctionalTestCase; import org.hibernate.testing.transaction.TransactionUtil; -import org.junit.Before; import org.junit.Test; import static junit.framework.TestCase.assertTrue; diff --git a/hibernate-core/src/test/java/org/hibernate/test/criteria/many_to_many/CriteriaManyToManyTest.java b/hibernate-core/src/test/java/org/hibernate/test/criteria/many_to_many/CriteriaManyToManyTest.java index e7d7219b68..3e6708948c 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/criteria/many_to_many/CriteriaManyToManyTest.java +++ b/hibernate-core/src/test/java/org/hibernate/test/criteria/many_to_many/CriteriaManyToManyTest.java @@ -10,7 +10,6 @@ import java.util.LinkedHashSet; import java.util.List; import java.util.Set; -import org.hibernate.Criteria; import org.hibernate.Session; import org.hibernate.Transaction; import org.hibernate.criterion.Restrictions; diff --git a/hibernate-core/src/test/java/org/hibernate/test/criterion/CriterionTest.java b/hibernate-core/src/test/java/org/hibernate/test/criterion/CriterionTest.java index cdc8bdf1e9..15876358a7 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/criterion/CriterionTest.java +++ b/hibernate-core/src/test/java/org/hibernate/test/criterion/CriterionTest.java @@ -6,7 +6,6 @@ */ package org.hibernate.test.criterion; -import org.hibernate.Criteria; import org.hibernate.IrrelevantEntity; import org.hibernate.SessionFactory; import org.hibernate.cfg.AvailableSettings; diff --git a/hibernate-core/src/test/java/org/hibernate/test/criterion/NationalizedIgnoreCaseTest.java b/hibernate-core/src/test/java/org/hibernate/test/criterion/NationalizedIgnoreCaseTest.java index 7dff458e48..93b4b656e7 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/criterion/NationalizedIgnoreCaseTest.java +++ b/hibernate-core/src/test/java/org/hibernate/test/criterion/NationalizedIgnoreCaseTest.java @@ -11,7 +11,6 @@ import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; -import org.hibernate.Criteria; import org.hibernate.annotations.Nationalized; import org.hibernate.criterion.Restrictions; import org.hibernate.dialect.DB2Dialect; diff --git a/hibernate-core/src/test/java/org/hibernate/test/dynamicentity/tuplizer/MyEntityInstantiator.java b/hibernate-core/src/test/java/org/hibernate/test/dynamicentity/tuplizer/MyEntityInstantiator.java index 6d240cf7e4..f509feb71c 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/dynamicentity/tuplizer/MyEntityInstantiator.java +++ b/hibernate-core/src/test/java/org/hibernate/test/dynamicentity/tuplizer/MyEntityInstantiator.java @@ -12,7 +12,7 @@ import java.lang.reflect.Proxy; import org.hibernate.HibernateException; import org.hibernate.internal.util.ReflectHelper; -import org.hibernate.metamodel.spi.Instantiator; +import org.hibernate.tuple.Instantiator; import org.hibernate.test.dynamicentity.Address; import org.hibernate.test.dynamicentity.Company; diff --git a/hibernate-core/src/test/java/org/hibernate/test/dynamicentity/tuplizer/MyEntityTuplizer.java b/hibernate-core/src/test/java/org/hibernate/test/dynamicentity/tuplizer/MyEntityTuplizer.java index 6784a58621..2acf7ffc63 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/dynamicentity/tuplizer/MyEntityTuplizer.java +++ b/hibernate-core/src/test/java/org/hibernate/test/dynamicentity/tuplizer/MyEntityTuplizer.java @@ -9,7 +9,7 @@ import org.hibernate.mapping.PersistentClass; import org.hibernate.property.access.spi.Getter; import org.hibernate.property.access.spi.Setter; import org.hibernate.proxy.ProxyFactory; -import org.hibernate.metamodel.spi.Instantiator; +import org.hibernate.tuple.Instantiator; import org.hibernate.tuple.entity.EntityMetamodel; import org.hibernate.tuple.entity.PojoEntityTuplizer; diff --git a/hibernate-core/src/test/java/org/hibernate/test/dynamicentity/tuplizer2/MyEntityInstantiator.java b/hibernate-core/src/test/java/org/hibernate/test/dynamicentity/tuplizer2/MyEntityInstantiator.java index e62c509fac..455050c6a3 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/dynamicentity/tuplizer2/MyEntityInstantiator.java +++ b/hibernate-core/src/test/java/org/hibernate/test/dynamicentity/tuplizer2/MyEntityInstantiator.java @@ -15,7 +15,7 @@ import org.hibernate.test.dynamicentity.Company; import org.hibernate.test.dynamicentity.Customer; import org.hibernate.test.dynamicentity.Person; import org.hibernate.test.dynamicentity.ProxyHelper; -import org.hibernate.metamodel.spi.Instantiator; +import org.hibernate.tuple.Instantiator; /** * @author Steve Ebersole diff --git a/hibernate-core/src/test/java/org/hibernate/test/dynamicentity/tuplizer2/MyEntityTuplizer.java b/hibernate-core/src/test/java/org/hibernate/test/dynamicentity/tuplizer2/MyEntityTuplizer.java index 224a2fea2f..86586d67dd 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/dynamicentity/tuplizer2/MyEntityTuplizer.java +++ b/hibernate-core/src/test/java/org/hibernate/test/dynamicentity/tuplizer2/MyEntityTuplizer.java @@ -13,7 +13,7 @@ import org.hibernate.property.access.spi.Setter; import org.hibernate.proxy.ProxyFactory; import org.hibernate.test.dynamicentity.ProxyHelper; import org.hibernate.test.dynamicentity.tuplizer.MyEntityInstantiator; -import org.hibernate.metamodel.spi.Instantiator; +import org.hibernate.tuple.Instantiator; import org.hibernate.tuple.entity.EntityMetamodel; import org.hibernate.tuple.entity.PojoEntityTuplizer; diff --git a/hibernate-core/src/test/java/org/hibernate/test/filter/CriteriaQueryWithAppliedFilterTest.java b/hibernate-core/src/test/java/org/hibernate/test/filter/CriteriaQueryWithAppliedFilterTest.java index 631e1df9b7..8f8f497321 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/filter/CriteriaQueryWithAppliedFilterTest.java +++ b/hibernate-core/src/test/java/org/hibernate/test/filter/CriteriaQueryWithAppliedFilterTest.java @@ -15,7 +15,6 @@ import javax.persistence.Table; import java.io.Serializable; import java.util.List; -import org.hibernate.Criteria; import org.hibernate.annotations.Filter; import org.hibernate.annotations.FilterDef; import org.hibernate.annotations.ParamDef; diff --git a/hibernate-core/src/test/java/org/hibernate/test/filter/DynamicFilterTest.java b/hibernate-core/src/test/java/org/hibernate/test/filter/DynamicFilterTest.java index ed578f3c12..22417fa308 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/filter/DynamicFilterTest.java +++ b/hibernate-core/src/test/java/org/hibernate/test/filter/DynamicFilterTest.java @@ -15,7 +15,6 @@ import java.util.List; import java.util.Map; import java.util.Set; -import org.hibernate.Criteria; import org.hibernate.FetchMode; import org.hibernate.Hibernate; import org.hibernate.Session; diff --git a/hibernate-core/src/test/java/org/hibernate/test/flush/NativeCriteriaSyncTest.java b/hibernate-core/src/test/java/org/hibernate/test/flush/NativeCriteriaSyncTest.java index 2175258f75..f51224c016 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/flush/NativeCriteriaSyncTest.java +++ b/hibernate-core/src/test/java/org/hibernate/test/flush/NativeCriteriaSyncTest.java @@ -7,17 +7,11 @@ package org.hibernate.test.flush; import static org.hibernate.testing.transaction.TransactionUtil.doInHibernate; -import static org.junit.Assert.*; -import org.hibernate.Criteria; -import org.hibernate.Session; -import org.hibernate.Transaction; import org.hibernate.criterion.Restrictions; import org.hibernate.test.hql.SimpleEntityWithAssociation; import org.hibernate.testing.TestForIssue; import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; -import org.junit.After; -import org.junit.Before; import org.junit.Test; /** diff --git a/hibernate-core/src/test/java/org/hibernate/test/hql/EntityJoinTest.java b/hibernate-core/src/test/java/org/hibernate/test/hql/EntityJoinTest.java index 716fd01078..c1183d5061 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/hql/EntityJoinTest.java +++ b/hibernate-core/src/test/java/org/hibernate/test/hql/EntityJoinTest.java @@ -17,8 +17,6 @@ import javax.persistence.Table; import org.hibernate.annotations.NaturalId; import org.hibernate.dialect.SybaseDialect; -import org.hibernate.engine.query.spi.HQLQueryPlan; -import org.hibernate.hql.spi.QueryTranslator; import org.hibernate.testing.SkipForDialect; import org.hibernate.testing.TestForIssue; diff --git a/hibernate-core/src/test/java/org/hibernate/test/hql/HQLTest.java b/hibernate-core/src/test/java/org/hibernate/test/hql/HQLTest.java index 4d256a378f..eead8e644c 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/hql/HQLTest.java +++ b/hibernate-core/src/test/java/org/hibernate/test/hql/HQLTest.java @@ -33,7 +33,6 @@ import org.hibernate.dialect.SybaseAnywhereDialect; import org.hibernate.dialect.SybaseDialect; import org.hibernate.dialect.TeradataDialect; import org.hibernate.dialect.function.SQLFunction; -import org.hibernate.engine.query.spi.HQLQueryPlan; import org.hibernate.engine.query.spi.ReturnMetadata; import org.hibernate.engine.spi.SessionFactoryImplementor; import org.hibernate.hql.internal.antlr.HqlTokenTypes; diff --git a/hibernate-core/src/test/java/org/hibernate/test/hql/QueryTranslatorTestCase.java b/hibernate-core/src/test/java/org/hibernate/test/hql/QueryTranslatorTestCase.java index 007c05b8a1..4699cf5509 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/hql/QueryTranslatorTestCase.java +++ b/hibernate-core/src/test/java/org/hibernate/test/hql/QueryTranslatorTestCase.java @@ -18,7 +18,6 @@ import junit.framework.ComparisonFailure; import org.hibernate.MappingException; import org.hibernate.QueryException; -import org.hibernate.engine.query.spi.HQLQueryPlan; import org.hibernate.engine.spi.SessionFactoryImplementor; import org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory; import org.hibernate.hql.internal.ast.QueryTranslatorImpl; diff --git a/hibernate-core/src/test/java/org/hibernate/test/hql/TupleSupportTest.java b/hibernate-core/src/test/java/org/hibernate/test/hql/TupleSupportTest.java index e091367502..775c9afe7d 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/hql/TupleSupportTest.java +++ b/hibernate-core/src/test/java/org/hibernate/test/hql/TupleSupportTest.java @@ -18,7 +18,6 @@ import org.hibernate.SessionFactory; import org.hibernate.cfg.AvailableSettings; import org.hibernate.cfg.Configuration; import org.hibernate.dialect.H2Dialect; -import org.hibernate.engine.query.spi.HQLQueryPlan; import org.hibernate.engine.spi.SessionFactoryImplementor; import org.junit.After; diff --git a/hibernate-core/src/test/java/org/hibernate/test/idprops/IdentifierPropertyReferencesTest.java b/hibernate-core/src/test/java/org/hibernate/test/idprops/IdentifierPropertyReferencesTest.java index 00947a5e21..7a34eb8bed 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/idprops/IdentifierPropertyReferencesTest.java +++ b/hibernate-core/src/test/java/org/hibernate/test/idprops/IdentifierPropertyReferencesTest.java @@ -8,7 +8,6 @@ package org.hibernate.test.idprops; import org.junit.Test; -import org.hibernate.Criteria; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.criterion.Projections; diff --git a/hibernate-core/src/test/java/org/hibernate/test/inheritance/discriminator/MultiInheritanceImplicitDowncastTest.java b/hibernate-core/src/test/java/org/hibernate/test/inheritance/discriminator/MultiInheritanceImplicitDowncastTest.java index 2d309fbace..c094e1651a 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/inheritance/discriminator/MultiInheritanceImplicitDowncastTest.java +++ b/hibernate-core/src/test/java/org/hibernate/test/inheritance/discriminator/MultiInheritanceImplicitDowncastTest.java @@ -52,7 +52,6 @@ import javax.persistence.MappedSuperclass; import javax.persistence.OneToMany; import javax.persistence.OrderColumn; -import org.hibernate.engine.query.spi.HQLQueryPlan; import org.hibernate.hql.spi.QueryTranslator; import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; diff --git a/hibernate-core/src/test/java/org/hibernate/test/keymanytoone/bidir/embedded/KeyManyToOneTest.java b/hibernate-core/src/test/java/org/hibernate/test/keymanytoone/bidir/embedded/KeyManyToOneTest.java index 07e3acc94b..89d40897f4 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/keymanytoone/bidir/embedded/KeyManyToOneTest.java +++ b/hibernate-core/src/test/java/org/hibernate/test/keymanytoone/bidir/embedded/KeyManyToOneTest.java @@ -9,7 +9,6 @@ import java.util.List; import org.junit.Test; -import org.hibernate.Criteria; import org.hibernate.Session; import org.hibernate.cfg.Configuration; import org.hibernate.cfg.Environment; diff --git a/hibernate-core/src/test/java/org/hibernate/test/legacy/FooBarTest.java b/hibernate-core/src/test/java/org/hibernate/test/legacy/FooBarTest.java index 84aa16082a..c9183a7447 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/legacy/FooBarTest.java +++ b/hibernate-core/src/test/java/org/hibernate/test/legacy/FooBarTest.java @@ -26,7 +26,6 @@ import java.util.TimeZone; import java.util.TreeMap; import java.util.TreeSet; -import org.hibernate.Criteria; import org.hibernate.FetchMode; import org.hibernate.FlushMode; import org.hibernate.Hibernate; @@ -81,8 +80,6 @@ import org.hibernate.testing.TestForIssue; import org.hibernate.testing.env.ConnectionProviderBuilder; import org.junit.Test; -import org.jboss.logging.Logger; - import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; diff --git a/hibernate-core/src/test/java/org/hibernate/test/legacy/FumTest.java b/hibernate-core/src/test/java/org/hibernate/test/legacy/FumTest.java index 7fffc1a267..ff6cb56949 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/legacy/FumTest.java +++ b/hibernate-core/src/test/java/org/hibernate/test/legacy/FumTest.java @@ -25,7 +25,6 @@ import java.util.Map; import java.util.Properties; import java.util.Set; -import org.hibernate.Criteria; import org.hibernate.FetchMode; import org.hibernate.FlushMode; import org.hibernate.Hibernate; diff --git a/hibernate-core/src/test/java/org/hibernate/test/legacy/MultiTableTest.java b/hibernate-core/src/test/java/org/hibernate/test/legacy/MultiTableTest.java index 27051f04d1..5223d6daae 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/legacy/MultiTableTest.java +++ b/hibernate-core/src/test/java/org/hibernate/test/legacy/MultiTableTest.java @@ -23,7 +23,6 @@ import java.util.Iterator; import java.util.List; import java.util.Set; -import org.hibernate.Criteria; import org.hibernate.FetchMode; import org.hibernate.LockMode; import org.hibernate.Session; diff --git a/hibernate-core/src/test/java/org/hibernate/test/legacy/ParentChildTest.java b/hibernate-core/src/test/java/org/hibernate/test/legacy/ParentChildTest.java index a0125d7889..c619c84008 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/legacy/ParentChildTest.java +++ b/hibernate-core/src/test/java/org/hibernate/test/legacy/ParentChildTest.java @@ -22,7 +22,6 @@ import org.hibernate.testing.RequiresDialectFeature; import org.hibernate.testing.SkipForDialect; import org.junit.Test; -import org.hibernate.Criteria; import org.hibernate.FetchMode; import org.hibernate.Hibernate; import org.hibernate.HibernateException; diff --git a/hibernate-core/src/test/java/org/hibernate/test/legacy/QueryByExampleTest.java b/hibernate-core/src/test/java/org/hibernate/test/legacy/QueryByExampleTest.java index 8b985f16ad..064b8f6f23 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/legacy/QueryByExampleTest.java +++ b/hibernate-core/src/test/java/org/hibernate/test/legacy/QueryByExampleTest.java @@ -9,7 +9,6 @@ import java.util.List; import org.junit.Test; -import org.hibernate.Criteria; import org.hibernate.Session; import org.hibernate.Transaction; import org.hibernate.criterion.Example; diff --git a/hibernate-core/src/test/java/org/hibernate/test/locking/paging/PagingAndLockingTest.java b/hibernate-core/src/test/java/org/hibernate/test/locking/paging/PagingAndLockingTest.java index d29bf5a3f3..2cb5948da7 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/locking/paging/PagingAndLockingTest.java +++ b/hibernate-core/src/test/java/org/hibernate/test/locking/paging/PagingAndLockingTest.java @@ -8,7 +8,6 @@ package org.hibernate.test.locking.paging; import java.util.List; -import org.hibernate.Criteria; import org.hibernate.LockMode; import org.hibernate.Query; import org.hibernate.SQLQuery; diff --git a/hibernate-core/src/test/java/org/hibernate/test/manytomany/ordered/OrderedManyToManyTest.java b/hibernate-core/src/test/java/org/hibernate/test/manytomany/ordered/OrderedManyToManyTest.java index 8a8fafd705..c1b39795fd 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/manytomany/ordered/OrderedManyToManyTest.java +++ b/hibernate-core/src/test/java/org/hibernate/test/manytomany/ordered/OrderedManyToManyTest.java @@ -8,7 +8,6 @@ package org.hibernate.test.manytomany.ordered; import java.util.List; -import org.hibernate.Criteria; import org.hibernate.FetchMode; import org.hibernate.Hibernate; import org.hibernate.Session; diff --git a/hibernate-core/src/test/java/org/hibernate/test/pagination/PaginationTest.java b/hibernate-core/src/test/java/org/hibernate/test/pagination/PaginationTest.java index adf6a0b39d..2a0bf2037f 100755 --- a/hibernate-core/src/test/java/org/hibernate/test/pagination/PaginationTest.java +++ b/hibernate-core/src/test/java/org/hibernate/test/pagination/PaginationTest.java @@ -12,12 +12,11 @@ import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; -import org.hibernate.Criteria; import org.hibernate.Query; import org.hibernate.SQLQuery; import org.hibernate.Session; import org.hibernate.criterion.Order; -import org.hibernate.engine.query.spi.HQLQueryPlan; + import org.hibernate.testing.DialectChecks; import org.hibernate.testing.RequiresDialectFeature; import org.hibernate.testing.TestForIssue; diff --git a/hibernate-core/src/test/java/org/hibernate/test/propertyref/cachedcollections/CachedPropertyRefCollectionTest.java b/hibernate-core/src/test/java/org/hibernate/test/propertyref/cachedcollections/CachedPropertyRefCollectionTest.java index 580994847e..2a57a3e1e3 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/propertyref/cachedcollections/CachedPropertyRefCollectionTest.java +++ b/hibernate-core/src/test/java/org/hibernate/test/propertyref/cachedcollections/CachedPropertyRefCollectionTest.java @@ -8,7 +8,6 @@ package org.hibernate.test.propertyref.cachedcollections; import org.junit.Test; -import org.hibernate.Criteria; import org.hibernate.FetchMode; import org.hibernate.Hibernate; import org.hibernate.Session; diff --git a/hibernate-core/src/test/java/org/hibernate/test/querycache/AbstractQueryCacheResultTransformerTest.java b/hibernate-core/src/test/java/org/hibernate/test/querycache/AbstractQueryCacheResultTransformerTest.java index 8dac163849..a144c63e5f 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/querycache/AbstractQueryCacheResultTransformerTest.java +++ b/hibernate-core/src/test/java/org/hibernate/test/querycache/AbstractQueryCacheResultTransformerTest.java @@ -15,7 +15,6 @@ import java.util.Map; import org.junit.Test; import org.hibernate.CacheMode; -import org.hibernate.Criteria; import org.hibernate.FetchMode; import org.hibernate.Hibernate; import org.hibernate.Query; @@ -28,7 +27,6 @@ import org.hibernate.criterion.Order; import org.hibernate.criterion.Projections; import org.hibernate.criterion.Property; import org.hibernate.criterion.Restrictions; -import org.hibernate.internal.SessionFactoryImpl; import org.hibernate.internal.util.ReflectHelper; import org.hibernate.proxy.HibernateProxy; import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; diff --git a/hibernate-core/src/test/java/org/hibernate/test/querycache/QueryCacheTest.java b/hibernate-core/src/test/java/org/hibernate/test/querycache/QueryCacheTest.java index 7855edda7a..4f1598e38a 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/querycache/QueryCacheTest.java +++ b/hibernate-core/src/test/java/org/hibernate/test/querycache/QueryCacheTest.java @@ -17,7 +17,6 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; -import org.hibernate.Criteria; import org.hibernate.EmptyInterceptor; import org.hibernate.Hibernate; import org.hibernate.Query; diff --git a/hibernate-core/src/test/java/org/hibernate/test/queryhint/QueryHintHANATest.java b/hibernate-core/src/test/java/org/hibernate/test/queryhint/QueryHintHANATest.java index ca46fd7ac2..0cd4e68511 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/queryhint/QueryHintHANATest.java +++ b/hibernate-core/src/test/java/org/hibernate/test/queryhint/QueryHintHANATest.java @@ -20,7 +20,6 @@ import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.ManyToOne; -import org.hibernate.Criteria; import org.hibernate.cfg.AvailableSettings; import org.hibernate.criterion.Restrictions; import org.hibernate.dialect.AbstractHANADialect; diff --git a/hibernate-core/src/test/java/org/hibernate/test/queryhint/QueryHintSQLServer2012Test.java b/hibernate-core/src/test/java/org/hibernate/test/queryhint/QueryHintSQLServer2012Test.java index cbcbdb7278..9026fa4e56 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/queryhint/QueryHintSQLServer2012Test.java +++ b/hibernate-core/src/test/java/org/hibernate/test/queryhint/QueryHintSQLServer2012Test.java @@ -13,7 +13,6 @@ import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.ManyToOne; -import org.hibernate.Criteria; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.cfg.AvailableSettings; diff --git a/hibernate-core/src/test/java/org/hibernate/test/queryhint/QueryHintTest.java b/hibernate-core/src/test/java/org/hibernate/test/queryhint/QueryHintTest.java index 504d3827e1..a3fa9cda80 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/queryhint/QueryHintTest.java +++ b/hibernate-core/src/test/java/org/hibernate/test/queryhint/QueryHintTest.java @@ -14,7 +14,6 @@ import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.ManyToOne; -import org.hibernate.Criteria; import org.hibernate.cfg.AvailableSettings; import org.hibernate.criterion.Restrictions; import org.hibernate.dialect.Oracle8iDialect; diff --git a/hibernate-core/src/test/java/org/hibernate/test/queryplan/GetHqlQueryPlanTest.java b/hibernate-core/src/test/java/org/hibernate/test/queryplan/GetHqlQueryPlanTest.java index 0ded247165..e53a72f76d 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/queryplan/GetHqlQueryPlanTest.java +++ b/hibernate-core/src/test/java/org/hibernate/test/queryplan/GetHqlQueryPlanTest.java @@ -10,7 +10,6 @@ import java.util.Arrays; import java.util.Map; import org.hibernate.Session; -import org.hibernate.engine.query.spi.HQLQueryPlan; import org.hibernate.query.spi.QueryInterpretationCache; import org.hibernate.engine.spi.SessionFactoryImplementor; import org.hibernate.engine.spi.SessionImplementor; diff --git a/hibernate-core/src/test/java/org/hibernate/test/readonly/ReadOnlyCriteriaQueryTest.java b/hibernate-core/src/test/java/org/hibernate/test/readonly/ReadOnlyCriteriaQueryTest.java index 00a1b39984..d5846aa5f6 100755 --- a/hibernate-core/src/test/java/org/hibernate/test/readonly/ReadOnlyCriteriaQueryTest.java +++ b/hibernate-core/src/test/java/org/hibernate/test/readonly/ReadOnlyCriteriaQueryTest.java @@ -10,7 +10,6 @@ import java.util.List; import org.junit.Test; -import org.hibernate.Criteria; import org.hibernate.Hibernate; import org.hibernate.ScrollableResults; import org.hibernate.Session; diff --git a/hibernate-core/src/test/java/org/hibernate/test/stateless/StatelessSessionQueryTest.java b/hibernate-core/src/test/java/org/hibernate/test/stateless/StatelessSessionQueryTest.java index 9e99980f33..2e2ae8c565 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/stateless/StatelessSessionQueryTest.java +++ b/hibernate-core/src/test/java/org/hibernate/test/stateless/StatelessSessionQueryTest.java @@ -40,29 +40,6 @@ public class StatelessSessionQueryTest extends BaseCoreFunctionalTestCase { return new String[] { "stateless/Contact.hbm.xml" }; } - @Test - @SkipForDialect(value = AbstractHANADialect.class, comment = " HANA doesn't support tables consisting of only a single auto-generated column") - public void testCriteria() { - TestData testData=new TestData(); - testData.createData(); - StatelessSession s = sessionFactory().openStatelessSession(); - assertEquals( 1, s.createCriteria( Contact.class ).list().size() ); - s.close(); - testData.cleanData(); - } - - @Test - @SkipForDialect(value = AbstractHANADialect.class, comment = " HANA doesn't support tables consisting of only a single auto-generated column") - public void testCriteriaWithSelectFetchMode() { - TestData testData=new TestData(); - testData.createData(); - StatelessSession s = sessionFactory().openStatelessSession(); - assertEquals( 1, s.createCriteria( Contact.class ).setFetchMode( "org", FetchMode.SELECT ) - .list().size() ); - s.close(); - testData.cleanData(); - } - @Test @SkipForDialect(value = AbstractHANADialect.class, comment = " HANA doesn't support tables consisting of only a single auto-generated column") public void testHQL() { @@ -75,29 +52,6 @@ public class StatelessSessionQueryTest extends BaseCoreFunctionalTestCase { testData.cleanData(); } - @Test - @TestForIssue( jiraKey = "HHH-13194") - @SkipForDialect(value = AbstractHANADialect.class, comment = " HANA doesn't support tables consisting of only a single auto-generated column") - public void testDeprecatedQueryApis() { - TestData testData=new TestData(); - testData.createData(); - - final String queryString = "from Contact c join fetch c.org join fetch c.org.country"; - StatelessSession s = sessionFactory().openStatelessSession(); - - org.hibernate.Query query = s.createQuery( queryString ); - assertEquals( 1, query.getResultList().size() ); - - query = s.getNamedQuery( Contact.class.getName() + ".contacts" ); - assertEquals( 1, query.getResultList().size() ); - - org.hibernate.SQLQuery sqlQuery = s.createSQLQuery( "select id from Contact" ); - assertEquals( 1, sqlQuery.getResultList().size() ); - - s.close(); - testData.cleanData(); - } - @Test @TestForIssue( jiraKey = "HHH-13194") @SkipForDialect(value = AbstractHANADialect.class, comment = " HANA doesn't support tables consisting of only a single auto-generated column") diff --git a/hibernate-spatial/src/main/java/org/hibernate/spatial/criterion/DWithinExpression.java b/hibernate-spatial/src/main/java/org/hibernate/spatial/criterion/DWithinExpression.java index f030a40c86..ba879b7fcd 100644 --- a/hibernate-spatial/src/main/java/org/hibernate/spatial/criterion/DWithinExpression.java +++ b/hibernate-spatial/src/main/java/org/hibernate/spatial/criterion/DWithinExpression.java @@ -7,7 +7,6 @@ package org.hibernate.spatial.criterion; -import org.hibernate.Criteria; import org.hibernate.HibernateException; import org.hibernate.criterion.CriteriaQuery; import org.hibernate.criterion.Criterion; diff --git a/hibernate-spatial/src/main/java/org/hibernate/spatial/criterion/ExpressionUtil.java b/hibernate-spatial/src/main/java/org/hibernate/spatial/criterion/ExpressionUtil.java index d1b1f3476e..a4614457eb 100644 --- a/hibernate-spatial/src/main/java/org/hibernate/spatial/criterion/ExpressionUtil.java +++ b/hibernate-spatial/src/main/java/org/hibernate/spatial/criterion/ExpressionUtil.java @@ -7,7 +7,6 @@ package org.hibernate.spatial.criterion; -import org.hibernate.Criteria; import org.hibernate.HibernateException; import org.hibernate.criterion.CriteriaQuery; import org.hibernate.dialect.Dialect; diff --git a/hibernate-spatial/src/main/java/org/hibernate/spatial/criterion/HavingSridExpression.java b/hibernate-spatial/src/main/java/org/hibernate/spatial/criterion/HavingSridExpression.java index 404932c2a3..aa2ba07656 100644 --- a/hibernate-spatial/src/main/java/org/hibernate/spatial/criterion/HavingSridExpression.java +++ b/hibernate-spatial/src/main/java/org/hibernate/spatial/criterion/HavingSridExpression.java @@ -7,7 +7,6 @@ package org.hibernate.spatial.criterion; -import org.hibernate.Criteria; import org.hibernate.HibernateException; import org.hibernate.criterion.CriteriaQuery; import org.hibernate.criterion.Criterion; diff --git a/hibernate-spatial/src/main/java/org/hibernate/spatial/criterion/IsEmptyExpression.java b/hibernate-spatial/src/main/java/org/hibernate/spatial/criterion/IsEmptyExpression.java index cc8437e167..d9f1eeeb95 100644 --- a/hibernate-spatial/src/main/java/org/hibernate/spatial/criterion/IsEmptyExpression.java +++ b/hibernate-spatial/src/main/java/org/hibernate/spatial/criterion/IsEmptyExpression.java @@ -7,7 +7,6 @@ package org.hibernate.spatial.criterion; -import org.hibernate.Criteria; import org.hibernate.HibernateException; import org.hibernate.criterion.CriteriaQuery; import org.hibernate.criterion.Criterion; diff --git a/hibernate-spatial/src/main/java/org/hibernate/spatial/criterion/SpatialFilter.java b/hibernate-spatial/src/main/java/org/hibernate/spatial/criterion/SpatialFilter.java index c36d48b19b..803d9136ba 100644 --- a/hibernate-spatial/src/main/java/org/hibernate/spatial/criterion/SpatialFilter.java +++ b/hibernate-spatial/src/main/java/org/hibernate/spatial/criterion/SpatialFilter.java @@ -6,7 +6,6 @@ */ package org.hibernate.spatial.criterion; -import org.hibernate.Criteria; import org.hibernate.HibernateException; import org.hibernate.criterion.CriteriaQuery; import org.hibernate.criterion.Criterion; diff --git a/hibernate-spatial/src/main/java/org/hibernate/spatial/criterion/SpatialProjections.java b/hibernate-spatial/src/main/java/org/hibernate/spatial/criterion/SpatialProjections.java index 08557171d2..512bebf885 100644 --- a/hibernate-spatial/src/main/java/org/hibernate/spatial/criterion/SpatialProjections.java +++ b/hibernate-spatial/src/main/java/org/hibernate/spatial/criterion/SpatialProjections.java @@ -6,7 +6,6 @@ */ package org.hibernate.spatial.criterion; -import org.hibernate.Criteria; import org.hibernate.HibernateException; import org.hibernate.criterion.CriteriaQuery; import org.hibernate.criterion.Projection; diff --git a/hibernate-spatial/src/main/java/org/hibernate/spatial/criterion/SpatialRelateExpression.java b/hibernate-spatial/src/main/java/org/hibernate/spatial/criterion/SpatialRelateExpression.java index cd9f677526..62f2bdc0ff 100644 --- a/hibernate-spatial/src/main/java/org/hibernate/spatial/criterion/SpatialRelateExpression.java +++ b/hibernate-spatial/src/main/java/org/hibernate/spatial/criterion/SpatialRelateExpression.java @@ -6,7 +6,6 @@ */ package org.hibernate.spatial.criterion; -import org.hibernate.Criteria; import org.hibernate.HibernateException; import org.hibernate.criterion.CriteriaQuery; import org.hibernate.criterion.Criterion; diff --git a/hibernate-spatial/src/main/java/org/hibernate/spatial/dialect/oracle/criterion/OracleSpatialProjection.java b/hibernate-spatial/src/main/java/org/hibernate/spatial/dialect/oracle/criterion/OracleSpatialProjection.java index fe3073d6d2..f6e5bc5fe2 100644 --- a/hibernate-spatial/src/main/java/org/hibernate/spatial/dialect/oracle/criterion/OracleSpatialProjection.java +++ b/hibernate-spatial/src/main/java/org/hibernate/spatial/dialect/oracle/criterion/OracleSpatialProjection.java @@ -6,7 +6,6 @@ */ package org.hibernate.spatial.dialect.oracle.criterion; -import org.hibernate.Criteria; import org.hibernate.HibernateException; import org.hibernate.criterion.CriteriaQuery; import org.hibernate.criterion.SimpleProjection; diff --git a/hibernate-spatial/src/main/java/org/hibernate/spatial/dialect/oracle/criterion/OracleSpatialRestrictions.java b/hibernate-spatial/src/main/java/org/hibernate/spatial/dialect/oracle/criterion/OracleSpatialRestrictions.java index dee6ff2acf..6c1e9ffa07 100644 --- a/hibernate-spatial/src/main/java/org/hibernate/spatial/dialect/oracle/criterion/OracleSpatialRestrictions.java +++ b/hibernate-spatial/src/main/java/org/hibernate/spatial/dialect/oracle/criterion/OracleSpatialRestrictions.java @@ -6,7 +6,6 @@ */ package org.hibernate.spatial.dialect.oracle.criterion; -import org.hibernate.Criteria; import org.hibernate.HibernateException; import org.hibernate.criterion.CriteriaQuery; import org.hibernate.criterion.Criterion; diff --git a/hibernate-spatial/src/test/java/org/hibernate/spatial/integration/AbstractTestStoreRetrieve.java b/hibernate-spatial/src/test/java/org/hibernate/spatial/integration/AbstractTestStoreRetrieve.java index 5037e4f7b0..956772e6a0 100644 --- a/hibernate-spatial/src/test/java/org/hibernate/spatial/integration/AbstractTestStoreRetrieve.java +++ b/hibernate-spatial/src/test/java/org/hibernate/spatial/integration/AbstractTestStoreRetrieve.java @@ -4,7 +4,6 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -import org.hibernate.Criteria; import org.hibernate.Session; import org.hibernate.Transaction; import org.hibernate.dialect.Dialect; diff --git a/hibernate-spatial/src/test/java/org/hibernate/spatial/integration/TestSpatialRestrictions.java b/hibernate-spatial/src/test/java/org/hibernate/spatial/integration/TestSpatialRestrictions.java index c82c16a650..b95687b029 100644 --- a/hibernate-spatial/src/test/java/org/hibernate/spatial/integration/TestSpatialRestrictions.java +++ b/hibernate-spatial/src/test/java/org/hibernate/spatial/integration/TestSpatialRestrictions.java @@ -11,7 +11,6 @@ import java.sql.SQLException; import java.util.List; import java.util.Map; -import org.hibernate.Criteria; import org.hibernate.Session; import org.hibernate.Transaction; import org.hibernate.criterion.Criterion;