0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【SpringBoot】EntityからDtoに詰め替える方法

Last updated at Posted at 2024-10-22

方法1: 手動でのマッピング

エンティティ例: User

@Entity
public class User {
    private Integer id;
    private String name;
    private Integer age;

    // コンストラクタ、ゲッター、セッターなど
}

DTO例: UserDto

public class UserDto {
    private Integer id;
    private String name;

    // コンストラクタ、ゲッター、セッターなど
}

サービス層での手動変換

@Service
public class UserService {

    @Autowired
    private UserRepository userRepository;

    public List<UserDto> getAllUsers() {
        List<User> users = userRepository.findAll();
        return users.stream().map(this::convertToDto).collect(Collectors.toList());
    }

    private UserDto convertToDto(User user) {
        UserDto dto = new UserDto();
        dto.setId(user.getId());
        dto.setName(user.getName());
        return dto;
    }
}
  • メリット: コードがシンプルで理解しやすい。
  • デメリット: エンティティとDTOのフィールドが多い場合、手動での変換が煩雑になる。

方法2: ModelMapperを使用した自動マッピング

ModelMapperは、Javaオブジェクト間のマッピングを自動的に行うためのライブラリです。エンティティとDTOのフィールド名が一致している場合、非常に簡単に変換ができます。

依存関係(Maven)

<dependency>
    <groupId>org.modelmapper</groupId>
    <artifactId>modelmapper</artifactId>
    <version>3.1.0</version> <!-- バージョンは最新のものに合わせてください -->
</dependency>

ModelMapperの設定

ModelMapperをSpringのコンポーネントとして設定します。

import org.modelmapper.ModelMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

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

サービス層での使用例

@Service
public class UserService {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private ModelMapper modelMapper;

    public List<UserDto> getAllUsers() {
        List<User> users = userRepository.findAll();
        return users.stream()
            .map(user -> modelMapper.map(user, UserDto.class))
            .collect(Collectors.toList());
    }
}
  • メリット: コード量を大幅に削減でき、フィールド名が一致している限り、手動でのマッピングが不要です。
  • デメリット: 複雑なマッピングやカスタムロジックが必要な場合には、調整が必要です。

まとめ

エンティティをDTOに変換する最適な方法は、プロジェクトの要件によって異なります。以下にそれぞれの特徴をまとめます。

  1. 手動マッピング: シンプルなプロジェクトでは有効ですが、大規模プロジェクトでは煩雑。
  2. ModelMapper: フィールド名が一致する場合には便利。動的な変換が少ない場合に推奨。
0
0
0

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?