在Hibernate中使用lazy属性 [英] Using lazy for properties in Hibernate

查看:130
本文介绍了在Hibernate中使用lazy属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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


lazy(可选 - 默认为false):指定此属性
应该在实例变量首先被访问。
它需要构建时字节码工具。


但是当我试图为我的某个属性设置lazy = true时在这个例子中,它没有加载它:



Hibernate映射文件:

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

< class name =Eventtable =EVENTSselect-before-update =true>
< id name =idcolumn =EVENT_ID>
< generator class =native/>
< / id>
< property name =datetype =timestampcolumn =EVENT_DATE/>
< property name =titlelazy =true/>

< set name =participantstable =PERSON_EVENTinverse =true>
< key column =EVENT_ID/>
<多对多列=PERSON_IDclass =Person/>
< / set>
< / class>

< / hibernate-mapping>

程式:

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

由hibernate生成的查询:

  Hibernate:选择event0_.EVENT_ID作为EVENT1_0_0_,event0_.EVENT_DATE作为EVENT2_0_0_,event0_.title作为title0_0_来自EVENTS event0_,其中event0_.EVENT_ID =? 

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

解决方案

使用Hibernate 5,这可以使用字节码增强功能轻松完成

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

  <插件> 
< groupId> org.hibernate.orm.tooling< / groupId>
< artifactId> hibernate-enhance-maven-plugin< / artifactId>
< version> $ {hibernate.version}< / version>
<执行次数>
<执行>
<配置>
< enableLazyInitialization> true< / enableLazyInitialization>
< / configuration>
<目标>
< goal>增强< / goal>
< /目标>
< /执行>
< /执行次数>
< / plugin>

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

  @Entity(name =Event)
@ Table(name =event)
public class Event扩展BaseEntity {

@Type(type =jsonb)
@Column(columnDefinition =jsonb)
@Basic(fetch = FetchType.LAZY)
私人位置位置;

public Location getLocation(){
return location;
}

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


当您获取实体时:

 事件事件= entityManager.find(Event.class,
eventHolder.get()。getId());

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

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

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

- 获取事件

SELECT e.location AS location2_0_
FROM event e
WHERE e.id = 1


The lazy attribute for property tag in hibernate allows to lazily load the property as per the link: http://docs.jboss.org/hibernate/orm/3.3/reference/en-US/html/mapping.html#mapping-declaration-property

lazy (optional - defaults to false): specifies that this property should be fetched lazily when the instance variable is first accessed. It requires build-time bytecode instrumentation.

But when I tried to set lazy=true for one of my property it is not loading it lazily in this example:

Hibernate Mapping file:

<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>

Program:

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();
    }

Query generated by 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=?

Please help me in understanding why the lazy is not working in this case?

解决方案

With Hibernate 5, this can be done easily using bytecode enhancement.

First, you need to add the following Maven plugin:

<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>

Then, you can simply annotate your entity properties with @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;
    }
}

When you fetch the entity:

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

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

Hibernate is going to load the lazy property using a secondary select:

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

这篇关于在Hibernate中使用lazy属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆