Lazy Initialization Exception in model mapper

Viewed 5362

Modelmapper is giving LazyInitializationException while converting from entity to dto.

Is there any way i can disable this. If am calling modelmapper.map inside transaction block it is working fine but it is loading all my lazy objects which i dont want at all. I want if lazy then do not load it at all.

Converter org.modelmapper.internal.converter.MergingCollectionConverter@6a51c12e failed to convert org.hibernate.collection.internal.PersistentSet to java.util.Set.

Caused by: org.modelmapper.MappingException: ModelMapper mapping errors:

1) Failed to get value from com.app.flashdiary.entity.Vendor.getApproved()

Caused by: org.hibernate.LazyInitializationException: could not initialize proxy [com.app.flashdiary.entity.Vendor#1] - no Session at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:169)

3 Answers

I found the solution from here:

https://github.com/modelmapper/modelmapper/issues/97

modelMapper.getConfiguration().setPropertyCondition(new Condition<Object, Object>() {
      public boolean applies(MappingContext<Object, Object> context) {
        return !(context.getSource() instanceof PersistentCollection);
      }
    });

I improved the @smile response, with his solution no PersistentCollection will be ever mapped. Instead with this solution the object that haven't LazyInitializationException will be mapped correctly:

    modelMapper.getConfiguration().setPropertyCondition(new Condition<Object, Object>() {
        public boolean applies(MappingContext<Object, Object> context) {
            //if the object is a PersistentCollection could be not initialized 
            //in case of lazy strategy, in this case the object will not be mapped:
            return (!(context.getSource() instanceof PersistentCollection) 
            || ((PersistentCollection)context.getSource()).wasInitialized());
        }
    });

JAVA_8

modelMapper.getConfiguration()
           .setPropertyCondition(context -> 
                 !(context.getSource() instanceof PersistentCollection)
            )
Related