diff --git a/hibernate-core/src/main/java/org/hibernate/cfg/annotations/BasicValueBinder.java b/hibernate-core/src/main/java/org/hibernate/cfg/annotations/BasicValueBinder.java index 5e6210e6ec94..e477c30033f6 100644 --- a/hibernate-core/src/main/java/org/hibernate/cfg/annotations/BasicValueBinder.java +++ b/hibernate-core/src/main/java/org/hibernate/cfg/annotations/BasicValueBinder.java @@ -222,7 +222,8 @@ public void setType( XClass modelPropertyTypeXClass, String declaringClassName, ConverterDescriptor converterDescriptor) { - if ( modelPropertyTypeXClass == null ) { + boolean isArray = modelXProperty.isArray(); + if ( modelPropertyTypeXClass == null && !isArray ) { // we cannot guess anything return; } @@ -232,7 +233,7 @@ public void setType( } assert columns.length == 1; - final XClass modelTypeXClass = modelXProperty.isArray() + final XClass modelTypeXClass = isArray ? modelXProperty.getElementClass() : modelPropertyTypeXClass; @@ -383,10 +384,18 @@ private void prepareCollectionElement(XProperty attributeXProperty, XClass eleme // todo (6.0) : @SqlType / @SqlTypeDescriptor + Class javaType; //noinspection unchecked - final Class javaType = buildingContext.getBootstrapContext() - .getReflectionManager() - .toClass( elementTypeXClass ); + if ( elementTypeXClass == null && attributeXProperty.isArray() ) { + javaType = buildingContext.getBootstrapContext() + .getReflectionManager() + .toClass( attributeXProperty.getElementClass() ); + } + else { + javaType = buildingContext.getBootstrapContext() + .getReflectionManager() + .toClass( elementTypeXClass ); + } implicitJavaTypeAccess = typeConfiguration -> javaType; diff --git a/hibernate-core/src/main/java/org/hibernate/collection/internal/StandardCollectionSemanticsResolver.java b/hibernate-core/src/main/java/org/hibernate/collection/internal/StandardCollectionSemanticsResolver.java index 6b5119a3eed6..16635d82f8ec 100644 --- a/hibernate-core/src/main/java/org/hibernate/collection/internal/StandardCollectionSemanticsResolver.java +++ b/hibernate-core/src/main/java/org/hibernate/collection/internal/StandardCollectionSemanticsResolver.java @@ -33,7 +33,7 @@ public class StandardCollectionSemanticsResolver implements CollectionSemanticsR @Override public CollectionSemantics resolveRepresentation(Collection bootDescriptor) { if ( bootDescriptor instanceof PrimitiveArray ) { - throw new NotYetImplementedFor6Exception(); + return StandardArraySemantics.INSTANCE; } if ( bootDescriptor instanceof Array ) { diff --git a/hibernate-core/src/main/java/org/hibernate/mapping/BasicValue.java b/hibernate-core/src/main/java/org/hibernate/mapping/BasicValue.java index b682efcf68eb..2515973e9520 100644 --- a/hibernate-core/src/main/java/org/hibernate/mapping/BasicValue.java +++ b/hibernate-core/src/main/java/org/hibernate/mapping/BasicValue.java @@ -434,12 +434,11 @@ else if ( ownerName != null && propertyName != null ) { ); } else { - impliedJavaType = null; + return null; } - return impliedJavaType == null - ? null - : typeConfiguration.getJavaTypeDescriptorRegistry().resolveDescriptor( impliedJavaType ); + resolvedJavaClass = impliedJavaType; + return typeConfiguration.getJavaTypeDescriptorRegistry().resolveDescriptor( impliedJavaType ); } diff --git a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/BasicValuedCollectionPart.java b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/BasicValuedCollectionPart.java index 1cda36cfac91..67113c35fc21 100644 --- a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/BasicValuedCollectionPart.java +++ b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/BasicValuedCollectionPart.java @@ -8,6 +8,7 @@ import java.util.Collections; import java.util.List; +import java.util.function.Consumer; import org.hibernate.LockMode; import org.hibernate.engine.FetchStyle; @@ -23,6 +24,7 @@ import org.hibernate.persister.collection.CollectionPersister; import org.hibernate.query.EntityIdentifierNavigablePath; import org.hibernate.query.NavigablePath; +import org.hibernate.sql.ast.Clause; import org.hibernate.sql.ast.spi.SqlExpressionResolver; import org.hibernate.sql.ast.spi.SqlSelection; import org.hibernate.sql.ast.tree.expression.ColumnReference; @@ -230,7 +232,13 @@ public FetchTiming getTiming() { return FetchTiming.IMMEDIATE; } -// + @Override + public void visitJdbcTypes( + Consumer action, Clause clause, TypeConfiguration typeConfiguration) { + action.accept( getJdbcMapping() ); + } + + // // @Override // public BasicType getBasicType() { // return mapper; diff --git a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/EmbeddedCollectionPart.java b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/EmbeddedCollectionPart.java index c099668af043..894e7f906e17 100644 --- a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/EmbeddedCollectionPart.java +++ b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/EmbeddedCollectionPart.java @@ -162,7 +162,7 @@ public Fetch generateFetch( fetchParent, FetchTiming.IMMEDIATE, selected, - false, + true, creationState ); } diff --git a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/PluralAttributeMappingImpl.java b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/PluralAttributeMappingImpl.java index 1eef259ae1b1..6500dbfd6124 100644 --- a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/PluralAttributeMappingImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/PluralAttributeMappingImpl.java @@ -32,6 +32,7 @@ import org.hibernate.metamodel.mapping.EmbeddableValuedModelPart; import org.hibernate.metamodel.mapping.EntityMappingType; import org.hibernate.metamodel.mapping.ForeignKeyDescriptor; +import org.hibernate.metamodel.mapping.JdbcMapping; import org.hibernate.metamodel.mapping.ManagedMappingType; import org.hibernate.metamodel.mapping.ModelPart; import org.hibernate.metamodel.mapping.PluralAttributeMapping; @@ -47,6 +48,7 @@ import org.hibernate.persister.entity.Joinable; import org.hibernate.property.access.spi.PropertyAccess; import org.hibernate.query.NavigablePath; +import org.hibernate.sql.ast.Clause; import org.hibernate.sql.ast.SqlAstJoinType; import org.hibernate.sql.ast.spi.FromClauseAccess; import org.hibernate.sql.ast.spi.SqlAliasBase; @@ -71,6 +73,7 @@ import org.hibernate.sql.results.graph.collection.internal.EagerCollectionFetch; import org.hibernate.sql.results.graph.collection.internal.SelectEagerCollectionFetch; import org.hibernate.type.EntityType; +import org.hibernate.type.spi.TypeConfiguration; import org.jboss.logging.Logger; @@ -857,6 +860,15 @@ public void visitSubParts(Consumer consumer, EntityMappingType treatT } } + @Override + public void visitJdbcTypes( + Consumer action, Clause clause, TypeConfiguration typeConfiguration) { + elementDescriptor.visitJdbcTypes( action, clause, typeConfiguration ); + if ( indexDescriptor != null ) { + indexDescriptor.visitJdbcTypes( action, clause, typeConfiguration ); + } + } + @Override public int getNumberOfFetchables() { return indexDescriptor == null ? 1 : 2; diff --git a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/ToOneAttributeMapping.java b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/ToOneAttributeMapping.java index dfe48e1227e3..5cad8537c497 100644 --- a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/ToOneAttributeMapping.java +++ b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/ToOneAttributeMapping.java @@ -14,6 +14,7 @@ import org.hibernate.mapping.OneToOne; import org.hibernate.mapping.ToOne; import org.hibernate.metamodel.mapping.AssociationKey; +import org.hibernate.metamodel.mapping.CollectionPart; import org.hibernate.metamodel.mapping.EntityAssociationMapping; import org.hibernate.metamodel.mapping.EntityIdentifierMapping; import org.hibernate.metamodel.mapping.EntityMappingType; @@ -495,11 +496,16 @@ public EntityFetch generateFetch( private TableGroup createTableGroupJoin( NavigablePath fetchablePath, LockMode lockMode, - DomainResultCreationState creationState, TableGroup parentTableGroup) { + DomainResultCreationState creationState, + TableGroup parentTableGroup) { final SqlAstJoinType sqlAstJoinType; + if ( isNullable ) { sqlAstJoinType = SqlAstJoinType.LEFT; } + else if ( parentTableGroup.getModelPart() instanceof EmbeddedCollectionPart ) { + sqlAstJoinType = SqlAstJoinType.LEFT; + } else { sqlAstJoinType = SqlAstJoinType.INNER; } diff --git a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/ordering/OrderByFragment.java b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/ordering/OrderByFragment.java index 3c4781ee9233..9533ef250f84 100644 --- a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/ordering/OrderByFragment.java +++ b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/ordering/OrderByFragment.java @@ -25,4 +25,5 @@ public interface OrderByFragment { * @param creationState The SQL AST creation state */ void apply(QuerySpec ast, TableGroup tableGroup, SqlAstCreationState creationState); + } diff --git a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/ordering/OrderByFragmentImpl.java b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/ordering/OrderByFragmentImpl.java new file mode 100644 index 000000000000..17a801f1f95c --- /dev/null +++ b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/ordering/OrderByFragmentImpl.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.metamodel.mapping.ordering; + +import java.util.List; + +import org.hibernate.metamodel.mapping.ordering.ast.OrderingSpecification; +import org.hibernate.sql.ast.spi.SqlAstCreationState; +import org.hibernate.sql.ast.tree.from.TableGroup; +import org.hibernate.sql.ast.tree.select.QuerySpec; + +/** + * @author Steve Ebersole + */ +public class OrderByFragmentImpl implements OrderByFragment { + private final List fragmentSpecs; + + public OrderByFragmentImpl(List fragmentSpecs) { + this.fragmentSpecs = fragmentSpecs; + } + + public List getFragmentSpecs() { + return fragmentSpecs; + } + + @Override + public void apply(QuerySpec ast, TableGroup tableGroup, SqlAstCreationState creationState) { + for ( int i = 0; i < fragmentSpecs.size(); i++ ) { + final OrderingSpecification orderingSpec = fragmentSpecs.get( i ); + + orderingSpec.getExpression().apply( + ast, + tableGroup, + orderingSpec.getCollation(), + orderingSpec.getSortOrder(), + creationState + ); + } + } +} diff --git a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/ordering/OrderByFragmentTranslator.java b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/ordering/OrderByFragmentTranslator.java index 51f4099a7d87..d37f8cbd8d50 100644 --- a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/ordering/OrderByFragmentTranslator.java +++ b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/ordering/OrderByFragmentTranslator.java @@ -6,16 +6,10 @@ */ package org.hibernate.metamodel.mapping.ordering; -import java.util.List; - import org.hibernate.grammars.ordering.OrderingLexer; import org.hibernate.grammars.ordering.OrderingParser; import org.hibernate.metamodel.mapping.PluralAttributeMapping; -import org.hibernate.metamodel.mapping.ordering.ast.OrderingSpecification; import org.hibernate.metamodel.mapping.ordering.ast.ParseTreeVisitor; -import org.hibernate.sql.ast.spi.SqlAstCreationState; -import org.hibernate.sql.ast.tree.from.TableGroup; -import org.hibernate.sql.ast.tree.select.QuerySpec; import org.jboss.logging.Logger; @@ -31,10 +25,9 @@ * Responsible for performing the translation of the order-by fragment associated * with an order set or map. * + * @author Steve Ebersole * @see javax.persistence.OrderBy * @see org.hibernate.annotations.OrderBy - * - * @author Steve Ebersole */ public class OrderByFragmentTranslator { private static final Logger LOG = Logger.getLogger( OrderByFragmentTranslator.class.getName() ); @@ -42,11 +35,11 @@ public class OrderByFragmentTranslator { /** * Perform the translation of the user-supplied fragment, returning the translation. * + * @return The translation. + * * @apiNote The important distinction to this split between (1) translating and (2) resolving aliases is that * both happen at different times. This is performed at boot-time while building the CollectionPersister * happens at runtime while loading the described collection - * - * @return The translation. */ public static OrderByFragment translate( String fragment, @@ -64,26 +57,7 @@ public static OrderByFragment translate( final ParseTreeVisitor visitor = new ParseTreeVisitor( pluralAttributeMapping, context ); - final List specs = visitor.visitOrderByFragment( parseTree ); - - return new OrderByFragment() { - private final List fragmentSpecs = specs; - - @Override - public void apply(QuerySpec ast, TableGroup tableGroup, SqlAstCreationState creationState) { - for ( int i = 0; i < fragmentSpecs.size(); i++ ) { - final OrderingSpecification orderingSpec = fragmentSpecs.get( i ); - - orderingSpec.getExpression().apply( - ast, - tableGroup, - orderingSpec.getCollation(), - orderingSpec.getSortOrder(), - creationState - ); - } - } - }; + return new OrderByFragmentImpl( visitor.visitOrderByFragment( parseTree ) ); } @@ -100,7 +74,7 @@ private static OrderingParser.OrderByFragmentContext buildParseTree(TranslationC try { return parser.orderByFragment(); } - catch ( ParseCancellationException e) { + catch (ParseCancellationException e) { // reset the input token stream and parser state lexer.reset(); parser.reset(); diff --git a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/ordering/ast/DomainPathContinuation.java b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/ordering/ast/DomainPathContinuation.java index cdc1989c3c62..c5a7f7870728 100644 --- a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/ordering/ast/DomainPathContinuation.java +++ b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/ordering/ast/DomainPathContinuation.java @@ -6,6 +6,7 @@ */ package org.hibernate.metamodel.mapping.ordering.ast; +import org.hibernate.metamodel.mapping.EmbeddableMappingType; import org.hibernate.metamodel.mapping.EmbeddableValuedModelPart; import org.hibernate.metamodel.mapping.ModelPart; import org.hibernate.metamodel.mapping.ordering.TranslationContext; @@ -47,11 +48,9 @@ public SequencePart resolvePathPart( String name, boolean isTerminal, TranslationContext translationContext) { - if ( referencedModelPart.getPartMappingType() instanceof EmbeddableValuedModelPart ) { - final EmbeddableValuedModelPart embeddableValuedPart = - (EmbeddableValuedModelPart) referencedModelPart.getPartMappingType(); - - final ModelPart subPart = embeddableValuedPart.findSubPart( name, null ); + if ( referencedModelPart instanceof EmbeddableValuedModelPart ) { + final EmbeddableMappingType embeddableMappingType = (EmbeddableMappingType) referencedModelPart.getPartMappingType(); + final ModelPart subPart = embeddableMappingType.findSubPart( name, null ); if ( subPart == null ) { throw new PathResolutionException( "Could not resolve path token : " + referencedModelPart + " -> " + name diff --git a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/ordering/ast/ParseTreeVisitor.java b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/ordering/ast/ParseTreeVisitor.java index f7164e7ecc5c..bc9e993886d4 100644 --- a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/ordering/ast/ParseTreeVisitor.java +++ b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/ordering/ast/ParseTreeVisitor.java @@ -105,9 +105,8 @@ public OrderingExpression visitExpression(ExpressionContext ctx) { for ( int i = 0; i < numberOfParts; i++ ) { final TerminalNode partNode = ctx.dotIdentifier().IDENTIFIER().get( i ); - partNode.getText(); pathConsumer.consumeIdentifier( - ctx.identifier().getText(), + partNode.getText(), firstPass, true ); diff --git a/hibernate-core/src/main/java/org/hibernate/sql/ast/spi/AbstractSqlAstWalker.java b/hibernate-core/src/main/java/org/hibernate/sql/ast/spi/AbstractSqlAstWalker.java index 3dca43b5433a..5fdfe4651fd4 100644 --- a/hibernate-core/src/main/java/org/hibernate/sql/ast/spi/AbstractSqlAstWalker.java +++ b/hibernate-core/src/main/java/org/hibernate/sql/ast/spi/AbstractSqlAstWalker.java @@ -22,7 +22,13 @@ import org.hibernate.internal.util.StringHelper; import org.hibernate.internal.util.collections.Stack; import org.hibernate.internal.util.collections.StandardStack; +import org.hibernate.metamodel.mapping.Association; +import org.hibernate.metamodel.mapping.CollectionPart; +import org.hibernate.metamodel.mapping.ForeignKeyDescriptor; import org.hibernate.metamodel.mapping.JdbcMapping; +import org.hibernate.metamodel.mapping.ModelPartContainer; +import org.hibernate.metamodel.mapping.PluralAttributeMapping; +import org.hibernate.metamodel.mapping.internal.BasicValuedCollectionPart; import org.hibernate.persister.entity.Loadable; import org.hibernate.query.QueryLiteralRendering; import org.hibernate.query.UnaryArithmeticOperator; @@ -462,7 +468,21 @@ public void visitTableGroup(TableGroup tableGroup) { appendSql( tableGroup.getPrimaryTableReference().getIdentificationVariable() ); appendSql( '.' ); //TODO: pretty sure the typecast to Loadable is quite wrong here - appendSql( ( (Loadable) tableGroup.getModelPart() ).getIdentifierColumnNames()[0] ); + + ModelPartContainer modelPart = tableGroup.getModelPart(); + if ( modelPart instanceof Loadable ) { + appendSql( ( (Loadable) tableGroup.getModelPart() ).getIdentifierColumnNames()[0] ); + } + else if ( modelPart instanceof PluralAttributeMapping ) { + CollectionPart elementDescriptor = ( (PluralAttributeMapping) modelPart ).getElementDescriptor(); + if ( elementDescriptor instanceof BasicValuedCollectionPart ) { + String mappedColumnExpression = ( (BasicValuedCollectionPart) elementDescriptor ).getMappedColumnExpression(); + appendSql( mappedColumnExpression ); + } + } + else { + throw new NotYetImplementedFor6Exception( getClass() ); + } } @Override diff --git a/hibernate-core/src/main/java/org/hibernate/sql/results/graph/embeddable/AbstractEmbeddableInitializer.java b/hibernate-core/src/main/java/org/hibernate/sql/results/graph/embeddable/AbstractEmbeddableInitializer.java index e016534dac36..a3e761819600 100644 --- a/hibernate-core/src/main/java/org/hibernate/sql/results/graph/embeddable/AbstractEmbeddableInitializer.java +++ b/hibernate-core/src/main/java/org/hibernate/sql/results/graph/embeddable/AbstractEmbeddableInitializer.java @@ -11,7 +11,6 @@ import org.hibernate.metamodel.mapping.EmbeddableMappingType; import org.hibernate.metamodel.mapping.EmbeddableValuedModelPart; -import org.hibernate.metamodel.mapping.EntityIdentifierMapping; import org.hibernate.metamodel.mapping.SingularAttributeMapping; import org.hibernate.metamodel.mapping.StateArrayContributorMapping; import org.hibernate.query.NavigablePath; diff --git a/hibernate-core/src/main/java/org/hibernate/sql/results/graph/embeddable/internal/EmbeddableFetchInitializer.java b/hibernate-core/src/main/java/org/hibernate/sql/results/graph/embeddable/internal/EmbeddableFetchInitializer.java index a75b69e521fa..0ae5bca5fcd2 100644 --- a/hibernate-core/src/main/java/org/hibernate/sql/results/graph/embeddable/internal/EmbeddableFetchInitializer.java +++ b/hibernate-core/src/main/java/org/hibernate/sql/results/graph/embeddable/internal/EmbeddableFetchInitializer.java @@ -9,15 +9,13 @@ import org.hibernate.sql.results.graph.AssemblerCreationState; import org.hibernate.sql.results.graph.FetchParentAccess; import org.hibernate.sql.results.graph.embeddable.AbstractEmbeddableInitializer; -import org.hibernate.sql.results.graph.embeddable.EmbeddableInitializer; import org.hibernate.sql.results.graph.embeddable.EmbeddableResultGraphNode; /** * @author Steve Ebersole */ public class EmbeddableFetchInitializer - extends AbstractEmbeddableInitializer - implements EmbeddableInitializer { + extends AbstractEmbeddableInitializer { public EmbeddableFetchInitializer( FetchParentAccess fetchParentAccess, EmbeddableResultGraphNode resultDescriptor, diff --git a/hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/Boy.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/Boy.java similarity index 88% rename from hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/Boy.java rename to hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/Boy.java index 1485eaf98fa1..95b0b96dcf7c 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/Boy.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/Boy.java @@ -6,7 +6,7 @@ */ //$Id$ -package org.hibernate.test.annotations.collectionelement; +package org.hibernate.orm.test.annotations.collectionelement; import java.util.HashMap; import java.util.HashSet; import java.util.Map; @@ -41,16 +41,16 @@ public class Boy { private Integer id; private String firstName; private String lastName; - private Set nickNames = new HashSet(); - private Set hatedNames = new HashSet(); - private Set preferredNames = new HashSet(); - private Map scorePerNickName = new HashMap(); - private Map scorePerPreferredName = new HashMap(); + private Set nickNames = new HashSet<>(); + private Set hatedNames = new HashSet<>(); + private Set preferredNames = new HashSet<>(); + private Map scorePerNickName = new HashMap<>(); + private Map scorePerPreferredName = new HashMap<>(); private int[] favoriteNumbers; - private Set favoriteToys = new HashSet(); - private Set characters = new HashSet(); - private Map foods = new HashMap(); - private Set countryAttitudes = new HashSet(); + private Set favoriteToys = new HashSet<>(); + private Set characters = new HashSet<>(); + private Map foods = new HashMap<>(); + private Set countryAttitudes = new HashSet<>(); @Id @GeneratedValue diff --git a/hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/Brand.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/Brand.java similarity index 93% rename from hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/Brand.java rename to hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/Brand.java index faf3774eab0c..46ac9d777539 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/Brand.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/Brand.java @@ -6,7 +6,7 @@ */ //$Id$ -package org.hibernate.test.annotations.collectionelement; +package org.hibernate.orm.test.annotations.collectionelement; import javax.persistence.Embeddable; /** diff --git a/hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/Bug.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/Bug.java similarity index 93% rename from hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/Bug.java rename to hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/Bug.java index 3255f340ac23..5f56b7ad9645 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/Bug.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/Bug.java @@ -4,7 +4,8 @@ * 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.test.annotations.collectionelement; +package org.hibernate.orm.test.annotations.collectionelement; + import javax.persistence.Column; import javax.persistence.Embeddable; diff --git a/hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/BugSystem.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/BugSystem.java similarity index 93% rename from hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/BugSystem.java rename to hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/BugSystem.java index 62050eb4ab55..88b0f2e88f3d 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/BugSystem.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/BugSystem.java @@ -4,7 +4,7 @@ * 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.test.annotations.collectionelement; +package org.hibernate.orm.test.annotations.collectionelement; import java.util.Set; import javax.persistence.ElementCollection; import javax.persistence.Entity; diff --git a/hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/Character.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/Character.java similarity index 85% rename from hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/Character.java rename to hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/Character.java index 803870dbb3d6..4cd9c317ce68 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/Character.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/Character.java @@ -4,7 +4,7 @@ * 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.test.annotations.collectionelement; +package org.hibernate.orm.test.annotations.collectionelement; /** diff --git a/hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/CountryAttitude.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/CountryAttitude.java similarity index 95% rename from hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/CountryAttitude.java rename to hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/CountryAttitude.java index 38dad5391f1f..900c5477fc1b 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/CountryAttitude.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/CountryAttitude.java @@ -6,7 +6,7 @@ */ //$Id$ -package org.hibernate.test.annotations.collectionelement; +package org.hibernate.orm.test.annotations.collectionelement; import javax.persistence.Column; import javax.persistence.Embeddable; import javax.persistence.ManyToOne; diff --git a/hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/CustomImprovedNamingCollectionElementTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/CustomImprovedNamingCollectionElementTest.java similarity index 58% rename from hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/CustomImprovedNamingCollectionElementTest.java rename to hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/CustomImprovedNamingCollectionElementTest.java index 87fab5d12935..10670c88e053 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/CustomImprovedNamingCollectionElementTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/CustomImprovedNamingCollectionElementTest.java @@ -4,112 +4,98 @@ * 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.test.annotations.collectionelement; +package org.hibernate.orm.test.annotations.collectionelement; -import org.hibernate.boot.MetadataBuilder; -import org.hibernate.boot.model.naming.Identifier; -import org.hibernate.boot.model.naming.ImplicitCollectionTableNameSource; -import org.hibernate.boot.model.naming.ImplicitJoinColumnNameSource; -import org.hibernate.boot.model.naming.ImplicitNamingStrategyJpaCompliantImpl; +import org.hibernate.cfg.AvailableSettings; import org.hibernate.testing.TestForIssue; -import org.junit.Test; +import org.hibernate.testing.orm.junit.ServiceRegistry; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.junit.jupiter.api.Test; /** * @author Gail Badner */ +@ServiceRegistry(settings = { + @ServiceRegistry.Setting(name = AvailableSettings.IMPLICIT_NAMING_STRATEGY, value = "org.hibernate.orm.test.annotations.collectionelement.MyImprovedNamingStrategy") +}) public class CustomImprovedNamingCollectionElementTest extends ImprovedNamingCollectionElementTest { - @Override - protected void configureMetadataBuilder(MetadataBuilder metadataBuilder) { - super.configureMetadataBuilder( metadataBuilder ); - metadataBuilder.applyImplicitNamingStrategy( new MyImprovedNamingStrategy() ); - } - @Test - @TestForIssue( jiraKey = "HHH-9387") - public void testDefaultTableNameOwnerEntityNameAndPKColumnOverride() { + @TestForIssue(jiraKey = "HHH-9387") + public void testDefaultTableNameOwnerEntityNameAndPKColumnOverride(SessionFactoryScope scope) { // NOTE: expected JPA entity names are explicit here (rather than just getting them from the PersistentClass) // to ensure that entity names/tables are not changed (which would invalidate these test cases). // Matrix has @Entity(name="Mtx"); entity table name defaults to "Mtx"; owner PK column is configured as "mId" // MyNamingStrategyDelegator will use the owner primary table name (instead of JPA entity name) in generated collection table. - checkDefaultCollectionTableName( Matrix.class, "mvalues", "Mtx_mvalues" ); + checkDefaultCollectionTableName( scope.getMetadataImplementor(), Matrix.class, "mvalues", "Mtx_mvalues" ); } @Test - @TestForIssue( jiraKey = "HHH-9387") - public void testDefaultTableNameOwnerPrimaryTableAndEntityNamesOverride() { + @TestForIssue(jiraKey = "HHH-9387") + public void testDefaultTableNameOwnerPrimaryTableAndEntityNamesOverride(SessionFactoryScope scope) { // NOTE: expected JPA entity names are explicit here (rather than just getting them from the PersistentClass) // to ensure that entity names/tables are not changed (which would invalidate these test cases). // Owner has @Entity( name="OWNER") @Table( name="OWNER_TABLE") // MyNamingStrategyDelegator will use owner primary table name (instead of JPA entity name) in generated collection table. - checkDefaultCollectionTableName( Owner.class, "elements", "OWNER_TABLE_elements" ); + checkDefaultCollectionTableName( + scope.getMetadataImplementor(), + Owner.class, + "elements", + "OWNER_TABLE_elements" + ); } @Test - @TestForIssue( jiraKey = "HHH-9389") - public void testDefaultJoinColumnOwnerEntityNameAndPKColumnOverride() { + @TestForIssue(jiraKey = "HHH-9389") + public void testDefaultJoinColumnOwnerEntityNameAndPKColumnOverride(SessionFactoryScope scope) { // NOTE: expected JPA entity names are explicit here (rather than just getting them from the PersistentClass) // to ensure that entity names/tables are not changed (which would invalidate these test cases). // Matrix has @Entity(name="Mtx"); entity table name defaults to "Mtx"; owner PK column is configured as "mId" // MyNamingStrategyDelegator will use owner primary table name, which will default to the JPA entity name // in generated join column. - checkDefaultJoinColumnName( Matrix.class, "mvalues", "Mtx_mId" ); + checkDefaultJoinColumnName( scope.getMetadataImplementor(), Matrix.class, "mvalues", "Mtx_mId" ); } @Test - @TestForIssue( jiraKey = "HHH-9389") - public void testDefaultJoinColumnOwnerPrimaryTableAndEntityNamesOverride() { + @TestForIssue(jiraKey = "HHH-9389") + public void testDefaultJoinColumnOwnerPrimaryTableAndEntityNamesOverride(SessionFactoryScope scope) { // NOTE: expected JPA entity names are explicit here (rather than just getting them from the PersistentClass) // to ensure that entity names/tables are not changed (which would invalidate these test cases). // Owner has @Entity( name="OWNER") @Table( name="OWNER_TABLE") // MyNamingStrategyDelegator will use the table name (instead of JPA entity name) in generated join column. - checkDefaultJoinColumnName( Owner.class, "elements", "OWNER_TABLE_id" ); + checkDefaultJoinColumnName( scope.getMetadataImplementor(), Owner.class, "elements", "OWNER_TABLE_id" ); } @Test - @TestForIssue( jiraKey = "HHH-9389") - public void testDefaultJoinColumnOwnerPrimaryTableOverride() { + @TestForIssue(jiraKey = "HHH-9389") + public void testDefaultJoinColumnOwnerPrimaryTableOverride(SessionFactoryScope scope) { // NOTE: expected JPA entity names are explicit here (rather than just getting them from the PersistentClass) // to ensure that entity names/tables are not changed (which would invalidate these test cases). // Boy has @Entity @Table(name="tbl_Boys") // MyNamingStrategyDelegator will use the table name (instead of JPA entity name) in generated join column. - checkDefaultJoinColumnName( Boy.class, "hatedNames", "tbl_Boys_id" ); + checkDefaultJoinColumnName( scope.getMetadataImplementor(), Boy.class, "hatedNames", "tbl_Boys_id" ); } @Test - @TestForIssue( jiraKey = "HHH-9387") - public void testDefaultTableNameOwnerPrimaryTableOverride() { + @TestForIssue(jiraKey = "HHH-9387") + public void testDefaultTableNameOwnerPrimaryTableOverride(SessionFactoryScope scope) { // NOTE: expected JPA entity names are explicit here (rather than just getting them from the PersistentClass) // to ensure that entity names/tables are not changed (which would invalidate these test cases). // Boy has @Entity @Table(name="tbl_Boys") // MyNamingStrategyDelegator will use the table name (instead of JPA entity name) in generated join column. - checkDefaultCollectionTableName( Boy.class, "hatedNames", "tbl_Boys_hatedNames" ); - } - - static class MyImprovedNamingStrategy extends ImplicitNamingStrategyJpaCompliantImpl { - @Override - public Identifier determineCollectionTableName(ImplicitCollectionTableNameSource source) { - // This impl uses the owner entity table name instead of the JPA entity name when - // generating the implicit name. - final String name = source.getOwningPhysicalTableName().getText() - + '_' - + transformAttributePath( source.getOwningAttributePath() ); - - return toIdentifier( name, source.getBuildingContext() ); - } - - @Override - public Identifier determineJoinColumnName(ImplicitJoinColumnNameSource source) { - final String name = source.getReferencedTableName() + "_" + source.getReferencedColumnName(); - return toIdentifier( name, source.getBuildingContext() ); - } + checkDefaultCollectionTableName( + scope.getMetadataImplementor(), + Boy.class, + "hatedNames", + "tbl_Boys_hatedNames" + ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/DefaultNamingCollectionElementTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/DefaultNamingCollectionElementTest.java new file mode 100644 index 000000000000..6936bc2f6ed9 --- /dev/null +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/DefaultNamingCollectionElementTest.java @@ -0,0 +1,483 @@ +/* + * 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.orm.test.annotations.collectionelement; + +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Locale; + +import org.hibernate.Filter; +import org.hibernate.Transaction; +import org.hibernate.boot.spi.MetadataImplementor; +import org.hibernate.cfg.AvailableSettings; +import org.hibernate.mapping.Collection; +import org.hibernate.mapping.Column; +import org.hibernate.mapping.ForeignKey; +import org.hibernate.query.Query; + +import org.hibernate.testing.TestForIssue; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.ServiceRegistry; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.hibernate.test.annotations.Country; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Tests @ElementCollection using the default "legacy" NamingStrategyDelegator which does not + * comply with JPA spec in some cases. See HHH-9387 and HHH-9389 for more information.. + * + * @author Emmanuel Bernard + * @author Hardy Ferentschik + * @author Gail Badner + */ +@SuppressWarnings("unchecked") +@DomainModel( + annotatedClasses = { + Boy.class, + Country.class, + TestCourse.class, + Matrix.class, + Owner.class, + BugSystem.class + } +) +@SessionFactory +@ServiceRegistry(settings = { + @ServiceRegistry.Setting(name = AvailableSettings.IMPLICIT_NAMING_STRATEGY, value = "legacy-hbm") +}) +public class DefaultNamingCollectionElementTest { + + @Test + public void testSimpleElement(SessionFactoryScope scope) { + assertEquals( + "BoyFavoriteNumbers", + scope.getMetadataImplementor().getCollectionBinding( Boy.class.getName() + '.' + "favoriteNumbers" ) + .getCollectionTable().getName() + ); + scope.inSession( + session -> { + Transaction transaction = session.getTransaction(); + try { + transaction.begin(); + + Boy boy = new Boy(); + boy.setFirstName( "John" ); + boy.setLastName( "Doe" ); + boy.getNickNames().add( "Johnny" ); + boy.getNickNames().add( "Thing" ); + boy.getScorePerNickName().put( "Johnny", 3 ); + boy.getScorePerNickName().put( "Thing", 5 ); + int[] favNbrs = new int[4]; + for ( int index = 0; index < favNbrs.length - 1; index++ ) { + favNbrs[index] = index * 3; + } + boy.setFavoriteNumbers( favNbrs ); + boy.getCharacters().add( Character.GENTLE ); + boy.getCharacters().add( Character.CRAFTY ); + + HashMap foods = new HashMap<>(); + foods.put( "breakfast", FavoriteFood.PIZZA ); + foods.put( "lunch", FavoriteFood.KUNGPAOCHICKEN ); + foods.put( "dinner", FavoriteFood.SUSHI ); + boy.setFavoriteFood( foods ); + session.persist( boy ); + transaction.commit(); + + session.clear(); + transaction = session.beginTransaction(); + boy = session.get( Boy.class, boy.getId() ); + assertNotNull( boy.getNickNames() ); + assertTrue( boy.getNickNames().contains( "Thing" ) ); + assertNotNull( boy.getScorePerNickName() ); + assertTrue( boy.getScorePerNickName().containsKey( "Thing" ) ); + assertEquals( Integer.valueOf( 5 ), boy.getScorePerNickName().get( "Thing" ) ); + assertNotNull( boy.getFavoriteNumbers() ); + assertEquals( 3, boy.getFavoriteNumbers()[1] ); + assertTrue( boy.getCharacters().contains( Character.CRAFTY ) ); + assertTrue( boy.getFavoriteFood().get( "dinner" ).equals( FavoriteFood.SUSHI ) ); + assertTrue( boy.getFavoriteFood().get( "lunch" ).equals( FavoriteFood.KUNGPAOCHICKEN ) ); + assertTrue( boy.getFavoriteFood().get( "breakfast" ).equals( FavoriteFood.PIZZA ) ); + List result = session.createQuery( + "select boy from Boy boy join boy.nickNames names where names = :name" ) + .setParameter( "name", "Thing" ).list(); + assertEquals( 1, result.size() ); + session.delete( boy ); + + transaction.commit(); + } + finally { + if ( transaction.isActive() ) { + transaction.rollback(); + } + } + } + ); + } + + @Test + public void testCompositeElement(SessionFactoryScope scope) { + scope.inSession( + session -> { + Transaction transaction = session.getTransaction(); + try { + transaction.begin(); + + Boy boy = new Boy(); + boy.setFirstName( "John" ); + boy.setLastName( "Doe" ); + Toy toy = new Toy(); + toy.setName( "Balloon" ); + toy.setSerial( "serial001" ); + toy.setBrand( new Brand() ); + toy.getBrand().setName( "Bandai" ); + boy.getFavoriteToys().add( toy ); + session.persist( boy ); + transaction.commit(); + + session.clear(); + + transaction = session.beginTransaction(); + boy = session.get( Boy.class, boy.getId() ); + assertNotNull( boy ); + assertNotNull( boy.getFavoriteToys() ); + assertTrue( boy.getFavoriteToys().contains( toy ) ); + Toy next = boy.getFavoriteToys().iterator().next(); + assertEquals( boy, next.getOwner(), "@Parent is failing" ); + session.delete( boy ); + transaction.commit(); + } + finally { + if ( transaction.isActive() ) { + transaction.rollback(); + } + } + } + ); + } + + @Test + public void testAttributedJoin(SessionFactoryScope scope) { + scope.inSession( + session -> { + Transaction transaction = session.getTransaction(); + try { + transaction.begin(); + Country country = new Country(); + country.setName( "Australia" ); + session.persist( country ); + + Boy boy = new Boy(); + boy.setFirstName( "John" ); + boy.setLastName( "Doe" ); + CountryAttitude attitude = new CountryAttitude(); + // TODO: doesn't work + attitude.setBoy( boy ); + attitude.setCountry( country ); + attitude.setLikes( true ); + boy.getCountryAttitudes().add( attitude ); + session.persist( boy ); + transaction.commit(); + + session.clear(); + + transaction = session.beginTransaction(); + boy = session.get( Boy.class, boy.getId() ); + assertTrue( boy.getCountryAttitudes().contains( attitude ) ); + session.delete( boy ); + session.delete( session.get( Country.class, country.getId() ) ); + transaction.commit(); + } + finally { + if ( transaction.isActive() ) { + transaction.rollback(); + } + } + } + ); + } + + @Test + public void testLazyCollectionofElements(SessionFactoryScope scope) { + assertEquals( + "BoyFavoriteNumbers", + scope.getMetadataImplementor().getCollectionBinding( Boy.class.getName() + '.' + "favoriteNumbers" ) + .getCollectionTable().getName() + ); + scope.inSession( + session -> { + Transaction transaction = session.getTransaction(); + try { + transaction.begin(); + Boy boy = new Boy(); + boy.setFirstName( "John" ); + boy.setLastName( "Doe" ); + boy.getNickNames().add( "Johnny" ); + boy.getNickNames().add( "Thing" ); + boy.getScorePerNickName().put( "Johnny", 3 ); + boy.getScorePerNickName().put( "Thing", 5 ); + int[] favNbrs = new int[4]; + for ( int index = 0; index < favNbrs.length - 1; index++ ) { + favNbrs[index] = index * 3; + } + boy.setFavoriteNumbers( favNbrs ); + boy.getCharacters().add( Character.GENTLE ); + boy.getCharacters().add( Character.CRAFTY ); + session.persist( boy ); + transaction.commit(); + + session.clear(); + + transaction = session.beginTransaction(); + boy = session.get( Boy.class, boy.getId() ); + assertNotNull( boy.getNickNames() ); + assertTrue( boy.getNickNames().contains( "Thing" ) ); + assertNotNull( boy.getScorePerNickName() ); + assertTrue( boy.getScorePerNickName().containsKey( "Thing" ) ); + assertEquals( new Integer( 5 ), boy.getScorePerNickName().get( "Thing" ) ); + assertNotNull( boy.getFavoriteNumbers() ); + assertEquals( 3, boy.getFavoriteNumbers()[1] ); + assertTrue( boy.getCharacters().contains( Character.CRAFTY ) ); + List result = session.createQuery( + "select boy from Boy boy join boy.nickNames names where names = :name" ) + .setParameter( "name", "Thing" ).list(); + assertEquals( 1, result.size() ); + session.delete( boy ); + transaction.commit(); + } + finally { + if ( transaction.isActive() ) { + transaction.rollback(); + } + } + } + ); + } + + @Test + public void testFetchEagerAndFilter(SessionFactoryScope scope) { + scope.inSession( + session -> { + Transaction tx = session.beginTransaction(); + try { + TestCourse test = new TestCourse(); + + LocalizedString title = new LocalizedString( "title in english" ); + title.getVariations().put( Locale.FRENCH.getLanguage(), "title en francais" ); + test.setTitle( title ); + session.save( test ); + + session.flush(); + session.clear(); + + Filter filter = session.enableFilter( "selectedLocale" ); + filter.setParameter( "param", "fr" ); + + Query q = session.createQuery( "from TestCourse t" ); + List l = q.list(); + assertEquals( 1, l.size() ); + + TestCourse t = session.get( TestCourse.class, test.getTestCourseId() ); + assertEquals( 1, t.getTitle().getVariations().size() ); + + tx.rollback(); + } + finally { + if ( tx.isActive() ) { + tx.rollback(); + } + } + } + ); + } + + @Test + public void testMapKeyType(SessionFactoryScope scope) { + + scope.inSession( + session -> { + Matrix m = new Matrix(); + m.getMvalues().put( 1, 1.1f ); + Transaction tx = session.beginTransaction(); + try { + session.persist( m ); + session.flush(); + session.clear(); + m = session.get( Matrix.class, m.getId() ); + assertEquals( 1.1f, m.getMvalues().get( 1 ), 0.01f ); + } + finally { + if ( tx.isActive() ) { + tx.rollback(); + } + } + } + ); + } + + @Test + public void testDefaultValueColumnForBasic(SessionFactoryScope scope) { + final MetadataImplementor metadataImplementor = scope.getMetadataImplementor(); + isDefaultValueCollectionColumnPresent( metadataImplementor, Boy.class.getName(), "hatedNames" ); + isDefaultValueCollectionColumnPresent( metadataImplementor, Boy.class.getName(), "preferredNames" ); + isCollectionColumnPresent( metadataImplementor, Boy.class.getName(), "nickNames", "nickNames" ); + isDefaultValueCollectionColumnPresent( metadataImplementor, Boy.class.getName(), "scorePerPreferredName" ); + } + + private void isDefaultValueCollectionColumnPresent( + MetadataImplementor metadataImplementor, + String collectionOwner, + String propertyName) { + isCollectionColumnPresent( metadataImplementor, collectionOwner, propertyName, propertyName ); + } + + private void isCollectionColumnPresent( + MetadataImplementor metadataImplementor, + String collectionOwner, + String propertyName, + String columnName) { + final Collection collection = metadataImplementor.getCollectionBinding( collectionOwner + "." + propertyName ); + final Iterator columnIterator = collection.getCollectionTable().getColumnIterator(); + boolean hasDefault = false; + while ( columnIterator.hasNext() ) { + Column column = (Column) columnIterator.next(); + if ( columnName.equals( column.getName() ) ) { + hasDefault = true; + } + } + assertTrue( hasDefault, "Could not find " + columnName ); + } + + @Test + @TestForIssue(jiraKey = "HHH-9387") + public void testDefaultTableNameNoOverrides(SessionFactoryScope scope) { + // NOTE: expected JPA entity names are explicit here (rather than just getting them from the PersistentClass) + // to ensure that entity names/tables are not changed (which would invalidate these test cases). + + // Products has @Entity (no @Table) + checkDefaultCollectionTableName( scope.getMetadataImplementor(), BugSystem.class, "bugs", "BugSystem_bugs" ); + } + + @Test + @TestForIssue(jiraKey = "HHH-9387") + public void testDefaultTableNameOwnerPrimaryTableOverride(SessionFactoryScope scope) { + // NOTE: expected JPA entity names are explicit here (rather than just getting them from the PersistentClass) + // to ensure that entity names/tables are not changed (which would invalidate these test cases). + + // Boy has @Entity @Table(name="tbl_Boys") + checkDefaultCollectionTableName( scope.getMetadataImplementor(), Boy.class, "hatedNames", "Boy_hatedNames" ); + } + + @Test + @TestForIssue(jiraKey = "HHH-9387") + public void testDefaultTableNameOwnerEntityNameAndPKColumnOverride(SessionFactoryScope scope) { + // NOTE: expected JPA entity names are explicit here (rather than just getting them from the PersistentClass) + // to ensure that entity names/tables are not changed (which would invalidate these test cases). + + // Matrix has @Entity(name="Mtx"); entity table name defaults to "Mtx"; owner PK column is configured as "mId" + // Legacy behavior used unqualified entity name (instead of JPA entity name) in generated collection table. + checkDefaultCollectionTableName( scope.getMetadataImplementor(), Matrix.class, "mvalues", "Matrix_mvalues" ); + } + + @Test + @TestForIssue(jiraKey = "HHH-9389") + public void testDefaultJoinColumnOwnerPrimaryTableAndEntityNamesOverride(SessionFactoryScope scope) { + // NOTE: expected JPA entity names are explicit here (rather than just getting them from the PersistentClass) + // to ensure that entity names/tables are not changed (which would invalidate these test cases). + + // Owner has @Entity( name="OWNER") @Table( name="OWNER_TABLE") + // Legacy behavior used unqualified entity name (instead of JPA entity name) in generated join column. + checkDefaultJoinColumnName( scope.getMetadataImplementor(), Owner.class, "elements", "Owner_id" ); + } + + protected void checkDefaultCollectionTableName( + MetadataImplementor metadataImplementor, + Class ownerEntityClass, + String ownerCollectionPropertyName, + String expectedCollectionTableName) { + final org.hibernate.mapping.Collection collection = metadataImplementor.getCollectionBinding( + ownerEntityClass.getName() + '.' + ownerCollectionPropertyName + ); + final org.hibernate.mapping.Table table = collection.getCollectionTable(); + assertEquals( expectedCollectionTableName, table.getName() ); + } + + @Test + @TestForIssue(jiraKey = "HHH-9389") + public void testDefaultJoinColumnNoOverrides(SessionFactoryScope scope) { + // NOTE: expected JPA entity names are explicit here (rather than just getting them from the PersistentClass) + // to ensure that entity names/tables are not changed (which would invalidate these test cases). + + // Products has @Entity (no @Table) + checkDefaultJoinColumnName( scope.getMetadataImplementor(), BugSystem.class, "bugs", "BugSystem_id" ); + } + + @Test + @TestForIssue(jiraKey = "HHH-9389") + public void testDefaultJoinColumnOwnerPrimaryTableOverride(SessionFactoryScope scope) { + // NOTE: expected JPA entity names are explicit here (rather than just getting them from the PersistentClass) + // to ensure that entity names/tables are not changed (which would invalidate these test cases). + + // Boy has @Entity @Table(name="tbl_Boys") + checkDefaultJoinColumnName( scope.getMetadataImplementor(), Boy.class, "hatedNames", "Boy_id" ); + } + + @Test + @TestForIssue(jiraKey = "HHH-9389") + public void testDefaultJoinColumnOwnerEntityNameAndPKColumnOverride(SessionFactoryScope scope) { + // NOTE: expected JPA entity names are explicit here (rather than just getting them from the PersistentClass) + // to ensure that entity names/tables are not changed (which would invalidate these test cases). + + // Matrix has @Entity(name="Mtx"); entity table name defaults to "Mtx"; owner PK column is configured as "mId" + // Legacy behavior used unqualified entity name (instead of JPA entity name) in generated join column. + checkDefaultJoinColumnName( scope.getMetadataImplementor(), Matrix.class, "mvalues", "Matrix_mId" ); + } + + @Test + @TestForIssue(jiraKey = "HHH-9387") + public void testDefaultTableNameOwnerPrimaryTableAndEntityNamesOverride(SessionFactoryScope scope) { + // NOTE: expected JPA entity names are explicit here (rather than just getting them from the PersistentClass) + // to ensure that entity names/tables are not changed (which would invalidate these test cases). + + // Owner has @Entity( name="OWNER") @Table( name="OWNER_TABLE") + // Legacy behavior used unqualified entity name (instead of JPA entity name) in generated collection table. + checkDefaultCollectionTableName( scope.getMetadataImplementor(), Owner.class, "elements", "Owner_elements" ); + } + + protected void checkDefaultJoinColumnName( + MetadataImplementor metadataImplementor, + Class ownerEntityClass, + String ownerCollectionPropertyName, + String ownerForeignKeyNameExpected) { + final org.hibernate.mapping.Collection ownerCollection = metadataImplementor.getCollectionBinding( + ownerEntityClass.getName() + '.' + ownerCollectionPropertyName + ); + // The default owner join column can only be computed if it has a PK with 1 column. + assertEquals( 1, ownerCollection.getOwner().getKey().getColumnSpan() ); + assertEquals( ownerForeignKeyNameExpected, ownerCollection.getKey().getColumnIterator().next().getText() ); + + boolean hasOwnerFK = false; + for ( Iterator it = ownerCollection.getCollectionTable().getForeignKeyIterator(); it.hasNext(); ) { + final ForeignKey fk = (ForeignKey) it.next(); + assertSame( ownerCollection.getCollectionTable(), fk.getTable() ); + if ( fk.getColumnSpan() > 1 ) { + continue; + } + if ( fk.getColumn( 0 ).getText().equals( ownerForeignKeyNameExpected ) ) { + assertSame( ownerCollection.getOwner().getTable(), fk.getReferencedTable() ); + hasOwnerFK = true; + } + } + assertTrue( hasOwnerFK ); + } +} diff --git a/hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/EmbeddableCollectionElementWithLazyManyToOneTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/EmbeddableCollectionElementWithLazyManyToOneTest.java similarity index 56% rename from hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/EmbeddableCollectionElementWithLazyManyToOneTest.java rename to hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/EmbeddableCollectionElementWithLazyManyToOneTest.java index 39796c4c0f9f..d1ea18fa2d63 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/EmbeddableCollectionElementWithLazyManyToOneTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/EmbeddableCollectionElementWithLazyManyToOneTest.java @@ -4,7 +4,7 @@ * 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.test.annotations.collectionelement; +package org.hibernate.orm.test.annotations.collectionelement; import java.util.HashSet; import java.util.Set; @@ -20,67 +20,64 @@ import org.hibernate.Hibernate; import org.hibernate.testing.TestForIssue; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; -import org.junit.Test; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.junit.jupiter.api.Test; -import static org.hibernate.testing.transaction.TransactionUtil.doInHibernate; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Gail Badner */ -public class EmbeddableCollectionElementWithLazyManyToOneTest extends BaseCoreFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Parent.class, - Child.class - }; - } +@DomainModel( + annotatedClasses = { + EmbeddableCollectionElementWithLazyManyToOneTest.Parent.class, + EmbeddableCollectionElementWithLazyManyToOneTest.Child.class + } +) +@SessionFactory +public class EmbeddableCollectionElementWithLazyManyToOneTest { @Test - @TestForIssue( jiraKey = "???") - public void testLazyManyToOneInEmbeddable() { + @TestForIssue(jiraKey = "???") + public void testLazyManyToOneInEmbeddable(SessionFactoryScope scope) { Parent p = new Parent(); p.containedChild = new ContainedChild( new Child() ); - doInHibernate( - this::sessionFactory, session -> { - session.persist( p ); - } + scope.inTransaction( + session -> + session.persist( p ) ); - doInHibernate( - this::sessionFactory, session -> { + scope.inTransaction( + session -> { Parent pRead = session.get( Parent.class, p.id ); assertFalse( Hibernate.isInitialized( pRead.containedChild.child ) ); } ); - doInHibernate( - this::sessionFactory, session -> { - session.delete( p ); - } + scope.inTransaction( + session -> + session.delete( p ) ); } @Test - @TestForIssue( jiraKey = "???") - public void testLazyManyToOneInCollectionElementEmbeddable() { + @TestForIssue(jiraKey = "???") + public void testLazyManyToOneInCollectionElementEmbeddable(SessionFactoryScope scope) { Parent p = new Parent(); p.containedChildren.add( new ContainedChild( new Child() ) ); - doInHibernate( - this::sessionFactory, session -> { - session.persist( p ); - } + scope.inTransaction( + session -> + session.persist( p ) ); - doInHibernate( - this::sessionFactory, session -> { + scope.inTransaction( + session -> { Parent pRead = session.get( Parent.class, p.id ); assertFalse( Hibernate.isInitialized( pRead.containedChildren ) ); assertEquals( 1, pRead.containedChildren.size() ); @@ -89,29 +86,27 @@ public void testLazyManyToOneInCollectionElementEmbeddable() { } ); - doInHibernate( - this::sessionFactory, session -> { - session.delete( p ); - } + scope.inTransaction( + session -> + session.delete( p ) ); } @Test - @TestForIssue( jiraKey = "???") - public void testLazyBoth() { + @TestForIssue(jiraKey = "???") + public void testLazyBoth(SessionFactoryScope scope) { Parent p = new Parent(); ContainedChild containedChild = new ContainedChild( new Child() ); p.containedChild = containedChild; p.containedChildren.add( containedChild ); - doInHibernate( - this::sessionFactory, session -> { - session.persist( p ); - } + scope.inTransaction( + session -> + session.persist( p ) ); - doInHibernate( - this::sessionFactory, session -> { + scope.inTransaction( + session -> { Parent pRead = session.get( Parent.class, p.id ); assertFalse( Hibernate.isInitialized( pRead.containedChild.child ) ); assertFalse( Hibernate.isInitialized( pRead.containedChildren ) ); @@ -121,35 +116,35 @@ public void testLazyBoth() { } ); - doInHibernate( - this::sessionFactory, session -> { - session.delete( p ); - } + scope.inTransaction( + session -> + session.delete( p ) ); } @Test - @TestForIssue( jiraKey = "HHH-13045") - public void testAccessIdOfManyToOneInEmbeddable() { + @TestForIssue(jiraKey = "HHH-13045") + public void testAccessIdOfManyToOneInEmbeddable(SessionFactoryScope scope) { Parent p = new Parent(); p.containedChildren.add( new ContainedChild( new Child() ) ); - doInHibernate( - this::sessionFactory, session -> { - session.persist( p ); - } + scope.inTransaction( + session -> + session.persist( p ) ); - doInHibernate( - this::sessionFactory, session -> { - assertFalse( session.createQuery( "from Parent p join p.containedChildren c where c.child.id is not null" ).getResultList().isEmpty() ); - } + scope.inTransaction( + session -> + assertFalse( session.createQuery( + "from Parent p join p.containedChildren c where c.child.id is not null" ) + .getResultList() + .isEmpty() ) + ); - doInHibernate( - this::sessionFactory, session -> { - session.delete( p ); - } + scope.inTransaction( + session -> + session.delete( p ) ); } @@ -162,7 +157,7 @@ public static class Parent { private ContainedChild containedChild; @ElementCollection - private Set containedChildren = new HashSet(); + private Set containedChildren = new HashSet<>(); } @Entity(name = "Child") diff --git a/hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/EntityWithAnElementCollection.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/EntityWithAnElementCollection.java similarity index 95% rename from hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/EntityWithAnElementCollection.java rename to hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/EntityWithAnElementCollection.java index 5784558131de..3fcac57d4c49 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/EntityWithAnElementCollection.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/EntityWithAnElementCollection.java @@ -4,7 +4,7 @@ * 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.test.annotations.collectionelement; +package org.hibernate.orm.test.annotations.collectionelement; import java.util.HashSet; import java.util.Set; diff --git a/hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/FavoriteFood.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/FavoriteFood.java similarity index 83% rename from hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/FavoriteFood.java rename to hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/FavoriteFood.java index 44445777ee07..eba8b5bedcd6 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/FavoriteFood.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/FavoriteFood.java @@ -4,7 +4,7 @@ * 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.test.annotations.collectionelement; +package org.hibernate.orm.test.annotations.collectionelement; public enum FavoriteFood { diff --git a/hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/ImprovedNamingCollectionElementTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/ImprovedNamingCollectionElementTest.java similarity index 65% rename from hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/ImprovedNamingCollectionElementTest.java rename to hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/ImprovedNamingCollectionElementTest.java index f31f2003c15a..d70f2aa6c8c1 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/ImprovedNamingCollectionElementTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/ImprovedNamingCollectionElementTest.java @@ -4,13 +4,14 @@ * 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.test.annotations.collectionelement; +package org.hibernate.orm.test.annotations.collectionelement; -import org.hibernate.boot.MetadataBuilder; -import org.hibernate.boot.model.naming.ImplicitNamingStrategyJpaCompliantImpl; +import org.hibernate.cfg.AvailableSettings; import org.hibernate.testing.TestForIssue; -import org.junit.Test; +import org.hibernate.testing.orm.junit.ServiceRegistry; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.junit.jupiter.api.Test; /** * Tests @ElementCollection using the "improved" NamingStrategyDelegator which complies @@ -18,49 +19,48 @@ * * @author Gail Badner */ +@ServiceRegistry(settings = { + @ServiceRegistry.Setting(name = AvailableSettings.IMPLICIT_NAMING_STRATEGY, value = "default") +}) public class ImprovedNamingCollectionElementTest extends DefaultNamingCollectionElementTest { - @Override - protected void configureMetadataBuilder(MetadataBuilder metadataBuilder) { - metadataBuilder.applyImplicitNamingStrategy( ImplicitNamingStrategyJpaCompliantImpl.INSTANCE ); - } @Test - @TestForIssue( jiraKey = "HHH-9387") - public void testDefaultTableNameOwnerEntityNameAndPKColumnOverride() { + @TestForIssue(jiraKey = "HHH-9387") + public void testDefaultTableNameOwnerEntityNameAndPKColumnOverride(SessionFactoryScope scope) { // NOTE: expected JPA entity names are explicit here (rather than just getting them from the PersistentClass) // to ensure that entity names/tables are not changed (which would invalidate these test cases). // Matrix has @Entity(name="Mtx"); entity table name defaults to "Mtx"; owner PK column is configured as "mId" - checkDefaultCollectionTableName( Matrix.class, "mvalues", "Mtx_mvalues" ); + checkDefaultCollectionTableName( scope.getMetadataImplementor(), Matrix.class, "mvalues", "Mtx_mvalues" ); } @Test - @TestForIssue( jiraKey = "HHH-9387") - public void testDefaultTableNameOwnerPrimaryTableAndEntityNamesOverride() { + @TestForIssue(jiraKey = "HHH-9387") + public void testDefaultTableNameOwnerPrimaryTableAndEntityNamesOverride(SessionFactoryScope scope) { // NOTE: expected JPA entity names are explicit here (rather than just getting them from the PersistentClass) // to ensure that entity names/tables are not changed (which would invalidate these test cases). // Owner has @Entity( name="OWNER") @Table( name="OWNER_TABLE") - checkDefaultCollectionTableName( Owner.class, "elements", "OWNER_elements" ); + checkDefaultCollectionTableName( scope.getMetadataImplementor(), Owner.class, "elements", "OWNER_elements" ); } @Test - @TestForIssue( jiraKey = "HHH-9389") - public void testDefaultJoinColumnOwnerEntityNameAndPKColumnOverride() { + @TestForIssue(jiraKey = "HHH-9389") + public void testDefaultJoinColumnOwnerEntityNameAndPKColumnOverride(SessionFactoryScope scope) { // NOTE: expected JPA entity names are explicit here (rather than just getting them from the PersistentClass) // to ensure that entity names/tables are not changed (which would invalidate these test cases). // Matrix has @Entity(name="Mtx"); entity table name defaults to "Mtx"; owner PK column is configured as "mId" - checkDefaultJoinColumnName( Matrix.class, "mvalues", "Mtx_mId" ); + checkDefaultJoinColumnName( scope.getMetadataImplementor(), Matrix.class, "mvalues", "Mtx_mId" ); } @Test - @TestForIssue( jiraKey = "HHH-9389") - public void testDefaultJoinColumnOwnerPrimaryTableAndEntityNamesOverride() { + @TestForIssue(jiraKey = "HHH-9389") + public void testDefaultJoinColumnOwnerPrimaryTableAndEntityNamesOverride(SessionFactoryScope scope) { // NOTE: expected JPA entity names are explicit here (rather than just getting them from the PersistentClass) // to ensure that entity names/tables are not changed (which would invalidate these test cases). // Owner has @Entity( name="OWNER") @Table( name="OWNER_TABLE") - checkDefaultJoinColumnName( Owner.class, "elements", "OWNER_id" ); + checkDefaultJoinColumnName( scope.getMetadataImplementor(), Owner.class, "elements", "OWNER_id" ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/LocalizedString.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/LocalizedString.java similarity index 95% rename from hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/LocalizedString.java rename to hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/LocalizedString.java index 8a7e58dba05b..b9b104a241a4 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/LocalizedString.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/LocalizedString.java @@ -6,7 +6,7 @@ */ //$Id$ -package org.hibernate.test.annotations.collectionelement; +package org.hibernate.orm.test.annotations.collectionelement; import java.io.Serializable; import java.util.HashMap; import java.util.Locale; diff --git a/hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/Matrix.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/Matrix.java similarity index 95% rename from hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/Matrix.java rename to hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/Matrix.java index 89d134ed030d..4ca97a93b2ca 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/Matrix.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/Matrix.java @@ -6,7 +6,7 @@ */ //$ -package org.hibernate.test.annotations.collectionelement; +package org.hibernate.orm.test.annotations.collectionelement; import java.util.Map; import java.util.SortedMap; import java.util.TreeMap; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/MyImprovedNamingStrategy.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/MyImprovedNamingStrategy.java new file mode 100644 index 000000000000..7f7869616969 --- /dev/null +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/MyImprovedNamingStrategy.java @@ -0,0 +1,31 @@ +/* + * 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.orm.test.annotations.collectionelement; + +import org.hibernate.boot.model.naming.Identifier; +import org.hibernate.boot.model.naming.ImplicitCollectionTableNameSource; +import org.hibernate.boot.model.naming.ImplicitJoinColumnNameSource; +import org.hibernate.boot.model.naming.ImplicitNamingStrategyJpaCompliantImpl; + +public class MyImprovedNamingStrategy extends ImplicitNamingStrategyJpaCompliantImpl { + @Override + public Identifier determineCollectionTableName(ImplicitCollectionTableNameSource source) { + // This impl uses the owner entity table name instead of the JPA entity name when + // generating the implicit name. + final String name = source.getOwningPhysicalTableName().getText() + + '_' + + transformAttributePath( source.getOwningAttributePath() ); + + return toIdentifier( name, source.getBuildingContext() ); + } + + @Override + public Identifier determineJoinColumnName(ImplicitJoinColumnNameSource source) { + final String name = source.getReferencedTableName() + "_" + source.getReferencedColumnName(); + return toIdentifier( name, source.getBuildingContext() ); + } +} diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/OrderByTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/OrderByTest.java new file mode 100644 index 000000000000..839dd3ffeacc --- /dev/null +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/OrderByTest.java @@ -0,0 +1,149 @@ +/* + * 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.orm.test.annotations.collectionelement; + +import java.util.HashSet; +import java.util.Iterator; + +import org.hibernate.Transaction; +import org.hibernate.dialect.TeradataDialect; + +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.hibernate.testing.orm.junit.SkipForDialect; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + + +@DomainModel( + annotatedClasses = { + Products.class, + Widgets.class, + BugSystem.class + } +) +@SessionFactory +public class OrderByTest { + + @Test + public void testOrderByName(SessionFactoryScope scope) { + scope.inSession( + session -> { + Transaction tx = session.beginTransaction(); + try { + + Products p = new Products(); + HashSet set = new HashSet<>(); + + Widgets widget = new Widgets(); + widget.setName( "hammer" ); + set.add( widget ); + session.persist( widget ); + + widget = new Widgets(); + widget.setName( "axel" ); + set.add( widget ); + session.persist( widget ); + + widget = new Widgets(); + widget.setName( "screwdriver" ); + set.add( widget ); + session.persist( widget ); + + p.setWidgets( set ); + session.persist( p ); + tx.commit(); + + tx = session.beginTransaction(); + session.clear(); + p = session.get( Products.class, p.getId() ); + assertTrue( p.getWidgets().size() == 3, "has three Widgets" ); + Iterator iter = p.getWidgets().iterator(); + assertEquals( "axel", ( (Widgets) iter.next() ).getName() ); + assertEquals( "hammer", ( (Widgets) iter.next() ).getName() ); + assertEquals( "screwdriver", ( (Widgets) iter.next() ).getName() ); + tx.commit(); + } + catch (Exception e) { + if ( tx.isActive() ) { + tx.rollback(); + } + throw e; + } + } + ); + } + + @Test + @SkipForDialect( + dialectClass = TeradataDialect.class, + matchSubTypes = true, + reason = "HHH-8190, uses Teradata reserved word - summary" + ) + public void testOrderByWithDottedNotation(SessionFactoryScope scope) { + scope.inSession( + session -> { + Transaction tx = session.beginTransaction(); + try { + BugSystem bs = new BugSystem(); + HashSet set = new HashSet<>(); + + Bug bug = new Bug(); + bug.setDescription( "JPA-2 locking" ); + bug.setSummary( "JPA-2 impl locking" ); + Person p = new Person(); + p.setFirstName( "Scott" ); + p.setLastName( "Marlow" ); + bug.setReportedBy( p ); + set.add( bug ); + + bug = new Bug(); + bug.setDescription( "JPA-2 annotations" ); + bug.setSummary( "JPA-2 impl annotations" ); + p = new Person(); + p.setFirstName( "Emmanuel" ); + p.setLastName( "Bernard" ); + bug.setReportedBy( p ); + set.add( bug ); + + bug = new Bug(); + bug.setDescription( "Implement JPA-2 criteria" ); + bug.setSummary( "JPA-2 impl criteria" ); + p = new Person(); + p.setFirstName( "Steve" ); + p.setLastName( "Ebersole" ); + bug.setReportedBy( p ); + set.add( bug ); + + bs.setBugs( set ); + session.persist( bs ); + tx.commit(); + + tx = session.beginTransaction(); + session.clear(); + bs = session.get( BugSystem.class, bs.getId() ); + assertTrue( bs.getBugs().size() == 3, "has three bugs" ); + Iterator iter = bs.getBugs().iterator(); + assertEquals( "Emmanuel", ( (Bug) iter.next() ).getReportedBy().getFirstName() ); + assertEquals( "Steve", ( (Bug) iter.next() ).getReportedBy().getFirstName() ); + assertEquals( "Scott", ( (Bug) iter.next() ).getReportedBy().getFirstName() ); + tx.commit(); + } + catch (Exception e) { + if ( tx.isActive() ) { + tx.rollback(); + } + throw e; + } + } + ); + + } +} diff --git a/hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/Owner.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/Owner.java similarity index 93% rename from hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/Owner.java rename to hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/Owner.java index 59ee41d3c0d9..d01f7e1d8323 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/Owner.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/Owner.java @@ -4,7 +4,7 @@ * 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.test.annotations.collectionelement; +package org.hibernate.orm.test.annotations.collectionelement; import java.util.HashSet; import java.util.Set; diff --git a/hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/Person.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/Person.java similarity index 90% rename from hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/Person.java rename to hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/Person.java index 070fc595107d..930f7dd11582 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/Person.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/Person.java @@ -4,7 +4,8 @@ * 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.test.annotations.collectionelement; +package org.hibernate.orm.test.annotations.collectionelement; + import javax.persistence.Embeddable; @Embeddable diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/PrimitiveArrayElementCollectionTempTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/PrimitiveArrayElementCollectionTempTest.java new file mode 100644 index 000000000000..f1379dc01a39 --- /dev/null +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/PrimitiveArrayElementCollectionTempTest.java @@ -0,0 +1,85 @@ +/* + * 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.orm.test.annotations.collectionelement; + +import javax.persistence.ElementCollection; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.OrderColumn; + +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; + +/** + * @author Andrea Boriero + */ +@DomainModel( + annotatedClasses = { + PrimitiveArrayElementCollectionTempTest.Favorite.class + } +) +@SessionFactory +public class PrimitiveArrayElementCollectionTempTest { + + @BeforeEach + public void setUp(SessionFactoryScope scope) { + scope.inTransaction( + session -> { + Favorite favorite = new Favorite( 1L ); + int[] favoriteNumbers = new int[2]; + favoriteNumbers[0] = 3; + favoriteNumbers[1] = 7; + favorite.setFavoriteNumbers( favoriteNumbers ); + session.persist( favorite ); + } + ); + } + + @Test + public void testIt(SessionFactoryScope scope) { + scope.inTransaction( + session -> { + Favorite favorite = session.get( Favorite.class, 1L ); + int[] favoriteNumbers = favorite.getFavoriteNumbers(); + assertThat( favoriteNumbers.length, is( 2 ) ); + assertThat( favoriteNumbers[0], is( 3 ) ); + assertThat( favoriteNumbers[1], is( 7 ) ); + } + ); + } + + @Entity(name = "Favorite") + public static class Favorite { + @Id + Long id; + + public Favorite() { + } + + public Favorite(Long id) { + this.id = id; + } + + @ElementCollection + @OrderColumn(name = "nbr_index") + int[] favoriteNumbers; + + public int[] getFavoriteNumbers() { + return favoriteNumbers; + } + + public void setFavoriteNumbers(int[] favoriteNumbers) { + this.favoriteNumbers = favoriteNumbers; + } + } +} diff --git a/hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/Products.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/Products.java similarity index 93% rename from hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/Products.java rename to hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/Products.java index 66ea32a8cf61..5bb5fbe8a0e7 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/Products.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/Products.java @@ -4,7 +4,7 @@ * 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.test.annotations.collectionelement; +package org.hibernate.orm.test.annotations.collectionelement; import java.util.Set; import javax.persistence.ElementCollection; import javax.persistence.Entity; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/QueryTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/QueryTest.java new file mode 100644 index 000000000000..8ecba9e2a730 --- /dev/null +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/QueryTest.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 . + */ +package org.hibernate.orm.test.annotations.collectionelement; + +import org.hibernate.testing.TestForIssue; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.junit.jupiter.api.Test; + +/** + * @author Steve Ebersole + */ +@DomainModel( + annotatedClasses = { EntityWithAnElementCollection.class } +) +@SessionFactory +public class QueryTest { + + @Test + @TestForIssue(jiraKey = "HHH-5209") + public void testMemberOfSyntax(SessionFactoryScope scope) { + // performs syntax checking of the MEMBER OF predicate against a basic collection + scope.inSession( + session -> + session.createQuery( "from EntityWithAnElementCollection e where 'abc' member of e.someStrings" ) + .list() + ); + } +} diff --git a/hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/TestCourse.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/TestCourse.java similarity index 94% rename from hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/TestCourse.java rename to hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/TestCourse.java index 639b3f2f6e46..5941fd150e69 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/TestCourse.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/TestCourse.java @@ -6,7 +6,7 @@ */ //$Id$ -package org.hibernate.test.annotations.collectionelement; +package org.hibernate.orm.test.annotations.collectionelement; import javax.persistence.Embedded; import javax.persistence.Entity; import javax.persistence.GeneratedValue; diff --git a/hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/Toy.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/Toy.java similarity index 96% rename from hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/Toy.java rename to hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/Toy.java index 8222b7548be4..2b89df82d8ac 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/Toy.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/Toy.java @@ -6,7 +6,7 @@ */ //$Id$ -package org.hibernate.test.annotations.collectionelement; +package org.hibernate.orm.test.annotations.collectionelement; import javax.persistence.AttributeOverride; import javax.persistence.Column; import javax.persistence.Embeddable; diff --git a/hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/Widgets.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/Widgets.java similarity index 91% rename from hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/Widgets.java rename to hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/Widgets.java index 2f418a152e2a..4209b57caaea 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/Widgets.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/Widgets.java @@ -4,7 +4,7 @@ * 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.test.annotations.collectionelement; +package org.hibernate.orm.test.annotations.collectionelement; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; diff --git a/hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/deepcollectionelements/A.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/deepcollectionelements/A.java similarity index 92% rename from hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/deepcollectionelements/A.java rename to hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/deepcollectionelements/A.java index 855d4d1ea62f..a8177c3d848b 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/deepcollectionelements/A.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/deepcollectionelements/A.java @@ -6,7 +6,7 @@ */ //$ -package org.hibernate.test.annotations.collectionelement.deepcollectionelements; +package org.hibernate.orm.test.annotations.collectionelement.deepcollectionelements; import java.util.List; import javax.persistence.ElementCollection; import javax.persistence.Entity; diff --git a/hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/deepcollectionelements/B.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/deepcollectionelements/B.java similarity index 89% rename from hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/deepcollectionelements/B.java rename to hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/deepcollectionelements/B.java index 9e598387d297..79bac468e92a 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/deepcollectionelements/B.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/deepcollectionelements/B.java @@ -6,7 +6,7 @@ */ //$ -package org.hibernate.test.annotations.collectionelement.deepcollectionelements; +package org.hibernate.orm.test.annotations.collectionelement.deepcollectionelements; import java.util.List; import javax.persistence.Embeddable; import javax.persistence.OneToMany; diff --git a/hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/deepcollectionelements/C.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/deepcollectionelements/C.java similarity index 87% rename from hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/deepcollectionelements/C.java rename to hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/deepcollectionelements/C.java index 2eed1f6ad121..7fb8c33d4318 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/deepcollectionelements/C.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/deepcollectionelements/C.java @@ -6,7 +6,7 @@ */ //$ -package org.hibernate.test.annotations.collectionelement.deepcollectionelements; +package org.hibernate.orm.test.annotations.collectionelement.deepcollectionelements; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; diff --git a/hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/deepcollectionelements/DeepCollectionElementTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/deepcollectionelements/DeepCollectionElementTest.java similarity index 75% rename from hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/deepcollectionelements/DeepCollectionElementTest.java rename to hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/deepcollectionelements/DeepCollectionElementTest.java index 1dc4dabfc6cf..2455b6f42e51 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/deepcollectionelements/DeepCollectionElementTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/deepcollectionelements/DeepCollectionElementTest.java @@ -4,25 +4,25 @@ * 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.test.annotations.collectionelement.deepcollectionelements; +package org.hibernate.orm.test.annotations.collectionelement.deepcollectionelements; import org.hibernate.SessionFactory; import org.hibernate.boot.registry.internal.StandardServiceRegistryImpl; import org.hibernate.cfg.Configuration; -import org.hibernate.testing.FailureExpected; import org.hibernate.testing.ServiceRegistryBuilder; -import org.hibernate.testing.junit4.BaseUnitTestCase; -import org.junit.Test; +import org.hibernate.testing.junit5.BaseUnitTest; +import org.hibernate.testing.orm.junit.FailureExpected; +import org.junit.jupiter.api.Test; /** * @author Emmanuel Bernard */ @FailureExpected( jiraKey = "HHH-3157" ) -public class DeepCollectionElementTest extends BaseUnitTestCase { +public class DeepCollectionElementTest extends BaseUnitTest { @Test - public void testInitialization() throws Exception { + public void testInitialization() { Configuration configuration = new Configuration(); configuration.addAnnotatedClass( A.class ); configuration.addAnnotatedClass( B.class ); diff --git a/hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/embeddables/withcustomenumdef/Location.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/embeddables/withcustomenumdef/Location.java similarity index 89% rename from hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/embeddables/withcustomenumdef/Location.java rename to hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/embeddables/withcustomenumdef/Location.java index 2431fd767f2c..9b8198c1d4ea 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/embeddables/withcustomenumdef/Location.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/embeddables/withcustomenumdef/Location.java @@ -4,7 +4,7 @@ * 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.test.annotations.collectionelement.embeddables.withcustomenumdef; +package org.hibernate.orm.test.annotations.collectionelement.embeddables.withcustomenumdef; import javax.persistence.Embeddable; import javax.persistence.EnumType; diff --git a/hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/embeddables/withcustomenumdef/Query.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/embeddables/withcustomenumdef/Query.java similarity index 93% rename from hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/embeddables/withcustomenumdef/Query.java rename to hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/embeddables/withcustomenumdef/Query.java index 5e73c37cd9d3..bc96ef0e4094 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/embeddables/withcustomenumdef/Query.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/embeddables/withcustomenumdef/Query.java @@ -4,7 +4,7 @@ * 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.test.annotations.collectionelement.embeddables.withcustomenumdef; +package org.hibernate.orm.test.annotations.collectionelement.embeddables.withcustomenumdef; import java.util.Collections; import java.util.HashSet; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/embeddables/withcustomenumdef/TestBasicOps.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/embeddables/withcustomenumdef/TestBasicOps.java new file mode 100644 index 000000000000..cbb1b7a152d5 --- /dev/null +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/embeddables/withcustomenumdef/TestBasicOps.java @@ -0,0 +1,99 @@ +/* + * 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.orm.test.annotations.collectionelement.embeddables.withcustomenumdef; + +import java.util.Iterator; + +import org.hibernate.Transaction; + +import org.hibernate.testing.TestForIssue; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * @author Steve Ebersole + */ +@DomainModel( + annotatedClasses = { + Query.class + } +) +@SessionFactory +public class TestBasicOps { + + @Test + public void testLoadAndStore(SessionFactoryScope scope) { + Query q = new Query( new Location( "first", Location.Type.COUNTY ) ); + scope.inTransaction( + session -> { + session.save( q ); + } + ); + + scope.inTransaction( + session -> { + Query q1 = session.get( Query.class, q.getId() ); + assertEquals( 1, q1.getIncludedLocations().size() ); + Location l = q1.getIncludedLocations().iterator().next(); + assertEquals( Location.Type.COUNTY, l.getType() ); + session.delete( q1 ); + } + ); + } + + @Test + @TestForIssue(jiraKey = "HHH-7072") + public void testEmbeddableWithNullables(SessionFactoryScope scope) { + scope.inSession( + session -> { + Transaction transaction = session.beginTransaction(); + try { + Query q = new Query( new Location( null, Location.Type.COMMUNE ) ); + session.save( q ); + transaction.commit(); + session.clear(); + + transaction = session.beginTransaction(); + q.getIncludedLocations().add( new Location( null, Location.Type.COUNTY ) ); + session.update( q ); + transaction.commit(); + session.clear(); + + transaction = session.beginTransaction(); + q = (Query) session.get( Query.class, q.getId() ); +// assertEquals( 2, q.getIncludedLocations().size() ); + transaction.commit(); + session.clear(); + + transaction = session.beginTransaction(); + Iterator itr = q.getIncludedLocations().iterator(); + itr.next(); + itr.remove(); + session.update( q ); + transaction.commit(); + session.clear(); + + transaction = session.beginTransaction(); + q = (Query) session.get( Query.class, q.getId() ); + assertEquals( 1, q.getIncludedLocations().size() ); + session.delete( q ); + transaction.commit(); + } + catch (Exception e) { + if ( transaction.isActive() ) { + transaction.rollback(); + } + throw e; + } + } + ); + } +} diff --git a/hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/indexedCollection/Contact.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/indexedCollection/Contact.java similarity index 85% rename from hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/indexedCollection/Contact.java rename to hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/indexedCollection/Contact.java index 8e4bc12a0dde..486e52d8044a 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/indexedCollection/Contact.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/indexedCollection/Contact.java @@ -6,7 +6,7 @@ */ //$ -package org.hibernate.test.annotations.collectionelement.indexedCollection; +package org.hibernate.orm.test.annotations.collectionelement.indexedCollection; import javax.persistence.Embeddable; /** diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/indexedCollection/IndexedCollectionOfElementsTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/indexedCollection/IndexedCollectionOfElementsTest.java new file mode 100644 index 000000000000..2f17116bc4ed --- /dev/null +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/indexedCollection/IndexedCollectionOfElementsTest.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 . + */ +package org.hibernate.orm.test.annotations.collectionelement.indexedCollection; + + +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + + +/** + * @author Emmanuel Bernard + */ +@DomainModel( + annotatedClasses = { + Sale.class + } +) +@SessionFactory +public class IndexedCollectionOfElementsTest { + + @Test + public void testIndexedCollectionOfElements(SessionFactoryScope scope) { + Sale sale = new Sale(); + Contact contact = new Contact(); + contact.setName( "Emmanuel" ); + sale.getContacts().add( contact ); + + scope.inTransaction( + session -> { + session.save( sale ); + session.flush(); + session.get( Sale.class, sale.getId() ); + assertEquals( 1, sale.getContacts().size() ); + } + ); + } +} diff --git a/hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/indexedCollection/Sale.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/indexedCollection/Sale.java similarity index 94% rename from hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/indexedCollection/Sale.java rename to hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/indexedCollection/Sale.java index 9b93cd8d12cb..62bfe4875ea7 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/indexedCollection/Sale.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/indexedCollection/Sale.java @@ -6,7 +6,7 @@ */ //$ -package org.hibernate.test.annotations.collectionelement.indexedCollection; +package org.hibernate.orm.test.annotations.collectionelement.indexedCollection; import java.util.ArrayList; import java.util.List; import javax.persistence.Column; diff --git a/hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/ordered/Address.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/ordered/Address.java similarity index 91% rename from hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/ordered/Address.java rename to hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/ordered/Address.java index 85aaeef70cb2..dccac062401c 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/ordered/Address.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/ordered/Address.java @@ -4,7 +4,7 @@ * 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.test.annotations.collectionelement.ordered; +package org.hibernate.orm.test.annotations.collectionelement.ordered; import javax.persistence.Embeddable; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/ordered/ElementCollectionSortingTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/ordered/ElementCollectionSortingTest.java new file mode 100644 index 000000000000..abca316fff9e --- /dev/null +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/ordered/ElementCollectionSortingTest.java @@ -0,0 +1,154 @@ +/* + * 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.orm.test.annotations.collectionelement.ordered; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import org.hibernate.Session; +import org.hibernate.SortOrder; +import org.hibernate.metamodel.mapping.PluralAttributeMapping; +import org.hibernate.metamodel.mapping.ordering.OrderByFragmentImpl; +import org.hibernate.metamodel.mapping.ordering.ast.OrderingSpecification; +import org.hibernate.persister.collection.BasicCollectionPersister; + +import org.hibernate.testing.TestForIssue; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + + +/** + * @author Steve Ebersole + * @author Lukasz Antoniak (lukasz dot antoniak at gmail dot com) + */ +@DomainModel( + annotatedClasses = { + Person.class + } +) +@SessionFactory +public class ElementCollectionSortingTest { + + @AfterEach + public void tearDown(SessionFactoryScope scope) { + scope.inTransaction( + session -> session.createQuery( "delete from Person" ).executeUpdate() + ); + } + + @Test + public void testSortingElementCollectionSyntax(SessionFactoryScope scope) { + scope.inTransaction( + session -> { + session.createQuery( "from Person p join fetch p.nickNamesAscendingNaturalSort" ).list(); + session.createQuery( "from Person p join fetch p.nickNamesDescendingNaturalSort" ).list(); + session.createQuery( "from Person p join fetch p.addressesAscendingNaturalSort" ).list(); + session.createQuery( "from Person p join fetch p.addressesDescendingNaturalSort" ).list(); + session.createQuery( "from Person p join fetch p.addressesCityAscendingSort" ).list(); + session.createQuery( "from Person p join fetch p.addressesCityDescendingSort" ).list(); + } + ); + } + + @Test + @TestForIssue(jiraKey = "HHH-6875") + public void testSortingEmbeddableCollectionOfPrimitives(SessionFactoryScope scope) { + scope.inTransaction( + session -> { + final Person steve = new Person(); + steve.setName( "Steve" ); + steve.getNickNamesAscendingNaturalSort().add( "sebersole" ); + steve.getNickNamesAscendingNaturalSort().add( "ebersole" ); + steve.getNickNamesDescendingNaturalSort().add( "ebersole" ); + steve.getNickNamesDescendingNaturalSort().add( "sebersole" ); + + final Person lukasz = new Person(); + lukasz.setName( "Lukasz" ); + lukasz.getNickNamesAscendingNaturalSort().add( "antoniak" ); + lukasz.getNickNamesAscendingNaturalSort().add( "lantoniak" ); + lukasz.getNickNamesDescendingNaturalSort().add( "lantoniak" ); + lukasz.getNickNamesDescendingNaturalSort().add( "antoniak" ); + + session.save( steve ); + session.save( lukasz ); + session.flush(); + + session.clear(); + + final List lukaszNamesAsc = Arrays.asList( "antoniak", "lantoniak" ); + final List lukaszNamesDesc = Arrays.asList( "lantoniak", "antoniak" ); + final List steveNamesAsc = Arrays.asList( "ebersole", "sebersole" ); + final List steveNamesDesc = Arrays.asList( "sebersole", "ebersole" ); + + // Testing object graph navigation. Lazy loading collections. + checkPersonNickNames( + lukaszNamesAsc, + lukaszNamesDesc, + (Person) session.get( Person.class, lukasz.getId() ) + ); + checkPersonNickNames( + steveNamesAsc, + steveNamesDesc, + (Person) session.get( Person.class, steve.getId() ) + ); + + session.clear(); + + // Testing HQL query. Eagerly fetching nicknames. + final List result = session.createQuery( + "select distinct p from Person p join fetch p.nickNamesAscendingNaturalSort join fetch p.nickNamesDescendingNaturalSort order by p.name" + ).list(); + assertEquals( 2, result.size() ); + checkPersonNickNames( lukaszNamesAsc, lukaszNamesDesc, result.get( 0 ) ); + checkPersonNickNames( steveNamesAsc, steveNamesDesc, result.get( 1 ) ); + + // Metadata verification. + checkSQLOrderBy( + session, + Person.class.getName(), + "nickNamesAscendingNaturalSort", + SortOrder.ASCENDING + ); + checkSQLOrderBy( + session, + Person.class.getName(), + "nickNamesDescendingNaturalSort", + SortOrder.DESCENDING + ); + } + ); + } + + private void checkSQLOrderBy(Session session, String entityName, String propertyName, SortOrder order) { + String roleName = entityName + "." + propertyName; + String alias = "alias1"; + BasicCollectionPersister collectionPersister = (BasicCollectionPersister) session.getSessionFactory() + .getCollectionMetadata( roleName ); + assertTrue( collectionPersister.hasOrdering() ); + PluralAttributeMapping attributeMapping = collectionPersister.getAttributeMapping(); + assertThat( attributeMapping.getFetchableName(), is( propertyName ) ); + OrderByFragmentImpl orderByFragment = (OrderByFragmentImpl) attributeMapping.getOrderByFragment(); + List fragmentSpecs = orderByFragment.getFragmentSpecs(); + assertThat( fragmentSpecs.size(), is( 1 ) ); + assertThat( fragmentSpecs.get( 0 ).getSortOrder(), is( order ) ); + } + + private void checkPersonNickNames(List expectedAscending, List expectedDescending, Person person) { + // Comparing lists to verify ordering. + assertEquals( expectedAscending, new ArrayList( person.getNickNamesAscendingNaturalSort() ) ); + assertEquals( expectedDescending, new ArrayList( person.getNickNamesDescendingNaturalSort() ) ); + } +} diff --git a/hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/ordered/Person.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/ordered/Person.java similarity index 98% rename from hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/ordered/Person.java rename to hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/ordered/Person.java index d3396ae037b6..0ecb44699c67 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/ordered/Person.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/ordered/Person.java @@ -4,7 +4,7 @@ * 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.test.annotations.collectionelement.ordered; +package org.hibernate.orm.test.annotations.collectionelement.ordered; import javax.persistence.ElementCollection; import javax.persistence.Entity; diff --git a/hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/recreate/Poi.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/recreate/Poi.java similarity index 92% rename from hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/recreate/Poi.java rename to hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/recreate/Poi.java index e71169afd5fc..f8dd1248141f 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/recreate/Poi.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/recreate/Poi.java @@ -4,7 +4,7 @@ * 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.test.annotations.collectionelement.recreate; +package org.hibernate.orm.test.annotations.collectionelement.recreate; import javax.persistence.Entity; import javax.persistence.GeneratedValue; diff --git a/hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/recreate/PoiArrival.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/recreate/PoiArrival.java similarity index 92% rename from hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/recreate/PoiArrival.java rename to hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/recreate/PoiArrival.java index 69935d2eead0..909f24ea8a55 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/recreate/PoiArrival.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/recreate/PoiArrival.java @@ -4,7 +4,7 @@ * 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.test.annotations.collectionelement.recreate; +package org.hibernate.orm.test.annotations.collectionelement.recreate; import javax.persistence.Embeddable; import javax.persistence.Temporal; diff --git a/hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/recreate/RaceExecution.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/recreate/RaceExecution.java similarity index 95% rename from hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/recreate/RaceExecution.java rename to hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/recreate/RaceExecution.java index f6dc672dddf2..11570cc9867f 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/recreate/RaceExecution.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/recreate/RaceExecution.java @@ -4,7 +4,7 @@ * 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.test.annotations.collectionelement.recreate; +package org.hibernate.orm.test.annotations.collectionelement.recreate; import java.util.Date; import java.util.HashMap; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/recreate/RecreateCollectionTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/recreate/RecreateCollectionTest.java new file mode 100644 index 000000000000..753840e1705a --- /dev/null +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/recreate/RecreateCollectionTest.java @@ -0,0 +1,84 @@ +/* + * 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.orm.test.annotations.collectionelement.recreate; + +import java.util.Date; + +import org.hibernate.BaseSessionEventListener; + +import org.hibernate.testing.TestForIssue; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + + +/** + * @author Sergey Astakhov + */ +@DomainModel( + annotatedClasses = { + Poi.class, + RaceExecution.class + } +) +@SessionFactory +public class RecreateCollectionTest { + + private static class StatementsCounterListener extends BaseSessionEventListener { + int statements; + + @Override + public void jdbcExecuteStatementEnd() { + statements++; + } + } + + @Test + @TestForIssue(jiraKey = "HHH-9474") + public void testUpdateCollectionOfElements(SessionFactoryScope scope) { + scope.inTransaction( + session -> { + Poi poi1 = new Poi( "Poi 1" ); + Poi poi2 = new Poi( "Poi 2" ); + + session.save( poi1 ); + session.save( poi2 ); + + RaceExecution race = new RaceExecution(); + + session.save( race ); + + Date currentTime = new Date(); + + race.arriveToPoi( poi1, currentTime ); + race.expectedArrive( poi2, new Date( currentTime.getTime() + 60 * 1000 ) ); + + session.flush(); + + assertEquals( 2, race.getPoiArrival().size() ); + + StatementsCounterListener statementsCounterListener = new StatementsCounterListener(); + + session.addEventListeners( statementsCounterListener ); + + race.arriveToPoi( poi2, new Date( currentTime.getTime() + 2 * 60 * 1000 ) ); + + session.flush(); + + assertEquals( 2, race.getPoiArrival().size() ); + + // There is should be one UPDATE statement. Without fix there is one DELETE and two INSERT-s. + + assertEquals( 1, statementsCounterListener.statements ); + } + ); + } + +} diff --git a/hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/DefaultNamingCollectionElementTest.java b/hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/DefaultNamingCollectionElementTest.java deleted file mode 100644 index bf281fc5e7ee..000000000000 --- a/hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/DefaultNamingCollectionElementTest.java +++ /dev/null @@ -1,404 +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.test.annotations.collectionelement; - -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Locale; - -import org.hibernate.Filter; -import org.hibernate.query.Query; -import org.hibernate.Session; -import org.hibernate.Transaction; -import org.hibernate.boot.MetadataBuilder; -import org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyHbmImpl; -import org.hibernate.mapping.Collection; -import org.hibernate.mapping.Column; -import org.hibernate.mapping.ForeignKey; - -import org.hibernate.testing.TestForIssue; -import org.hibernate.testing.junit4.BaseNonConfigCoreFunctionalTestCase; -import org.hibernate.test.annotations.Country; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; - -/** - * Tests @ElementCollection using the default "legacy" NamingStrategyDelegator which does not - * comply with JPA spec in some cases. See HHH-9387 and HHH-9389 for more information.. - * - * @author Emmanuel Bernard - * @author Hardy Ferentschik - * @author Gail Badner - */ -@SuppressWarnings("unchecked") -public class DefaultNamingCollectionElementTest extends BaseNonConfigCoreFunctionalTestCase { - - @Test - public void testSimpleElement() throws Exception { - assertEquals( - "BoyFavoriteNumbers", - metadata().getCollectionBinding( Boy.class.getName() + '.' + "favoriteNumbers" ) - .getCollectionTable().getName() - ); - Session s = openSession(); - s.getTransaction().begin(); - Boy boy = new Boy(); - boy.setFirstName( "John" ); - boy.setLastName( "Doe" ); - boy.getNickNames().add( "Johnny" ); - boy.getNickNames().add( "Thing" ); - boy.getScorePerNickName().put( "Johnny", 3 ); - boy.getScorePerNickName().put( "Thing", 5 ); - int[] favNbrs = new int[4]; - for (int index = 0; index < favNbrs.length - 1; index++) { - favNbrs[index] = index * 3; - } - boy.setFavoriteNumbers( favNbrs ); - boy.getCharacters().add( Character.GENTLE ); - boy.getCharacters().add( Character.CRAFTY ); - - HashMap foods = new HashMap(); - foods.put( "breakfast", FavoriteFood.PIZZA); - foods.put( "lunch", FavoriteFood.KUNGPAOCHICKEN); - foods.put( "dinner", FavoriteFood.SUSHI); - boy.setFavoriteFood(foods); - s.persist( boy ); - s.getTransaction().commit(); - s.clear(); - Transaction tx = s.beginTransaction(); - boy = (Boy) s.get( Boy.class, boy.getId() ); - assertNotNull( boy.getNickNames() ); - assertTrue( boy.getNickNames().contains( "Thing" ) ); - assertNotNull( boy.getScorePerNickName() ); - assertTrue( boy.getScorePerNickName().containsKey( "Thing" ) ); - assertEquals( Integer.valueOf( 5 ), boy.getScorePerNickName().get( "Thing" ) ); - assertNotNull( boy.getFavoriteNumbers() ); - assertEquals( 3, boy.getFavoriteNumbers()[1] ); - assertTrue( boy.getCharacters().contains( Character.CRAFTY ) ); - assertTrue( boy.getFavoriteFood().get("dinner").equals(FavoriteFood.SUSHI)); - assertTrue( boy.getFavoriteFood().get("lunch").equals(FavoriteFood.KUNGPAOCHICKEN)); - assertTrue( boy.getFavoriteFood().get("breakfast").equals(FavoriteFood.PIZZA)); - List result = s.createQuery( "select boy from Boy boy join boy.nickNames names where names = :name" ) - .setParameter( "name", "Thing" ).list(); - assertEquals( 1, result.size() ); - s.delete( boy ); - tx.commit(); - s.close(); - } - - @Test - public void testCompositeElement() throws Exception { - Session s = openSession(); - s.getTransaction().begin(); - Boy boy = new Boy(); - boy.setFirstName( "John" ); - boy.setLastName( "Doe" ); - Toy toy = new Toy(); - toy.setName( "Balloon" ); - toy.setSerial( "serial001" ); - toy.setBrand( new Brand() ); - toy.getBrand().setName( "Bandai" ); - boy.getFavoriteToys().add( toy ); - s.persist( boy ); - s.getTransaction().commit(); - s.clear(); - Transaction tx = s.beginTransaction(); - boy = (Boy) s.get( Boy.class, boy.getId() ); - assertNotNull( boy ); - assertNotNull( boy.getFavoriteToys() ); - assertTrue( boy.getFavoriteToys().contains( toy ) ); - assertEquals( "@Parent is failing", boy, boy.getFavoriteToys().iterator().next().getOwner() ); - s.delete( boy ); - tx.commit(); - s.close(); - } - - @Test - public void testAttributedJoin() throws Exception { - Session s = openSession(); - s.getTransaction().begin(); - Country country = new Country(); - country.setName( "Australia" ); - s.persist( country ); - - Boy boy = new Boy(); - boy.setFirstName( "John" ); - boy.setLastName( "Doe" ); - CountryAttitude attitude = new CountryAttitude(); - // TODO: doesn't work - attitude.setBoy( boy ); - attitude.setCountry( country ); - attitude.setLikes( true ); - boy.getCountryAttitudes().add( attitude ); - s.persist( boy ); - s.getTransaction().commit(); - s.clear(); - - Transaction tx = s.beginTransaction(); - boy = (Boy) s.get( Boy.class, boy.getId() ); - assertTrue( boy.getCountryAttitudes().contains( attitude ) ); - s.delete( boy ); - s.delete( s.get( Country.class, country.getId() ) ); - tx.commit(); - s.close(); - } - - @Test - public void testLazyCollectionofElements() throws Exception { - assertEquals( - "BoyFavoriteNumbers", - metadata().getCollectionBinding( Boy.class.getName() + '.' + "favoriteNumbers" ) - .getCollectionTable().getName() - ); - Session s = openSession(); - s.getTransaction().begin(); - Boy boy = new Boy(); - boy.setFirstName( "John" ); - boy.setLastName( "Doe" ); - boy.getNickNames().add( "Johnny" ); - boy.getNickNames().add( "Thing" ); - boy.getScorePerNickName().put( "Johnny", 3 ); - boy.getScorePerNickName().put( "Thing", 5 ); - int[] favNbrs = new int[4]; - for (int index = 0; index < favNbrs.length - 1; index++) { - favNbrs[index] = index * 3; - } - boy.setFavoriteNumbers( favNbrs ); - boy.getCharacters().add( Character.GENTLE ); - boy.getCharacters().add( Character.CRAFTY ); - s.persist( boy ); - s.getTransaction().commit(); - s.clear(); - Transaction tx = s.beginTransaction(); - boy = (Boy) s.get( Boy.class, boy.getId() ); - assertNotNull( boy.getNickNames() ); - assertTrue( boy.getNickNames().contains( "Thing" ) ); - assertNotNull( boy.getScorePerNickName() ); - assertTrue( boy.getScorePerNickName().containsKey( "Thing" ) ); - assertEquals( new Integer( 5 ), boy.getScorePerNickName().get( "Thing" ) ); - assertNotNull( boy.getFavoriteNumbers() ); - assertEquals( 3, boy.getFavoriteNumbers()[1] ); - assertTrue( boy.getCharacters().contains( Character.CRAFTY ) ); - List result = s.createQuery( "select boy from Boy boy join boy.nickNames names where names = :name" ) - .setParameter( "name", "Thing" ).list(); - assertEquals( 1, result.size() ); - s.delete( boy ); - tx.commit(); - s.close(); - } - - @Test - public void testFetchEagerAndFilter() throws Exception { - Session s = openSession(); - Transaction tx = s.beginTransaction(); - - TestCourse test = new TestCourse(); - - LocalizedString title = new LocalizedString( "title in english" ); - title.getVariations().put( Locale.FRENCH.getLanguage(), "title en francais" ); - test.setTitle( title ); - s.save( test ); - - s.flush(); - s.clear(); - - Filter filter = s.enableFilter( "selectedLocale" ); - filter.setParameter( "param", "fr" ); - - Query q = s.createQuery( "from TestCourse t" ); - List l = q.list(); - assertEquals( 1, l.size() ); - - TestCourse t = (TestCourse) s.get( TestCourse.class, test.getTestCourseId() ); - assertEquals( 1, t.getTitle().getVariations().size() ); - - tx.rollback(); - - s.close(); - } - - @Test - public void testMapKeyType() throws Exception { - Matrix m = new Matrix(); - m.getMvalues().put( 1, 1.1f ); - Session s = openSession(); - Transaction tx = s.beginTransaction(); - s.persist( m ); - s.flush(); - s.clear(); - m = (Matrix) s.get( Matrix.class, m.getId() ); - assertEquals( 1.1f, m.getMvalues().get( 1 ), 0.01f ); - tx.rollback(); - s.close(); - } - - @Test - public void testDefaultValueColumnForBasic() throws Exception { - isDefaultValueCollectionColumnPresent( Boy.class.getName(), "hatedNames" ); - isDefaultValueCollectionColumnPresent( Boy.class.getName(), "preferredNames" ); - isCollectionColumnPresent( Boy.class.getName(), "nickNames", "nickNames" ); - isDefaultValueCollectionColumnPresent( Boy.class.getName(), "scorePerPreferredName"); - } - - private void isDefaultValueCollectionColumnPresent(String collectionOwner, String propertyName) { - isCollectionColumnPresent( collectionOwner, propertyName, propertyName ); - } - - private void isCollectionColumnPresent(String collectionOwner, String propertyName, String columnName) { - final Collection collection = metadata().getCollectionBinding( collectionOwner + "." + propertyName ); - final Iterator columnIterator = collection.getCollectionTable().getColumnIterator(); - boolean hasDefault = false; - while ( columnIterator.hasNext() ) { - Column column = (Column) columnIterator.next(); - if ( columnName.equals( column.getName() ) ) hasDefault = true; - } - assertTrue( "Could not find " + columnName, hasDefault ); - } - - @Test - @TestForIssue( jiraKey = "HHH-9387") - public void testDefaultTableNameNoOverrides() { - // NOTE: expected JPA entity names are explicit here (rather than just getting them from the PersistentClass) - // to ensure that entity names/tables are not changed (which would invalidate these test cases). - - // Products has @Entity (no @Table) - checkDefaultCollectionTableName( BugSystem.class, "bugs", "BugSystem_bugs" ); - } - - @Test - @TestForIssue( jiraKey = "HHH-9387") - public void testDefaultTableNameOwnerPrimaryTableOverride() { - // NOTE: expected JPA entity names are explicit here (rather than just getting them from the PersistentClass) - // to ensure that entity names/tables are not changed (which would invalidate these test cases). - - // Boy has @Entity @Table(name="tbl_Boys") - checkDefaultCollectionTableName( Boy.class, "hatedNames", "Boy_hatedNames" ); - } - - @Test - @TestForIssue( jiraKey = "HHH-9387") - public void testDefaultTableNameOwnerEntityNameAndPKColumnOverride() { - // NOTE: expected JPA entity names are explicit here (rather than just getting them from the PersistentClass) - // to ensure that entity names/tables are not changed (which would invalidate these test cases). - - // Matrix has @Entity(name="Mtx"); entity table name defaults to "Mtx"; owner PK column is configured as "mId" - // Legacy behavior used unqualified entity name (instead of JPA entity name) in generated collection table. - checkDefaultCollectionTableName( Matrix.class, "mvalues", "Matrix_mvalues" ); - } - - @Test - @TestForIssue( jiraKey = "HHH-9389") - public void testDefaultJoinColumnOwnerPrimaryTableAndEntityNamesOverride() { - // NOTE: expected JPA entity names are explicit here (rather than just getting them from the PersistentClass) - // to ensure that entity names/tables are not changed (which would invalidate these test cases). - - // Owner has @Entity( name="OWNER") @Table( name="OWNER_TABLE") - // Legacy behavior used unqualified entity name (instead of JPA entity name) in generated join column. - checkDefaultJoinColumnName( Owner.class, "elements", "Owner_id" ); - } - - protected void checkDefaultCollectionTableName( - Class ownerEntityClass, - String ownerCollectionPropertyName, - String expectedCollectionTableName) { - final org.hibernate.mapping.Collection collection = metadata().getCollectionBinding( - ownerEntityClass.getName() + '.' + ownerCollectionPropertyName - ); - final org.hibernate.mapping.Table table = collection.getCollectionTable(); - assertEquals( expectedCollectionTableName, table.getName() ); - } - - @Test - @TestForIssue( jiraKey = "HHH-9389") - public void testDefaultJoinColumnNoOverrides() { - // NOTE: expected JPA entity names are explicit here (rather than just getting them from the PersistentClass) - // to ensure that entity names/tables are not changed (which would invalidate these test cases). - - // Products has @Entity (no @Table) - checkDefaultJoinColumnName( BugSystem.class, "bugs", "BugSystem_id" ); - } - - @Test - @TestForIssue( jiraKey = "HHH-9389") - public void testDefaultJoinColumnOwnerPrimaryTableOverride() { - // NOTE: expected JPA entity names are explicit here (rather than just getting them from the PersistentClass) - // to ensure that entity names/tables are not changed (which would invalidate these test cases). - - // Boy has @Entity @Table(name="tbl_Boys") - checkDefaultJoinColumnName( Boy.class, "hatedNames", "Boy_id" ); - } - - @Test - @TestForIssue( jiraKey = "HHH-9389") - public void testDefaultJoinColumnOwnerEntityNameAndPKColumnOverride() { - // NOTE: expected JPA entity names are explicit here (rather than just getting them from the PersistentClass) - // to ensure that entity names/tables are not changed (which would invalidate these test cases). - - // Matrix has @Entity(name="Mtx"); entity table name defaults to "Mtx"; owner PK column is configured as "mId" - // Legacy behavior used unqualified entity name (instead of JPA entity name) in generated join column. - checkDefaultJoinColumnName( Matrix.class, "mvalues", "Matrix_mId" ); - } - - @Test - @TestForIssue( jiraKey = "HHH-9387") - public void testDefaultTableNameOwnerPrimaryTableAndEntityNamesOverride() { - // NOTE: expected JPA entity names are explicit here (rather than just getting them from the PersistentClass) - // to ensure that entity names/tables are not changed (which would invalidate these test cases). - - // Owner has @Entity( name="OWNER") @Table( name="OWNER_TABLE") - // Legacy behavior used unqualified entity name (instead of JPA entity name) in generated collection table. - checkDefaultCollectionTableName( Owner.class, "elements", "Owner_elements" ); - } - - protected void checkDefaultJoinColumnName( - Class ownerEntityClass, - String ownerCollectionPropertyName, - String ownerForeignKeyNameExpected) { - final org.hibernate.mapping.Collection ownerCollection = metadata().getCollectionBinding( - ownerEntityClass.getName() + '.' + ownerCollectionPropertyName - ); - // The default owner join column can only be computed if it has a PK with 1 column. - assertEquals ( 1, ownerCollection.getOwner().getKey().getColumnSpan() ); - assertEquals( ownerForeignKeyNameExpected, ownerCollection.getKey().getColumnIterator().next().getText() ); - - boolean hasOwnerFK = false; - for ( Iterator it=ownerCollection.getCollectionTable().getForeignKeyIterator(); it.hasNext(); ) { - final ForeignKey fk = (ForeignKey) it.next(); - assertSame( ownerCollection.getCollectionTable(), fk.getTable() ); - if ( fk.getColumnSpan() > 1 ) { - continue; - } - if ( fk.getColumn( 0 ).getText().equals( ownerForeignKeyNameExpected ) ) { - assertSame( ownerCollection.getOwner().getTable(), fk.getReferencedTable() ); - hasOwnerFK = true; - } - } - assertTrue( hasOwnerFK ); - } - - @Override - protected void configureMetadataBuilder(MetadataBuilder metadataBuilder) { - metadataBuilder.applyImplicitNamingStrategy( ImplicitNamingStrategyLegacyHbmImpl.INSTANCE ); - } - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Boy.class, - Country.class, - TestCourse.class, - Matrix.class, - Owner.class, - BugSystem.class - }; - } -} diff --git a/hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/OrderByTest.java b/hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/OrderByTest.java deleted file mode 100644 index 77935fb7c699..000000000000 --- a/hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/OrderByTest.java +++ /dev/null @@ -1,127 +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.test.annotations.collectionelement; - -import java.util.HashSet; -import java.util.Iterator; - -import org.hibernate.Session; -import org.hibernate.Transaction; -import org.hibernate.dialect.TeradataDialect; - -import org.hibernate.testing.SkipForDialect; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; -import org.junit.Test; -import junit.framework.Assert; - -public class OrderByTest extends BaseCoreFunctionalTestCase { - @Test - public void testOrderByName() throws Exception { - Session s = openSession(); - Transaction tx = s.beginTransaction(); - - Products p = new Products(); - HashSet set = new HashSet(); - - Widgets widget = new Widgets(); - widget.setName("hammer"); - set.add(widget); - s.persist(widget); - - widget = new Widgets(); - widget.setName("axel"); - set.add(widget); - s.persist(widget); - - widget = new Widgets(); - widget.setName("screwdriver"); - set.add(widget); - s.persist(widget); - - p.setWidgets(set); - s.persist(p); - tx.commit(); - - tx = s.beginTransaction(); - s.clear(); - p = (Products) s.get(Products.class,p.getId()); - Assert.assertTrue("has three Widgets", p.getWidgets().size() == 3); - Iterator iter = p.getWidgets().iterator(); - Assert.assertEquals( "axel", ((Widgets)iter.next()).getName() ); - Assert.assertEquals( "hammer", ((Widgets)iter.next()).getName() ); - Assert.assertEquals( "screwdriver", ((Widgets)iter.next()).getName() ); - tx.commit(); - s.close(); - } - - @Test - @SkipForDialect( - value = TeradataDialect.class, - jiraKey = "HHH-8190", - comment = "uses Teradata reserved word - summary" - ) - public void testOrderByWithDottedNotation() throws Exception { - Session s = openSession(); - Transaction tx = s.beginTransaction(); - - BugSystem bs = new BugSystem(); - HashSet set = new HashSet(); - - Bug bug = new Bug(); - bug.setDescription("JPA-2 locking"); - bug.setSummary("JPA-2 impl locking"); - Person p = new Person(); - p.setFirstName("Scott"); - p.setLastName("Marlow"); - bug.setReportedBy(p); - set.add(bug); - - bug = new Bug(); - bug.setDescription("JPA-2 annotations"); - bug.setSummary("JPA-2 impl annotations"); - p = new Person(); - p.setFirstName("Emmanuel"); - p.setLastName("Bernard"); - bug.setReportedBy(p); - set.add(bug); - - bug = new Bug(); - bug.setDescription("Implement JPA-2 criteria"); - bug.setSummary("JPA-2 impl criteria"); - p = new Person(); - p.setFirstName("Steve"); - p.setLastName("Ebersole"); - bug.setReportedBy(p); - set.add(bug); - - bs.setBugs(set); - s.persist(bs); - tx.commit(); - - tx = s.beginTransaction(); - s.clear(); - bs = (BugSystem) s.get(BugSystem.class,bs.getId()); - Assert.assertTrue("has three bugs", bs.getBugs().size() == 3); - Iterator iter = bs.getBugs().iterator(); - Assert.assertEquals( "Emmanuel", ((Bug)iter.next()).getReportedBy().getFirstName() ); - Assert.assertEquals( "Steve", ((Bug)iter.next()).getReportedBy().getFirstName() ); - Assert.assertEquals( "Scott", ((Bug)iter.next()).getReportedBy().getFirstName() ); - tx.commit(); - s.close(); - - } - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Products.class, - Widgets.class, - BugSystem.class - }; - } - -} diff --git a/hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/QueryTest.java b/hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/QueryTest.java deleted file mode 100644 index 0ba3b1e3b803..000000000000 --- a/hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/QueryTest.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 . - */ -package org.hibernate.test.annotations.collectionelement; - -import org.hibernate.Session; - -import org.junit.Test; - -import org.hibernate.testing.TestForIssue; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; - -/** - * @author Steve Ebersole - */ -public class QueryTest extends BaseCoreFunctionalTestCase { - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { EntityWithAnElementCollection.class }; - } - - @Test - @TestForIssue( jiraKey = "HHH-5209" ) - public void testMemberOfSyntax() { - // performs syntax checking of the MEMBER OF predicate against a basic collection - Session s = openSession(); - s.createQuery( "from EntityWithAnElementCollection e where 'abc' member of e.someStrings" ).list(); - s.close(); - } -} diff --git a/hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/embeddables/withcustomenumdef/TestBasicOps.java b/hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/embeddables/withcustomenumdef/TestBasicOps.java deleted file mode 100644 index 20b31fc62ca6..000000000000 --- a/hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/embeddables/withcustomenumdef/TestBasicOps.java +++ /dev/null @@ -1,84 +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.test.annotations.collectionelement.embeddables.withcustomenumdef; - -import static junit.framework.Assert.assertEquals; - -import java.util.Iterator; - -import org.hibernate.Session; -import org.hibernate.testing.TestForIssue; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; -import org.junit.Test; - -/** - * @author Steve Ebersole - */ -public class TestBasicOps extends BaseCoreFunctionalTestCase { - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { Query.class }; - } - - @Test - public void testLoadAndStore() { - Session s = openSession(); - s.beginTransaction(); - Query q = new Query( new Location( "first", Location.Type.COUNTY ) ); - s.save( q ); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - q = (Query) s.get( Query.class, q.getId() ); - assertEquals( 1, q.getIncludedLocations().size() ); - Location l = q.getIncludedLocations().iterator().next(); - assertEquals( Location.Type.COUNTY, l.getType() ); - s.delete( q ); - s.getTransaction().commit(); - s.close(); - } - - @Test - @TestForIssue(jiraKey = "HHH-7072") - public void testEmbeddableWithNullables() { - Session s = openSession(); - s.beginTransaction(); - Query q = new Query( new Location( null, Location.Type.COMMUNE ) ); - s.save( q ); - s.getTransaction().commit(); - s.clear(); - - s.beginTransaction(); - q.getIncludedLocations().add( new Location( null, Location.Type.COUNTY ) ); - s.update( q ); - s.getTransaction().commit(); - s.clear(); - - s.beginTransaction(); - q = (Query) s.get( Query.class, q.getId() ); -// assertEquals( 2, q.getIncludedLocations().size() ); - s.getTransaction().commit(); - s.clear(); - - s.beginTransaction(); - Iterator itr = q.getIncludedLocations().iterator(); - itr.next(); - itr.remove(); - s.update( q ); - s.getTransaction().commit(); - s.clear(); - - s.beginTransaction(); - q = (Query) s.get( Query.class, q.getId() ); - assertEquals( 1, q.getIncludedLocations().size() ); - s.delete( q ); - s.getTransaction().commit(); - s.close(); - } -} diff --git a/hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/indexedCollection/IndexedCollectionOfElementsTest.java b/hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/indexedCollection/IndexedCollectionOfElementsTest.java deleted file mode 100644 index 1c154435ebf5..000000000000 --- a/hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/indexedCollection/IndexedCollectionOfElementsTest.java +++ /dev/null @@ -1,42 +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.test.annotations.collectionelement.indexedCollection; - -import org.junit.Test; - -import org.hibernate.Session; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; - -import static org.junit.Assert.assertEquals; - -/** - * @author Emmanuel Bernard - */ -public class IndexedCollectionOfElementsTest extends BaseCoreFunctionalTestCase { - @Test - public void testIndexedCollectionOfElements() throws Exception { - Sale sale = new Sale(); - Contact contact = new Contact(); - contact.setName( "Emmanuel" ); - sale.getContacts().add(contact); - Session s = openSession( ); - s.getTransaction().begin(); - s.save( sale ); - s.flush(); - s.get( Sale.class, sale.getId() ); - assertEquals( 1, sale.getContacts().size() ); - s.getTransaction().rollback(); - s.close(); - } - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Sale.class - }; - } -} diff --git a/hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/ordered/ElementCollectionSortingTest.java b/hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/ordered/ElementCollectionSortingTest.java deleted file mode 100644 index 453354d0bf3d..000000000000 --- a/hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/ordered/ElementCollectionSortingTest.java +++ /dev/null @@ -1,125 +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.test.annotations.collectionelement.ordered; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import org.hibernate.LockMode; -import org.hibernate.Session; -import org.hibernate.SortOrder; -import org.hibernate.engine.spi.SessionImplementor; -import org.hibernate.metamodel.mapping.PluralAttributeMapping; -import org.hibernate.persister.collection.BasicCollectionPersister; -import org.hibernate.persister.collection.CollectionPersister; -import org.hibernate.query.NavigablePath; -import org.hibernate.sql.ast.spi.SqlAliasBase; -import org.hibernate.sql.ast.spi.SqlAliasBaseImpl; - -import org.hibernate.testing.TestForIssue; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; -import org.junit.Assert; -import org.junit.Test; - -import static org.hamcrest.CoreMatchers.notNullValue; -import static org.hamcrest.MatcherAssert.assertThat; - -/** - * @author Steve Ebersole - * @author Lukasz Antoniak (lukasz dot antoniak at gmail dot com) - */ -public class ElementCollectionSortingTest extends BaseCoreFunctionalTestCase { - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { Person.class }; - } - - @Test - public void testSortingElementCollectionSyntax() { - Session session = openSession(); - session.beginTransaction(); - -// session.createQuery( "from Person p join fetch p.nickNamesAscendingNaturalSort" ).list(); -// session.createQuery( "from Person p join fetch p.nickNamesDescendingNaturalSort" ).list(); -// -// session.createQuery( "from Person p join fetch p.addressesAscendingNaturalSort" ).list(); - session.createQuery( "from Person p join fetch p.addressesDescendingNaturalSort" ).list(); - session.createQuery( "from Person p join fetch p.addressesCityAscendingSort" ).list(); - session.createQuery( "from Person p join fetch p.addressesCityDescendingSort" ).list(); - - session.getTransaction().commit(); - session.close(); - } - - @Test - @TestForIssue( jiraKey = "HHH-6875" ) - public void testSortingEmbeddableCollectionOfPrimitives() { - final Session session = openSession(); - session.beginTransaction(); - - final Person steve = new Person(); - steve.setName( "Steve" ); - steve.getNickNamesAscendingNaturalSort().add( "sebersole" ); - steve.getNickNamesAscendingNaturalSort().add( "ebersole" ); - steve.getNickNamesDescendingNaturalSort().add( "ebersole" ); - steve.getNickNamesDescendingNaturalSort().add( "sebersole" ); - - final Person lukasz = new Person(); - lukasz.setName( "Lukasz" ); - lukasz.getNickNamesAscendingNaturalSort().add( "antoniak" ); - lukasz.getNickNamesAscendingNaturalSort().add( "lantoniak" ); - lukasz.getNickNamesDescendingNaturalSort().add( "lantoniak" ); - lukasz.getNickNamesDescendingNaturalSort().add( "antoniak" ); - - session.save( steve ); - session.save( lukasz ); - session.flush(); - - session.clear(); - - final List lukaszNamesAsc = Arrays.asList( "antoniak", "lantoniak" ); - final List lukaszNamesDesc = Arrays.asList( "lantoniak", "antoniak" ); - final List steveNamesAsc = Arrays.asList( "ebersole", "sebersole" ); - final List steveNamesDesc = Arrays.asList( "sebersole", "ebersole" ); - - // Testing object graph navigation. Lazy loading collections. - checkPersonNickNames( lukaszNamesAsc, lukaszNamesDesc, (Person) session.get( Person.class, lukasz.getId() ) ); - checkPersonNickNames( steveNamesAsc, steveNamesDesc, (Person) session.get( Person.class, steve.getId() ) ); - - session.clear(); - - // Testing HQL query. Eagerly fetching nicknames. - final List result = session.createQuery( - "select distinct p from Person p join fetch p.nickNamesAscendingNaturalSort join fetch p.nickNamesDescendingNaturalSort order by p.name" - ).list(); - Assert.assertEquals( 2, result.size() ); - checkPersonNickNames( lukaszNamesAsc, lukaszNamesDesc, result.get( 0 ) ); - checkPersonNickNames( steveNamesAsc, steveNamesDesc, result.get( 1 ) ); - - // Metadata verification. -// checkSQLOrderBy( session, Person.class.getName(), "nickNamesAscendingNaturalSort", "asc" ); -// checkSQLOrderBy( session, Person.class.getName(), "nickNamesDescendingNaturalSort", "desc" ); - - session.getTransaction().rollback(); - session.close(); - } - -// private void checkSQLOrderBy(Session session, String entityName, String propertyName, String order) { -// String roleName = entityName + "." + propertyName; -// String alias = "alias1"; -// BasicCollectionPersister collectionPersister = (BasicCollectionPersister) session.getSessionFactory().getCollectionMetadata( roleName ); -// Assert.assertTrue( collectionPersister.hasOrdering() ); -// Assert.assertEquals( alias + "." + propertyName + " " + order, collectionPersister.getSQLOrderByString( alias ) ); -// } - - private void checkPersonNickNames(List expectedAscending, List expectedDescending, Person person) { - // Comparing lists to verify ordering. - Assert.assertEquals( expectedAscending, new ArrayList( person.getNickNamesAscendingNaturalSort() ) ); - Assert.assertEquals( expectedDescending, new ArrayList( person.getNickNamesDescendingNaturalSort() ) ); - } -} diff --git a/hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/recreate/RecreateCollectionTest.java b/hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/recreate/RecreateCollectionTest.java deleted file mode 100644 index 4b30dc1c1e06..000000000000 --- a/hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/recreate/RecreateCollectionTest.java +++ /dev/null @@ -1,86 +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.test.annotations.collectionelement.recreate; - -import org.hibernate.BaseSessionEventListener; -import org.hibernate.Session; - -import org.hibernate.testing.TestForIssue; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; -import org.junit.Test; - -import java.util.Date; - -import static org.junit.Assert.assertEquals; - -/** - * @author Sergey Astakhov - */ -public class RecreateCollectionTest extends BaseCoreFunctionalTestCase { - - private static class StatementsCounterListener extends BaseSessionEventListener { - int statements; - - @Override - public void jdbcExecuteStatementEnd() { - statements++; - } - } - - @Test - @TestForIssue(jiraKey = "HHH-9474") - public void testUpdateCollectionOfElements() throws Exception { - Session s = openSession(); - - s.getTransaction().begin(); - - Poi poi1 = new Poi( "Poi 1" ); - Poi poi2 = new Poi( "Poi 2" ); - - s.save( poi1 ); - s.save( poi2 ); - - RaceExecution race = new RaceExecution(); - - s.save( race ); - - Date currentTime = new Date(); - - race.arriveToPoi( poi1, currentTime ); - race.expectedArrive( poi2, new Date( currentTime.getTime() + 60 * 1000 ) ); - - s.flush(); - - assertEquals( 2, race.getPoiArrival().size() ); - - StatementsCounterListener statementsCounterListener = new StatementsCounterListener(); - - s.addEventListeners( statementsCounterListener ); - - race.arriveToPoi( poi2, new Date( currentTime.getTime() + 2 * 60 * 1000 ) ); - - s.flush(); - - assertEquals( 2, race.getPoiArrival().size() ); - - // There is should be one UPDATE statement. Without fix there is one DELETE and two INSERT-s. - - assertEquals( 1, statementsCounterListener.statements ); - - s.getTransaction().rollback(); - s.close(); - } - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Poi.class, - RaceExecution.class - }; - } - -}