ModelMapperが便利

エキサイト株式会社 メディア開発 佐々木です。

SpringBootで開発をしているのですが、データの詰め替えとか割と頻繁にあり、データのマッピング処理が面倒になってきます。そこで、 ModelMapper というライブラリが便利です。(ただしパフォーマンス的には良くないので、パフォーマンスに問題がある場合は、MapStruct等を使ったほうがいいです)

Gradleの設定

Gradleの依存関係を定義します。

dependencies {
     ....
     implementation 'org.modelmapper:modelmapper:2.1.1'
     ....
}

Beanの定義

Beanの定義をします。

`ModelMapperConfig.class`

@Configuration
public class ModelMapperConfig {
    @Bean
    public ModelMapper modelMapper(){
        return new ModelMapper();
    }
}

下記の2つのデータ型をマッピングしたいとします。

`Form.class`
@Data
class Form {
  @NotNull
  private Long id;
  @NotEmpty
  private String name;
}

※ Formクラスは、通常バリデーションの為、バリデーション用アノテーションがついています
`Data.class`

@Data
class Entity {
  private Long id;
  private String name;
}

この2つをマッピングするときに、下記のように実装すると簡単にマッピングできます。

@RestController
@RequestMapping
@RequiredArgsConstructor
public class DemoController {

    private final ModelMapper modelMapper;

    @GetMapping
    public Entity index(Form form) {
        Entity entity = modelMapper.map(form, Entity.class);
        return entity;
    }
}

プロパティ名が同じであることはマッピングの大事な要素ですが、簡単にマッピングすることが可能です。 パフォーマンスはそんなによくないので、バッチ処理等をするときは、MapStruct等を使うことをオススメします。