**1. 映射類**
```java
/**
* 映射類可以用接口也可以用抽象類,這里我想用抽象類來演示
*/
@Mapper
public abstract class BeforeWithAfterMapper {
public static BeforeWithAfterMapper INSTANCE = Mappers.getMapper(BeforeWithAfterMapper.class);
/**
* 映射前執行的方法
*/
@BeforeMapping
protected void beforeMapping() {
System.out.println("映射前執行的方法!");
}
@Mapping(source = "carId", target = "carDtoId")
@Mapping(source = "carName", target = "carDtoName")
public abstract CarDto toDto(Car source1);
/**
* 完成映射后執行的方法
*/
@AfterMapping
protected void afterMapping() {
System.out.println("完成映射后執行的方法!");
}
}
```
**2. 測試**
```java
@Test
public void testBeforeWithAfterMapper() {
Car car = new Car();
car.setCarId(1001);
car.setCarName("紅旗");
CarDto carDto = BeforeWithAfterMapper.INSTANCE.toDto(car);
System.out.println(carDto);
}
```
控制臺打印的順序如下,可見被注解`@BeforeMapping`和`@AfterMapping`標注的方法先后被執行了。
```
映射前執行的方法!
完成映射后執行的方法!
CarDto(carDtoId=1001, carDtoName=紅旗)
```
**3. 查看MapStruct編譯后的代碼**
```java
public class BeforeWithAfterMapperImpl extends BeforeWithAfterMapper {
public BeforeWithAfterMapperImpl() {
}
public CarDto toDto(Car source1) {
this.beforeMapping();
if (source1 == null) {
return null;
} else {
CarDto carDto = new CarDto();
carDto.setCarDtoId(source1.getCarId());
carDto.setCarDtoName(source1.getCarName());
this.afterMapping();
return carDto;
}
}
}
```
- MapStruct屬性映射
- MapStruct是什么
- maven依賴
- 基本映射
- 字段名不一致的映射
- 字段類型不一致的映射
- 基本數據類型轉換
- 日期格式轉換
- 使用表達式轉換
- 枚舉映射
- 多個源類的映射
- 集合的映射
- 添加自定義映射方法
- 映射前后
- 添加默認值
- 映射異常處理
- SpringDataJPA
- SpringDataJPA是什么
- 與JPA、Hibernate的關系
- 環境搭建
- 簡單CURD操作
- 內部原理
- 主鍵生成策略
- 聯合主鍵
- 查詢方式
- 方法命名規則查詢
- 限制查詢結果查詢
- 注解@Query查詢
- 命名參數查詢
- SpEL表達式查詢
- 原生查詢
- 更新與刪除
- Specification動態查詢
- 核心接口
- 查詢例子
- 分頁查詢與排序
- 多表查詢
- 一對一查詢
- 一對多查詢
- 多對多查詢
- 注意事項
- Specification多表查詢
- @Query多表查詢
- 只查詢指定字段
- 級聯操作
- 加載規則