I'm working on a project that aims to solve common JPA problems when mapping entities to DTOs using ModelMapper. This issue has already been solved on the project. Project link: JPA Model Mapper
"Its crucial for performance to declare entities as lazy load so we
don't need to fetch all related entities every time we need some data.
But this technique leads to some issues. The most common one is the
LazyInitializationException that can be pretty annoying sometimes.
Most of the time we would just want a null object for a not loaded
entity instead of an object that throws an exception if accessed..."
Source: JPA Model Mapper
Therefore, in the project we deal with LazyInitializationException by setting null for all not loaded entities. The examples below show how it works.
Remapping an entity setting null for all not loaded entities:
TypedQuery<SystemEntity> query =
em.createQuery("select s from SystemEntity s where s.id = 1", SystemEntity.class);
SystemEntity system = query.getSingleResult();
return new JpaModelMapper(em).mapEntity(system, SystemEntity.class);
Remapping an entity to a DTO setting null for all not loaded entities:
TypedQuery<SystemEntity> query =
em.createQuery("select s from SystemEntity s where s.id = 1", SystemEntity.class);
SystemEntity system = query.getSingleResult();
return new JpaModelMapper(em).mapEntity(system, SystemDTO.class);
For more informations please see JPA Model Mapper