开发者

Understanding the Lazy fetch

@Entity
public class Bid {

    @Id
    @GeneratedValue
    @Column(name = "bid_id")
    private Long bidId;

    @Column(name = "bid_amt")
    private double bidAmount;

    @Basic(fetch = FetchType.LAZY, optional = false)
    private String person;

    @ManyToOne(targetEntity = Item.class, fetch = FetchType.LAZY)
    @JoinColumn(name = "bid_item", referencedColumnName = "item_id", nullable = false)
    private Item item;

    public Long getBidId() {
        return bidId;
    }

    public double getBidAmount() {
        return bidAmount;
    }

    public String getPerson() {
        return person;
    }

    public Item getItem() {
        return item;
    }

    public void setBidAmount(final double bidAmount) {
        this.bidAmount = bidAmount;
    }

    public void setPerson(final String person) {
        this.person = person;
    }

    public void setItem(final Item item) {
        this.item = item;
    }

    public Bid() {
    }

    @Override
    public String开发者_如何学运维 toString() {
        return "Bid [bidId=" + bidId + ", bidAmount=" + bidAmount + ", person="
                + person + /* ", item=" + item + */"]";
    }

}

Test Case:

@Test
    public void testBidRead() {
        final Session currentSession = sessionFactory.getCurrentSession();
        final List<Bid> bids = currentSession.createQuery("from Bid").list();
        for (final Bid bid : bids) {
            System.out.println(bid);
        }
    }

And the SQL the Hibernate generated is:

/* 
from
    Bid */ select
        bid0_.bid_id as bid1_1_,
        bid0_.bid_amt as bid2_1_,
        bid0_.bid_item as bid4_1_,
        bid0_.person as person1_ 
    from
        Bid bid0_

Question: Although I marked person attribute as lazy && optional, why is it part of SQL query? Does this mean that Hibernate is not fetching lazily? Same is the case with Item.

How do I fetch attributes lazily?


To make the person attribute (as opposed to association) truly lazy, you must bytecode instrument your classes at build time. The reference documentation has some information on how to do it.

http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html_single/#performance-fetching-lazyproperties


Person is a single (string) property

Fetching it while other fetching (for the non-lazy fetches like bidId and bidAmount) is done on the same object is common sense

As the query has to be executed anyway and transporting a varchar (or whatever) along with the bidId and bidAmount is not much overhead

And it loads in the item id (not the item itself) so that the item itself can be loaded when you call getItem() without another query to get the id (caching the id in between the construction and getItem() call)


It seems that hibernate is loading just foreign key values, not the whole Person or Item. What's wrong with it?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜