Sobes.tech
Junior — Middle

How do the MapStruct and Lombok libraries work together in code generation for mapping and automatic method creation?

sobes.tech AI

Answer from AI

MapStruct and Lombok are two popular Java libraries that are often used together to simplify development.

  • Lombok automatically generates boilerplate code such as getters, setters, constructors, equals, hashCode, and toString methods using annotations (@Getter, @Setter, @Data, etc.). This reduces boilerplate code in model classes.

  • MapStruct generates code for mapping between objects of different types (e.g., DTO and Entity) at compile time, using interfaces with annotations (@Mapper).

How they work together:

  1. Lombok generates the necessary access methods and constructors in models.
  2. MapStruct uses these generated methods to create mapping code.

For example, if you have a class with the @Data annotation from Lombok, MapStruct can call the getters and setters generated by Lombok to copy data between objects.

Example:

@Data // Lombok generates getters and setters
public class UserDTO {
    private String name;
    private int age;
}

@Data
public class UserEntity {
    private String name;
    private int age;
}

@Mapper
public interface UserMapper {
    UserMapper INSTANCE = Mappers.getMapper(UserMapper.class);
    UserEntity toEntity(UserDTO dto);
    UserDTO toDTO(UserEntity entity);
}

During compilation, Lombok will create the access methods, and MapStruct will generate the implementation of UserMapper, using these methods for field mapping.

Thus, Lombok reduces boilerplate code in models, and MapStruct automatically generates the conversion code between them.