- What is DTO?
- The DTO Pattern (Data Transfer Object)
- DTO stands for Data Transfer Object, these are the objects that move from one layer to another layer.
- DTO can be also used to hide the implementation detail of database layer objects. Exposing the Entities to the web layer without handling the response properly can become a security issue.
- For example, If we have an endpoint that exposes the details of entities class called User. The endpoint handles the GET request. If the response is not handled properly with the GET endpoint one can get all the fields of the User class even the password also, which is not a good practice for writing restful services. To overcome these problems DTO came into the picture, with DTO we can choose which fields we need to expose to the web layer. (cho ví dụ)
- Best Way to develop DTOs: The way to start developing DTOs is to understand that their sole purpose is to transfer subset of data of your business entities to different clients(could be UI, or an external service).
- Entity To DTO Conversion for a Spring REST API
- mapping entity to dto java spring boot
- Spring Boot – Map Entity to DTO using ModelMapper
- ModelMapper: Guide to Using ModelMapper
- ModelMapper is a maven library which is used for the conversion of entities object to DTO and vice-versa.
- When use DTO?
- Truyền tải dữ liệu giữa các tầng
- Tối ưu hóa dữ liệu truyền tải qua mạng
- Tăng cường bảo mật (ẩn thông tin nhạy cảm và kiểm soát dữ liệu hiển thị).
- Chuẩn hóa dữ liệu đầu vào và đầu ra
- WHY use DTO?
- separation of concerns (SEPARATION OF CONCERNS)
- For Example
PHÂN BIỆT POJO, DTO, ENTITY
Application Service Interface
- Do define an
interface
for each application service in the application contracts package.
- Do inherit from the
IApplicationService
interface.
- Do use the
AppService
postfix for the interface name (ex: IProductAppService
).
- Do create DTOs (Data Transfer Objects) for inputs and outputs of the service.
- Do not get/return entities for the service methods.
- Do define DTOs based on the DTO best practices.
Best Practices/Application Services | Documentation Center | ABP.IO
Kết hợp Audit Entity with Base Entity
Sử dụng một lớp BaseEntity
kết hợp với các tính năng Auditing của JPA có thể rất hữu ích và thường là một phương pháp hay để quản lý các thuộc tính chung và auditing trong ứng dụng của bạn. Điều này giúp giảm thiểu mã lặp lại và đảm bảo rằng tất cả các thực thể trong ứng dụng của bạn đều tuân theo cùng một cấu trúc auditing.
1. Tạo lớp BaseEntity
Lớp BaseEntity
sẽ chứa các trường cơ bản như id
, createdAt
, và updatedAt
.