首页 > 解决方案 > 渴望获取特定对象的特定惰性属性

问题描述

我有以下模型:

@Table(name = "foo")
public class Foo {

    @ManyToOne(fetch = FetchType.LAZY)
    private Bar bar;

}

Entity Framework在类似情况下在 .NET 中使用时,我可以急切地将Bar属性带入以下内容:

context.Foo.Include(f => f.bar).First()

Hibernate有什么等价的吗?

我的情况是我将一个具有惰性属性的对象保存到我的服务器中的会话中。然后当我检索会话属性时,我无法访问休眠会话的惰性属性已经消失了。我不能把这个属性当作是EAGER因为它是从@MappedSuperclass许多其他类使用的继承而来的。

谢谢你的帮助。

标签: javahibernate

解决方案


  1. JPA实体图

    @Entity
    @Table(name = "foo")
    @NamedEntityGraph(name = "foo.bar",
            attributeNodes = @NamedAttributeNode("bar")
    )
    public class Foo {
    
        @ManyToOne(fetch = FetchType.LAZY)
        private Bar bar;
    
    }
    
    Foo foo = entityManager.find(
        Foo.class,
        id,
        Collections.singletonMap(
            "javax.persistence.fetchgraph",
            entityManager.getEntityGraph("foo.bar")
        )
    );
    

    您可以在那里看到另一个示例和更详细的说明。

  2. 休眠配置文件

    @Entity
    @Table(name = "foo")
    @FetchProfile(
        name = "foo.bar",
        fetchOverrides = {
            @FetchProfile.FetchOverride(
                entity = Foo.class,
                association = "bar",
                mode = FetchMode.JOIN
            )
        }
    )
    public class Foo {
        @ManyToOne(fetch = FetchType.LAZY)
        private Bar bar;
    }
    
    
    session.enableFetchProfile("foo.bar");
    Foo foo = session.byId(Foo.class).load(id);
    

推荐阅读