Search code examples
javamappingdomain-driven-designmapstruct

How to use Mapstruct with Ad Hoc Setters


I am trying to apply MapStruct to DDD. I created my entities with ad hoc setters like this:

@AllArgsContructor 
@NoArgsConstructor //necessary to MapStruct
@Getter
class Employee { 
    private String id; 
    private String name;
    
    public void updateName(String newName) {
        this.name = newName;
    }
    
}

and I have a EmployeeDto to send data to frontend API:

@Getter
@AlArgsConstructor
@NoArgsConstructor //necessary to MapStruct
class EmployeeDto {
    private String name;
    private String id;
}

so, I am trying to use MapStruct to map, but it is not working because my ad hoc setter. How could I resolve this problem?


Solution

  • You have to implement custom AccessorNamingStrategy. The way how to do it is well documented in section 13.1. Custom Accessor Naming Strategy of a MapStruct documentation.

    In your case it should look something like this:

    public class CustomAccessorNamingStrategy extends DefaultAccessorNamingStrategy {
      @Override
      public boolean isSetterMethod(ExecutableElement method) {
        String methodName = method.getSimpleName().toString();
        return methodName.startsWith("update") && methodName.length() > 6;
      }
    
      @Override
      public String getPropertyName(ExecutableElement getterOrSetterMethod) {
        if (isSetterMethod(getterOrSetterMethod)) {
          String methodName = getterOrSetterMethod.getSimpleName().toString();
          return IntrospectorUtils.decapitalize(methodName.substring(6));
        } else {
          return super.getPropertyName(getterOrSetterMethod);
        }
      }
    }