在本教程中,我们将学习如何在Spring Boot应用程序中创建DTO(数据传输对象)类,以及如何使用ModelMapper库将实体转换为DTO,反之亦然。
数据传输对象设计模式是一种经常使用的设计模式。它基本上用于从客户端到服务器一枪传递具有多个属性的数据,以避免多次调用远程服务器。
在用Java(和Spring Boot)编写的RESTful API上使用DTO的另一个优点是,它们可以帮助隐藏域对象(JPA实体)的实现细节。如果我们不仔细处理通过哪些操作可以更改哪些属性,则通过端点公开实体可能会成为安全问题。
ModelMapper库
ModelMapper的目标是通过基于惯例的方式自动确定一个对象模型如何映射到另一个对象模型,从而简化对象映射,同时提供一种简单的,重构安全的API来处理特定的用例,同时人类也可以这样做。
在http://modelmapper.org/上了解有关模型映射器库的更多信息 。
我们将在pom.xml中需要此依赖项:
<dependency> <groupId>org.modelmapper</groupId> <artifactId>modelmapper</artifactId> <version>2.3.5</version> </dependency>
|
假设JPA Entity:
@Data @NoArgsConstructor @AllArgsConstructor @Entity @Table(name = "posts", uniqueConstraints = {@UniqueConstraint(columnNames = {"title"})}) public class Post { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(name = "title") private String title; @Column(name = "description") private String description; @Column(name = "content") private String content; }
|
定义DTO对象:PostDto.java
@Data public class PostDto { private long id; private String title; private String description; private String content; }
|
不使用ModelMapper库的代码,需要手工一个个字段转:
Post post = postRepository.findById(id) .orElseThrow(() -> new ResourceNotFoundException("Post", "id", id)); post.setTitle(postRequest.getTitle()); post.setDescription(postRequest.getDescription()); post.setContent(postRequest.getContent()); return postRepository.save(post);
|
使用ModelMapper库的代码:
Post post = postService.getPostById(id);
// convert entity to DTO PostDto postResponse = modelMapper.map(post, PostDto.class);
return ResponseEntity.ok().body(postResponse);
|
注意的是:modelMapper需要在配置为一个Bean才能被注入使用:
@SpringBootApplication public class SpringbootBlogApiApplication {
@Bean public ModelMapper modelMapper() { return new ModelMapper(); } public static void main(String args) { SpringApplication.run(SpringbootBlogApiApplication.class, args); }
}
|
实体和DTO双向转换:
// convert DTO to entity Post postRequest = modelMapper.map(postDto, Post.class);
Post post = postService.createPost(postRequest);
// convert entity to DTO PostDto postResponse = modelMapper.map(post, PostDto.class);
|
本教程演示了如何在Spring Boot REST API项目中执行从Entity到DTO以及从DTO到Entity的转换。我们使用了模型映射器库,而不是手工编写这些转换。