一般都是定义一个映射的接口类,并在类上标记注解@Mapper 。定义抽象类也可以。这里先说接口类
在类中定义一个单例的实例对象INSTANCE
XxxMapper INSTANCE = Mappers.getMapper(XxxMapper.class);
就可以使用了
public interface XxxMapper {
XxxMapper INSTANCE = Mappers.getMapper(XxxMapper.class);
@Mappings({
//不同名字段映射
@Mapping(source = "ad.id", target = "thirdPartyAdId"),
//将传入的参数变量设置为目标字段的值(跟上面的不同名映射不一样)
@Mapping(source = "positionType", target = "posType"),
//将源对象里面拓展字段(对象里的对象)设置在目标对象首层里对应的属性中(扁平化)
@Mapping(source = "extMap", target = "."),
//忽略某个对象下某个字段
@Mapping(target = "appInfo.appTags", ignore = true),
//通过表达式对目标字段使用固定枚举值,需要在@Mapper注解中使用imports导入该枚举类
@Mapping(target = "dsp", expression = "java(DspTypeEnum.TENCENT.getValue())"),
//也可以通过表达式赋予当前时间
@Mapping(target = "createTime", expression = "java(new java.util.Date())"),
//当源字段为空时,目标字段使用默认值
@Mapping(source = "from", target = "from", defaultValue = "mixer"),
//目标字段直接写死固定值的情况
@Mapping(target = "platformType", constant = "normal"),
//需要逻辑处理的字段,使用qualifiedByName指定处理方法,就在本类中定义处理方法并用@Named注解
@Mapping(source = "ad.ecpmE3", target = "ecpm", qualifiedByName = "ecpmE3ToEcpm"),
//自定义方法需传入多个参数时,使用表达式传入即可
@Mapping(target = "expireSeconds", expression = "java(XxxMapper.INSTANCE.expireSecondsConvertor(ad.getEndTime(), defaultExpireSeconds))"),
})
Ad toAd(com.tencent.platform.ad.mixer.protocol.entity.Ad tencentAd, int positionType, Long defaultExpireSeconds);
@Named("styleCodeConverter")
default int styleCodeConverter(int positionType){
if (positionType == PositionTypeEnum.DISTRIBUTE.getValue()) {
//应用样式广告
return StyleCodeEnum.APPLICATION.getValue();
}
//默认为H5样式
return StyleCodeEnum.H5.getValue();
}
@Named("ecpmE3ToEcpm")
default BigDecimal ecpmE3ToEcpm(Long ecpmE3) {
if (ecpmE3 != null) {
//ecpmE3 千分比,需要除以1000
return BigDecimal.valueOf(ecpmE3).divide(BigDecimal.valueOf(1000), 4, RoundingMode.HALF_UP);
}
return null;
}
@Named("expireSecondsConvertor")
default int expireSecondsConvertor(long endTime, long defaultExpireSeconds){
//endTime和defaultEndTime哪个小返回哪个
if (endTime > 0) {
long differenceInSeconds = (endTime - System.currentTimeMillis()) / 1000;
return (int) Math.min(defaultExpireSeconds, differenceInSeconds);
}
return (int) defaultExpireSeconds;
}
}
只更新部分字段(不是new一个新目标对象),并对部分字段做处理
@Mapping(source = "ad.id", target = "thirdPartyAdId")
@Mapping(target = "expire", ignore = true)
@Mapping(source = "extMap", target = ".")
void toUserVO2(com.tencent.platform.ad.mixer.protocol.entity.Ad tencentAd, @MappingTarget Ad ad);
也可以引入Spring的Bean,使用已有的方法做逻辑处理
@Mapper(componentModel = "spring")
public abstract class YyyMapper{
@Autowired
protected AdService adService;
@Mapping(target = "imei", expression = "java(adService.encryptImei(ad.getImei()))")
public abstract Ad sourceToTarget(TencentAd ad);
}