LoginSignup
6

More than 1 year has passed since last update.

EntityをDTOに変換する方法【Java】【Spring Boot】

Last updated at Posted at 2022-04-20

実装メモです。参考になれば幸いです。

EntityをDTOに変換

DTOクラス

DTOクラス内にofメソッドを定義。

DTO.java
public static DTO of(Entity entity) {
  DTO dto = new DTO();
  dto.setId(entity.getId());
  dto.setTitle(entity.getTitle());
  dto.setDescription(entity.getDescription());
  dto.setCreateTime(entity.getCreateTime());
  dto.setUpdateTime(entity.getUpdateTime());
  return dto;
}

Serviceクラス

あとはofメソッドの引数にEntityをセットすれば、DTOに変換できます。
※私はServiceクラスでDTO変換の処理をしていますが、Controllerクラスで実装していただいても構いません。(どこで処理するかは設計思想によるってやつですね)

aaaService.java
return DTO.of(aaaRepository.save(entity)); 

List<Entity>をList<DTO>に変換

Serviceクラス

List<Entity>をList<DTO>に変換するメソッドを定義(先程定義したDTOクラスのofメソッドを使い回します)

aaaService.java
public List<DTO> entityToDto(List<Entity> entity) {
    List<DTO> dtoList =
        entity.stream().map(DTO::of).collect(Collectors.toList());
    return dtoList;
  }

あとはentityToDtoメソッドの引数にList<Entity>をセットすれば、List<DTO>に変換できます。

aaaService.java
return entityToDto(aaaRepository.findAll());

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6