Understanding @Mapping(target = "field", source = "") in MapStruct

Published on 2024.02.07

Introduction

MapStruct is a powerful code generation tool that simplifies the mapping between Java beans. It generates boilerplate code for mapping properties between two beans, eliminating the need to write it manually. One of the core annotations provided by MapStruct is @Mapping, which allows you to define custom mappings between fields.

The @Mapping Annotation

The @Mapping annotation in MapStruct is used to specify how a particular property of the source bean should be mapped to a property in the target bean. It provides the source and target attributes to define the source and target fields respectively.

Using @Mapping(target = "field", source = "")

The @Mapping(target = "field", source = "") allows you to explicitly specify which field from the source bean should be mapped to a specific field in the target bean.

@Mapping(target = "name", source = "fullName")

In the example above, the name field in the target bean will be mapped from the fullName field in the source bean.

Mapping with Different Names

Sometimes, the fields in the source and target beans may have different names. In such cases, you can use the source attribute to specify the source field's name.

@Mapping(target = "title", source = "name")

Here, the title field in the target bean will be mapped from the name field in the source bean.

Mapping with Complex Objects

MapStruct also supports mapping complex objects. You can use . operator to access properties of the complex objects.

@Mapping(target = "address.street", source = "fullAddress")

In this example, the street property of the address object in the target bean will be mapped from the fullAddress property in the source bean.

Conclusion

In this article, we have explored the usage of @Mapping(target = "field", source = "") in MapStruct. It allows you to define custom mappings between fields of source and target beans. By using this annotation, you can easily control the mapping of properties, even when they have different names or are part of complex objects. MapStruct simplifies the mapping process and reduces the boilerplate code, making it a valuable tool for Java developers.