С 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 собирается загрузить свойство lazy с помощью вторичного 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