0

I'm getting an Exception^ Exception occurred in target VM: failed to lazily initialize a collection, no session or session was closed org.hibernate.LazyInitializationException: failed to lazily initialize a collection, no session or session was closed

I do not understand why I have problems. I do not use lazy loading. This is my Role.hbm.xml:

<hibernate-mapping>
    <class name="ru.itlect.bzdur.security.Role" table="Roles" >
        <meta attribute="class-description">
        </meta>
        <id column="id" name="id" type="int">
            <generator class="native"/>
        </id>
        <property column="displayName" name="displayName" not-null="true" type="string"/>
        <property column="removed" name="removed" not-null="true" type="boolean"/>
        <property column="hidden" name="hidden" not-null="true" type="boolean"/>
        <property column="system" name="system" not-null="true" type="boolean"/>
        <set name="permitionParams" table="Permitions" inverse="true" lazy="false" fetch="select" cascade="all" >
            <key>
                <column name="RoleID" not-null="true" />
            </key>
            <one-to-many class="ru.itlect.bzdur.security.PermitionParam" />
        </set>
    </class>
</hibernate-mapping>

The more strange the place where I loose Hibernate Session. Role.java:

public class Role {

    private int id;

    private Set<PermitionParam> permitionParams;
    private final Map<String, PermitionParam> permitionMap = new HashMap<>();

...
    public void setPermitionParams(Set<PermitionParam> permitionParams) {
        permitionMap.clear();

        if(permitionParams == null){
            this.permitionParams = new HashSet<>();
            return;
        }

        this.permitionParams = permitionParams;
        for(PermitionParam param : permitionParams){
            permitionMap.put(param.getPermition().getName(), param);
        }
    }
...
}

The Exception is thrown on the line: for(PermitionParam param : permitionParams){, whene I call save() methode of the CrudRepository. Hibernate creates the new copy of the Role object and calls its setters. I do not understand how I can loose the Session in that moment.

Please help me.

1 Answers1

0

The fix is you need to initialize the lazy objects with in the transaction before passing to service layer. look here more here or here

Community
  • 1
  • 1
Prabhakaran Ramaswamy
  • 23,910
  • 10
  • 51
  • 62