mapstruct自定义转换,怎样将String转化为List

源码:https://gitee.com/cao_wen_bin/test
最近在公司遇到了这样一个为题,前端传过来的是一个List<Manager>,往数据库中保存到时候是String,这个String使用谷歌的json转化器。
当查询的时候在将这个数据库中String的数据以List<Manager>的形式返回给前端。
使用mapstruct中在怎样将String转化为List。在此记录一下。

1.引入依赖

<!--mapstruct-->
<dependency><groupId>org.mapstruct</groupId><artifactId>mapstruct</artifactId><version>1.5.5.Final</version>
</dependency>
<dependency><groupId>org.mapstruct</groupId><artifactId>mapstruct-processor</artifactId><version>1.5.5.Final</version>
</dependency>

2.PO->DTO

package com.cao.pojo;import lombok.Data;
import lombok.ToString;
import lombok.experimental.Accessors;@Data
@Accessors(chain = true)
@ToString
public class Manager {private String name;private String code;
}

需求是将PO转化为DTO,但是PO中的类型是String,而DTO中的类型是List

ManagerPO中的acctManagerList属性是String

package com.cao.po;import lombok.Data;
import lombok.ToString;
import lombok.experimental.Accessors;@Data
@Accessors(chain = true)
@ToString
public class ManagerPO {private Long id;private String acctManagerListString;
}

ManagerDTO中的acctManagerList属性是List<Manager>

package com.cao.dto;import com.cao.pojo.Manager;
import lombok.Data;
import lombok.ToString;
import lombok.experimental.Accessors;import java.util.List;
@Data
@Accessors(chain = true)
@ToString
public class ManagerDTO {private Long id;private List<Manager> acctManagerList;
}

3.编写转换代码

因为我是使用的Gson把List<Manager>转换为String,所以从String转换为List<Manager>也要用相同的json转换,不然会出现异常

import com.cao.dto.ManagerDTO;
import com.cao.po.ManagerPO;
import com.cao.pojo.Manager;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.apache.commons.lang3.StringUtils;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.factory.Mappers;import java.util.List;@Mapper
public interface ManagerBeanConvert {ManagerBeanConvert INSTANCE = Mappers.getMapper(ManagerBeanConvert.class);@Mapping(target = "id", source = "id")@Mapping(target = "acctManagerList", expression = "java(MapStruct.strToList(managerPO.getAcctManagerListString()))")ManagerDTO po2Dto(ManagerPO managerPO);@Mapping(target = "id", source = "id")@Mapping(target = "acctManagerListString", expression = "java(MapStruct.listToStr(managerDTO.getAcctManagerList()))")ManagerPO dto2Po(ManagerDTO managerDTO);class MapStruct {/*** po中的String转为dto中的list*/public static List<Manager> strToList(String acctManagerListString) {if (StringUtils.isNotEmpty(acctManagerListString)) {// 将po中的acctManagerListString用Gson转换成为list(必须和list转String使用相同的转换器)List<Manager> managerList = new Gson().fromJson(acctManagerListString, new TypeToken<List<Manager>>() {}.getType());return managerList;}return null;}/*** dto中的list转为po中的String*/public static String listToStr(List<Manager> managerList) {if (!CollectionUtils.isEmpty(managerList)) {// 将dto中的acctManagerList用Gson转换成为String(必须和String转list使用相同的转换器)String managerListString = new Gson().toJson(managerList);return managerListString;}return null;}}
}

4.测试代码和测试

import com.cao.beanconvert.ManagerBeanConvert;
import com.cao.dto.ManagerDTO;
import com.cao.po.ManagerPO;
import com.cao.pojo.Manager;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;import java.util.*;
@Slf4j
public class BeanConvertTest {public static void main(String[] args) {// po中的String转为dto中的listpoString2DtoList();System.out.println("=====================");// dto中的list转为po中的StringdtoList2PoString();}private static void dtoList2PoString() {List<Manager> managerList = new ArrayList<>();managerList.add(new Manager().setCode("0001").setName("管理员1号"));managerList.add(new Manager().setCode("0002").setName("管理员2号"));ManagerDTO managerDTO = new ManagerDTO().setId(3L).setAcctManagerList(managerList);log.info("managerDTO是: {}",managerDTO);ManagerPO managerPO = ManagerBeanConvert.INSTANCE.dto2Po(managerDTO);log.info("managerDTO转换为managerPO结果是: {}",managerPO);}private static void poString2DtoList() {//设置List<Manager>List<Manager> managerList = new ArrayList<>();managerList.add(new Manager().setCode("0001").setName("管理员1号"));managerList.add(new Manager().setCode("0002").setName("管理员2号"));//使用Gson将list转换成StringString managerListString = new Gson().toJson(managerList);ManagerPO managerPO = new ManagerPO();managerPO.setId(1L).setAcctManagerListString(managerListString);log.info("managerPO是:{}",managerPO);ManagerDTO managerDTO = ManagerBeanConvert.INSTANCE.po2Dto(managerPO);log.info("managerPO转换为managerDTO结果是: {}",managerDTO);}
}

在这里插入图片描述

5.改造

虽然上面的写法已经可以满足需求了,但是在ManagerBeanConvert接口中写内部类的话不规范,所以要修改。
新建一个专门的用于类型属性的转换的类AttributeConvertUtil,将接口中的内部类挪到这个新建的类中,并在方法上面加上@Named(“别名”)

import com.cao.pojo.Manager;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.apache.commons.lang3.StringUtils;
import org.mapstruct.Named;
import org.springframework.util.CollectionUtils;import java.util.List;public class AttributeConvertUtil {/*** po中的String转为dto中的list*/@Named("strToList")public List<Manager> strToList(String acctManagerListString) {if (StringUtils.isNotEmpty(acctManagerListString)) {// 将po中的acctManagerListString用Gson转换成为list(必须和list转String使用相同的转换器)List<Manager> managerList = new Gson().fromJson(acctManagerListString, new TypeToken<List<Manager>>() {}.getType());return managerList;}return null;}/*** dto中的list转为po中的String*/@Named("listToStr")public String listToStr(List<Manager> managerList) {if (!CollectionUtils.isEmpty(managerList)) {// 将dto中的acctManagerList用Gson转换成为String(必须和String转list使用相同的转换器)String managerListString = new Gson().toJson(managerList);return managerListString;}return null;}
}

修改接口,
1.在@Mapper上引用我们的自定义转换代码类AttributeConvertUtil
2.使用qualifiedByName指定我们使用的自定义转换方法

import com.cao.dto.ManagerDTO;
import com.cao.po.ManagerPO;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.factory.Mappers;@Mapper(uses = AttributeConvertUtil.class) //将自定义类引入进来
public interface ManagerBeanConvert {ManagerBeanConvert INSTANCE = Mappers.getMapper(ManagerBeanConvert.class);@Mapping(target = "id", source = "id")@Mapping(target = "acctManagerList", source = "acctManagerListString", qualifiedByName = "strToList")// qualifiedByName的值和别名一样ManagerDTO po2Dto(ManagerPO managerPO);@Mapping(target = "id", source = "id")@Mapping(target = "acctManagerListString", source = "acctManagerList", qualifiedByName = "listToStr") // qualifiedByName的值和别名一样ManagerPO dto2Po(ManagerDTO managerDTO);
}

源码:https://gitee.com/cao_wen_bin/test

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/647361.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

【知识---如何创建 GitHub 个人访问令牌】

提示&#xff1a;文章写完后&#xff0c;目录可以自动生成&#xff0c;如何生成可参考右边的帮助文档 文章目录 前言登录到 GitHub 帐户。在右上角的头像旁边&#xff0c;点击用户名&#xff0c;然后选择 "Settings"。在左侧导航栏中&#xff0c;选择 "Develope…

Mysql索引相关学习笔记:B+ Tree、索引分类、索引优化、索引失效场景及其他常见面试题

前言 索引是Mysql中常用到的一个功能&#xff0c;可以大大加快查询速度&#xff0c;同时面试中也是经常碰到。本文是学习Mysql索引的归纳总结。 索引采用的数据结构——B 树 本部分主要是参考自小林Coding B树的由来 二分查找可以每次缩减一半&#xff0c;从而提高查找效率…

对话框与多窗体设计 —— 标准对话框

三、对话框与多窗体设计3.1 标准对话框3.1.1 QFileDialog对话框3.1.2 QColorDialog对话框3.1.3 QFontDialog对话框3.1.4 QInputDialog标准输入对话框3.1.5 QMessageBox消息对话框 三、对话框与多窗体设计 一个完整的应用程序设计中&#xff0c;不可避免地会涉及多个窗 体、对框…

vue---打印本地当前时间Demo

<template><view class"content" tap"getCurrentTime()">打印时间</view> </template><script>export default {data() {return {title: Hello}},onLoad() {},methods: {getCurrentTime() {//获取当前时间并打印var _this …

论文写作之十个问题

前言 最近进入瓶颈&#xff1f; 改论文&#xff0c;改到有些抑郁了 总是不对&#xff0c;总是被打回 好的写作&#xff0c;让人一看就清楚明白非常重要 郁闷时候看看大佬们怎么说的 沈向洋、华刚&#xff1a;读科研论文的三个层次、四个阶段与十个问题 十问 What is the pro…

springboot127基于Springboot技术的实验室管理系统

简介 【毕设源码推荐 javaweb 项目】基于springbootvue 的 适用于计算机类毕业设计&#xff0c;课程设计参考与学习用途。仅供学习参考&#xff0c; 不得用于商业或者非法用途&#xff0c;否则&#xff0c;一切后果请用户自负。 看运行截图看 第五章 第四章 获取资料方式 **项…

vue 跨域XMLHttpRequest

vue 跨域 使用XMLHttpRequest 亲测好使 let urlhttp://127.0.0.1:9000/pssnotifyyb?b1//urlhttps://api.j4u.ink/v1/store/other/proxy/remote/moyu.jsonvar xhrnew XMLHttpRequest()xhr.open(GET,url,true)//第三个参数是是否异步请求,默认true xhr.onreadystatec…

Elasticsearch内核解析 - 数据模型篇

Elasticsearch内核解析 - 数据模型篇 - 知乎 Elasticsearch是一个实时的分布式搜索和分析引擎&#xff0c;它可以帮助我们用很快的速度去处理大规模数据&#xff0c;可以用于全文检索、结构化检索、推荐、分析以及统计聚合等多种场景。 Elasticsearch是一个建立在全文搜索引擎…

SpringBoot增加全局traceId日志追踪

文章目录 实现思路定义过滤器返回参数增加traceIdlogback.xml增加traceId 实现思路 增加Filter处理请求&#xff0c;生成traceId保存到TreadLocal中&#xff08;slf4j的MDC&#xff09;增加返回AOP切面&#xff0c;返回数据之前把traceId写到返回实体里日志logback.xml文件配置…

蓝牙 | 软件: Qualcomm BT Audio 问题分析(1)----ACAT Tools安装

大家好&#xff01; 我是“声波电波还看今朝”成员的一位FAE Devin.wen&#xff0c;欢迎大家关注我们的账号。 今天给大家大概讲解“如何排查Qualcomm BT Audio”的疑难杂症&#xff08;一&#xff09;如何安装ACAT Tools。 大家在遇到Audio方面的问题&#xff0c;比如 无声、…

[蓝桥杯]真题讲解:飞机降落(DFS枚举)

[蓝桥杯]真题讲解&#xff1a;飞机降落&#xff08;DFS枚举&#xff09; 一、视频讲解二、暴力代码&#xff08;也是正解代码&#xff09; 一、视频讲解 视频讲解 二、暴力代码&#xff08;也是正解代码&#xff09; //飞机降落&#xff1a; 暴力枚举DFS #include<bits/…

hadoop 问题集

1. org.apache.hadoop.yarn.exceptions.InvalidAuxServiceException: The auxService:mapreduce_shuffle does not exist yarn中没有aux的信息。在yarn&#xff0d;site.xml中加入&#xff1a; <property> <name>yarn.nodemanager.aux-services</name> …

【python】自动微分的一个例子

一、例子 import torchx torch.arange(4.0) x.requires_grad_(True) y 2 * torch.dot(x, x) print(y) y.backward() x.grad 4 * x print(x.grad) 二、解读 1. import torch 这一行导入了PyTorch库。PyTorch是一个开源的机器学习库&#xff0c;广泛用于计算机视觉和自然语…

DAY10_SpringBoot—SpringMVC重定向和转发RestFul风格JSON格式SSM框架整合

目录 1 SpringMVC1.1 重定向和转发1.1.1 转发1.1.2 重定向1.1.3 转发练习1.1.4 重定向练习1.1.5 重定向/转发特点1.1.6 重定向/转发意义 1.2 RestFul风格1.2.1 RestFul入门案例1.2.2 简化业务调用 1.3 JSON1.3.1 JSON介绍1.3.2 JSON格式1.3.2.1 Object格式1.3.2.2 Array格式1.3…

点灯大师(STM32)

这段代码是用于STM32F10x系列微控制器的C语言程序&#xff0c;目的是初始化GPIOC的Pin 13为输出&#xff0c;并设置其输出高电平。以下是对代码的逐行解释&#xff1a; #include "stm32f10x.h" 这一行引入了STM32F10x设备的头文件&#xff0c;包含了用于STM32F10x系…

Linux 命令 grep 的用法简介

Linux 命令 grep 的用法简介 文章目录 Linux 命令 grep 的用法简介基本语法&#xff1a;常见选项&#xff1a;示例&#xff1a; grep 是一个在 Unix 和类 Unix 系统中常用的文本搜索工具&#xff0c;它用于在文件中查找匹配指定模式的文本行。下面是 grep 命令的一些常见选项和…

一站式VR全景婚礼的优势表现在哪里?

你是否想过&#xff0c;婚礼也可以用一种全新的方式呈现&#xff0c;VR全景婚礼让每位用户沉浸式体验婚礼现场感。现在很多年轻人&#xff0c;都想让自己的婚礼与众不同&#xff0c;而VR全景婚礼也是未来发展的方向之一。 很多婚庆公司开通了VR婚礼这一服务&#xff0c;就是通过…

YOLOv5改进系列(28)——添加DSConv注意力卷积(ICCV 2023|用于管状结构分割的动态蛇形卷积)

【YOLOv5改进系列】前期回顾: YOLOv5改进系列(0)——重要性能指标与训练结果评价及分析 YOLOv5改进系列(1)——添加SE注意力机制

Java学习9--递归+计算阶乘+加减乘除计算器

递归的本质就是自己调用自己。 如果 F(N)F(N-1)*S - - S为辅助参数 - - 并且F(0)是确定的数值 - - 那么如果知道N - 必然可以运用递归算出F(N)比如想要求阶乘&#xff0c;下面这个算法就可以使用&#xff1a; n的阶乘为&#xff1a;n! n*(n-1)!其中0!1 下面用程序来计算5的阶…