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?

【DTO(データ転送オブジェクト)とエンティティ(DBエンティティ)間の「型の不一致」エラー】

Last updated at Posted at 2025-06-26

エラーが出たので今後同じエラーが出た際の備忘録用に書きました
今回出たのは下記のエラー。
これはよくあるDTO(データ転送オブジェクト)とエンティティ(DBエンティティ)間の「型の不一致」エラーらしいです!

[INFO] 2 errors
[INFO] -------------------------------------------------------------
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  4.222 s
[INFO] Finished at: 2025-06-26T14:28:20+09:00
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.13.0:compile (default-compile) on project my-spring-app: Compilation failure: Compilation failure:
[ERROR] /home/mizumoto/my-spring/backend/src/main/java/com/example/myspringapp/controller/UsersController.java:[55,37] incompatible types: java.util.List<com.example.myspringapp.entity.Users> cannot be converted to java.util.List<com.example.myspringapp.dto.UserListDto>
[ERROR] /home/mizumoto/my-spring/backend/src/main/java/com/example/myspringapp/service/UsersService.java:[24,41] incompatible types: java.util.List<com.example.myspringapp.dto.UserListDto> cannot be converted to java.util.List<com.example.myspringapp.entity.Users>
[ERROR] -> [Help 1]

エラーの要点

incompatible types: List<Users> cannot be converted to List<UserListDto>

ということは…
サービスやリポジトリが返しているのは List(エンティティ)
なのにコントローラー側は List(DTO)を期待している
この「齟齬(そご)」が原因でコンパイルエラーが発生しています!

解決方法

DTOで返したい ⇒ サービスでDTOに変換する

@GetMapping("/users")
public List<UserListDto> getUsers(@RequestParam Integer id) {
    List<Users> users = usersService.getUsers(id);

    return users.stream()
                .map(user -> new UserListDto(
                    user.getId(),
                    user.getUsername(),
                    user.getMailadress(),
                    user.getPassword(),
                    user.getPhoneNumber(),
                    user.isDeleted()
                ))
                .collect(Collectors.toList());
}

または、DTO変換はサービス層でやってもOKです。 その場合、usersService.getUsers(id) の戻り値は List になります!

問題 対応
Repository / Service が List<Users> を返してるのに Controller が List<UserListDto> と受け取ろうとしてた
DTOとEntityは型が違う 必要なら .map() 等で明示的に変換するべし!
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?