java~modelMapper需要注意的幾點
對于modelMapper來說,主要實現(xiàn)的是對象與對象的賦值,在這微服務里的數(shù)據(jù)傳輸對象中用的比較多,DTO這個對象是從業(yè)務模型抽象出來的,滿足某一種業(yè)務,它與數(shù)據(jù)持久化模型沒有關(guān)系,而如果我們把數(shù)據(jù)表模型取出后,以DTO返回給使用端時,就需要一種賦值機制,這就是modelMapper需要做的事。
在目前開發(fā)過程中,由于使用了lombok插件,使得我們減少了很多重復的代碼,它以注解的形式體現(xiàn)在代碼上,即@getter表示對外公司讀方法,@setter對外公開寫方法,而后者在設(shè)計時一般不對外公開,為對象的賦值一般通過@Builder來實現(xiàn),但這對于modelMapper是一件壞事 ,它必須要求你公開@setter注解,才可以為你賦值,這也是可以想像的,modelMapper的機制應該就是說取所有字段 ,然后使用自己的setter方法為它賦值。
注意地址:
- 必須公開@setter注解
- DTO對象不能繼承原來的模型,應該新建一個單純的實體,因為注解是可以從父類集成下來的
@Builder(toBuilder = true) @Getter @Setter @AllArgsConstructor @NoArgsConstructor public class UserDto { private String name; }
下面是數(shù)據(jù)模型
@Builder(toBuilder = true) @Getter @NoArgsConstructor @AllArgsConstructor public class UserInfo { private String name; private String email; @MinMoney(message = "金額不能小于0.") @MaxMoney(value = 10, message = "金額不能大于10.") private Money price; }
下面是使用方法,同時可以使用BeanUtils類的方法也可以實現(xiàn)。
modelMapper方法
ModelMapper modelMapper = new ModelMapper(); userDto = modelMapper.map(userinfo, UserDto.class);
BeanUtils方法
UserInfo userinfo= UserInfo.builder().name("zzl").build();
UserDto userDto=new UserDto();
BeanUtils.copyProperties(userinfo,userDto);
感謝閱讀!
浙公網(wǎng)安備 33010602011771號