**1. 兩個存在字段類型不一致的實體類**
```java
@Data
public class Flight {
private String flightId;
private String flightName;
private String createTime;
}
@Data
public class FlightDto {
private String flightDtoId;
private String flightDtoName;
private LocalDateTime createTime;
}
```
**2. 映射接口**
```java
//imports將表達式用到的相關類導入到當前類中
@Mapper(imports = {DateUtils.class, UUID.class})
public interface FlightMapper {
FlightMapper INSTANCE = Mappers.getMapper(FlightMapper.class);
//flightDtoId取值為表達式expression的返回值
@Mapping(target = "flightDtoId", expression = "java(UUID.randomUUID().toString())")
//當flightName為null時,flightDtoName取值為defaultExpression的返回值
@Mapping(source = "flightName", target = "flightDtoName", defaultExpression = "java(UUID.randomUUID().toString())")
//當類型不一致時可以使用expression表達式進行轉換
@Mapping(target = "createTime", expression = "java(DateUtils.strToLocalDateTime(source.getCreateTime()))")
FlightDto toDto(Flight source);
//如果不使用imports屬性,則需要在表達式中寫全名
//@Mapping(, expression="java(java.util.UUID.randomUUID().toString())")
}
```
我定義的`DateUtils.strToLocalDateTime(...)`方法如下:
```java
public class DateUtils {
public static LocalDateTime strToLocalDateTime(String str) {
DateTimeFormatter df = DateTimeFormatter.ofPattern("yyy-MM-dd HH:mm:ss");
return LocalDateTime.parse(str, df);
}
}
```
**3. 測試**
```java
@Test
public void testFlightMapper() {
Flight flight = new Flight();
flight.setFlightId("10001");
flight.setFlightName(null );
flight.setCreateTime("2021-10-21 10:38:29");
FlightDto flightDto = FlightMapper.INSTANCE.toDto(flight);
//Flight:Flight(flightId=10001, flightName=null, createTime=2021-10-21 10:38:29)
System.out.println("Flight:" + flight);
//FlightDto:FlightDto(flightDtoId=48c367e7-..., flightDtoName=2bc3454e-..., createTime=2021-10-21T10:38:29)
System.out.println("FlightDto:" + flightDto);
}
```
**4. 查看映射接口被Mapstruct編譯后的代碼**
```java
public class FlightMapperImpl implements FlightMapper {
public FlightMapperImpl() {
}
public FlightDto toDto(Flight source) {
if (source == null) {
return null;
} else {
FlightDto flightDto = new FlightDto();
if (source.getFlightName() != null) {
flightDto.setFlightDtoName(source.getFlightName());
} else {
flightDto.setFlightDtoName(UUID.randomUUID().toString());
}
flightDto.setFlightDtoId(UUID.randomUUID().toString());
flightDto.setCreateTime(DateUtils.strToLocalDateTime(source.getCreateTime()));
return flightDto;
}
}
}
```
- MapStruct屬性映射
- MapStruct是什么
- maven依賴
- 基本映射
- 字段名不一致的映射
- 字段類型不一致的映射
- 基本數據類型轉換
- 日期格式轉換
- 使用表達式轉換
- 枚舉映射
- 多個源類的映射
- 集合的映射
- 添加自定義映射方法
- 映射前后
- 添加默認值
- 映射異常處理
- SpringDataJPA
- SpringDataJPA是什么
- 與JPA、Hibernate的關系
- 環境搭建
- 簡單CURD操作
- 內部原理
- 主鍵生成策略
- 聯合主鍵
- 查詢方式
- 方法命名規則查詢
- 限制查詢結果查詢
- 注解@Query查詢
- 命名參數查詢
- SpEL表達式查詢
- 原生查詢
- 更新與刪除
- Specification動態查詢
- 核心接口
- 查詢例子
- 分頁查詢與排序
- 多表查詢
- 一對一查詢
- 一對多查詢
- 多對多查詢
- 注意事項
- Specification多表查詢
- @Query多表查詢
- 只查詢指定字段
- 級聯操作
- 加載規則