**1. 兩個字段名不一致的實體類**
```java
@Data
public class Car {
private Integer carId;
private String carName;
}
@Data
public class CarDto {
private Integer carDtoId;
private String carDtoName;
}
```
**2. 映射接口**
```java
@Mapper
public interface CarMapper {
CarMapper INSTANCE = Mappers.getMapper(CarMapper.class);
/**
* 使用@Mapping的source和target讓兩個實體類的屬性進行對應
*/
@Mapping(source = "carId", target = "carDtoId")
@Mapping(source = "carName", target = "carDtoName")
CarDto toDto(Car source);
}
```
**3. 測試**
```java
@Test
public void testCarMapper() {
Car car = new Car();
car.setCarId(1001);
car.setCarName("紅旗");
CarDto carDto = CarMapper.INSTANCE.toDto(car);
//Car:Car(carId=1001, carName=紅旗)
System.out.println("Car:" + car);
//Car-->CarDto:CarDto(carDtoId=1001, carDtoName=紅旗)
System.out.println("Car-->CarDto:" + carDto);
}
```
**4. 查看映射接口被Mapstruct編譯后的代碼**
```java
public class CarMapperImpl implements CarMapper {
public CarMapperImpl() {
}
public CarDto toDto(Car source) {
if (source == null) {
return null;
} else {
CarDto carDto = new CarDto();
carDto.setCarDtoId(source.getCarId());
carDto.setCarDtoName(source.getCarName());
return carDto;
}
}
}
```
- MapStruct屬性映射
- MapStruct是什么
- maven依賴
- 基本映射
- 字段名不一致的映射
- 字段類型不一致的映射
- 基本數據類型轉換
- 日期格式轉換
- 使用表達式轉換
- 枚舉映射
- 多個源類的映射
- 集合的映射
- 添加自定義映射方法
- 映射前后
- 添加默認值
- 映射異常處理
- SpringDataJPA
- SpringDataJPA是什么
- 與JPA、Hibernate的關系
- 環境搭建
- 簡單CURD操作
- 內部原理
- 主鍵生成策略
- 聯合主鍵
- 查詢方式
- 方法命名規則查詢
- 限制查詢結果查詢
- 注解@Query查詢
- 命名參數查詢
- SpEL表達式查詢
- 原生查詢
- 更新與刪除
- Specification動態查詢
- 核心接口
- 查詢例子
- 分頁查詢與排序
- 多表查詢
- 一對一查詢
- 一對多查詢
- 多對多查詢
- 注意事項
- Specification多表查詢
- @Query多表查詢
- 只查詢指定字段
- 級聯操作
- 加載規則