@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
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);
}
}
Hibernate生成的SQL是:
/*
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_
问题:虽然我将person
属性标记为 lazy&amp;&amp;可选,为什么它是SQL查询的一部分?这是否意味着Hibernate不是懒散的? Item的情况也是如此。
如何懒惰地获取属性?
答案 0 :(得分:2)
Person
是单个(字符串)属性
在同一个对象上进行其他抓取(对于bidId
和bidAmount
之类的非延迟抓取)获取它是常识
因为无论如何都必须执行查询,并且varchar
和bidId
一起传输bidAmount
(或其他任何内容)并不需要太多开销
它加载项 id (而不是项目本身),以便在您调用getItem()
而无需其他查询来获取ID(缓存id)时可以加载项目本身在构造和getItem()
调用之间)
答案 1 :(得分:2)
要使person属性(而不是关联)真正变得懒惰,您必须在构建时对字符串进行字节编码。参考文档提供了有关如何执行此操作的一些信息。
答案 2 :(得分:1)
似乎hibernate只加载外键值,而不是整个Person或Item。怎么了?