In the ORM (Object-Relational Mapping) world, entities (POJOs) map directly to database tables, while DTOs (Data Transfer Objects) provide a customized view of the table data for REST clients. Exposing entities directly is discouraged for the following reasons:
Category
, the client should only send Category
details, not related entities like BlogPosts
, Blogger
, Address
, or AadharCard
.createdOn
are not set, the database may receive null
or unintended values, leading to data inconsistencies.To convert between entities and DTOs automatically, third-party libraries like MapStruct or ModelMapper are commonly used. Below are the steps to use ModelMapper in a Spring Boot application.
Include the ModelMapper dependency in your pom.xml
:
<!-- <https://mvnrepository.com/artifact/org.modelmapper/modelmapper> -->
<dependency>
<groupId>org.modelmapper</groupId>
<artifactId>modelmapper</artifactId>
<version>3.2.3</version>
</dependency>
To make ModelMapper
injectable as a dependency in other Spring beans, configure it as a Spring bean using either:
<bean>
tags.@Bean
annotated method in a @Configuration
class.Example using @Configuration
and @Bean
:
@Configuration
public class AppConfig {
@Bean
public ModelMapper modelMapper() {
ModelMapper modelMapper = new ModelMapper();
modelMapper.getConfiguration()
.setMatchingStrategy(MatchingStrategies.STRICT) // Only matching property names are transferred
.setPropertyCondition(Conditions.isNotNull()); // Only non-null properties are transferred
return modelMapper;
}
}
@Bean
vs @Component
@Component
and its subtypes (e.g., @Service
, @Repository
) are preferred for component scanning and automatic wiring when you control the source code.@Bean
is used when automatic configuration is not possible, such as for third-party libraries like ModelMapper
or PasswordEncoder
in Spring Security, where you cannot annotate the classes with @Component
.