MapStruct and Lombok are two popular Java libraries that can be used to improve the productivity and maintainability of Java code. However, when used together, they can sometimes lead to compilation errors due to conflicts in their annotation processing. This article will provide a solution to this issue and explain how to properly configure MapStruct and Lombok to work together seamlessly.
The Problem
When MapStruct and Lombok are used together, the compilation process can fail with an error message similar to the following:
Unknown property "id" in result type com.vg.once.dto.OneDto. Did you mean "null"?
This error occurs because MapStruct expects to find getters and setters for the properties of the DTO class, but Lombok generates synthetic accessors and mutators instead. As a result, MapStruct is unable to map the properties of the entity class to the corresponding properties in the DTO class.
The Solution
To resolve this issue, you need to tell MapStruct to use Lombok's synthetic accessors and mutators. This can be done by adding the following annotation to the Mapper interface:
@Mapper(config = LombokProcessorConfig.class)
The LombokProcessorConfig class is a built-in MapStruct configuration class that tells MapStruct to use Lombok's synthetic accessors and mutators.
Example
Here is an example of a Mapper interface that uses Lombok's synthetic accessors and mutators:
@Mapper(config = LombokProcessorConfig.class) public interface OneMapper { @Mapping(target="id", source="one.id") OneDto createOne (One one); }
Additional Considerations
In addition to adding the LombokProcessorConfig annotation, there are a few other things you need to consider when using MapStruct and Lombok together:
<dependency> <groupId>org.mapstruct</groupId> <artifactId>mapstruct-processor</artifactId> <version>${mapstruct.version}</version> <classifier>ap</classifier> </dependency>
Conclusion
By following these steps, you can use MapStruct and Lombok together to improve the productivity and maintainability of your Java code.
The above is the detailed content of How to Resolve Compilation Errors When Using MapStruct and Lombok Together in Java?. For more information, please follow other related articles on the PHP Chinese website!