How to manage Lazy Loading in Mapstruct?

Viewed 8967

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;
}
  1. 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)
  1. Fetching relationships: This is the way. Add a join to query the addresses and Mapstruct will do the rest.
2 Answers

You can use ignore option.

 @Mapping(source = "user.id", target = "userId", ignore = true)

But in this way you can't map the relational fields like eager fetch type.

Related