[英]Hibernate OneToMany FetchType.LAZY is not working unless accessing the collection?
我使用spring 4.1.4.RELEASE + hibernate 4.3.6.Final,這是我的實體代碼:
public class BaseEntity implements Serializable {
}
public class MarketInfo extends BaseEntity {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private int id;
@Column(name = "market_id", unique = true, length = 15)
private String marketId;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "market")
private List<MarketChannelGroup> channelGroups;
public List<MarketChannelGroup> getChannelGroups() {
return channelGroups;
}
public void setChannelGroups(List<MarketChannelGroup> channelGroups) {
this.channelGroups = channelGroups;
}
...
}
public class MarketChannelGroup extends BaseEntity {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private int id;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "market_id", referencedColumnName = "market_id")
private MarketInfo market;
...
}
我有一個MarketInfo,我希望當我調用它的getChannelGroups()方法時,它會返回List,但是我可以看到在這種情況下沒有觸發HQL查詢,似乎我們必須訪問該List中的一些項來觸發HQL查詢,否則,MarketInfo的channelGroups為空。
情況1:
System.out.println(market.getChannelGroups()); // this is working, market's channelGroups is not empty. HQL query is triggered.
// here market's channelGroups is not empty
案例2:
market.getChannelGroups(); // this is not working, market's channelGroups is still empty.HQL query is not triggered.
// here market's channelGroups is empty
案例3:
market.getIndexes().get(0).getDate(); // this is working, market's channelGroups is not empty. HQL query is triggered.
// here market's channelGroups is not empty
誰能幫忙解釋一下?
market.getChannelGroups(); //這不起作用,市場的channelGroups仍然是空的。
發生這種情況的原因可能是market.getChannelGroups()
調用由於延遲加載而返回代理 。 當您在返回的對象上調用方法時會發生實際加載,在這種情況下,該方法是通道組集合。 因此,要觸發將實體加載到集合中,您必須調用以下內容,例如:
market.getChannelGroups().size();
現在為什么以下呼叫有效?
System.out.println(market.getChannelGroups());
如果您了解System.out.println()
是如何工作的原因將是明確的,即它在傳入的對象上調用toString()
方法,在這種情況下等效於以下內容:
System.out.println(market.getChannelGroups().toString());
這是println(Object)
方法的JavaDoc:
打印一個對象,然后終止該行。 此方法首先調用String.valueOf(x)來獲取打印對象的字符串值,然后表現為調用print(String)然后調用println()。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.