### Test Object Mapping in QuickStart
Source: https://www.mapstruct.plus/introduction/quick-start
Demonstrate the object mapping functionality by creating instances of source and target objects, converting them using the generated converter, and asserting the mapped values.
```java
public class QuickStart {
private static Converter converter = new Converter();
public static void main(String[] args) {
User user = new User();
user.setUsername("jack");
user.setAge(23);
user.setYoung(false);
UserDto userDto = converter.convert(user, UserDto.class);
System.out.println(userDto); // UserDto{username='jack', age=23, young=false}
assert user.getUsername().equals(userDto.getUsername());
assert user.getAge() == userDto.getAge();
assert user.isYoung() == userDto.isYoung();
User newUser = converter.convert(userDto, User.class);
System.out.println(newUser); // User{username='jack', age=23, young=false}
assert user.getUsername().equals(newUser.getUsername());
assert user.getAge() == newUser.getAge();
assert user.isYoung() == newUser.isYoung();
}
}
```
--------------------------------
### Mapstruct Plus QuickStart Test for Spring Boot
Source: https://www.mapstruct.plus/introduction/quick-start
This Java code demonstrates the usage of Mapstruct Plus in a Spring Boot application. It includes setting up a test class, autowiring a Converter, and performing bidirectional object conversions between User and UserDto objects. Assertions are used to verify the correctness of the conversions.
```java
@SpringBootTest
public class QuickStartTest {
@Autowired
private Converter converter;
@Test
public void test() {
User user = new User();
user.setUsername("jack");
user.setAge(23);
user.setYoung(false);
UserDto userDto = converter.convert(user, UserDto.class);
System.out.println(userDto); // UserDto{username='jack', age=23, young=false}
assert user.getUsername().equals(userDto.getUsername());
assert user.getAge() == userDto.getAge();
assert user.isYoung() == userDto.isYoung();
User newUser = converter.convert(userDto, User.class);
System.out.println(newUser); // User{username='jack', age=23, young=false}
assert user.getUsername().equals(newUser.getUsername());
assert user.getAge() == newUser.getAge();
assert user.isYoung() == newUser.isYoung();
}
}
```
--------------------------------
### Mapstruct Plus QuickStart Test for Solon
Source: https://www.mapstruct.plus/introduction/quick-start
This Java code demonstrates the usage of Mapstruct Plus within a Solon application environment. It features a test class annotated with `@SolonTest` and `@ExtendWith(SolonJUnit5Extension.class)`, injecting a Converter instance and performing bidirectional object conversions between User and UserDto. Assertions validate the accuracy of these conversions.
```java
@SolonTest(DemoApp.class)
@ExtendWith(SolonJUnit5Extension.class)
public class QuickStartTest {
@Inject
private Converter converter;
@Test
public void test() {
User user = new User();
user.setUsername("jack");
user.setAge(23);
user.setYoung(false);
UserDto userDto = converter.convert(user, UserDto.class);
System.out.println(userDto); // UserDto{username='jack', age=23, young=false}
assert user.getUsername().equals(userDto.getUsername());
assert user.getAge() == userDto.getAge();
assert user.isYoung() == userDto.isYoung();
User newUser = converter.convert(userDto, User.class);
System.out.println(newUser); // User{username='jack', age=23, young=false}
assert user.getUsername().equals(newUser.getUsername());
assert user.getAge() == newUser.getAge();
assert user.isYoung() == newUser.isYoung();
}
}
```
--------------------------------
### Add MapStruct Plus Maven Dependency for SpringBoot
Source: https://www.mapstruct.plus/introduction/quick-start
Include the mapstruct-plus-spring-boot-starter dependency in your Maven project for Spring Boot applications. This starter simplifies integration with the Spring environment.
```xml
最新版本io.github.linpeiliemapstruct-plus-spring-boot-starter${mapstruct-plus.version}org.apache.maven.pluginsmaven-compiler-plugin3.8.11.81.8io.github.linpeiliemapstruct-plus-processor${mapstruct-plus.version}
```
--------------------------------
### Add MapStruct Plus Gradle Dependency for SpringBoot
Source: https://www.mapstruct.plus/introduction/quick-start
Add the mapstruct-plus-spring-boot-starter dependency to your Gradle build file for Spring Boot projects. This provides automatic configuration and integration with Spring.
```gradle
dependencies {
implementation group: 'io.github.linpeilie', name: 'mapstruct-plus-spring-boot-starter', version: ${mapstruct-plus.version}
annotationProcessor group: 'io.github.linpeilie', name: 'mapstruct-plus-processor', version: ${mapstruct-plus.version}
}
```
--------------------------------
### Add MapStruct Plus Maven Dependency for Non-SpringBoot
Source: https://www.mapstruct.plus/introduction/quick-start
Include the mapstruct-plus and mapstruct-plus-processor dependencies in your Maven project for non-SpringBoot applications. This enables the annotation processing for generating mappers.
```xml
最新版本io.github.linpeiliemapstruct-plus${mapstruct-plus.version}org.apache.maven.pluginsmaven-compiler-plugin3.8.11.81.8io.github.linpeiliemapstruct-plus-processor${mapstruct-plus.version}
```
--------------------------------
### Mapstruct Plus Maven Dependencies and Compiler Plugin for Solon
Source: https://www.mapstruct.plus/introduction/quick-start
This XML configuration outlines the necessary Maven dependencies and build plugin configurations for integrating Mapstruct Plus with a Solon project. It specifies the mapstruct-plus-solon-plugin dependency and configures the Maven compiler plugin to use the Mapstruct Plus annotation processor, setting the default component model to 'solon'.
```xml
org.dromara.solon-pluginsmapstruct-plus-solon-pluginsorg.apache.maven.pluginsmaven-compiler-plugin3.8.1${java.version}${java.version}io.github.linpeiliemapstruct-plus-processor${mapstruct-plus.version}
-Amapstruct.defaultComponentModel=solon
```
--------------------------------
### Add MapStruct Plus Gradle Dependency for Non-SpringBoot
Source: https://www.mapstruct.plus/introduction/quick-start
Add the mapstruct-plus and mapstruct-plus-processor dependencies to your Gradle build file for non-SpringBoot projects. This ensures the necessary libraries are available for mapping.
```gradle
dependencies {
implementation group: 'io.github.linpeilie', name: 'mapstruct-plus', version: ${mapstruct-plus.version}
annotationProcessor group: 'io.github.linpeilie', name: 'mapstruct-plus-processor', version: ${mapstruct-plus.version}
}
```
--------------------------------
### Configure Mapper ComponentModel in Non-SpringBoot
Source: https://www.mapstruct.plus/introduction/quick-start
Apply the @ComponentModelConfig annotation to a configuration class. This tells MapStruct Plus how to manage the generated mappers, 'default' is used for non-Spring environments.
```java
@ComponentModelConfig(componentModel = "default")
public class MapperConfiguration {
}
```
--------------------------------
### Define Java Classes for Mapping
Source: https://www.mapstruct.plus/introduction/quick-start
Define source and target Java classes for object mapping. These classes typically have fields that need to be mapped between them. MapStruct Plus will generate the mapping logic.
```java
public class UserDto {
private String username;
private int age;
private boolean young;
// getter、setter、toString、equals、hashCode
}
```
```java
public class User {
private String username;
private int age;
private boolean young;
// getter、setter、toString、equals、hashCode
}
```
--------------------------------
### Specify Object Mapping Relationship
Source: https://www.mapstruct.plus/introduction/quick-start
Use the @AutoMapper annotation on one of the classes (e.g., User or UserDto) and set the 'target' attribute to the class it should map to. This defines the bidirectional mapping configuration.
```java
@AutoMapper(target = UserDto.class)
public class User {
// ...
}
```
--------------------------------
### Maven Configuration for Lombok Integration with MapStruct Plus
Source: https://www.mapstruct.plus/guide/faq
This Maven configuration specifies the necessary annotation processors for integrating Lombok with MapStruct Plus. It ensures that both Lombok and the MapStruct Plus processor are available during the compilation phase. This setup is for Lombok versions prior to 1.18.16.
```xml
org.apache.maven.pluginsmaven-compiler-plugin3.8.11.81.8org.projectlomboklombok${lombok.version}io.github.linpeiliemapstruct-plus-processor${mapstruct-plus.version}
```
--------------------------------
### Gradle Configuration for Lombok Integration with MapStruct Plus
Source: https://www.mapstruct.plus/guide/faq
This Gradle configuration defines the annotation processors required for integrating Lombok with MapStruct Plus. It ensures that Lombok, the MapStruct Plus processor, and the Lombok-MapStruct binding are correctly set up for annotation processing. This setup is for Lombok versions prior to 1.18.16.
```gradle
dependencies {
annotationProcessor group: 'org.projectlombok', name: 'lombok', version: {lombok.version}
annotationProcessor group: 'io.github.linpeilie', name: 'mapstruct-plus-processor', version: ${mapstruct-plus.version}
}
```
--------------------------------
### Custom Mapping Rules for Specific Target Classes
Source: https://www.mapstruct.plus/guide/multiple-class-convert
This example illustrates how to define specific mapping rules for different target classes when converting a single source class to multiple targets. It utilizes `@AutoMappings` to group multiple `@AutoMapping` annotations. The `targetClass` attribute within `@AutoMapping` is crucial for applying a rule only to a designated target type (e.g., `UserDto.class` or `UserVO.class`). If `targetClass` is omitted, the rule applies to all target classes. The `expression` attribute allows for custom Java expressions for complex transformations, `dateFormat` for date formatting, `ignore` to skip a field, `numberFormat` for number formatting, and `target` to map to a differently named field in the target class.
```java
@Data
@AutoMappers({
@AutoMapper(target = UserDto.class),
@AutoMapper(target = UserVO.class)
})
public class User {
private String username;
private int age;
private boolean young;
@AutoMapping(targetClass = UserDto.class, target = "educations", expression = "java(java.lang.String.join(\",\", source.getEducationList()))")
private List educationList;
@AutoMappings({
@AutoMapping(targetClass = UserDto.class, dateFormat = "yyyy-MM-dd HH:mm:ss"),
@AutoMapping(targetClass = UserVO.class, ignore = true)
})
private Date birthday;
@AutoMapping(targetClass = UserDto.class, numberFormat = "$0.00")
private double assets;
@AutoMapping(numberFormat = "$0.00")
private double money;
@AutoMappings({
@AutoMapping(targetClass = UserVO.class, target = "voField")
})
private String voField;
}
```
--------------------------------
### MapStruct 使用映射器实例
Source: https://www.mapstruct.plus/mapstruct/1-5-5-Final
展示了如何通过映射器接口的 INSTANCE 属性来访问映射器,并调用映射方法。
```java
Car car = ...;
CarDto dto = CarMapper.INSTANCE.carToCarDto( car );
```
--------------------------------
### Gradle Dependencies for MapStruct
Source: https://www.mapstruct.plus/mapstruct/1-5-5-Final
This snippet illustrates how to integrate MapStruct into a Gradle project by adding the necessary dependencies for implementation and annotation processing. It also includes a note for using MapStruct in test code. Requires Gradle build tool.
```gradle
...
plugins {
...
id "com.diffplug.eclipse.apt" version "3.26.0" // Only for Eclipse
}
dependencies {
...
implementation "org.mapstruct:mapstruct:${mapstructVersion}"
annotationProcessor "org.mapstruct:mapstruct-processor:${mapstructVersion}"
// If you are using mapstruct in test code
testAnnotationProcessor "org.mapstruct:mapstruct-processor:${mapstructVersion}"
}
...
```
--------------------------------
### Add MapStructPlus Dependency for SpringBoot Gradle
Source: https://www.mapstruct.plus/introduction/install
This Gradle snippet configures MapStructPlus for Spring Boot projects. It includes the starter dependency for Spring Boot integration and the annotation processor. Replace '最新版本' with the actual version number you are using.
```gradle
dependencies {
implementation 'io.github.linpeilie:mapstruct-plus-spring-boot-starter:最新版本'
annotationProcessor 'io.github.linpeilie:mapstruct-plus-processor:最新版本'
}
```
--------------------------------
### Add MapStructPlus Dependency for SpringBoot Maven
Source: https://www.mapstruct.plus/introduction/install
This configuration adds the MapStructPlus Spring Boot starter dependency and configures the Maven compiler plugin for Spring Boot projects. It ensures that MapStructPlus integrates seamlessly with the Spring Boot ecosystem. Avoid adding separate MapStruct dependencies.
```xml
最新版本io.github.linpeiliemapstruct-plus-spring-boot-starter${mapstruct-plus.version}org.apache.maven.pluginsmaven-compiler-plugin3.8.11.81.8io.github.linpeiliemapstruct-plus-processor${mapstruct-plus.version}
```
--------------------------------
### MapStruct 构造函数选择规则示例
Source: https://www.mapstruct.plus/mapstruct/1-5-5-Final
展示了 MapStruct 在选择目标类型构造函数时的不同场景。包括默认构造函数、唯一公共构造函数、带 @Default 注解的构造函数,以及导致编译异常的模糊情况。
```java
public class Vehicle {
protected Vehicle() { }
// MapStruct will use this constructor, because it is a single public constructor
public Vehicle(String color) { }
}
public class Car {
// MapStruct will use this constructor, because it is a parameterless empty constructor
public Car() { }
public Car(String make, String color) { }
}
public class Truck {
public Truck() { }
// MapStruct will use this constructor, because it is annotated with @Default
@Default
public Truck(String make, String color) { }
}
public class Van {
// There will be a compilation error when using this class because MapStruct cannot pick a constructor
public Van(String make) { }
public Van(String make, String color) { }
}
```
--------------------------------
### MapStruct 使用 CDI 组件模型
Source: https://www.mapstruct.plus/mapstruct/1-5-5-Final
演示了如何配置 MapStruct 映射器使用 CDI 作为组件模型,从而允许通过依赖注入获取映射器实例。
```java
@Mapper(componentModel = MappingConstants.ComponentModel.CDI) public interface CarMapper {
CarDto carToCarDto(Car car);
}
// Injected example:
@Inject
private CarMapper mapper;
```
--------------------------------
### 在 MapStruct 接口中实现自定义默认映射方法 (Java)
Source: https://www.mapstruct.plus/mapstruct/1-5-5-Final
展示如何在 MapStruct 映射接口中定义一个默认方法来处理无法自动生成的自定义映射逻辑。当映射参数和返回类型匹配时,MapStruct 会调用此自定义方法。
```java
@Mapper
public interface CarMapper {
@Mapping(...) // 假设这里有其他映射配置
...
CarDto carToCarDto(Car car);
default PersonDto personToPersonDto(Person person) {
// hand-written mapping logic
return new PersonDto(); // 示例返回
}
}
```
--------------------------------
### MapStruct 修改已存在的对象实例 (Java)
Source: https://www.mapstruct.plus/mapstruct/1-5-5-Final
演示如何使用 `@MappingTarget` 注解来更新现有的对象实例,而不是创建新对象。可以将目标对象作为参数传递,并用 `@MappingTarget` 标注。
```java
@Mapper
public interface CarMapper {
void updateCarFromDto(CarDto carDto, @MappingTarget Car car);
}
```
--------------------------------
### MapStruct 映射器工厂获取实例
Source: https://www.mapstruct.plus/mapstruct/1-5-5-Final
演示了在不使用依赖注入框架时,如何通过 org.mapstruct.factory.Mappers 类获取 MapStruct 映射器的实例。
```java
CarMapper mapper = Mappers.getMapper( CarMapper.class );
```
--------------------------------
### MapStruct 使用构造函数映射 DTO 到 Bean
Source: https://www.mapstruct.plus/mapstruct/1-5-5-Final
演示了如何定义一个 MapStruct 接口来将一个 DTO 对象映射到一个 Bean 对象,并展示了生成的转换器实现类如何利用构造函数进行映射。
```java
public class Person {
private final String name;
private final String surname;
public Person(String name, String surname) {
this.name = name;
this.surname = surname;
}
}
public interface PersonMapper {
Person map(PersonDto dto);
}
// GENERATED CODE
public class PersonMapperImpl implements PersonMapper {
public Person map(PersonDto dto) {
if (dto == null) {
return null;
}
String name;
String surname;
name = dto.getName();
surname = dto.getSurname();
Person person = new Person( name, surname );
return person;
}
}
```
--------------------------------
### MapStruct 多来源参数映射方法 (Java)
Source: https://www.mapstruct.plus/mapstruct/1-5-5-Final
展示如何使用 MapStruct 映射方法处理来自多个源参数的映射,例如将几个实体组合到一个数据传输对象中。需要指定目标属性的来源。
```java
@Mapper
public interface AddressMapper {
@Mapping(target = "description", source = "person.description")
@Mapping(target = "houseNumber", source = "address.houseNo")
DeliveryAddressDto personAndAddressToDeliveryAddressDto(Person person, Address address);
}
```
--------------------------------
### MapStruct 映射器接口单例声明
Source: https://www.mapstruct.plus/mapstruct/1-5-5-Final
展示了如何在 MapStruct 接口或抽象类中声明一个名为 INSTANCE 的静态 final 属性,以获取映射器的单例实例。
```java
@Mapper
public interface CarMapper {
CarMapper INSTANCE = Mappers.getMapper( CarMapper.class );
CarDto carToCarDto(Car car);
}
@Mapper
public abstract class CarMapper {
public static final CarMapper INSTANCE = Mappers.getMapper( CarMapper.class );
CarDto carToCarDto(Car car);
}
```
--------------------------------
### Maven Configuration for Lombok (1.18.16+) with MapStruct Plus
Source: https://www.mapstruct.plus/guide/faq
This Maven configuration integrates Lombok versions 1.18.16 and later with MapStruct Plus. It includes the necessary annotation processors: Lombok, MapStruct Plus, and the 'lombok-mapstruct-binding' for seamless integration. This ensures proper code generation for mappers.
```xml
org.apache.maven.pluginsmaven-compiler-plugin3.8.11.81.8org.projectlomboklombok${lombok.version}io.github.linpeiliemapstruct-plus-processor${mapstruct-plus.version}org.projectlomboklombok-mapstruct-binding0.2.0
```
--------------------------------
### Maven Dependency and Plugin Configuration for MapStruct
Source: https://www.mapstruct.plus/mapstruct/1-5-5-Final
This snippet shows how to add MapStruct as a dependency and configure the Maven compiler plugin to use the annotation processor. It ensures MapStruct generates mapper implementations during the build process. Requires Maven build tool.
```xml
...
1.5.5.Final
...
org.mapstructmapstruct${org.mapstruct.version}
...
org.apache.maven.pluginsmaven-compiler-plugin3.8.11.81.8org.mapstructmapstruct-processor${org.mapstruct.version}
...
```
--------------------------------
### Add MapStructPlus Dependency for Non-SpringBoot Gradle
Source: https://www.mapstruct.plus/introduction/install
This snippet demonstrates how to add the MapStructPlus dependency for a non-SpringBoot project using Gradle. It includes the main library and the annotation processor. Remember to use the '最新版本' placeholder with your actual latest version.
```gradle
dependencies {
implementation 'io.github.linpeilie:mapstruct-plus:最新版本'
annotationProcessor 'io.github.linpeilie:mapstruct-plus-processor:最新版本'
}
```
--------------------------------
### Gradle Configuration for Lombok (1.18.16+) with MapStruct Plus
Source: https://www.mapstruct.plus/guide/faq
This Gradle configuration sets up integration for Lombok versions 1.18.16 and later with MapStruct Plus. It specifies the annotation processors needed, including Lombok, MapStruct Plus, and the 'lombok-mapstruct-binding' artifact, ensuring correct annotation processing for mapper generation.
```gradle
dependencies {
annotationProcessor group: 'org.projectlombok', name: 'lombok', version: {lombok.version}
annotationProcessor group: 'io.github.linpeilie', name: 'mapstruct-plus-processor', version: ${mapstruct-plus.version}
annotationProcessor group: 'org.projectlombok', name: 'lombok-mapstruct-binding', version: '0.2.0'
}
```
--------------------------------
### Ant Javac Task Configuration for MapStruct
Source: https://www.mapstruct.plus/mapstruct/1-5-5-Final
This snippet demonstrates how to configure the Ant javac task to include MapStruct's annotation processor. It specifies the source and destination directories, as well as the paths to the MapStruct JAR files. Requires Ant build tool.
```xml
...
...
```
--------------------------------
### 在 MapStruct 抽象类中实现自定义方法 (Java)
Source: https://www.mapstruct.plus/mapstruct/1-5-5-Final
演示如何在 MapStruct 抽象映射器类中实现自定义方法。MapStruct 会生成该抽象类的子类,并实现所有非抽象方法,同时调用自定义实现的方法。这种方式允许在抽象类中声明其他属性。
```java
@Mapper
public abstract class CarMapper {
@Mapping(...) // 假设这里有其他映射配置
...
public abstract CarDto carToCarDto(Car car);
public PersonDto personToPersonDto(Person person) {
// hand-written mapping logic
return new PersonDto(); // 示例返回
}
}
```
--------------------------------
### MapStruct 嵌套对象属性映射到目标属性 (Java)
Source: https://www.mapstruct.plus/mapstruct/1-5-5-Final
展示如何使用 `target = ""`, `source = "nestedObject"` 配置来将源对象中嵌套 Bean 的所有属性映射到目标对象。显式定义映射可以解决命名冲突。
```java
@Mapper
public interface CustomerMapper {
@Mapping(target = "name", source = "record.name")
@Mapping(target = ".", source = "record")
@Mapping(target = ".", source = "account")
Customer customerDtoToCustomer(CustomerDto customerDto);
}
```
--------------------------------
### MapStruct 多来源参数:直接引用来源参数 (Java)
Source: https://www.mapstruct.plus/mapstruct/1-5-5-Final
演示 MapStruct 如何直接使用来源参数进行转换,包括非 Bean 类型参数。参数 `hn` 是一个 `Integer` 类型,映射到 `houseNumber` 属性。
```java
@Mapper
public interface AddressMapper {
@Mapping(target = "description", source = "person.description")
@Mapping(target = "houseNumber", source = "hn")
DeliveryAddressDto personAndAddressToDeliveryAddressDto(Person person, Integer hn);
}
```
--------------------------------
### Add MapStructPlus Dependency for Non-SpringBoot Maven
Source: https://www.mapstruct.plus/introduction/install
This snippet shows how to add the MapStructPlus dependency and configure the Maven compiler plugin for a non-SpringBoot environment. Ensure you do not include MapStruct dependencies separately to avoid version conflicts. The compiler plugin is configured for Java 1.8 source and target versions.
```xml
最新版本io.github.linpeiliemapstruct-plus${mapstruct-plus.version}org.apache.maven.pluginsmaven-compiler-plugin3.8.11.81.8io.github.linpeiliemapstruct-plus-processor${mapstruct-plus.version}
```
--------------------------------
### Date Formatting with @AutoMapping 'dateFormat'
Source: https://www.mapstruct.plus/guide/class-convert
Explains how to handle conversions between date/time types and String with specific formats using the 'dateFormat' attribute in @AutoMapping. This is applicable for types like LocalDateTime, Date, and LocalDate.
```java
@Data
@AutoMapper(target = OrderEntity.class)
public class Order {
@AutoMapping(dateFormat = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime orderTime;
@AutoMapping(dateFormat = "yyyy_MM_dd HH:mm:ss")
private Date createTime;
@AutoMapping(target = "orderDate", dateFormat = "yyyy-MM-dd")
private String date;
}
@Data
@AutoMapper(target = Order.class)
public class OrderEntity {
@AutoMapping(dateFormat = "yyyy-MM-dd HH:mm:ss")
private String orderTime;
@AutoMapping(dateFormat = "yyyy_MM_dd HH:mm:ss")
private String createTime;
@AutoMapping(target = "date", dateFormat = "yyyy-MM-dd")
private LocalDate orderDate;
}
```
--------------------------------
### MapStruct 将 Map 映射到 Bean
Source: https://www.mapstruct.plus/mapstruct/1-5-5-Final
展示了如何使用 MapStruct 将一个 Map 映射到一个指定的 Bean 对象,包括使用 @Mapping 注解指定源属性名。
```java
public class Customer {
private Long id;
private String name;
//getters and setter omitted for brevity
}
@Mapper
public interface CustomerMapper {
@Mapping(target = "name", source = "customerName")
Customer toCustomer(Map map);
}
// GENERATED CODE
public class CustomerMapperImpl implements CustomerMapper {
@Override
public Customer toCustomer(Map map) {
// ...
if ( map.containsKey( "id" ) ) {
customer.setId( Integer.parseInt( map.get( "id" ) ) );
}
if ( map.containsKey( "customerName" ) ) {
customer.setName( map.get( "customerName" ) );
}
// ...
}
}
```
--------------------------------
### Configure Multiple Target Classes with @AutoMappers
Source: https://www.mapstruct.plus/guide/multiple-class-convert
This snippet demonstrates how to configure a single source class (`User`) to be mapped to multiple target classes (`UserDto`, `UserVO`) using the `@AutoMappers` annotation. Each `@AutoMapper` within `@AutoMappers` specifies a distinct target class for conversion. This is useful when a single data object needs to be represented in different formats for different parts of an application.
```java
@Data
@AutoMappers({
@AutoMapper(target = UserDto.class),
@AutoMapper(target = UserVO.class)
})
public class User {
// fields
}
```
--------------------------------
### Nested Custom Object Mapping
Source: https://www.mapstruct.plus/guide/class-convert
Explains how MapStruct Plus handles mapping between classes containing nested custom objects. It automatically finds and uses mappers for these nested types. For instance, when mapping Car to CarDto, it will use the SeatConfigurationToSeatConfigurationDtoMapper if defined.
```java
@AutoMapper(target = CarDto.class)
@Data
public class Car {
private SeatConfiguration seatConfiguration;
}
@Data
public class CarDto {
private SeatConfigurationDto seatConfiguration;
}
@Data
@AutoMapper(target = SeatConfigurationDto.class)
public class SeatConfiguration {
// fields
}
@Data
public class SeatConfigurationDto {
// fields
}
```
--------------------------------
### Simple Class Conversion with @AutoMapper
Source: https://www.mapstruct.plus/guide/class-convert
Demonstrates how to generate mappers between two classes using the @AutoMapper annotation. The 'target' attribute specifies the destination class. By default, MapStruct Plus generates mappers for both directions (source to target and target to source) unless 'reverseConvertGenerate' is set to false.
```java
@AutoMapper(target = CarDto.class)
public class Car {
// ...
}
```
--------------------------------
### Custom Type Converter with @AutoMapper 'uses'
Source: https://www.mapstruct.plus/guide/class-convert
Illustrates how to introduce custom type converters for transforming properties of different types. This involves creating a converter class (e.g., StringToListString) and referencing it in the @AutoMapper annotation using the 'uses' attribute. The converter method can be static or non-static. For Spring Boot applications, the converter must be a Spring Bean.
```java
@Component
public class StringToListString {
public List stringToListString(String str) {
return StrUtil.split(str);
}
}
@AutoMapper(target = User.class, uses = StringToListStringConverter.class)
public class UserDto {
private String username;
private int age;
private boolean young;
@AutoMapping(target = "educationList")
private String educations;
// ...
}
@SpringBootTest
public class QuickStartTest {
@Autowired
private Converter converter;
@Test
public void ueseTest() {
UserDto userDto = new UserDto();
userDto.setEducations("1,2,3");
final User user = converter.convert(userDto, User.class);
System.out.println(user.getEducationList()); // [1, 2, 3]
assert user.getEducationList().size() == 3;
}
}
```
--------------------------------
### Immutable Type Conversion in MapStruct Plus
Source: https://www.mapstruct.plus/guide/class-convert
Demonstrates the conversion method signature for immutable types in MapStruct Plus. When a target type is marked as immutable using the @Immutable annotation, the `convert` method with a `@MappingTarget` parameter will simply return the target object, as modifications are not applicable to immutable types.
```java
public T convert(S source, @MappingTarget T target) {
return target;
}
```
--------------------------------
### Java Cross-Module Enum Mapping with 'useEnums' in @AutoMapper
Source: https://www.mapstruct.plus/guide/enum-convert
Explains how to enable automatic enum conversion across different modules using the 'useEnums' attribute within the @AutoMapper annotation. This is necessary when the enum and the using class are not in the same module. Enums specified in 'useEnums' must be annotated with @AutoEnumMapper.
```java
@AutoMapper(target = TargetClass.class, useEnums = {Enum1.class, Enum2.class})
public class SourceClass {
// ... fields that use enums
}
```
--------------------------------
### Custom Property Mapping with @AutoMapping
Source: https://www.mapstruct.plus/guide/class-convert
Details how to customize property mapping when attribute names or types differ between source and target classes using the @AutoMapping annotation. The 'target' attribute specifies the destination property name, and the 'source' attribute can be used for nested property access.
```java
@AutoMapper(target = CarDto.class)
@Data
public class Car {
@AutoMapping(target = "seat")
private SeatConfiguration seatConfiguration;
}
@Data
@AutoMapper(target = GoodsVo.class, reverseConvertGenerate = false)
public class Goods {
@AutoMapping(source = "sku.price", target = "price")
private Sku sku;
}
@Data
public class GoodsVo {
private Integer price;
}
```
--------------------------------
### Java Enum Automatic Mapping with @AutoEnumMapper
Source: https://www.mapstruct.plus/guide/enum-convert
Demonstrates how to use the @AutoEnumMapper annotation on an enum to enable automatic conversion. This requires a unique field within the enum, specified in the annotation's 'value' attribute. The enum and the using class must be in the same module.
```java
@Getter
@AllArgsConstructor
@AutoEnumMapper("state")
public enum GoodsStateEnum {
ENABLED(1, "启用"),
DISABLED(0, "禁用");
private final Integer state;
private final String desc;
}
```
```java
@Data
@AutoMapper(target = GoodsVo.class, reverseConvertGenerate = false)
public class Goods {
private GoodsStateEnum state;
}
```
```java
@Data
public class GoodsVo {
private Integer state;
}
```
```java
@Test
public void enumMapTest() {
final GoodsVo goodsVo = converter.convert(goods, GoodsVo.class);
System.out.println(goodsVo);
Assert.equals(goodsVo.getState(), goods.getState().getState());
final Goods goods2 = converter.convert(goodsVo, Goods.class);
System.out.println(goods2);
Assert.equals(goods2.getState(), GoodsStateEnum.ENABLED);
}
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.