SpringRESTAPIのエンティティからDTOへの変換
1. 概要
このチュートリアルでは、Springアプリケーションの内部エンティティとクライアントに公開される外部DTO (データ転送オブジェクト)の間で発生する必要のある変換を処理します。
2. モデルマッパー
このエンティティを実行するために使用するメインライブラリ-DTO変換ModelMapperを紹介することから始めましょう。
pom.xmlでこの依存関係が必要になります。
<dependency>
<groupId>org.modelmapper</groupId>
<artifactId>modelmapper</artifactId>
<version>2.4.5</version>
</dependency>
このライブラリの新しいバージョンがあるかどうかを確認するには、こちらにアクセスしてください。
次に、Spring構成でModelMapperBeanを定義します。
@Bean
public ModelMapper modelMapper() {
return new ModelMapper();
}
3. DTO
次に、この両面問題のDTO側である PostDTOを紹介しましょう。
public class PostDto {
private static final SimpleDateFormat dateFormat
= new SimpleDateFormat("yyyy-MM-dd HH:mm");
private Long id;
private String title;
private String url;
private String date;
private UserDto user;
public Date getSubmissionDateConverted(String timezone) throws ParseException {
dateFormat.setTimeZone(TimeZone.getTimeZone(timezone));
return dateFormat.parse(this.date);
}
public void setSubmissionDate(Date date, String timezone) {
dateFormat.setTimeZone(TimeZone.getTimeZone(timezone));
this.date = dateFormat.format(date);
}
// standard getters and setters
}
2つのカスタム日付関連メソッドは、クライアントとサーバー間での日付変換を処理することに注意してください。
- getSubmissionDateConverted()メソッドは、サーバーのタイムゾーンで日付StringをDateに変換し、永続的なPostエンティティで使用します
- setSubmissionDate()メソッドは、現在のユーザーのタイムゾーンでDTOの日付をPostのDateに設定します
4. サービスレイヤー
次に、サービスレベルの操作を見てみましょう。これは明らかにエンティティ(DTOではない)で機能します。
public List<Post> getPostsList(
int page, int size, String sortDir, String sort) {
PageRequest pageReq
= PageRequest.of(page, size, Sort.Direction.fromString(sortDir), sort);
Page<Post> posts = postRepository
.findByUser(userService.getCurrentUser(), pageReq);
return posts.getContent();
}
次に、サービスの上のレイヤーであるコントローラーレイヤーを見ていきます。 これは、変換が実際に行われる場所です。
5. コントローラレイヤー
次に、 Postリソースの単純なRESTAPIを公開して、標準のコントローラー実装を調べてみましょう。
ここでは、いくつかの簡単なCRUD操作を示します。作成、更新、取得、すべての取得です。 操作が非常に簡単であることを考えると、特にエンティティ-DTO変換の側面に関心があります。
@Controller
class PostRestController {
@Autowired
private IPostService postService;
@Autowired
private IUserService userService;
@Autowired
private ModelMapper modelMapper;
@GetMapping
@ResponseBody
public List<PostDto> getPosts(...) {
//...
List<Post> posts = postService.getPostsList(page, size, sortDir, sort);
return posts.stream()
.map(this::convertToDto)
.collect(Collectors.toList());
}
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
@ResponseBody
public PostDto createPost(@RequestBody PostDto postDto) {
Post post = convertToEntity(postDto);
Post postCreated = postService.createPost(post));
return convertToDto(postCreated);
}
@GetMapping(value = "/{id}")
@ResponseBody
public PostDto getPost(@PathVariable("id") Long id) {
return convertToDto(postService.getPostById(id));
}
@PutMapping(value = "/{id}")
@ResponseStatus(HttpStatus.OK)
public void updatePost(@PathVariable("id") Long id, @RequestBody PostDto postDto) {
if(!Objects.equals(id, postDto.getId())){
throw new IllegalArgumentException("IDs don't match");
}
Post post = convertToEntity(postDto);
postService.updatePost(post);
}
}
これがPostエンティティからPostDtoへの変換です:
private PostDto convertToDto(Post post) {
PostDto postDto = modelMapper.map(post, PostDto.class);
postDto.setSubmissionDate(post.getSubmissionDate(),
userService.getCurrentUser().getPreference().getTimezone());
return postDto;
}
DTOからエンティティへの変換は次のとおりです。
private Post convertToEntity(PostDto postDto) throws ParseException {
Post post = modelMapper.map(postDto, Post.class);
post.setSubmissionDate(postDto.getSubmissionDateConverted(
userService.getCurrentUser().getPreference().getTimezone()));
if (postDto.getId() != null) {
Post oldPost = postService.getPostById(postDto.getId());
post.setRedditID(oldPost.getRedditID());
post.setSent(oldPost.isSent());
}
return post;
}
ご覧のとおり、モデルマッパーを使用すると、変換ロジックがすばやく簡単になります。マッパーの map APIを使用して、データを変換しています変換ロジックを1行も記述せずに。
6. ユニットテスト
最後に、エンティティとDTO間の変換が正常に機能することを確認するために、非常に簡単なテストを実行してみましょう。
public class PostDtoUnitTest {
private ModelMapper modelMapper = new ModelMapper();
@Test
public void whenConvertPostEntityToPostDto_thenCorrect() {
Post post = new Post();
post.setId(1L);
post.setTitle(randomAlphabetic(6));
post.setUrl("www.test.com");
PostDto postDto = modelMapper.map(post, PostDto.class);
assertEquals(post.getId(), postDto.getId());
assertEquals(post.getTitle(), postDto.getTitle());
assertEquals(post.getUrl(), postDto.getUrl());
}
@Test
public void whenConvertPostDtoToPostEntity_thenCorrect() {
PostDto postDto = new PostDto();
postDto.setId(1L);
postDto.setTitle(randomAlphabetic(6));
postDto.setUrl("www.test.com");
Post post = modelMapper.map(postDto, Post.class);
assertEquals(postDto.getId(), post.getId());
assertEquals(postDto.getTitle(), post.getTitle());
assertEquals(postDto.getUrl(), post.getUrl());
}
}
7. 結論
この記事では、Spring REST API で、これらの変換を手動で記述する代わりに、モデルマッパーライブラリを使用して、エンティティからDTOへの変換、およびDTOからエンティティへの変換を簡略化するについて詳しく説明しました。
例の完全なソースコードは、GitHubプロジェクトで入手できます。