Skip to main content

Command Palette

Search for a command to run...

Spring Boot MapStruct Example

Updated
Spring Boot MapStruct Example
Y

Tech Lead & Architect | 13+ Years in Cloud, Backend, and AI - Experienced software engineer with expertise in Java, Spring Boot, Microservices, Angular, React, Kafka, DevOps, Python, PySpark, Databricks, and Generative AI. Certified in TOGAF, AWS, and Google Cloud. Passionate about building scalable, secure, and high-performance systems. Enthusiast in Data Engineering & Agentic AI. Author of 1,200+ technical articles sharing insights across diverse tech stacks.

Date: 2021-07-20

This article explores MapStruct, a powerful tool for simplifying data mapping in Java applications, particularly within the context of Spring Boot. MapStruct significantly reduces the boilerplate code usually associated with converting data between different object models, such as database entities and data transfer objects (DTOs). Imagine you have a database table representing customer information, and you need to present this information to a user through a web application. The data in the database might be structured differently from the way you want to display it on the screen. Manually writing the code to transform the database representation into a user-friendly format is tedious and error-prone. MapStruct automates this process, making development faster and more reliable.

MapStruct is an annotation-based code generator. Instead of writing lengthy conversion methods by hand, you annotate interfaces that define how the data transformations should occur. MapStruct then automatically generates the corresponding Java code at compile time. This generated code is efficient because it utilizes direct method calls, making the mapping process fast and predictable. The type safety provided by MapStruct ensures that errors related to incompatible data types are caught during compilation, preventing runtime surprises. This combination of speed, safety, and ease of understanding makes MapStruct a highly attractive option for developers.

The practical application of MapStruct is best understood through the example of a multi-tiered application. In such an architecture, you typically have distinct layers, each with its own data models. You might have database entities, representing data stored in your database; service layer objects, which handle business logic; and DTOs, which serve as containers for data exchanged between the application and its users, such as via a web API. MapStruct excels at bridging the gaps between these layers by providing a clean and efficient way to translate data from one model to another.

Let's imagine a simplified scenario involving an e-commerce application. You might have an Order entity stored in your database, containing detailed information about each order, including customer details, ordered items, and shipping addresses. For the purposes of a web application's user interface, you'd likely create a simplified OrderDTO, containing only the information needed for display, such as order ID, total amount, and order status. MapStruct would help you seamlessly convert between the Order entity and the OrderDTO, eliminating the need for manual conversion code.

To use MapStruct in a Spring Boot application, you first need to include it as a dependency in your project’s configuration file (often named pom.xml if using Maven). This file specifies all the external libraries your application relies upon. In addition to MapStruct, you would also specify dependencies for Spring Boot, a database (such as H2 for testing purposes), and potentially Lombok, a library that reduces boilerplate code in Java classes. The MapStruct dependency would also include the necessary plugin information to ensure that the code generation process works correctly with your project's build system.

A configuration file, usually called application.properties, defines settings for your application, including database connection details and properties related to Spring's data access framework (JPA) and the H2 console, which can be used to view and manage your database during development.

The core of the MapStruct implementation involves creating a mapper interface. This interface declares methods that define the mapping logic. For example, a method might be defined to map an Order entity to an OrderDTO. Instead of providing a concrete implementation of this method, you annotate it with MapStruct annotations that specify the mapping rules. These annotations typically indicate which fields should be copied from the source object (the Order entity) to the target object (the OrderDTO). MapStruct will then generate the Java code that performs this mapping.

The mapper interface would be declared as a Spring component, making it readily available for injection into other parts of your application, such as your controllers and services. This is a key aspect of Spring's dependency injection mechanism.

In your controllers—which handle incoming HTTP requests—you would use the mapper to convert between entities and DTOs. When a user requests information, the controller retrieves data from the database (likely through a service layer and a repository), uses the mapper to convert the retrieved entity to a DTO, and then sends this DTO as a response to the user. Similarly, when a user submits data, the controller would use the mapper to convert the DTO to an entity before saving it to the database.

Executing the application would involve running the main class of your Spring Boot application. This is typically a class annotated with @SpringBootApplication, which serves as the entry point for your application. Once the application is running, you can test its endpoints using tools such as Postman, which allow you to send HTTP requests to your application and examine the responses.

The advantages of using MapStruct are numerous. The generated code is efficient, ensuring fast data transformation. The type safety prevents common errors. The code is readable and maintainable, as the mapping logic is explicitly defined in the mapper interface. Finally, it significantly reduces development time by automating a tedious and error-prone task. In essence, MapStruct empowers developers to focus on the core logic of their applications rather than getting bogged down in repetitive data conversion tasks.

Read more

More from this blog

The Engineering Orbit

1174 posts

The Engineering Orbit shares expert insights, tutorials, and articles on the latest in engineering and tech to empower professionals and enthusiasts in their journey towards innovation.