Học viên: Dương Xuân Vũ
Lớp: Java Fullstack 15
Email: xuanvufb2@gmail.com
Nguồn tham khảo : https://www.javaguides.net/2021/02/spring-boot-dto-example-entity-to-dto.html

1. Giới thiệu

Trong bài viết trước mình đã có viết về cách chúng ta tự custom cho mình 1 kiểu dữ liệu trả về, nếu mọi người có thể tham khảo tại: https://techmaster.vn/posts/37543/convert-dto-trong-java

Hôm nay mình sẽ giới thiệu cách sử dụng dependency của springboot
Bài viết được tham dịch từ : https://www.javaguides.net/2021/02/spring-boot-dto-example-entity-to-dto.html

2. Cùng bắt tay vào làm nào

Bước 1: Thêm dependency vào file Pom.xml

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

Bước 2: Tạo class Entity ban đầu

Giả sử bây giờ ta có 1 class Post

import jakarta.persistence.*;

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;
}
Post.java

Bước 3: Tạo class PostDto chứa các dữ liệu cần trả về

Đối tượng Dto này chỉ chứa các dữ liệu cần thiết mà mình cần lấy nhé:

import lombok.Data;

@Data
public class PostDto {
	private long id;
	private String title;
	private String description;
	private String content;
}
PostDto.java

Bước 4 : Tạo Repository

import com.springboot.blog.entity.Post;
import org.springframework.data.jpa.repository.JpaRepository;

public interface PostRepository extends JpaRepository<Post, Long> {

}
PostRepository.java

Bước 5 : Tạo ra Service để xử lý các logic

Trong Service chúng ta sẽ chỉ tương tác với đối tượng Post nhé

Đầu tiên ta tạo 1 interface CRUD

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);
}
PostService.java

Tiếp theo tạo Service xử lý

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;
   }
}
PostServiceImpl.java

OK, vậy là chúng ta đã xong phần service

Bước 6 : Cấu hình ModelMapper và đánh dấu nó là @Bean

Ở đây ta sẽ gọi nó ở trước phương thức main, nhớ đánh dấu nó là @Bean để ta có thể sử dụng nhé

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);
   }

}

Bước 7 : Controller

Tại đây, chúng ta sử dụng ModelMapper để chuyển đổi các đối tượng nhanh chóng trong các API khác nhau:

  • Chúng ta sử dụng ModelMapper trong phương thức getAllPosts() để chuyển đổi Entity thành DTO :
@GetMapping
public List<PostDto> getAllPosts() {
	return postService.getAllPosts().stream().map(post -> modelMapper.map(post, PostDto.class))
			.collect(Collectors.toList());
}
  • Tiếp theo sử dụng ModelMapper trong phương thức getPostById() để chuyển đổi Entity thành DTO :
@GetMapping("/{id}")
public ResponseEntity<PostDto> getPostById(@PathVariable(name = "id") Long id) {
   
	Post post = postService.getPostById(id);
   
	// chuyển sang DTO
	PostDto postResponse = modelMapper.map(post, PostDto.class);
   
	return ResponseEntity.ok().body(postResponse);
}
  • Trong phương thức createPost() ta sẽ chuyển đổi Entity thành DTO và ngược lại:
@PostMapping
public ResponseEntity<PostDto> createPost(@RequestBody PostDto postDto) {

	// convert DTO sang Entity
	Post postRequest = modelMapper.map(postDto, Post.class);

	Post post = postService.createPost(postRequest);

	// convert entity sang DTO
	PostDto postResponse = modelMapper.map(post, PostDto.class);

	return new ResponseEntity<PostDto>(postResponse, HttpStatus.CREATED);
}
  • Và trong updatePost() :
@PutMapping("/{id}")
public ResponseEntity<PostDto> updatePost(@PathVariable long id, @RequestBody PostDto postDto) {
	// convert DTO sang Entity
	Post postRequest = modelMapper.map(postDto, Post.class);

	Post post = postService.updatePost(id, postRequest);

	// entity sang DTO
	PostDto postResponse = modelMapper.map(post, PostDto.class);

	return ResponseEntity.ok().body(postResponse);
}

Vậy là ta đã hoàn thành class Controller đầy đủ:

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);
	}
}
PostController.java

3. Kết luận

Vậy là ta đã hoàn thiện thêm cách sử dụng dependency rồi, hi vọng các bạn sẽ thấy hữu ích

Tùy theo nhu cầu sử dụng, hãy lựa chọn phương pháp hợp lý cho mình nhé.