Lazy loading not working in JPA with hibernate

后端 未结 1 838
醉话见心
醉话见心 2021-01-22 01:16

I am using JPA with hibernate in my spring boot application. Whenever I try to fetch the enities using jpa methods, its returning the entity plus all the association present ins

相关标签:
1条回答
  • 2021-01-22 01:44

    Was tricky to investigate but I had this issue as I was using mapstruct and it happens to do deep/ nested mapping and in the process, it calls getter of the lazy loaded property. The issue was resolved when I used mapstrct @BeforeMapping.

    @Mapper
    public interface HibernateAwareMapper {
        @BeforeMapping
        default <T> Set<T> fixLazyLoadingSet(Collection<?> c, @TargetType Class<?> targetType) {
            if (!Util.wasInitialized(c)) {
                return Collections.emptySet();
            }
            return null;
        }
    
        @BeforeMapping
        default <T> List<T> fixLazyLoadingList(Collection<?> c, @TargetType Class<?> targetType) {
            if (!Util.wasInitialized(c)) {
                return Collections.emptyList();
            }
            return null;
        }
    
       class Util {
           static boolean wasInitialized(Object c) {
               if (!(c instanceof PersistentCollection)) {
                   return true;
               }
    
               PersistentCollection pc = (PersistentCollection) c;
               return pc.wasInitialized();
           }
       }
    }
    

    Ref. by kokorin

    0 讨论(0)
提交回复
热议问题