2

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());
    }

2 Answers 2

7

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();
    }

}
Sign up to request clarification or add additional context in comments.

Comments

2
@Mapper
public abstract class EmployeeMapper {

    @Mapping
    public abstract Employee toEmployee(EmployeeDTO dto);

    @AfterMapping
    void mapCustomId(Employee source, @MappingTarget EmployeeDTO dto) {
        dto.setCustomId(EmployeeFormatter.simulationIdGenerator())
    }
}

1 Comment

Great ! Thanks for the response but based on your response it can be done in a simple way. Check my post edit ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.