← Back to list

MapStruct : Another way to map between Entity and DTO

Use this mapper to reduce boilerplate and improve performance of your Java Application.

Full Stack Developer · 2024-12-30 14:47 · 84 claps · 2.2 min read
#java #mapstruct #mapper #data-mapper #modelmapper
Open on Medium ↗

MapStruct : Another way to map between Entity and DTO

Use this mapper to reduce boilerplate and improve performance of your Java Application.

Photo by laura adai on Unsplash

Photo by laura adai on Unsplash

MapStruct is widely used in enterprise projects for simplifying the conversion of objects in applications where DTOs and entities are heavily utilized.

Earlier we had seen another library to do this, heres a quick link —

[embed]Mapping Domain Object to DTO made easy! Do it in one line using MODELMAPPER Let’s use this library to simplify mapping/conversion between entities / models / dtomedium.com

Features of MapStruct:

Compile-Time Mapping:

  • MapStruct generates mapping code during compile-time, ensuring that mappings are type-safe and checked by the compiler.

No Runtime Overhead:

  • Unlike reflection-based mappers, MapStruct generates plain Java code, making it highly efficient and with no runtime overhead.

Custom Mappings:

  • Developers can define custom mappings for specific fields or transformations.

Automatic Field Mapping:

  • Fields with the same name and compatible types are mapped automatically.

Support for Nested Mapping:

  • MapStruct supports mapping nested objects seamlessly.

Integration with Spring and CDI:

  • MapStruct can integrate with Spring Framework or CDI to inject mappers as beans.

Custom Converters and Expressions:

  • You can use custom conversion methods or expressions for fields that need special transformations.

How It Works:

  1. Define Mapper Interface: Create an interface and annotate it with @Mapper or @Mapper(componentModel = "spring") for Spring integration.
  2. Define Mapping Methods: Specify methods in the interface to convert between source and target types.
  3. Use Generated Mapper: MapStruct generates the implementation of the mapper interface, which you can use directly in your code.

Example:

1. DTO and Entity Classes:

public class UserEntity {
    private String firstName;
    private String lastName;
    private int age;
    // Getters and Setters
}

public class UserDTO {
    private String fullName;
    private int age;
    // Getters and Setters
}

2. Mapper Interface:

import org.mapstruct.*;

@Mapper
public interface UserMapper {
    @Mapping(source = "firstName", target = "fullName", qualifiedByName = "combineName")
    UserDTO toDto(UserEntity entity);
    @Named("combineName")
    default String combineName(String firstName, String lastName) {
        return firstName + " " + lastName;
    }
}

3. Generated Implementation (Generated Automatically):

public class UserMapperImpl implements UserMapper {
    @Override
    public UserDTO toDto(UserEntity entity) {
        if (entity == null) {
            return null;
        }
        UserDTO dto = new UserDTO();
        dto.setFullName(combineName(entity.getFirstName(), entity.getLastName()));
        dto.setAge(entity.getAge());
        return dto;
    }

@Override
    public String combineName(String firstName, String lastName) {
        return firstName + " " + lastName;
    }
}

4. Usage:

UserEntity entity = new UserEntity();
entity.setFirstName("John");
entity.setLastName("Doe");
entity.setAge(25);

UserMapper mapper = Mappers.getMapper(UserMapper.class);
UserDTO dto = mapper.toDto(entity);
System.out.println(dto.getFullName()); // Outputs: John Doe
System.out.println(dto.getAge());     // Outputs: 25

Finally, Let’s relate it to above code and note down benefits of MapStruct:

  1. Minimizes Boilerplate Code: Reduces the manual effort required to write mapping code.
  2. Improves Performance: Generates optimized code, avoiding runtime costs.
  3. Simplifies Maintenance: Generated code is easy to read and debug.
  4. Integration Friendly: Works well with Spring and other frameworks.

Hope this helps!!!


메타데이터
post_id
5ee23effb222
slug
mapstruct-another-way-to-map-between-entity-and-dto-5ee23effb222
url
https://medium.com/@ByteCodeBlogger/mapstruct-another-way-to-map-between-entity-and-dto-5ee23effb222
canonical_url
https://medium.com/@ByteCodeBlogger/mapstruct-another-way-to-map-between-entity-and-dto-5ee23effb222
author_url
https://medium.com/@ByteCodeBlogger
status
ok
fetched_at
2026-08-06 22:44:10