![](/img/trans.png)
[英]Hibernate with Kotlin: @ManyToOne(fetch = FetchType.LAZY)
[英]Hibernate ManyToOne with FetchType.LAZY not fetching lazy
我正在使用Hibernate和spring。
我有這樣的模型類。
@Entity
@Table(name = "forumtopic")
public final class Forumtopic extends AbstractUserTracking implements
java.io.Serializable {
/**SNIP **/
private Forumcategory forumcategory;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "FkForumcategoryId", nullable = false)
public Forumcategory getForumcategory() {
return this.forumcategory;
}
public void setForumcategory(final Forumcategory forumcategory) {
this.forumcategory = forumcategory;
}
}
它一般工作,但類不是懶惰加載,但在加載ForumEntry后急切。
Hibernate:
select
forumtopic0_.PkId as PkId19_0_,
forumtopic0_.CreateDate as CreateDate19_0_,
forumtopic0_.FkCreateUserId as FkCreate3_19_0_,
forumtopic0_.FkLastUserId as FkLastUs4_19_0_,
forumtopic0_.LastChange as LastChange19_0_,
forumtopic0_.FkForumcategoryId as FkForum10_19_0_,
forumtopic0_.PublishCategory as PublishC6_19_0_,
forumtopic0_.State as State19_0_,
forumtopic0_.Text as Text19_0_,
forumtopic0_.Topic as Topic19_0_,
forumtopic0_.FkTpUserId as FkTpUserId19_0_
from
forumtopic forumtopic0_
where
forumtopic0_.PkId=?
Hibernate:
select
forumcateg0_.PkId as PkId17_0_,
forumcateg0_.CreateDate as CreateDate17_0_,
forumcateg0_.Name as Name17_0_,
forumcateg0_.FkRequestId as FkReques4_17_0_,
forumcateg0_.FkTpUserId as FkTpUserId17_0_
from
forumcategory forumcateg0_
where
forumcateg0_.PkId=?
在沒有調用getter的情況下,在ForumTopic之后加載了ForumCategory。
這個問題出現在我的所有@ ManyToOne關聯中。 但是@OneToMany關聯是懶洋洋地加載的。
我正在使用maven2進行構建。 這些是我的依賴。
<dependency> <groupId>org.springframework</groupId> <artifactId>spring</artifactId> <version>2.5.6</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>3.3.1.GA</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>ejb3-persistence</artifactId> <version>1.0.2.GA</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-annotations</artifactId> <type>jar</type> <version>3.4.0.GA</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-entitymanager</artifactId> <type>jar</type> <version>3.4.0.GA</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-search</artifactId> <version>3.1.0.GA</version> </dependency>
有人可以幫我理解發生了什么嗎?
我想這是因為你的類被聲明為final
,因此Hibernate不能為它們生成惰性代理。 嘗試從類聲明中刪除final
。
返回ForumTopic后看起來事務/會話已關閉。 因此它變成了分離的實體。 當您嘗試執行getForumCategory時,沒有會話來執行該操作。 你可以在同一個會話中預取ForumCategory,比如
在你的getForumTopic中,在返回一個列表之前(假設你有一個getAllForumTopic)
public List<ForumTopic> getAllForumTopic() {
<snip>
List<ForumTopic> topics = <SNIP: get the list of ForumTopic>
for(ForumTopic topic: topics)
topic.getForumCategory()
return topics;
}
這將在同一會話中獲取ForumCategory。 否則,您必須在getAllForumTopic的調用函數中創建一個事務,並在需要調用getForumCategory時使用相同的事務。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.