Search code examples
hibernategwtlazy-loadingrequestfactory

RequestFactory fetch a collection eagerly when it's set to Lazy in Hibernate


In this code I fetch a user by username and password using GWT RequestFactory

  userContextProvider.get().getUser(userName, password).with(extraData).
    fire(new Receiver<User>() {
        @Override
        public void onSuccess (User user) {
        //Do something  
        @Override
        public void onFailure(ServerFailure error) {
          //Error
        }
    });

A user can have one or many groups, so normally, in the extraData I would have

String [] extraData = {groups};

In my DAO I fetch the user like this

   Criteria c = session.createCriteria(User.class);
   c.add(Restrictions.eq("user", username));
   c.add(Restrictions.eq("password", password));            
   utilisateur =  (Utilisateur) c.uniqueResult();

And in the User model, the group collection is set to lazy

@ManyToMany(fetch = FetchType.LAZY, mappedBy = "users")
    public List<Group> getGroups() {
        return this.groups;
    }

But, in Hibernate Log I see two queries, one for the user (that's ok) and the other for the groupe

My question is : Is it normal that with in RequestFactory override the lazy loading of Hibernate ? and how to work around it ?


Solution

  • Think a minute about what's happening.

    You're asking for a user entity with its groups, in one request. So the server prepares the user and groups to send them back to your GWT client app.

    If you want lazy fetching on the client-side, then ask for the user, then when needed ask for its group, as a separate request (with its separate RequestContext instance, Receiver, and call to fire())