在本教程中,我們將學(xué)習(xí)如何在Spring Boot?應(yīng)用程序中創(chuàng)建 DTO(數(shù)據(jù)傳輸對象)類,以及如何使用 ModelMapper 庫將實(shí)體轉(zhuǎn)換為 DTO,反之亦然。
數(shù)據(jù)傳輸對象設(shè)計模式是一種常用的設(shè)計模式。它基本上用于一次性將具有多個屬性的數(shù)據(jù)從客戶端傳遞到服務(wù)器,以避免多次調(diào)用遠(yuǎn)程服務(wù)器。
在用Java編寫的RESTful API上使用DTO(以及在Spring Boot上)的另一個優(yōu)點(diǎn)是,它們可以幫助隱藏域?qū)ο螅↗PA實(shí)體)的實(shí)現(xiàn)細(xì)節(jié)。如果我們不仔細(xì)處理可以通過哪些操作更改哪些屬性,則通過終結(jié)點(diǎn)公開實(shí)體可能會成為安全問題。
讓我們從介紹ModelMapper Java庫開始,我們將使用它來將實(shí)體轉(zhuǎn)換為DTO,反之亦然。
模型映射器庫
我們將在pom中需要這種依賴.xml:
<dependency>
<groupId>org.modelmapper</groupId>
<artifactId>modelmapper</artifactId>
<version>2.3.5</version>
</dependency>
第 1 步:將模型映射器庫添加到 Pom.xml
我們將在pom中需要這種依賴.xml:文章來源:http://www.zghlxwxcb.cn/news/detail-458122.html
<dependency>
<groupId>org.modelmapper</groupId>
<artifactId>modelmapper</artifactId>
<version>2.3.5</version>
</dependency>
步驟 2:定義 JPA 實(shí)體 - Post.java
package net.javaguides.springboot.model;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@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;
}
步驟 3:定義 DTO 類 - PostDto.java
package net.javaguides.springboot.payload;
import java.util.HashSet;
import java.util.Set;
import lombok.Data;
@Data
public class PostDto {
private long id;
private String title;
private String description;
private String content;
}
僅包含客戶端所需的 DTO 類中的那些詳細(xì)信息。實(shí)體和 DTO 字段看起來相同,但您將向客戶端添加所需的字段。文章來源地址http://www.zghlxwxcb.cn/news/detail-458122.html
步驟 4:存儲庫層
package com.springboot.blog.repository;
import com.springboot.blog.entity.Post;
import org.springframework.data.jpa.repository.JpaRepository;
public interface PostRepository extends JpaRepository<Post, Long> {
}
第 5 步:服務(wù)層
PostService?接口
package net.javaguides.springboot.service;
import java.util.List;
import net.javaguides.springboot.model.Post;
public interface PostService {
List<Post> getAllPosts();
Post createPost(Post post);
Post updatePost(long id, Post post);
void deletePost(long id);
Post getPostById(long id);
}
PostServiceImpl Class
package net.javaguides.springboot.service.impl;
import java.util.List;
import java.util.Optional;
import org.springframework.stereotype.Service;
import net.javaguides.springboot.exception.ResourceNotFoundException;
import net.javaguides.springboot.model.Post;
import net.javaguides.springboot.repository.PostResository;
import net.javaguides.springboot.service.PostService;
@Service
public class PostServiceImpl implements PostService{
private final PostResository postRepository;
public PostServiceImpl(PostResository postRepository) {
super();
this.postRepository = postRepository;
}
@Override
public List<Post> getAllPosts() {
return postRepository.findAll();
}
@Override
public Post createPost(Post post) {
return postRepository.save(post);
}
@Override
public Post updatePost(long id, Post postRequest) {
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);
}
@Override
public void deletePost(long id) {
Post post = postRepository.findById(id)
.orElseThrow(() -> new ResourceNotFoundException("Post", "id", id));
postRepository.delete(post);
}
@Override
public Post getPostById(long id) {
Optional<Post> result = postRepository.findById(id);
if(result.isPresent()) {
return result.get();
}else {
throw new ResourceNotFoundException("Post", "id", id);
}
// Post post = postRepository.findById(id)
// .orElseThrow(() -> new ResourceNotFoundException("Post", "id", id));
//return post;
}
}
步驟 6:將 ModelMapper 類配置為 Spring Bean
package net.javaguides.springboot;
import org.modelmapper.ModelMapper;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class SpringbootBlogApiApplication {
@Bean
public ModelMapper modelMapper() {
return new ModelMapper();
}
public static void main(String[] args) {
SpringApplication.run(SpringbootBlogApiApplication.class, args);
}
}
步驟 7:控制器層
package net.javaguides.springboot.contoller;
import java.util.List;
import java.util.stream.Collectors;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import net.javaguides.springboot.model.Post;
import net.javaguides.springboot.payload.ApiResponse;
import net.javaguides.springboot.payload.PostDto;
import net.javaguides.springboot.service.PostService;
@RestController
@RequestMapping("/api/posts")
public class PostController {
@Autowired
private ModelMapper modelMapper;
private PostService postService;
public PostController(PostService postService) {
super();
this.postService = postService;
}
@GetMapping
public List<PostDto> getAllPosts() {
return postService.getAllPosts().stream().map(post -> modelMapper.map(post, PostDto.class))
.collect(Collectors.toList());
}
@GetMapping("/{id}")
public ResponseEntity<PostDto> getPostById(@PathVariable(name = "id") Long id) {
Post post = postService.getPostById(id);
// convert entity to DTO
PostDto postResponse = modelMapper.map(post, PostDto.class);
return ResponseEntity.ok().body(postResponse);
}
@PostMapping
public ResponseEntity<PostDto> createPost(@RequestBody PostDto postDto) {
// 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);
return new ResponseEntity<PostDto>(postResponse, HttpStatus.CREATED);
}
// change the request for DTO
// change the response for DTO
@PutMapping("/{id}")
public ResponseEntity<PostDto> updatePost(@PathVariable long id, @RequestBody PostDto postDto) {
// convert DTO to Entity
Post postRequest = modelMapper.map(postDto, Post.class);
Post post = postService.updatePost(id, postRequest);
// entity to DTO
PostDto postResponse = modelMapper.map(post, PostDto.class);
return ResponseEntity.ok().body(postResponse);
}
@DeleteMapping("/{id}")
public ResponseEntity<ApiResponse> deletePost(@PathVariable(name = "id") Long id) {
postService.deletePost(id);
ApiResponse apiResponse = new ApiResponse(Boolean.TRUE, "Post deleted successfully", HttpStatus.OK);
return new ResponseEntity<ApiResponse>(apiResponse, HttpStatus.OK);
}
}
@PostMapping
public ResponseEntity<PostDto> createPost(@RequestBody PostDto postDto) {
// 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);
return new ResponseEntity<PostDto>(postResponse, HttpStatus.CREATED);
}
// change the request for DTO
// change the response for DTO
@PutMapping("/{id}")
public ResponseEntity<PostDto> updatePost(@PathVariable long id, @RequestBody PostDto postDto) {
// convert DTO to Entity
Post postRequest = modelMapper.map(postDto, Post.class);
Post post = postService.updatePost(id, postRequest);
// entity to DTO
PostDto postResponse = modelMapper.map(post, PostDto.class);
return ResponseEntity.ok().body(postResponse);
}
@GetMapping("/{id}")
public ResponseEntity<PostDto> getPostById(@PathVariable(name = "id") Long id) {
Post post = postService.getPostById(id);
// convert entity to DTO
PostDto postResponse = modelMapper.map(post, PostDto.class);
return ResponseEntity.ok().body(postResponse);
}
@GetMapping
public List<PostDto> getAllPosts() {
return postService.getAllPosts().stream().map(post -> modelMapper.map(post, PostDto.class))
.collect(Collectors.toList());
}
結(jié)論
引用
- ModelMapper - Simple, Intelligent, Object Mapping.
- ModelMapper 3.0.1-SNAPSHOT API
到了這里,關(guān)于Spring Boot DTO 示例 - 實(shí)體到 DTO 的轉(zhuǎn)換的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!