If you've used JPA you've probably run into the classic
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: class, could not initialize proxy - no Session
I'm using ModelMapper to map my hibernate objects into DTOs and, of course, I'm running into this issue. I originally, up to this point, had everything set to EAGER but I have quickly learned that that is NOT the solution as everything is now EXTREMELY slow to load. So, now I'm back to setting things to LAZY
.
So my question is: is there a way to customize the ModelMapper
so that it can check if the field is lazy before mapping / and if it's lazy, don't map it?
I've been doing some research into custom mappings here http://modelmapper.org/user-manual/property-mapping/
but i can't seem to find a way to throw in some logic.
I found a solution here but this is for Dozer
EDIT:
I am using Spring Boot JPA. Here is some of my code:
@Data
@Entity
@Table(name = "vm_request")
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
public class VirtualMachineRequest {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
// removed other properties
@OneToMany(mappedBy = "request", cascade = CascadeType.ALL, orphanRemoval = true)
@ToString.Exclude
@EqualsAndHashCode.Exclude
private Set<VirtualMachine> virtualMachines;
}
I am mapping this object to a DTO:
@Data
public class VirtualMachineRequestDTO {
private Long id;
// removed other properties
private Set<VirtualMachineDTO> virtualMachines;
}
using ModelMapper
as such:
public VirtualMachineRequestDTO convertToDTO(VirtualMachineRequest request) {
VirtualMachineRequestDTO requestDTO = mapper.map(request, VirtualMachineRequestDTO.class);
return requestDTO;
}
My problem is that since the virtualMachines
set is Lazy
by default (and this is intended for certain situations), ModelMapper
encounters the exception LazyInitializationException
I'm trying to find a way to have ModelMapper
ignore the field if it's lazy and hasn't been initialized.