Chapter 12. Fetch plans, strategies, and profiles

 

In this chapter

  • Lazy and eager loading
  • Fetch plans, strategies, and profiles
  • Optimizing SQL execution

In this chapter, we explore Hibernate’s solution for the fundamental ORM problem of navigation, as mentioned in section 1.2.5. We show you how to retrieve data from the database and how you can optimize this loading.

Hibernate provides the following ways to get data out of the database and into memory:

12.1. Lazy and eager loading

Path: /examples/src/test/java/org/jpwh/test/fetching/LazyProxyCollections.java

Path: /examples/src/test/java/org/jpwh/test/fetching/LazyProxyCollections.java

Path: /examples/src/test/java/org/jpwh/test/fetching/LazyProxyCollections.java

Path: /examples/src/test/java/org/jpwh/test/fetching/LazyProxyCollections.java

Path: /model/src/main/java/org/jpwh/model/fetching/proxy/Item.java

@Entity
public class Item {

    @ManyToOne(fetch = FetchType.LAZY)
    public User getSeller() {
        return seller;
    }
    // ...
}

Path: /examples/src/test/java/org/jpwh/test/fetching/LazyProxyCollections.java

Path: /examples/src/test/java/org/jpwh/test/fetching/LazyProxyCollections.java

Path: /examples/src/test/java/org/jpwh/test/fetching/LazyProxyCollections.java

Bid firstBid = bids.iterator().next();
// select * from BID where ITEM_ID = ?

// Alternative: Hibernate.initialize(bids);

Path: /model/src/main/java/org/jpwh/model/fetching/proxy/Item.java

@Entity
public class Item {

    @OneToMany(mappedBy = "item")
    @org.hibernate.annotations.LazyCollection(
       org.hibernate.annotations.LazyCollectionOption.EXTRA
    )
    public Set<Bid> getBids() {
        return bids;
    }
    // ...
}

Path: /model/src/main/java/org/jpwh/model/fetching/interception/User.java

@Entity
@org.hibernate.annotations.Proxy(lazy = false)
public class User {
    // ...
}

Path: /examples/src/test/java/org/jpwh/test/fetching/LazyInterception.java

Path: /model/src/main/java/org/jpwh/model/fetching/interception/Item.java

Path: /examples/src/test/java/org/jpwh/test/fetching/LazyInterception.java

Path: /model/src/main/java/org/jpwh/model/fetching/interception/Item.java

@Entity
public class Item {

    @Basic(fetch = FetchType.LAZY)
    protected String description;

    // ...
}

Path: /examples/src/test/java/org/jpwh/test/fetching/LazyInterception.java

Path: /model/src/main/java/org/jpwh/model/fetching/eagerjoin/Item.java

Path: /examples/src/test/java/org/jpwh/test/fetching/EagerJoin.java

12.2. Selecting a fetch strategy

Path: /examples/src/test/java/org/jpwh/test/fetching/NPlusOneSelects.java

Path: /examples/src/test/java/org/jpwh/test/fetching/NPlusOneSelects.java

12.3. Using fetch profiles