2013-05-15 48 views
4

我已經SessionsUsers類具有以下bi-directionalOneToMany映射(與Hibernate逆向工程工具生成):Hibernate的一對多雙向關係是慢

public class Users { 
    @OneToMany(fetch=FetchType.LAZY, mappedBy="users") 
    public Set<Sessions> getSessionses() { 
     return this.sessionses; 
    } 
} 

public class Sessions { 
    @ManyToOne(fetch=FetchType.LAZY) 
    @JoinColumn(name="USER_ID") 
    public Users getUsers() { 
     return this.users; 
    } 
} 

這裏是我的代碼,這爲用戶創建新的會話:

Session s = ...; 
Users user = (Users) s.createCriteria(Users.class) 
      ./*restrictions...*/.uniqueResult(); 
Sessions userSession = new Sessions(); 
userSession.setUsers(user); 
s.save(userSession); 
user.getSessionses().add(userSession); // here getSessionses() has 2k records 

用戶有2k個會話,因此最後一行很慢。

如何在不取得整個會話集合的情況下將會話與用戶關聯起來?

+0

如何加載'user'實體? –

+1

你真的需要收集成爲一個集合嗎?當你添加一個元素時,休眠需要加載元素來檢查是否重複 – Guillaume

+0

@Guillaume Set是Hibernate強制要求的維護唯一性的數據結構 – sanbhat

回答

3

看看Hibernate的extra-lazy loading功能。 您可以通過使用@LazyCollection(LazyCollectionOption.EXTRA)註釋您的收藏來啓用該功能。有this example來看看,並有Setthis one中使用。

public class Users { 
    @OneToMany(fetch=FetchType.LAZY, mappedBy="users") 
    @LazyCollection(LazyCollectionOption.EXTRA) 
    public Set<Sessions> getSessionses() { 
     return this.sessionses; 
    } 
} 
+0

太好了,謝謝!它完美的作品。在這種情況下,hibernate只生成單個查詢:'SELECT 1 FROM SESSIONS WHERE USER_ID =?和SESSION_ID =?'。這是唯一的解決方案,它有助於解決問題,而無需將Set 更改爲列表。 –

1

我不能肯定,如果休眠想補充一點連接兩種方式,但不是增加一個SessionUser設置SessionUser。這樣你不必加載每一個會話。

+0

Hibernate [doc](http://docs.jboss.org/hibernate/core/3.3/reference/en/html/tutorial.html#tutorial-associations-usingbidir)說:'「設置鏈接兩側」是絕對必要的雙向鏈接。因此需要在兩側設置鏈接。 –

+0

您是否可以通過任何官方文檔證明鏈接駁回我的評論? –