Hibernate fetching in criteria ignored

大城市里の小女人 提交于 2019-12-01 09:40:47

问题


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;
   ....
 }

Here is the LoginSession class:

@Entity(name="T_LoginSession")
public class LoginSession extends BasicDTO
{

    @ManyToOne
    @JoinColumn(name="userId")  
    protected User user;
    ...

And I have this Criteria:

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);

The problem is that the fetching is always Lazy. How can I make it to be Eager (via criteria and not via attribute annotation)?

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).

Are the names of the fields (the first parameter of the setFetchMode method) correct?

Question: Is this bug related to my issue?


回答1:


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




回答2:


Try:

 Criteria crt = session.createCriteria(User.class);
 crt.setFetchMode("sessions", FetchMode.JOIN);



回答3:


Try following

Criteria crit = session.createCriteria(User.class);
crit.setFetchMode("session.userId", FetchMode.EAGER);
User myThingy = (User)crit.uniqueResult();



回答4:


Try setting the jointype on the alias:

Criteria crit = session.createCriteria(User.class);
crit.createAlias("userLoginSession", "session", Criteria.INNER_JOIN);
crit.add(Restrictions.eq("session.token", sessionToken));
crit.setMaxResults(1);
crit.setFirstResult(0);
crit.setFetchSize(1);


来源:https://stackoverflow.com/questions/25841292/hibernate-fetching-in-criteria-ignored

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!