Chaitanya Chaitanya - 1 year ago 116
Java Question

Using lazy for properties in Hibernate

The lazy attribute for property tag in hibernate allows to lazily load the property as per the link:

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



public static void main(String[] args) {
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
Event event = (Event) session.get(Event.class, 135L);

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?

Answer Source

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

First, you need to add the following Maven 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, 

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

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

SELECT AS id1_0_0_
FROM   event e

-- Fetched event

SELECT e.location AS location2_0_
FROM   event e
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download