模型映射器中的延迟初始化异常

问题描述:

在从实体转换为dto时,Modelmapper提供LazyInitializationException.

Modelmapper is giving LazyInitializationException while converting from entity to dto.

有什么办法可以禁用此功能吗?如果在事务块内调用modelmapper.map,它工作正常,但它正在加载我根本不需要的所有惰性对象. 我要是懒惰就根本不要加载它.

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.

转换器org.modelmapper.internal.converter.MergingCollectionConverter@6a51c12e无法将org.hibernate.collection.internal.PersistentSet转换为java.util.Set.

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

由以下原因引起:org.modelmapper.MappingException:ModelMapper映射错误:

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

1)无法从com.app.flashdiary.entity.Vendor.getApproved()

原因:org.hibernate.LazyInitializationException:无法初始化代理[com.app.flashdiary.entity.Vendor#1]-没有会话 在org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:169)

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)

我从这里找到了解决方案:

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);
      }
    });