• mapstruct更新现有实体忽略null空值


    JPA在做更新的时候经常要判断不是null的字段进行set很麻烦。

    例如:目标实体 A.a1=1,A.a2=2 源实体 B.a1=null,B.a2=1。要实现转换后 A.a1=1,A.a2=1。

    1、class上加注解。这个注解参数好像1.3版本以后才开始有的。

    @Mapper(nullValuePropertyMappingStrategy = NullValuePropertyMappingStrategy.IGNORE)

    2、必须用更新现有的Bean的方法。

    void updateAFromB(B b, @MappingTarget A a);

    mapstruct 1.3.1版文档原文

    10.6. Controlling mapping result for ‘null’ properties in bean mappings (update mapping methods only).

    MapStruct offers control over the property to set in an@MappingTargetannotated target bean when the source property equalsnullor the presence check method results in ‘absent’.

    By default the target property will be set to null.

    However:

    1. By specifyingnullValuePropertyMappingStrategy = NullValuePropertyMappingStrategy.SET_TO_DEFAULTon@Mapping,@BeanMapping,@Mapperor@MappingConfig, the mapping result can be altered to returndefaultvalues. ForListMapStruct generates anArrayList, forMapaHashMap, for arrays an empty array, forString``""and for primitive / boxed types a representation offalseor0. For all other objects an new instance is created. Please note that a default constructor is required. If not available, use the@Mapping#defaultValue.

    2. By specifyingnullValuePropertyMappingStrategy = NullValuePropertyMappingStrategy.IGNOREon@Mapping,@BeanMapping,@Mapperor@MappingConfig, the mapping result will be equal to the original value of the@MappingTargetannotated target.

    The strategy works in a hierarchical fashion. SettingMapping#nullValuePropertyMappingStrategyon mapping level will overridenullValuePropertyMappingStrategyon mapping method level will override@Mapper#nullValuePropertyMappingStrategy, and@Mapper#nullValuePropertyMappingStrategywill override@MappingConfig#nullValuePropertyMappingStrategy.

  • 相关阅读:
    C++STL面试详解
    视频如何拼接?建议收藏这些方法
    【软考 系统架构设计师】案例分析③ 面向对象设计
    【免费源码下载】完美运营版商城 虚拟商品全功能商城 全能商城小程序 智慧商城系统 全品类百货商城php+uniapp
    18 方差分析
    Echarts社区新地址
    这世上又多了一只爬虫(spiderflow)
    FastDFS模拟场景
    DirectX12学习笔记-创建窗口
    【Flutter组件】路由与导航
  • 原文地址:https://blog.csdn.net/fwdwqdwq/article/details/126434954