**1. 3個存在同名屬性也存在不同名屬性的實體類**
```java
@Data
public class Address {
private Integer stuId;
private String address;
}
@Data
public class Score {
private Integer stuId;
private Double score;
}
@Data
public class StudentDto {
private Integer stuId;
private String address;
private Double score;
}
```
**2. 映射接口**
```java
@Mapper
public interface StudentMapper {
StudentMapper INSTANCE = Mappers.getMapper(StudentMapper.class);
/**
* 1)當source1與source2不存在同名的屬性時可以進行自動映射。
* 2)當source1與source2存在同名的屬性時則需要明確指定是哪個source。
*/
@Mapping(source = "source1.stuId", target = "stuId")
StudentDto toDto(Address source1, Score source2);
}
```
**3. 測試**
```java
@Test
public void testStudentMapper() {
Address address = new Address();
Score score = new Score();
address.setStuId(1001);
address.setAddress("亞洲-中國");
score.setStuId(1002);
score.setScore(65.5d);
StudentDto studentDto = StudentMapper.INSTANCE.toDto(address, score);
//Address:Address(stuId=1001, address=亞洲-中國)
System.out.println("Address:" + address);
//Score:Score(stuId=1002, score=65.5)
System.out.println("Score:" + score);
//StudentDto:StudentDto(stuId=1001, address=亞洲-中國, score=65.5)
System.out.println("StudentDto:" + studentDto);
}
```
**4. 查看映射接口被Mapstruct編譯后的代碼**
```java
public class StudentMapperImpl implements StudentMapper {
public StudentMapperImpl() {
}
public StudentDto toDto(Address source1, Score source2) {
if (source1 == null && source2 == null) {
return null;
} else {
StudentDto studentDto = new StudentDto();
if (source1 != null) {
studentDto.setStuId(source1.getStuId());
studentDto.setAddress(source1.getAddress());
}
if (source2 != null) {
studentDto.setScore(source2.getScore());
}
return studentDto;
}
}
}
```
- MapStruct屬性映射
- MapStruct是什么
- maven依賴
- 基本映射
- 字段名不一致的映射
- 字段類型不一致的映射
- 基本數據類型轉換
- 日期格式轉換
- 使用表達式轉換
- 枚舉映射
- 多個源類的映射
- 集合的映射
- 添加自定義映射方法
- 映射前后
- 添加默認值
- 映射異常處理
- SpringDataJPA
- SpringDataJPA是什么
- 與JPA、Hibernate的關系
- 環境搭建
- 簡單CURD操作
- 內部原理
- 主鍵生成策略
- 聯合主鍵
- 查詢方式
- 方法命名規則查詢
- 限制查詢結果查詢
- 注解@Query查詢
- 命名參數查詢
- SpEL表達式查詢
- 原生查詢
- 更新與刪除
- Specification動態查詢
- 核心接口
- 查詢例子
- 分頁查詢與排序
- 多表查詢
- 一對一查詢
- 一對多查詢
- 多對多查詢
- 注意事項
- Specification多表查詢
- @Query多表查詢
- 只查詢指定字段
- 級聯操作
- 加載規則