Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to manage Lazy Loading in Mapstruct?

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.
like image 893
Dorin Brage Avatar asked Mar 15 '16 15:03

Dorin Brage


People also ask

How does JPA lazy loading work?

Lazy loading in Hibernate and JPA means fetching and loading the data, only when it is needed, from a persistent storage like a database. Lazy loading improves the performance of data fetching and significantly reduces the memory footprint.

How is lazy loading implemented in hibernate?

To enable lazy loading explicitly you must use “fetch = FetchType. LAZY” on an association that you want to lazy load when you are using hibernate annotations. @OneToMany( mappedBy = "category", fetch = FetchType.

Is MapStruct slow?

Throughput. In throughput mode, MapStruct was the fastest of the tested frameworks, with JMapper a close second.

Is lazy loading default in hibernate?

1. Working with lazy associations. By default, Hibernate uses lazy select fetching for collections and lazy proxy fetching for single-valued associations. These defaults make sense for most associations in the majority of applications.


Video Answer


1 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.

like image 178
Mehmet Bektaş Avatar answered Oct 23 '22 17:10

Mehmet Bektaş