美文网首页
MapStruct数据转换涉及非静态方法

MapStruct数据转换涉及非静态方法

作者: 灿烂的GL | 来源:发表于2023-06-20 16:27 被阅读0次

技术场景:mapStruct将DO转化成DTO的时候涉及到字段的转换,转换方法是非静态方法,需要从数据库获取数据进行转换

业务场景:数据库存储的是省市的编码,查询后需要将省市编码转换成省市名,方便前端显示

方案设计:将省市名和编码作为初始化数据取出,然后通过mapStruct转化将编码转化成编码名

实现步骤:
1、省市编码在程序初始化的就加载到缓存,通过指定方法调取

@Component
public class DeviceCityInitHelper {

    @Resource
    DeviceMapper deviceMapper;

    private static Map<String, String> DEVICE_CITY_INIT_DATA = new HashMap<>(50);

    /**
     * 初始化省市编码信息到缓存
     */
    @PostConstruct
    private void init(){
        List<DeviceCityDO> allDeviceAndCityList = deviceMapper.selectProvinceAndCityInfo();
        Map<String, String> allDeviceAndCityMap = new HashMap<>(allDeviceAndCityList.size());
        allDeviceAndCityList.stream().forEach(e->
                allDeviceAndCityMap.put(e.getCode(),e.getName())
        );
        DEVICE_CITY_INIT_DATA = allDeviceAndCityMap;

    }

    /**
     *根据code获取名字(省/市)
     * @param code
     * @return
     */
    public static String getNameByCode(String code){
            return DEVICE_CITY_INIT_DATA.get(code);
    }

}

2、mapStruct转换

@Mapping(target = "province", expression = "java(DeviceCityInitHelper.getNameByCode(deviceDO.getProvinceCode()))")
@Mapping(target = "city", expression = "java(DeviceCityInitHelper.getNameByCode(deviceDO.getCityCode()))")
DeviceInfoDTO do2Dto(DeviceDO deviceDO);

相关文章

网友评论

      本文标题:MapStruct数据转换涉及非静态方法

      本文链接:https://www.haomeiwen.com/subject/udnyydtx.html