小编典典

在Hibernate中使用惰性的属性

hibernate

hibernate中的property标签的lazy属性允许按照以下链接延迟加载属性:http :
//docs.jboss.org/hibernate/orm/3.3/reference/en-US/html/mapping.html#mapping-
declaration -属性

lazy(可选-默认为false):指定在首次访问实例变量时应延迟获取此属性。它需要构建时字节码检测。

但是,当我尝试为我的其中一个属性设置lazy = true时,在此示例中它不会延迟加载:

hibernate映射文件:

<hibernate-mapping package="org.hibernate.tutorial.domain">

    <class name="Event" table="EVENTS" select-before-update="true">
        <id name="id" column="EVENT_ID">
            <generator class="native" />
        </id>
        <property name="date" type="timestamp" column="EVENT_DATE" />
        <property name="title" lazy="true"/>

        <set name="participants" table="PERSON_EVENT" inverse="true">
            <key column="EVENT_ID" />
            <many-to-many column="PERSON_ID" class="Person" />
        </set>
    </class>

</hibernate-mapping>

程序:

public static void main(String[] args) {
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        session.beginTransaction();
        Event event = (Event) session.get(Event.class, 135L);
        session.getTransaction().commit();
        System.out.println(event);
        HibernateUtil.getSessionFactory().close();
    }

由hibernate生成的查询:

Hibernate: select event0_.EVENT_ID as EVENT1_0_0_, event0_.EVENT_DATE as EVENT2_0_0_, event0_.title as title0_0_ from EVENTS event0_ where event0_.EVENT_ID=?

请帮助我了解为什么在这种情况下懒惰不起作用?


阅读 265

收藏
2020-06-20

共1个答案

小编典典

使用Hibernate 5,可以使用字节码增强轻松完成此操作

首先,您需要添加以下Maven插件:

<plugin>
    <groupId>org.hibernate.orm.tooling</groupId>
    <artifactId>hibernate-enhance-maven-plugin</artifactId>
    <version>${hibernate.version}</version>
    <executions>
        <execution>
            <configuration>
                <enableLazyInitialization>true</enableLazyInitialization>
            </configuration>
            <goals>
                <goal>enhance</goal>
            </goals>
        </execution>
    </executions>
</plugin>

然后,您可以简单地使用以下注释您的实体属性@Basic(fetch = FetchType.LAZY)

@Entity(name = "Event")
@Table(name = "event")
public class Event extends BaseEntity {

    @Type(type = "jsonb")
    @Column(columnDefinition = "jsonb")
    @Basic(fetch = FetchType.LAZY)
    private Location location;

    public Location getLocation() {
        return location;
    }

    public void setLocation(Location location) {
        this.location = location;
    }
}

当您获取实体时:

Event event = entityManager.find(Event.class, 
    eventHolder.get().getId());

LOGGER.debug("Fetched event");
assertEquals("Cluj-Napoca", event.getLocation().getCity());

Hibernate将使用辅助选择来加载惰性属性:

SELECT e.id AS id1_0_0_
FROM   event e
WHERE  e.id = 1

-- Fetched event

SELECT e.location AS location2_0_
FROM   event e
WHERE  e.id = 1
2020-06-20