Issue
I have this object:
Entity
@Entity
public class someClass{
private String name;
private String labelKey;
@ManyToMany(cascade = {CascadeType.PERSIST,CascadeType.MERGE}, fetch = FetchType.LAZY)
private Set<Product> products = new HashSet<>();
}
DTO
public class someClass{
private String name;
private String labelKey;
private Set<Product> products = new HashSet<>();
}
My problem is that when I get this object but products are lazy initialized, when I mapp entity to DTO using Dozer, I get a LaziInitializedException, then i want to get that when I get products lazy initialized, this products will return a empry Set. Is this possible?
Thanks for your time and sorry for my english, it's not my native language.
Solution
As you can see in this tutorial here you can instruct dozer
to exclude some field from the mapping.
If you do so, then the dozer will not invoke the method of getProducts
of your entity class and therefore the exception LaziInitializedException
will not be thrown.
At the same time because your DTO object is initialized with an empty HashSet
for the field products, this is what will remain at the end in the DTO.
So your requirement will work, where your entity is lazily initialized for products and your DTO returns an empty list while at the same time the mapping happens from dozer
.
Here is the configuration that you need for the mapper of dozer
.
BeanMappingBuilder mappingExclusion = new BeanMappingBuilder() {
@Override
protected void configure() {
mapping(SomeClassEntity.class, SomeClassDto.class).exclude("products");
}
};
mapper = new DozerBeanMapper();
mapper.addMapping(mappingExclusion);
Then you can use it to do the mapping as following
mapper.map(someClassEntityInstance, someClassDtoInstance);
Answered By - Panagiotis Bougioukos
Answer Checked By - Marie Seifert (JavaFixing Admin)