MapStruct 代码展示
时间: 2023-07-09 09:52:43 浏览: 43
好的,下面是一个简单的示例,展示了如何使用 MapStruct 实现字段到字段的映射。
假设有两个类:Source 和 Target,它们的字段名不同,需要进行映射。
```java
public class Source {
private String name;
private int age;
// getter 和 setter 略
}
public class Target {
private String fullName;
private int yearsOld;
// getter 和 setter 略
}
```
首先,需要定义一个 Mapper 接口,使用 `@Mapper` 注解标注该接口,并在该接口中定义一个抽象方法,用于实现字段映射。
```java
@Mapper
public interface SourceTargetMapper {
SourceTargetMapper INSTANCE = Mappers.getMapper(SourceTargetMapper.class);
@Mapping(source = "name", target = "fullName")
@Mapping(source = "age", target = "yearsOld")
Target sourceToTarget(Source source);
}
```
上述代码中,我们使用 `@Mapper` 注解标注了 `SourceTargetMapper` 接口,并定义了一个抽象方法 `sourceToTarget`,该方法用于将 `Source` 类型的对象映射为 `Target` 类型的对象。
在 `sourceToTarget` 方法上,我们使用 `@Mapping` 注解标注了两个字段的映射关系:`name` 字段映射到 `fullName` 字段,`age` 字段映射到 `yearsOld` 字段。
最后,我们通过 `Mappers.getMapper` 方法获取一个 `SourceTargetMapper` 实例,然后就可以使用 `sourceToTarget` 方法进行字段映射了。
```java
Source source = new Source();
source.setName("张三");
source.setAge(20);
Target target = SourceTargetMapper.INSTANCE.sourceToTarget(source);
System.out.println(target.getFullName()); // 输出:张三
System.out.println(target.getYearsOld()); // 输出:20
```
上述代码中,我们创建了一个 `Source` 对象,设置了 `name` 和 `age` 两个字段的值,然后通过 `SourceTargetMapper.INSTANCE.sourceToTarget(source)` 方法将 `Source` 对象映射为 `Target` 对象,并输出了映射后的结果。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)