0
votes

I use Mapstruct in my project. In one of the entities I have the set [oneToMany] structure. When I retrieve all data using findAll () in the repository, if there are no bindings, then an empty HashSet is returned.

Mapstuct maps entities on the DTO and when it encounters an empty Set it gives the NullPointException exception. In the created mapper there is a condition that if HashSet is null then return nulla, but here is an empty collection. How to map entities on the DTO so that in the case of an empty collection it returns nulla?

Simply code:

Entity:

public class Employee{

....
private Set workplaces;
...
}

Mapstruct:

@Mapper(componentModel = "spring")
public interface EmployeeMapper{
EmployeeDTO toDTOFromEntity(Employee employee);
}
1

1 Answers

0
votes

I must miss something but mapstruct generate a code like this:

if ( set != null ) {
    employeeDTO.setWorkplaces( new HashSet( set ) );
} else {
    employeeDTO.setWorkplaces( null );
}

So a new Hashset of an empty set won't cause a nullpointer ?