什么是Dto,Entity,用來干什么?
Dto data transfer object 數據傳輸實體,主要用於數據傳輸的實體模型;
Entity 持久層的領域模型;
當我在做分布式微服務的時候,通常是用Entity來做持久層的實體類,Dto來做接口傳輸的實體類。這個時候就有一個麻煩事,Entity和Dto的互轉。通常的轉換方法有兩個途徑,一個是通過反射的方式,來進行對象屬性的復制;另一種是,通過硬編碼進行對象屬性的賦值;
1. 在service層中添加實體類轉換函數
@Service
public MyEntityService {
public SomeDto getEntityById(Long id){
SomeEntity dbResult = someDao.findById(id);
SomeDto dtoResult = convert(dbResult);
// ... more logic happens
return dtoResult;
}
public SomeDto convert(SomeEntity entity){
//... Object creation and using getter/setter for converting
}
}
2. 在各自的實體類中添加轉換函數
public class SomeDto {
// ... some attributes
public SomeDto(SomeEntity entity) {
this.attribute = entity.getAttribute();
// ... nesting convertion & convertion of lists and arrays
}
}
3. 通過反射的方式來進行,目前有common-beanutils,或者springframework的beanutils,或者modelmapper進行更復雜的定制。這樣做得有點就是完全沒有額外的編碼負擔,且通用性強;但是缺點是,性能很低(這里可能比硬編碼的轉換方式多上100倍時間左右)所以對於大數據量的轉換,或者對反應時間敏感的場景,請不要使用;
ModelMapper modelMapper = new ModelMapper();
UserDTO userDTO = modelMapper.map(user, UserDTO.class);
4. 通過mapstruct在編譯階段,創建一個convert類,來進行轉化,優點是自動代碼生成,轉換效率優良;缺點是雖然省略的硬編碼,但是每個實體都需要寫一個轉換接口,着實不是很優雅。
@Mapper
public interface SheetConverter {
@Mappings({})
SheetDto sheetToSheetDto(Sheet sheet);
@Mappings({})
Sheet sheetDtoToSheet(SheetDto sheetDto);
}