Search in sources :

Example 1 with GraphSemantic

use of org.hibernate.graph.GraphSemantic in project hibernate-orm by hibernate.

the class EntityGraphLoadPlanBuilderTest method testLoadPlanBuildingWithSubgraph.

@ParameterizedTest
@EnumSource(GraphSemantic.class)
void testLoadPlanBuildingWithSubgraph(GraphSemantic graphSemantic) {
    scope.inTransaction(em -> {
        final RootGraphImplementor<Cat> eg = em.createEntityGraph(Cat.class);
        eg.addSubgraph("owner", Person.class);
        final SelectStatement sqlAst = buildSqlSelectAst(Cat.class, eg, graphSemantic, scope);
        // Check the from-clause
        assertEntityValuedJoinedGroup(sqlAst, "owner", Person.class, this::assertPersonHomeAddressJoinedGroup);
        // Check the domain-result graph
        assertDomainResult(sqlAst, Cat.class, "owner", Person.class, entityFetch -> {
            if (graphSemantic == GraphSemantic.LOAD) {
                assertThat(entityFetch, instanceOf(EntityFetchJoinedImpl.class));
                final EntityResult entityResult = ((EntityFetchJoinedImpl) entityFetch).getEntityResult();
                final Map<String, Class<? extends Fetch>> fetchClassByAttributeName = entityResult.getFetches().stream().collect(Collectors.toMap(fetch -> fetch.getFetchedMapping().getPartName(), Fetch::getClass));
                final Map<String, Class<? extends Fetch>> expectedFetchClassByAttributeName = new HashMap<>();
                expectedFetchClassByAttributeName.put("pets", DelayedCollectionFetch.class);
                expectedFetchClassByAttributeName.put("homeAddress", EmbeddableFetchImpl.class);
                expectedFetchClassByAttributeName.put("company", EntityDelayedFetchImpl.class);
                assertThat(fetchClassByAttributeName, is(expectedFetchClassByAttributeName));
            }
        });
    });
}
Also used : EntityFetchJoinedImpl(org.hibernate.sql.results.graph.entity.internal.EntityFetchJoinedImpl) DelayedCollectionFetch(org.hibernate.sql.results.graph.collection.internal.DelayedCollectionFetch) Fetch(org.hibernate.sql.results.graph.Fetch) EntityFetch(org.hibernate.sql.results.graph.entity.EntityFetch) CoreMatchers.is(org.hamcrest.CoreMatchers.is) Entity(jakarta.persistence.Entity) AssignableMatcher.assignableTo(org.hibernate.testing.hamcrest.AssignableMatcher.assignableTo) EntityPersister(org.hibernate.persister.entity.EntityPersister) GraphSemantic(org.hibernate.graph.GraphSemantic) DelayedCollectionFetch(org.hibernate.sql.results.graph.collection.internal.DelayedCollectionFetch) TableGroupJoin(org.hibernate.sql.ast.tree.from.TableGroupJoin) EntityValuedModelPart(org.hibernate.metamodel.mapping.EntityValuedModelPart) CoreMatchers.notNullValue(org.hamcrest.CoreMatchers.notNullValue) CoreMatchers.instanceOf(org.hamcrest.CoreMatchers.instanceOf) Assert.assertThat(org.junit.Assert.assertThat) PluralAttributeMapping(org.hibernate.metamodel.mapping.PluralAttributeMapping) TestForIssue(org.hibernate.testing.TestForIssue) SessionFactoryScopeAware(org.hibernate.testing.orm.junit.SessionFactoryScopeAware) Map(java.util.Map) EntityResult(org.hibernate.sql.results.graph.entity.EntityResult) FetchType(jakarta.persistence.FetchType) Fetchable(org.hibernate.sql.results.graph.Fetchable) EntityDelayedFetchImpl(org.hibernate.sql.results.graph.entity.internal.EntityDelayedFetchImpl) LockOptions(org.hibernate.LockOptions) CollectionUtils(org.junit.platform.commons.util.CollectionUtils) LazyTableGroup(org.hibernate.sql.ast.tree.from.LazyTableGroup) Collection(java.util.Collection) DomainResult(org.hibernate.sql.results.graph.DomainResult) Set(java.util.Set) Id(jakarta.persistence.Id) DomainModel(org.hibernate.testing.orm.junit.DomainModel) Collectors(java.util.stream.Collectors) EmbeddableFetchImpl(org.hibernate.sql.results.graph.embeddable.internal.EmbeddableFetchImpl) SelectStatement(org.hibernate.sql.ast.tree.select.SelectStatement) Test(org.junit.jupiter.api.Test) LoadQueryInfluencers(org.hibernate.engine.spi.LoadQueryInfluencers) List(java.util.List) FromClause(org.hibernate.sql.ast.tree.from.FromClause) EmbeddedAttributeMapping(org.hibernate.metamodel.mapping.internal.EmbeddedAttributeMapping) OneToMany(jakarta.persistence.OneToMany) ManyToOne(jakarta.persistence.ManyToOne) HashMap(java.util.HashMap) EnumSource(org.junit.jupiter.params.provider.EnumSource) Embedded(jakarta.persistence.Embedded) RootGraphImplementor(org.hibernate.graph.spi.RootGraphImplementor) CollectionMatchers.hasSize(org.hibernate.testing.hamcrest.CollectionMatchers.hasSize) LoaderSelectBuilder(org.hibernate.loader.ast.internal.LoaderSelectBuilder) Embeddable(jakarta.persistence.Embeddable) CollectionMatchers.isEmpty(org.hibernate.testing.hamcrest.CollectionMatchers.isEmpty) ElementCollection(jakarta.persistence.ElementCollection) Fetch(org.hibernate.sql.results.graph.Fetch) Consumer(java.util.function.Consumer) EntityFetch(org.hibernate.sql.results.graph.entity.EntityFetch) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) StandardVirtualTableGroup(org.hibernate.sql.ast.tree.from.StandardVirtualTableGroup) SessionFactoryScope(org.hibernate.testing.orm.junit.SessionFactoryScope) AttributeMapping(org.hibernate.metamodel.mapping.AttributeMapping) SessionFactory(org.hibernate.testing.orm.junit.SessionFactory) TableGroup(org.hibernate.sql.ast.tree.from.TableGroup) EffectiveEntityGraph(org.hibernate.engine.spi.EffectiveEntityGraph) EntityFetchJoinedImpl(org.hibernate.sql.results.graph.entity.internal.EntityFetchJoinedImpl) SelectStatement(org.hibernate.sql.ast.tree.select.SelectStatement) HashMap(java.util.HashMap) EntityResult(org.hibernate.sql.results.graph.entity.EntityResult) EnumSource(org.junit.jupiter.params.provider.EnumSource) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest)

Example 2 with GraphSemantic

use of org.hibernate.graph.GraphSemantic in project hibernate-orm by hibernate.

the class HqlEntityGraphTest method testSemanticsWithSubgraph.

@ParameterizedTest
@EnumSource(GraphSemantic.class)
void testSemanticsWithSubgraph(GraphSemantic graphSemantic) {
    scope.inTransaction(session -> {
        final RootGraphImplementor<Cat> eg = session.createEntityGraph(Cat.class);
        eg.addSubgraph("owner", Person.class);
        final SelectStatement sqlAst = buildSqlSelectAst(Cat.class, "select c from Cat as c", eg, graphSemantic, session);
        // Check the from-clause
        assertEntityValuedJoinedGroup(sqlAst, "owner", Person.class, this::assertPersonHomeAddressJoinedGroup);
        // Check the domain-result graph
        assertDomainResult(sqlAst, Cat.class, "owner", Person.class, entityFetch -> {
            if (graphSemantic == GraphSemantic.LOAD) {
                assertThat(entityFetch, instanceOf(EntityFetchJoinedImpl.class));
                final EntityResult entityResult = ((EntityFetchJoinedImpl) entityFetch).getEntityResult();
                final Map<String, Class<? extends Fetch>> fetchClassByAttributeName = entityResult.getFetches().stream().collect(Collectors.toMap(fetch -> fetch.getFetchedMapping().getPartName(), Fetch::getClass));
                final Map<String, Class<? extends Fetch>> expectedFetchClassByAttributeName = new HashMap<>();
                expectedFetchClassByAttributeName.put("pets", DelayedCollectionFetch.class);
                expectedFetchClassByAttributeName.put("homeAddress", EmbeddableFetchImpl.class);
                expectedFetchClassByAttributeName.put("company", EntityDelayedFetchImpl.class);
                assertThat(fetchClassByAttributeName, is(expectedFetchClassByAttributeName));
            }
        });
    });
}
Also used : EntityFetchJoinedImpl(org.hibernate.sql.results.graph.entity.internal.EntityFetchJoinedImpl) DelayedCollectionFetch(org.hibernate.sql.results.graph.collection.internal.DelayedCollectionFetch) Fetch(org.hibernate.sql.results.graph.Fetch) EntityFetch(org.hibernate.sql.results.graph.entity.EntityFetch) CoreMatchers.is(org.hamcrest.CoreMatchers.is) Entity(jakarta.persistence.Entity) AssignableMatcher.assignableTo(org.hibernate.testing.hamcrest.AssignableMatcher.assignableTo) EntityPersister(org.hibernate.persister.entity.EntityPersister) GraphSemantic(org.hibernate.graph.GraphSemantic) DelayedCollectionFetch(org.hibernate.sql.results.graph.collection.internal.DelayedCollectionFetch) TableGroupJoin(org.hibernate.sql.ast.tree.from.TableGroupJoin) EntityValuedModelPart(org.hibernate.metamodel.mapping.EntityValuedModelPart) CoreMatchers.notNullValue(org.hamcrest.CoreMatchers.notNullValue) CoreMatchers.instanceOf(org.hamcrest.CoreMatchers.instanceOf) Assert.assertThat(org.junit.Assert.assertThat) PluralAttributeMapping(org.hibernate.metamodel.mapping.PluralAttributeMapping) TestForIssue(org.hibernate.testing.TestForIssue) SqmQueryImplementor(org.hibernate.query.hql.spi.SqmQueryImplementor) SessionFactoryScopeAware(org.hibernate.testing.orm.junit.SessionFactoryScopeAware) Map(java.util.Map) EntityResult(org.hibernate.sql.results.graph.entity.EntityResult) FetchType(jakarta.persistence.FetchType) Fetchable(org.hibernate.sql.results.graph.Fetchable) EntityDelayedFetchImpl(org.hibernate.sql.results.graph.entity.internal.EntityDelayedFetchImpl) SqmSelectStatement(org.hibernate.query.sqm.tree.select.SqmSelectStatement) CollectionUtils(org.junit.platform.commons.util.CollectionUtils) LazyTableGroup(org.hibernate.sql.ast.tree.from.LazyTableGroup) Collection(java.util.Collection) DomainResult(org.hibernate.sql.results.graph.DomainResult) Set(java.util.Set) Id(jakarta.persistence.Id) DomainModel(org.hibernate.testing.orm.junit.DomainModel) QuerySqmImpl(org.hibernate.query.sqm.internal.QuerySqmImpl) Collectors(java.util.stream.Collectors) EmbeddableFetchImpl(org.hibernate.sql.results.graph.embeddable.internal.EmbeddableFetchImpl) SelectStatement(org.hibernate.sql.ast.tree.select.SelectStatement) Test(org.junit.jupiter.api.Test) LoadQueryInfluencers(org.hibernate.engine.spi.LoadQueryInfluencers) List(java.util.List) SessionImplementor(org.hibernate.engine.spi.SessionImplementor) FromClause(org.hibernate.sql.ast.tree.from.FromClause) EmbeddedAttributeMapping(org.hibernate.metamodel.mapping.internal.EmbeddedAttributeMapping) OneToMany(jakarta.persistence.OneToMany) ManyToOne(jakarta.persistence.ManyToOne) HashMap(java.util.HashMap) EnumSource(org.junit.jupiter.params.provider.EnumSource) Embedded(jakarta.persistence.Embedded) RootGraphImplementor(org.hibernate.graph.spi.RootGraphImplementor) QueryImplementor(org.hibernate.query.spi.QueryImplementor) CollectionMatchers.hasSize(org.hibernate.testing.hamcrest.CollectionMatchers.hasSize) StandardSqmTranslator(org.hibernate.query.sqm.sql.internal.StandardSqmTranslator) Embeddable(jakarta.persistence.Embeddable) CollectionMatchers.isEmpty(org.hibernate.testing.hamcrest.CollectionMatchers.isEmpty) ElementCollection(jakarta.persistence.ElementCollection) SqmTranslation(org.hibernate.query.sqm.sql.SqmTranslation) Fetch(org.hibernate.sql.results.graph.Fetch) Consumer(java.util.function.Consumer) EntityFetch(org.hibernate.sql.results.graph.entity.EntityFetch) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) StandardVirtualTableGroup(org.hibernate.sql.ast.tree.from.StandardVirtualTableGroup) SessionFactoryScope(org.hibernate.testing.orm.junit.SessionFactoryScope) AttributeMapping(org.hibernate.metamodel.mapping.AttributeMapping) SessionFactory(org.hibernate.testing.orm.junit.SessionFactory) TableGroup(org.hibernate.sql.ast.tree.from.TableGroup) EntityFetchJoinedImpl(org.hibernate.sql.results.graph.entity.internal.EntityFetchJoinedImpl) SqmSelectStatement(org.hibernate.query.sqm.tree.select.SqmSelectStatement) SelectStatement(org.hibernate.sql.ast.tree.select.SelectStatement) HashMap(java.util.HashMap) EntityResult(org.hibernate.sql.results.graph.entity.EntityResult) EnumSource(org.junit.jupiter.params.provider.EnumSource) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest)

Example 3 with GraphSemantic

use of org.hibernate.graph.GraphSemantic in project hibernate-orm by hibernate.

the class SessionImpl method internalLoad.

@Override
public Object internalLoad(String entityName, Object id, boolean eager, boolean nullable) {
    final EffectiveEntityGraph effectiveEntityGraph = getLoadQueryInfluencers().getEffectiveEntityGraph();
    final GraphSemantic semantic = effectiveEntityGraph.getSemantic();
    final RootGraphImplementor<?> graph = effectiveEntityGraph.getGraph();
    boolean clearedEffectiveGraph = false;
    if (semantic != null) {
        if (!graph.appliesTo(entityName)) {
            log.debug("Clearing effective entity graph for subsequent-select");
            clearedEffectiveGraph = true;
            effectiveEntityGraph.clear();
        }
    }
    try {
        final LoadType type;
        if (nullable) {
            type = LoadEventListener.INTERNAL_LOAD_NULLABLE;
        } else {
            type = eager ? LoadEventListener.INTERNAL_LOAD_EAGER : LoadEventListener.INTERNAL_LOAD_LAZY;
        }
        LoadEvent event = loadEvent;
        loadEvent = null;
        event = recycleEventInstance(event, id, entityName);
        fireLoadNoChecks(event, type);
        Object result = event.getResult();
        if (!nullable) {
            UnresolvableObjectException.throwIfNull(result, id, entityName);
        }
        if (loadEvent == null) {
            event.setEntityClassName(null);
            event.setEntityId(null);
            event.setInstanceToLoad(null);
            event.setResult(null);
            loadEvent = event;
        }
        return result;
    } finally {
        if (clearedEffectiveGraph) {
            effectiveEntityGraph.applyGraph(graph, semantic);
        }
    }
}
Also used : LoadEvent(org.hibernate.event.spi.LoadEvent) LoadType(org.hibernate.event.spi.LoadEventListener.LoadType) EffectiveEntityGraph(org.hibernate.engine.spi.EffectiveEntityGraph) GraphSemantic(org.hibernate.graph.GraphSemantic)

Example 4 with GraphSemantic

use of org.hibernate.graph.GraphSemantic in project hibernate-orm by hibernate.

the class LoaderSelectBuilder method determineGraphTraversalState.

private static EntityGraphTraversalState determineGraphTraversalState(LoadQueryInfluencers loadQueryInfluencers) {
    if (loadQueryInfluencers != null) {
        final EffectiveEntityGraph effectiveEntityGraph = loadQueryInfluencers.getEffectiveEntityGraph();
        if (effectiveEntityGraph != null) {
            final GraphSemantic graphSemantic = effectiveEntityGraph.getSemantic();
            final RootGraphImplementor rootGraphImplementor = effectiveEntityGraph.getGraph();
            if (graphSemantic != null && rootGraphImplementor != null) {
                return new StandardEntityGraphTraversalStateImpl(graphSemantic, rootGraphImplementor);
            }
        }
    }
    return null;
}
Also used : RootGraphImplementor(org.hibernate.graph.spi.RootGraphImplementor) EffectiveEntityGraph(org.hibernate.engine.spi.EffectiveEntityGraph) GraphSemantic(org.hibernate.graph.GraphSemantic) StandardEntityGraphTraversalStateImpl(org.hibernate.sql.results.internal.StandardEntityGraphTraversalStateImpl)

Example 5 with GraphSemantic

use of org.hibernate.graph.GraphSemantic in project hibernate-orm by hibernate.

the class NaturalIdMultiLoadAccessStandard method multiLoad.

@Override
@SuppressWarnings("unchecked")
public List<T> multiLoad(Object... ids) {
    final CacheMode sessionCacheMode = session.getCacheMode();
    boolean cacheModeChanged = false;
    if (cacheMode != null) {
        // todo : account for "conceptually equal"
        if (cacheMode != sessionCacheMode) {
            session.setCacheMode(cacheMode);
            cacheModeChanged = true;
        }
    }
    session.autoFlushIfRequired((Set) CollectionHelper.setOf(entityDescriptor.getQuerySpaces()));
    final LoadQueryInfluencers loadQueryInfluencers = session.getLoadQueryInfluencers();
    try {
        final EffectiveEntityGraph effectiveEntityGraph = loadQueryInfluencers.getEffectiveEntityGraph();
        final GraphSemantic initialGraphSemantic = effectiveEntityGraph.getSemantic();
        final RootGraphImplementor<?> initialGraph = effectiveEntityGraph.getGraph();
        final boolean hadInitialGraph = initialGraphSemantic != null;
        if (graphSemantic != null) {
            if (rootGraph == null) {
                throw new IllegalArgumentException("Graph semantic specified, but no RootGraph was supplied");
            }
            effectiveEntityGraph.applyGraph(rootGraph, graphSemantic);
        }
        try {
            return (List<T>) entityDescriptor.getMultiNaturalIdLoader().multiLoad(ids, this, session);
        } finally {
            if (graphSemantic != null) {
                if (hadInitialGraph) {
                    effectiveEntityGraph.applyGraph(initialGraph, initialGraphSemantic);
                } else {
                    effectiveEntityGraph.clear();
                }
            }
        }
    } finally {
        if (cacheModeChanged) {
            // change it back
            session.setCacheMode(sessionCacheMode);
        }
    }
}
Also used : LoadQueryInfluencers(org.hibernate.engine.spi.LoadQueryInfluencers) CacheMode(org.hibernate.CacheMode) List(java.util.List) EffectiveEntityGraph(org.hibernate.engine.spi.EffectiveEntityGraph) GraphSemantic(org.hibernate.graph.GraphSemantic)

Aggregations

GraphSemantic (org.hibernate.graph.GraphSemantic)7 List (java.util.List)5 EffectiveEntityGraph (org.hibernate.engine.spi.EffectiveEntityGraph)5 RootGraphImplementor (org.hibernate.graph.spi.RootGraphImplementor)5 Map (java.util.Map)4 Set (java.util.Set)4 LoadQueryInfluencers (org.hibernate.engine.spi.LoadQueryInfluencers)4 EntityPersister (org.hibernate.persister.entity.EntityPersister)4 ElementCollection (jakarta.persistence.ElementCollection)3 Embeddable (jakarta.persistence.Embeddable)3 Embedded (jakarta.persistence.Embedded)3 Entity (jakarta.persistence.Entity)3 FetchType (jakarta.persistence.FetchType)3 Id (jakarta.persistence.Id)3 ManyToOne (jakarta.persistence.ManyToOne)3 OneToMany (jakarta.persistence.OneToMany)3 Collection (java.util.Collection)3 HashMap (java.util.HashMap)3 Consumer (java.util.function.Consumer)3 Collectors (java.util.stream.Collectors)3