weblog@kentama

技術的なメモ置き場。主にJava。

【MapStruct】他のMapperを使用する

独自にマッピングロジックを指定したいときに、独自のMapperを用意して使うことができる。

環境

  • MapStruct : 1.2.0.Final
  • Java : 9
  • JUnit : 4.12
  • AssertJ : 3.9.1

LocalDate <-> String 変換を行うMapper

public class DateMapper {

    public String asString(LocalDate date) {
        return date != null ? date.format(DateTimeFormatter.ISO_DATE) : null;
    }

    public LocalDate asDate(String date) throws ParseException {
        return date != null ? LocalDate.parse(date, DateTimeFormatter.ISO_DATE) : null;
    }
}

Mapper

@Mapper のuses属性に上記で作成したクラスを指定する。

@Mapper(uses = DateMapper.class)
public interface PersonMapper {
    PersonMapper MAPPER = Mappers.getMapper(PersonMapper.class);

    Person toPerson(PersonEntity entity);

    PersonEntity toPersonEnity(Person dto);
}

生成されたMapper

/*
@Generated(
    value = "org.mapstruct.ap.MappingProcessor",
    date = "2018-03-10T23:10:12+0900",
    comments = "version: 1.2.0.Final, compiler: javac, environment: Java 9.0.1 (Oracle Corporation)"
)
*/
public class PersonMapperImpl implements PersonMapper {

    private final DateMapper dateMapper = new DateMapper();

    @Override
    public Person toPerson(PersonEntity entity) {
        if ( entity == null ) {
            return null;
        }

        Person person = new Person();

        person.setName( entity.getName() );
        person.setBirthday( dateMapper.asString( entity.getBirthday() ) );

        return person;
    }

    @Override
    public PersonEntity toPersonEnity(Person dto) {
        if ( dto == null ) {
            return null;
        }

        PersonEntity personEntity = new PersonEntity();

        personEntity.setName( dto.getName() );
        try {
            personEntity.setBirthday( dateMapper.asDate( dto.getBirthday() ) );
        }
        catch ( ParseException e ) {
            throw new RuntimeException( e );
        }

        return personEntity;
    }
}

テストコード

@Test
public void test1() {
    PersonEntity entity = new PersonEntity("マイケル", LocalDate.of(1963, 2, 17));

    Person person = PersonMapper.MAPPER.toPerson(entity);

    assertThat(person.getName()).isEqualTo("マイケル");
    assertThat(person.getBirthday()).isEqualTo("1963-02-17");
}

@Test
public void test2() {
    Person person = new Person("マイケル", "1963-02-17");

    PersonEntity entity = PersonMapper.MAPPER.toPersonEnity(person);

    assertThat(entity.getName()).isEqualTo("マイケル");
    assertThat(entity.getBirthday()).isEqualTo(LocalDate.of(1963, 2, 17));
}