參考
步驟
- pom.xml dependencies 中添加
<dependency>
<groupId>org.modelmapper</groupId>
<artifactId>modelmapper</artifactId>
<version>2.4.2</version>
</dependency>
- 入口文件注冊 @Bean
public class SuddenlyNlineLearningPlatformApplication {
// 裝配bean 實現dto轉換類自動注入
@Bean
public ModelMapper modelMapper() {
return new ModelMapper();
}
public static void main(String[] args) {
SpringApplication.run(SuddenlyNlineLearningPlatformApplication.class, args);
}
}
- 根據實體創建對應接口相應的 DTO 類
學生實體參考:
public class Student implements Serializable {
/**
* 序列化安全
*/
private static final long serialVersionUID = 1L;
private Integer id;
/**
* 賬號
*/
private String account;
/**
* 密碼
*/
private String password;
/**
* 用戶名
*/
private String name;
/**
* 頭像
*/
private String avatarUrl;
/**
* 性別
*/
private Byte gender;
/**
* 手機號
*/
private String phoneNumber;
/**
* 手機號驗證狀態
*/
private byte phoneVerificationStatus;
/**
* 賬號
*/
private String bewrite;
/**
* 創建時間
*/
private Date createdAt;
/**
* 更新時間
*/
private Date updatedAt;
}
接口不想顯示密碼與實踐字段,創建對應的DAO,DAO參考
public class InfoStudentDto implements Serializable {
/**
* 序列化安全
*/
private static final long serialVersionUID = 1L;
private Integer id;
/**
* 用戶名
*/
private String name;
/**
* 頭像
*/
private String avatarUrl;
/**
* 性別
*/
private Byte gender;
/**
* 手機號
*/
private String phoneNumber;
}
- 在控制器內使用
public class Info {
@Autowired
StudentService studentService;
// 自動注入
@Autowired
ModelMapper modelMapper;
/**
* 根據id獲取學生信息
*/
@ApiOperation(value = "顯示學生信息", notes = "查看別人的(隱藏部分字段)")
@ApiImplicitParam(name = "id", value = "學生id", required = true,
dataType = "int", paramType = "query")
@RequestMapping(value = "show", method = RequestMethod.GET)
public ResponseEntity<ResponseBody<InfoStudentDto>> show(@RequestParam("id") Integer id){
// 轉換
InfoStudentDto infoStudentDto = modelMapper.map(studentService.findById(id), InfoStudentDto.class);
return ResponseEntity.ok( new ResponseBody(infoStudentDto));
}
}
- 運行測試
總結
- 沒有演示如何轉換list
- 沒有測試DTO轉實體