Cha*_*nya 4 java orm hibernate lazy-loading properties
hibernate中property标记的lazy属性允许按照以下链接延迟加载属性:http : //docs.jboss.org/hibernate/orm/3.3/reference/zh-CN/html/mapping.html#mapping-declaration -属性
lazy(可选-默认为false):指定在首次访问实例变量时应延迟获取此属性。它需要构建时字节码检测。
但是,当我尝试为我的其中一个属性设置lazy = true时,在此示例中它不会延迟加载:
休眠映射文件:
<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>
Run Code Online (Sandbox Code Playgroud)
程序:
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();
}
Run Code Online (Sandbox Code Playgroud)
由休眠生成的查询:
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=?
Run Code Online (Sandbox Code Playgroud)
请帮助我了解为什么在这种情况下懒惰不起作用?
使用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>
Run Code Online (Sandbox Code Playgroud)
然后,您可以简单地使用以下注释您的实体属性@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;
}
}
Run Code Online (Sandbox Code Playgroud)
当您获取实体时:
Event event = entityManager.find(Event.class,
eventHolder.get().getId());
LOGGER.debug("Fetched event");
assertEquals("Cluj-Napoca", event.getLocation().getCity());
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8698 次 |
| 最近记录: |