我已經Sessions
和Users
類具有以下bi-directional
OneToMany
映射(與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個會話,因此最後一行很慢。
如何在不取得整個會話集合的情況下將會話與用戶關聯起來?
如何加載'user'實體? –
你真的需要收集成爲一個集合嗎?當你添加一個元素時,休眠需要加載元素來檢查是否重複 – Guillaume
@Guillaume Set是Hibernate強制要求的維護唯一性的數據結構 – sanbhat