Using lazy for properties in Hibernate

前端 未结 3 1337
一个人的身影
一个人的身影 2021-01-03 05:41

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

3条回答
  •  失恋的感觉
    2021-01-03 06:40

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

    First, you need to add the following Maven plugin:

    
        org.hibernate.orm.tooling
        hibernate-enhance-maven-plugin
        ${hibernate.version}
        
            
                
                    true
                
                
                    enhance
                
            
        
    
    

    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
    

提交回复
热议问题