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;
}
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)
join
to query the addresses
and Mapstruct will do the rest.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.
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.
Throughput. In throughput mode, MapStruct was the fastest of the tested frameworks, with JMapper a close second.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With