I am dealing with a problem related with lazy loaded objects from the database.
Let's say that we have the below entity.
@Entity(name = "User")
@Table(name = "USERS")
public class User{
@Id
@GeneratedValue
private int id
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name="NOTES_ID")
private List<Note> notes;
}
And the Dto would be
@Mapper
public interface UserDtoMapper{
/** the INSTACE HERE **/
User fromDto(UserDto dto);
UserDto toDto(User user);
}
So which could be the best approach for fetching all the users without to have a EJBException because I'm fetching them laziness?
Edit: Solution
Let's say you have the following data model
public class User{
private String name;
//... other fields
@OneToMany
private Set<Address> addresses;
}
- Querying without addresses, exception: When mapping from Model to DTO it will try to map
addresses
but because is lazy loaded (via hibernate, or any other framework) will end up in exception.
Additionally you can ignore the addresses
from being mapped, as @Mehmet Bektaş . But is not needed to define the source
, it's optional.
@Mapping(target = "addresses", ignore = true)
- Fetching relationships: This is the way. Add a
join
to query theaddresses
and Mapstruct will do the rest.