This project aims to facilitate the mapping between DTOs (Data Transfer Objects) and Entities in a Java 17 and Spring Boot 3 application.
The primary objective of this project is to streamline the mapping process, particularly when dealing with DTOs constructed using Java records, which aren't fully supported by conventional mappers like ModelMapper due to their nature (final fields that can be only initialized when constructor called).
To achieve this, we utilize MapStruct, a code generator that simplifies the implementation of mapping interfaces. It helps to reduce boilerplate code and enhances maintainability by providing a clear and concise way to define mappings between DTOs and Entities.
- Java Records for DTOs: Utilizing Java records for DTOs to succinctly represent data structures.
- BaseEntity: A base entity class containing common fields that should be extended by project-specific entities. This can be modified to suit different project contexts.
- Generic Entity to ID Mapper: Using Java reflection, we've implemented a generic mapper for mapping entities to their corresponding IDs.
- MapStruct Mappings: Defining mapping interfaces for DTOs and Entities using MapStruct, allowing for concise and efficient mapping logic.
- Singleton Mapper Instances: Ensuring a single instance of each mapper is created by providing a factory method within the mapping definition interface. This helps maintain consistency and reduces resource consumption.
project/
│
├── src/
│ ├── main/
│ │ ├── java/
│ │ │ ├── com.houssem.dtojavarecordmapper/
│ │ │ │ ├── dto/
│ │ │ │ │ ├── CategoryDto.java
│ │ │ │ │ ├── RequestDto.java
│ │ │ │ │ └── ...
│ │ │ │ ├── entity/
│ │ │ │ │ ├── BaseEntity.java
│ │ │ │ │ ├── Category.java
│ │ │ │ │ ├── Request.java
│ │ │ │ │ └── ...
│ │ │ │ ├── mapper/
│ │ │ │ │ ├── common/
│ │ │ │ │ | ├──EntityIdMapper.java
│ │ │ │ │ | ├──GenericMapper.java
│ │ │ │ │ ├── CategoryMapper.java
│ │ │ │ │ ├── RequestCommonMapper.java
│ │ │ │ │ ├── RequestMapper.java
│ │ │ │ │ └── ...
│ │ │ │ └── ...
│ │ │ └── ...
│ │ └── resources/
│ │ └── application.properties
│ └── test/
│ ├── java/
│ │ ├── com.houssem.dtojavarecordmapper/
│ │ │ └── ...
│ └── resources/
│ └── ...
├── pom.xml
└── README.md
- Define DTOs: Create DTO classes using Java records in the
dto
package. - Extend BaseEntity: Extend the
BaseEntity
class in your project-specific entity classes located in theentity
package. - Implement Mappings: Implement mapping interfaces for each entity using MapStruct in the
mapper
package. - Access Mappers: Import the singleton mapper instances created by the factory method provided within the mapping definition interfaces.
- Unit Tests: Refer to unit tests to understand various use cases and ensure mappings work as expected.
- Java 17
- Spring Boot 3
- MapStruct
- Spring data JPA
- H2 data base
For further details and examples, refer to the project source code. Feel free to contribute or raise issues if you encounter any problems.
Happy coding!