忽略了标准中的Hibernate提取 [英] Hibernate fetching in criteria ignored
问题描述
我有一些类User与LoginSession类有一对多关系(我的User类中有一个LoginSessions集合)。
I have some class User which has one to many relation to LoginSession class (I have a collection of LoginSessions in my User class).
@Entity(name="T_User")
public class User()
{
....
@OneToMany(fetch=FetchType.LAZY, mappedBy="user", cascade=CascadeType.ALL)
@Fetch(FetchMode.SELECT)
@JsonIgnore
private Set<LoginSession> userLoginSession;
....
}
这是LoginSession类:
Here is the LoginSession class:
@Entity(name="T_LoginSession")
public class LoginSession extends BasicDTO
{
@ManyToOne
@JoinColumn(name="userId")
protected User user;
...
我有这个标准:
Criteria crit = session.createCriteria(User.class);
crit.setFetchMode("loginSession", FetchMode.JOIN);
crit.createAlias("userLoginSession", "session");
crit.add(Restrictions.eq("session.token", sessionToken));
crit.setMaxResults(1);
crit.setFirstResult(0);
crit.setFetchSize(1);
问题是提取始终是Lazy。我怎样才能让它成为渴望(通过标准,而不是通过属性注释)?
The problem is that the fetching is always Lazy. How can I make it to be Eager (via criteria and not via attribute annotation)?
注意:
如果我在私有Set< LoginSession>上面添加
在注释中设置的响应提取(我不会按标准 @Fetch
注释userLoginSession setFetchMode
进行自定义。)
Note:
If I am adding @Fetch
annotation above the private Set<LoginSession> userLoginSession
the response fetching as set in the annotation (I wont it to be customised by the criteria setFetchMode
).
字段的名称( setFetchMode
方法的第一个参数)是否正确?
Are the names of the fields (the first parameter of the setFetchMode
method) correct?
问题:
是这个与我的问题有关的错误?
推荐答案
如上所述此处您无法同时过滤和急切获取集合。您可以使用相关子查询来解决它:
as noted here you can not filter and eager fetch a collection at the same time. you can solve it with a correlated subquery:
DetachedCriteria subquery = DetachedCriteria.For(User.class)
.createAlias("userLoginSession", "session")
.add(Restrictions.eq("session.token", sessionToken))
.setFirstResult(0)
.setMaxResults(1) // assuming token is unique otherwise this won't restrict users but loginsessions
.setProjection(Projections.id());
Criteria crit = session.createCriteria(User.class)
.add(Subqueries.propertyIn("id", subquery)
.setFetchMode("userLoginSession", FetchMode.JOIN);
注意:这是我头脑中的文本编辑器代码。方法名称可能会有所不同
Note: this is text editor code of the top of my head. Methodnames may vary
这篇关于忽略了标准中的Hibernate提取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!