DTO ↔ Entity Conversion Made Easy in Spring Boot Using ModelMapper

Introduction

When building REST APIs in Spring Boot, one of the most common problems developers face is how to separate Entities from API responses and requests. Directly exposing Entities is a bad practice—it leads to tight coupling, security issues, and unnecessary data exposure.

This is where DTOs (Data Transfer Objects) and a powerful library like ModelMapper come in. In this blog, we’ll explore why DTOs are important, how to use them in Spring Boot, and how ModelMapper simplifies conversions between DTOs and Entities.

What is a DTO?

A DTO (Data Transfer Object) is a simple Java object used to transfer data between processes, layers, or services. In Spring Boot, DTOs act as a bridge between the Controller and Service layers.

Why use DTOs?

  1. Encapsulation of Data – Prevents exposing sensitive fields like IDs, passwords, or salaries.

  2. Decoupling – Entities are tightly bound to the database; DTOs make your API independent of schema changes.

  3. Validation & Transformation – DTOs can carry validation annotations like @NotBlank, @Email, etc.

  4. Security – Avoids leaking DB structure directly.

  5. Control over Responses – You decide exactly what fields go to the client.

What is ModelMapper?

ModelMapper is a Java library that simplifies object mapping. Instead of writing repetitive code like book.setTitle(bookRequest.getTitle()), ModelMapper lets you do it in one line.It automatically matches fields by name and type, making conversions clean, consistent, and easy to maintain.ook

				
					Book book = modelMapper.map(bookRequest, Book.class);
				
			

Example: Book Entity

Book.java
@Entity
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Book {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer bookId;
    private String title;
    private String author;
    private Double price;
    private String isbn;
}

DTOs:

BookRequest.java
Copy to clipboard
@Data
@NoArgsConstructor
@AllArgsConstructor
public class BookRequest {
  private String title;
  private String author;
  private Double price;
}
BookResponse.java
@Data
@NoArgsConstructor
@AllArgsConstructor
public class BookResponse {
    private String title;
    private String author;
    private Double price;
    private String isbn;
}

Workflow

  1. Request Flow (Controller → Service → Repository)

    • Client sends a BookRequest JSON.

    • Controller receives BookRequest.

    • Service maps BookRequest → Book Entity using ModelMapper.

    • Repository saves the Entity to DB.

  2. Response Flow (Repository → Service → Controller)

    • Repository fetches Book Entity.

    • Service maps Book Entity → BookResponse.

    • Controller returns BookResponse to client

ModelMapper Configuration

AppConfig.java
@Configuration
public class AppConfig {
    @Bean
    public ModelMapper modelMapper() {
        return new ModelMapper();
    }
}

Example of Service Layer

BookServiceImpl.java
@Service
public class BookServiceImpl implements BookService {
    
    @Autowired
    private ModelMapper modelMapper;

    @Autowired
    private BookRepository bookRepository;

    @Override
    public void addBook(BookRequest bookRequest) {
        Book book = modelMapper.map(bookRequest, Book.class);
        book.setIsbn(generateIsbn()); // custom ISBN generator
        bookRepository.save(book);
    }

    @Override
    public BookResponse getBookById(Integer id) {
        Book book = bookRepository.findById(id).orElseThrow();
        return modelMapper.map(book, BookResponse.class);
    }

    private String generateIsbn() {
        return "ISBN-" + UUID.randomUUID().toString().substring(0, 13);
    }
}

Benefits Recap

✔ Cleaner code (no boilerplate setters/getters mapping).
✔ Decouples Entities from API.
✔ Safer and more maintainable REST APIs.

LINK TO WATCH FULL VIDEOhttps://youtu.be/AH4V-m6Ksec 


Conclusion:
DTOs are essential for building secure and maintainable Spring Boot applications. With ModelMapper, DTO ↔ Entity conversion becomes effortless and clean. If you’re still writing manual mapping code, it’s time to switch!

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top