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
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