简体   繁体   中英

failed to lazily initialize a collection of role:

I tried to fetch record with this code

session.beginTransaction();

        /* create criteria */
        Criteria cr = session.createCriteria(User.class);
        /* set pagination */
        cr.setFirstResult((start - 1) * limit);
        cr.setMaxResults(start);

        /* set sort order */
        if(sortField!= null) {
            if(order != null && order.equalsIgnoreCase("asc")) {
                cr.addOrder(Order.asc(sortField));      
            } else if(order != null && order.equalsIgnoreCase("desc")) {
                cr.addOrder(Order.desc(sortField));
            }
        }
        userList = cr.list();
        session.flush();
        session.getTransaction().commit();

but i get following error due to lazy loading.

org.codehaus.jackson.map.JsonMappingException: failed to lazily initialize a collection of role: models.User.accesstokens, could not initialize proxy - no Session (through reference chain: java.util.ArrayList[0]->
at org.codehaus.jackson.map.JsonMappingException.wrapWithPath(JsonMappingException.java:215)
at org.codehaus.jackson.map.JsonMappingException.wrapWithPath(JsonMappingException.java:180)
at org.codehaus.jackson.map.ser.SerializerBase.wrapAndThrow(SerializerBase.java:128)
at org.codehaus.jackson.map.ser.BeanSerializer.serializeFields(BeanSerializer.java:253)
at org.codehaus.jackson.map.ser.BeanSerializer.serialize(BeanSerializer.java:212)

You're getting this error because the serialization occurs outside the persistence context. When a select is performed on the User entity, the query does not retrieve the field (or associated entities) accesstokens. Instead, the field is replaced with a proxy, which will be used to retrieve data from database when the property accesstokens is accessed. If you access the accesstokens property before committing your transaction, you will not have any issue because the session is still active. However, in your case, the session is not active when the User objects are being serialized.

One possible solution would be to load the required data before serialization occurs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM