Hibernate延迟加载属性XML映射

时间:2011-08-25 21:41:17

标签: java hibernate lazy-loading

是否有可能让Hibernate延迟加载实体上的属性?我们继承了一个默认加载的项目中有一些clobs。我希望在将映射转换为Annotations之前将XML修改为止损。

2 个答案:

答案 0 :(得分:2)

是。请参阅"Using lazy property fetching"

答案 1 :(得分:0)

使用Hibernate 5,this can be done as follows:

首先,您需要添加以下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