Why Avoid Exposing Entities Directly to REST Clients?

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:

  1. Entity Associations and Performance Issues
  2. Unnecessary Data in Resource Creation
  3. Security Risks
  4. Issues with Resource Updates

Using DTOs with ModelMapper

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.

1. Add ModelMapper Dependency

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>

2. Configure ModelMapper as a Spring Bean

To make ModelMapper injectable as a dependency in other Spring beans, configure it as a Spring bean using either:

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