2
votes

I have the object like this:

class User {

 private String firstName;

 private String secondName;

 private int age;

 ....
 get/set methods

}

And another object has User as a property:

class UserHolder {

 private User user;

 ....
 get/set methods

}

I want to convert UserHolder to User use MapStruct.

When I write this mapper I've something like this:

@Mapper(componentModel = "spring")
public interface UserHolderMapper {

 @Mapping(source = "user.firstName", target = "firstName")
 @Mapping(source = "user.secondName", target = "secondName")
 @Mapping(source = "user.age", target = "age")
 User toUser(UserHolder source);

}

But it contains a lot of boilerplate code (in @Mapping annotation), how I can say to mapper that I want to map source.user to this target without specifying fields of target?

2

2 Answers

2
votes

This is currently not possible. There is already a feature request #1406 which is quite similar to what you need.

In any case as a workaround your mapper can look like:

@Mapper(componentModel = "spring")
public interface UserHolderMapper {

    default User toUser(UserHolder source) {
        return source == null ? null : toUser(source.getUser());
    }

    User toUser(UserDto source);
}

I don't know what the object in UserHolder is. UserDto is just a presumption, it can be any object.

In case you don't want to expose User toUser(UserDto source) then you can create an abstract mapper and make that method protected and abstract there. MapStruct will be able to handle it

0
votes

I may be late to the party. However following should work fine.

@Mapper(componentModel = "spring")
public interface UserHolderMapper {

 @Mapping(source = "source.user", target = ".")
 User toUser(UserHolder source);

}