jueves, 26 de mayo de 2022

MapStruct walking to map between java beans 3

 


MapStruct walking to map between java beans 3

https://github.com/jalbertomr/mapStructDemo

Company has a natural collection of Employee, the CompanyMapper uses EmployeeMapper


CompanyMapper


@Mapper(uses=EmployeeMapper.class)
public interface CompanyMapper {
CompanyDto companyToDto(Company company);
}

The Code autogenerated for CompanyMapper


@Generated(
value = "org.mapstruct.ap.MappingProcessor",
date = "2022-05-26T19:07:18-0500",
comments = "version: 1.4.2.Final, compiler: javac, environment: Java 11.0.8 (Oracle Corporation)"
)
public class CompanyMapperImpl implements CompanyMapper {

private final EmployeeMapper employeeMapper = Mappers.getMapper( EmployeeMapper.class );

@Override
public CompanyDto companyToDto(Company company) {
if ( company == null ) {
return null;
}

CompanyDto companyDto = new CompanyDto();

companyDto.setEmployees( employeeMapper.employeesListToDto( company.getEmployees() ) );

return companyDto;
}
}

CompanyMapper with a specific CollectionStrategy 

@Mapper(uses= EmployeeMapper.class, collectionMappingStrategy= CollectionMappingStrategy.ADDER_PREFERRED)
public interface CompanyMapperAdderPreferred {
CompanyDto companyToDto(Company company);
}

The Code autogenerated for CompanyMapper with CollectionStrategy


@Generated(
value = "org.mapstruct.ap.MappingProcessor",
date = "2022-05-26T19:07:18-0500",
comments = "version: 1.4.2.Final, compiler: javac, environment: Java 11.0.8 (Oracle Corporation)"
)
public class CompanyMapperAdderPreferredImpl implements CompanyMapperAdderPreferred {

private final EmployeeMapper employeeMapper = Mappers.getMapper( EmployeeMapper.class );

@Override
public CompanyDto companyToDto(Company company) {
if ( company == null ) {
return null;
}

CompanyDto companyDto = new CompanyDto();

if ( company.getEmployees() != null ) {
for ( Employee employee : company.getEmployees() ) {
companyDto.addEmployee( employeeMapper.employeeToDto( employee ) );
}
}

return companyDto;
}
}
@Tests

@Slf4j
class CompanyMapperTest {
private CompanyMapper companyMapper = Mappers.getMapper(CompanyMapper.class);

@Test
void companyToDtoTest() throws ParseException {
//given
Division division = new Division(1, "North");
Date startDate = new SimpleDateFormat("YYYY-mm-dd HH:mm:ss").parse("2022-06-01 09:00:05");
Employee employee = new Employee(33L, "Jose Alberto", "Martinez", division, startDate);
Company company = new Company();
company.addEmployee(employee);
//when
CompanyDto companyDto = companyMapper.companyToDto(company);
log.info("company: {}", company);
log.info("companyDto: {}", companyDto);
//Then
Assertions.assertEquals(company.getEmployees().get(0).getDivision().getName(),companyDto.getEmployees().get(0).getDivisionDto().getName()
);
//...
}
}


eot

No hay comentarios:

Publicar un comentario