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)
The right way to fix a LazyInitializationException is to fetch all required associations within your service layer. The best option for that is to load the entity with all required associations in one query.
Lazy Loading means that the object won't be loaded to the Session context until it is accessed in code. Hibernate creates a dynamic Proxy Object subclass that will hit the database only when we first use the object.
Hibernate now can "lazy-load" the children, which means that it does not actually load all the children when loading the parent. Instead, it loads them when requested to do so. You can either request this explicitly or, and this is far more common, hibernate will load them automatically when you try to access a child.
In computer programming, lazy initialization is the tactic of delaying the creation of an object, the calculation of a value, or some other expensive process until the first time it is needed. It is a kind of lazy evaluation that refers specifically to the instantiation of objects or other resources.
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());
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With