国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

Spring Boot DTO 示例 - 實(shí)體到 DTO 的轉(zhuǎn)換

這篇具有很好參考價值的文章主要介紹了Spring Boot DTO 示例 - 實(shí)體到 DTO 的轉(zhuǎn)換。希望對大家有所幫助。如果存在錯誤或未考慮完全的地方,請大家不吝賜教,您也可以點(diǎn)擊"舉報違法"按鈕提交疑問。

在本教程中,我們將學(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,反之亦然。

模型映射器庫

ModelMapper 旨在通過根據(jù)約定自動確定一個對象模型如何映射到另一個對象模型,使對象映射變得容易,就像人類一樣,同時提供一個簡單的、重構(gòu)安全的 API 來處理特定的用例。
ModelMapper - Simple, Intelligent, Object Mapping.?閱讀有關(guān)模型映射器庫的更多信息。

我們將在pom中需要這種依賴.xml:

<dependency>
    <groupId>org.modelmapper</groupId>
    <artifactId>modelmapper</artifactId>
    <version>2.3.5</version>
</dependency>

第 1 步:將模型映射器庫添加到 Pom.xml

我們將在pom中需要這種依賴.xml:

<dependency>
    <groupId>org.modelmapper</groupId>
    <artifactId>modelmapper</artifactId>
    <version>2.3.5</version>
</dependency>

步驟 2:定義 JPA 實(shí)體 - Post.java

讓我們創(chuàng)建一個Post實(shí)體類并向其添加以下內(nèi)容:
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

讓我們創(chuàng)建PostDto類并向其添加以下內(nèi)容:
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:存儲庫層

讓我們創(chuàng)建一個PostRepository來與Post實(shí)體的數(shù)據(jù)庫進(jìn)行通信:
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ù)層

在服務(wù)層中,我們將只使用Post實(shí)體,而不使用PostDto類:

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;
	}
}
請注意,我們不是在服務(wù)層中使用實(shí)體到 DTO,反之亦然。

步驟 6:將 ModelMapper 類配置為 Spring Bean

讓我們將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:控制器層

在下面的PostController類中,我們注入了ModelMapper類,并在不同的REST API中將其用于實(shí)體到DTO的轉(zhuǎn)換,反之亦然:
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);
	}
}
我們在createPost()方法中使用ModelMapper將實(shí)體轉(zhuǎn)換為DTO,反之亦然:
        @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);
	}
我們在更新Post()?方法中使用 ModelMapper 將實(shí)體轉(zhuǎn)換為 DTO,反之亦然:
	// 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);
	}
我們在 getPostById()?方法中使用 ModelMapper 將實(shí)體轉(zhuǎn)換為 DTO,反之亦然:
	@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);
	}
我們在getAllPosts()方法中使用ModelMapper將實(shí)體轉(zhuǎn)換為DTO,反之亦然:
        @GetMapping
	public List<PostDto> getAllPosts() {

		return postService.getAllPosts().stream().map(post -> modelMapper.map(post, PostDto.class))
				.collect(Collectors.toList());
	}

結(jié)論

本教程演示了如何在 Spring 引導(dǎo) REST API 項(xiàng)目中執(zhí)行從實(shí)體到 DTO 以及從 DTO 到實(shí)體的轉(zhuǎn)換。我們使用了模型映射器庫,而不是手動編寫這些轉(zhuǎn)換。

引用

  • 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)!

本文來自互聯(lián)網(wǎng)用戶投稿,該文觀點(diǎn)僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務(wù),不擁有所有權(quán),不承擔(dān)相關(guān)法律責(zé)任。如若轉(zhuǎn)載,請注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實(shí)不符,請點(diǎn)擊違法舉報進(jìn)行投訴反饋,一經(jīng)查實(shí),立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費(fèi)用

相關(guān)文章

  • Spring Boot學(xué)習(xí)隨筆- 集成MyBatis-Plus(一),第一個MP程序(環(huán)境搭建、@TableName、@TableId、@TableField示例)

    Spring Boot學(xué)習(xí)隨筆- 集成MyBatis-Plus(一),第一個MP程序(環(huán)境搭建、@TableName、@TableId、@TableField示例)

    學(xué)習(xí)視頻:【編程不良人】Mybatis-Plus整合SpringBoot實(shí)戰(zhàn)教程,提高的你開發(fā)效率,后端人員必備! MyBatis-Plus是一個基于MyBatis的增強(qiáng)工具,旨在簡化開發(fā),提高效率。它擴(kuò)展了MyBatis的功能,提供了許多實(shí)用的特性,包括強(qiáng)大的CRUD操作、條件構(gòu)造器、分頁插件、代碼生成器等。MyBa

    2024年02月04日
    瀏覽(17)
  • SSMP整合案例(2) Spring Boot整合Lombok簡化實(shí)體類開發(fā)

    SSMP整合案例(2) Spring Boot整合Lombok簡化實(shí)體類開發(fā)

    好啊 接著我們上文SSMP整合案例(1) 構(gòu)建 Spring Boot Vue MySql項(xiàng)目環(huán)境 我們繼續(xù) 接下來 我們要在java項(xiàng)目中 建立出數(shù)據(jù)庫表對應(yīng)的實(shí)體類 我們還是先看看自己上文中 創(chuàng)建的這個 book表 其中四個字段 主鍵id 數(shù)字枚舉類型的type 字符串類型name 字符串類型 description 我們打開idea 找到上

    2024年02月09日
    瀏覽(21)
  • 關(guān)于VS2022使用EF生成實(shí)體模型報錯的問題:運(yùn)行轉(zhuǎn)換:System.NullReferenceException:對象引用未設(shè)置為對象的示例。

    關(guān)于VS2022使用EF生成實(shí)體模型報錯的問題:運(yùn)行轉(zhuǎn)換:System.NullReferenceException:對象引用未設(shè)置為對象的示例。

    起因: 之前版本vs2022生成EF模型一直沒有問題,在更新了最新的vs2022之后,版本號17.6+,出現(xiàn)此問題: 正在運(yùn)行轉(zhuǎn)換:System.NullReferenceException:未將對象引用設(shè)置到對象的實(shí)例。 具體錯誤如下: 正在運(yùn)行轉(zhuǎn)換: System.NullReferenceException: 未將對象引用設(shè)置到對象的實(shí)例。 在 Micro

    2024年02月08日
    瀏覽(35)
  • 【Spring Boot】Spring Boot實(shí)現(xiàn)完整論壇功能示例代碼

    以下是一個簡單的Spring Boot論壇系統(tǒng)示例代碼: 首先是數(shù)據(jù)庫設(shè)計,我們創(chuàng)建以下幾張表: user表,存儲用戶信息,包括id、username、password、email、create_time等字段。 topic表,存儲帖子信息,包括id、title、content、user_id、create_time等字段。 comment表,存儲評論信息,包括id、con

    2024年02月11日
    瀏覽(28)
  • 2. 示例:Spring Boot 入門

    2. 示例:Spring Boot 入門

    1.1 概述 Spring Boot是由Pivotal團(tuán)隊(duì)提供的全新框架,其設(shè)計目的是用來簡化新Spring應(yīng)用的初始搭建以及開發(fā)過程。習(xí)慣優(yōu)于配置 1.2 為什么使用Spring Boot J2EE笨重的開發(fā)、繁多的配置、低下的開發(fā)效率、復(fù)雜的部署流程、第三方技術(shù)集成難度大。 1.3 Spring Boot是什么 一站式整合所有

    2024年02月01日
    瀏覽(16)
  • Github點(diǎn)贊接近 100k 的Spring Boot學(xué)習(xí)教程+實(shí)戰(zhàn)項(xiàng)目推薦

    Github點(diǎn)贊接近 100k 的Spring Boot學(xué)習(xí)教程+實(shí)戰(zhàn)項(xiàng)目推薦

    很明顯的一個現(xiàn)象,除了一些老項(xiàng)目,現(xiàn)在 Java 后端項(xiàng)目基本都是基于 Spring Boot 進(jìn)行開發(fā),畢竟它這么好用以及天然微服務(wù)友好。不夸張的說, Spring Boot 是 Java 后端領(lǐng)域最最最重要的技術(shù)之一,熟練掌握它對于 Java 程序員至關(guān)重要。 這篇文章我會推薦一些優(yōu)質(zhì)的? Spring Bo

    2024年02月03日
    瀏覽(26)
  • 【Spring Boot】四種核心類的依賴關(guān)系:實(shí)體類、數(shù)據(jù)處理類、業(yè)務(wù)處理類、控制器類

    //1.配置項(xiàng)目環(huán)境,創(chuàng)建Spring Boot項(xiàng)目。 //2.數(shù)據(jù)庫設(shè)置,配置數(shù)據(jù)庫。 //3.創(chuàng)建實(shí)體類,映射到數(shù)據(jù)庫。 //4.創(chuàng)建數(shù)據(jù)處理層類,Repository //5.創(chuàng)建業(yè)務(wù)處理類,Service類 //6.創(chuàng)建控制器類,Controller類 Article.java java import javax.persistence.Entity; import javax.persistence.GeneratedValue; import java

    2024年02月11日
    瀏覽(18)
  • Spring Boot 實(shí)現(xiàn) WebSocket 示例

    Spring Boot 實(shí)現(xiàn) WebSocket 示例

    WebSocket協(xié)議提供了一種標(biāo)準(zhǔn)化的方法,通過單個TCP連接在客戶機(jī)和服務(wù)器之間建立全雙工、雙向的通信通道。它是一種不同于HTTP的TCP協(xié)議,但被設(shè)計為在HTTP上工作,使用端口80和443,并允許重用現(xiàn)有的防火墻規(guī)則。 WebSocket 協(xié)議是獨(dú)立的基于 TCP 協(xié)議。它與 HTTP 的唯一關(guān)系是

    2024年02月14日
    瀏覽(22)
  • Spring Boot集成Redis簡單示例

    要在Spring Boot中集成Redis,你可以使用Spring Data Redis庫來簡化操作。 下面是一個示例代碼: 首先,在你的Spring Boot項(xiàng)目的pom.xml文件中添加以下依賴: 接下來,配置Redis連接信息。在application.properties(或application.yml)文件中添加以下配置: 然后,創(chuàng)建一個Redis服務(wù)類來執(zhí)行一些

    2024年01月22日
    瀏覽(97)
  • java中用SXSSFWorkbook把多個list數(shù)據(jù)和單個實(shí)體dto導(dǎo)出到excel如何導(dǎo)出到多個sheet頁詳細(xì)實(shí)例?(親測)

    以下是一個詳細(xì)的示例,展示了如何使用SXSSFWorkbook將多個List數(shù)據(jù)和單個實(shí)體DTO導(dǎo)出到多個Sheet頁: import org.apache.poi.xssf.streaming.SXSSFWorkbook; import org.apache.poi.xssf.streaming.SXSSFSheet; import org.apache.poi.xssf.streaming.SXSSFRow; import org.apache.poi.xssf.streaming.SXSSFCell; import java.io.FileOutputStream;

    2024年02月11日
    瀏覽(25)

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包