Reputation: 662
I need to convert a dto
to entity
and the entity
has a field to populate which doesn't needs any field of the dto
. Indeed, the @Mapping
annotation doesn't take any source.
Let's illustrate it with this simple example :
public class Employee {
private String firstName;
private String customId;
}
public class EmployeeDto {
private String firstName;
}
As you can the field customId
of the Employee
entity doesn't exist in the EmployeeDTO
.
Also, I have the following formatter
. Obviously, I created an @CustomIdGenerator
@interface
public class EmployeeFormatter {
@CustomIdGenerator
public static String simulationIdGenerator() {
return // businessLogic
}
}
And finally my mapper looks like this :
@Mapper(uses = EmployeeFormatter.class)
public abstract class EmployeeMapper {
@Mapping(target = "customId", qualifiedBy = customIdGenerator.class)
public abstract Employee toEmployee(EmployeeDTO dto);
}
But in the generated classes it doesn't work. Do you know if there is any way to use a mapper whithout parameter ?
Thanks for your help ;)
EDIT :
Based on the response of @Nikolai Shevchenko the following code works :
@AfterMapping
void setCustomId(@MappingTarget Employee employee) {
employee.setCustomId(EmployeeFormatter.customIdGenerator());
}
Upvotes: 2
Views: 3454
Reputation: 1123
You can try using expression field in the mapping like this(another way of doing this without source param)
@Mapper(uses = EmployeeFormatter.class)
public abstract class EmployeeMapper {
@Mapping(target = "customId", expression = "java(getCustomId())")
public abstract Employee toEmployee(EmployeeDTO dto);
public String getCustomId() {
return EmployeeFormatter.customIdGenerator();
}
}
Upvotes: 7
Reputation: 7521
@Mapper
public abstract class EmployeeMapper {
@Mapping
public abstract Employee toEmployee(EmployeeDTO dto);
@AfterMapping
void mapCustomId(Employee source, @MappingTarget EmployeeDTO dto) {
dto.setCustomId(EmployeeFormatter.simulationIdGenerator())
}
}
Upvotes: 2