hibernategrailsgrails-orm

Grails GORM: could not initialize proxy - no Session


I have a method with the following structure:

public void run(){
    ... 
    for (...) { //this part works correct

        User.withTransaction {
            User user = User.findByUsername(...);

            Position pos = Position.findByName(...)
            if(pos){ ...
            } else { ...
                try{
                    pos.save(flush:true);
                    user.position = pos;
                } catch (Exception e){ ... }
            }
            ...
            try{
                user.save(flush:true, failOnError: true);
            } catch (Exception e){ ... }
        }
    }
    //this part doesn't work
    User.findAll().each {
    ...
        if (...){
            User.withTransaction{
                ...
                //here the operation fails with 
                //org.hibernate.LazyInitializationException: 
                //could not initialize proxy - no Session
                if (!userDetailsMap.containsKey(it.username) 
                         && it.userStatus != blocked){
                    it.userStatus = blocked
                    it.save(flush:true) 
                }
            }
        }
    }
}

The exception I'm getting here is org.hibernate.LazyInitializationException: could not initialize proxy - no Session in the second part of my code. Here the userStatus field is a reference to a different domain class.

I tried to add it.refresh() and Hibernate.initialize(it)to the code before properties are checked, but no use. What am I doing wrong here?

upd: I tried to call the it.attach method before the properties are checked, but right after the method call the value of it.attached is false.


Solution

  • I don't think you are doing anything 'wrong', it is just that the object got detached from the hibernate session. A couple of things I'd try: