根据表名动态获取数据

查询接口

    @ApiOperation("通用高级搜索")@PostMapping("/highSearch")public ResponseResult highSearch(@RequestBody HighSearchVO highSearchVO) {return dynamicDataRetrievalService.highSearch(highSearchVO);}

Service

    @Override@Transactionalpublic ResponseResult highSearch(HighSearchVO highSearchVO) {// 检索highSearchVO.setPageNo((highSearchVO.getPageNo() - 1) * highSearchVO.getPageSize());for (HighSearch highSearch : highSearchVO.getHighSearches()) {if ("datetime".equals(highSearch.getColumnType())) {SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");String[] times = highSearch.getSearchValue().split("\\|");try {highSearch.setStartDate(sdf.parse(times[0]));highSearch.setEndDate(sdf.parse(times[1]));} catch (ParseException e) {e.printStackTrace();return ResponseResult.fail("时间格式不正确");}}}List<Map<String, Object>> maps = dynamicDataRetrievalMapper.highSearch(highSearchVO);

由于是动态的,不能确定返回的List<>中填写哪个实体类型,所以可以用List<Map<String, Object>>数据结构来接,key是数据库字段名,value是对应的值:

list: [{"task_name": "落盘任务test1","center_freq": "9600MHz","file_location": "/files/2022_05_22_10_38_29_281_I_9600MHz_43803","pdw_format_id": 1,"file_name": "2022_05_22_10_38_29_281_I_9600MHz_43803","fileSuffix": [".dat",".pls"],"target_id": 3,"file_size": 9.2980568E7,"gather_time": "2022-05-22T10:38:29.281","in_time": "2023-11-15T16:04:37","pulse_num": 43803,"gather_id": 2,"id": 46,"system_model_id": 1},{"task_name": "落盘任务test1","center_freq": "9600MHz","file_location": "/files/2022_05_22_10_38_29_281_I_9600MHz_43803","pdw_format_id": 1,"file_name": "2022_05_22_10_38_29_281_I_9600MHz_43803","fileSuffix": [".dat",".pls"],"target_id": 3,"file_size": 9.2980568E7,"gather_time": "2022-05-22T10:38:29.281","in_time": "2023-11-15T16:04:37","pulse_num": 43803,"gather_id": 2,"id": 46,"system_model_id": 1}]

HighSearchVO

@ApiModel(description = "高级搜索前端传参")
@Data
public class HighSearchVO {@ApiModelProperty("表名")private String tableName;@ApiModelProperty("搜索字段集合")private List<HighSearch> highSearches;@ApiModelProperty("排序字段")private String orderColumn;@ApiModelProperty("排序控制(asc,desc)")private String orderControl;@ApiModelProperty("页数")private Integer pageSize;@ApiModelProperty("页码")private Integer pageNo;}

 HighSearch 

@ApiModel(description = "HIGH_SEARCH实体对象")
@Data
public class HighSearch {@ApiModelProperty(value = "字段名")private String columnName;@ApiModelProperty(value = "字段搜索值")private String searchValue;@ApiModelProperty(value = "字段类型")private String columnType;@ApiModelProperty(value = "开始时间(如果根据时间查询)")private Date startDate;@ApiModelProperty(value = "结束时间(如果根据时间查询)")private Date endDate;
}

动态sql:

<select id="highSearch" resultType="java.util.Map" parameterType="com.lin.entity.vo.HighSearchVO">select * from ${tableName}where 1 = 1<if test="highSearches != null"><foreach collection="highSearches" item="item" separator="AND" open="AND"><choose><when test="item.columnType == 'bigint'||item.columnType == 'int'||item.columnType == 'double'">${item.columnName} = ${item.searchValue}</when><when test="item.columnType == 'varchar'||item.columnType == 'VARCHAR'">${item.columnName} like concat(concat('%', #{item.searchValue}), '%')</when><when test="item.columnType == 'datetime'">${item.columnName} between #{item.startDate} and #{item.endDate}</when></choose></foreach></if><if test="orderColumn != null and orderColumn != ''">order by ${orderColumn} ${orderControl}</if>limit #{pageNo},#{pageSize}</select>

 

请求参数:

{"tableName": "file_meta_data","orderColumn": "id","orderControl": "desc","pageNo": 1,"pageSize": 10,"highSearches": [{"columnName": "id","searchValue": 21,"columnType": "bigint"},{"columnName": "name","searchValue": "小明","columnType": "varchar"}]
}

动态下载导出数据excel

使用到阿里的easy-excel

    @GetMapping("download")public void download(HttpServletResponse response) throws IOException {// 这里注意 有同学反应使用swagger 会导致各种问题,请直接用浏览器或者用postmanresponse.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");response.setCharacterEncoding("utf-8");// 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系String fileName = URLEncoder.encode("测试", "UTF-8").replaceAll("\\+", "%20");response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");EasyExcel.write(response.getOutputStream(), DownloadData.class).sheet("模板").doWrite(data());}private List<DownloadData> data() {List<DownloadData> list = ListUtils.newArrayList();for (int i = 0; i < 10; i++) {DownloadData data = new DownloadData();data.setString("字符串" + 0);data.setDate(new Date());data.setDoubleData(0.56);list.add(data);}return list;}

上面那个是定死的下载哪个实体对应的数据,而我们现在要求动态,动态获取数据list已经搞定了,但是数据List<Map<String, Object>>要转为阿里api可以识别的(问题一),以及根据表名获取.class运行时类(问题二)。

问题二解决:

/*** 表对象枚举*/
public enum TableObjectEnum {file_meta_data(FileMetaData.class),radar_sort_pwd(RadarSortPwd.class),;private Class<?> aClass;TableObjectEnum(Class<?> aClass) {this.aClass = aClass;}public Class<?> getaClass() {return aClass;}public void setaClass(Class<?> aClass) {this.aClass = aClass;}// 根据表名获取对应的 Class(.class运行时类)public static Class getClassForTableName(String tableName) throws ClassNotFoundException {for (TableObjectEnum tableObjectEnum : TableObjectEnum.values()) {if (tableObjectEnum.name().equalsIgnoreCase(tableName)) {return tableObjectEnum.getaClass();}}throw new ClassNotFoundException("表名没找到对应的类" + tableName);}
}

问题一解决:

/*** 将数据转化为导出可以支持的数据** @param dataList*/private <T> List<T> convertData(List<Map<String, Object>> dataList, Class<T> objectType) {List<T> objectList = new ArrayList<>();ObjectMapper objectMapper = new ObjectMapper();objectMapper.registerModule(new JavaTimeModule()); // 注册 Java 8 日期/时间模块try {// 遍历 dataList 并将每个 Map 转换为对象,添加到列表中for (Map<String, Object> data : dataList) {T object = objectMapper.convertValue(data, objectType);objectList.add(object);}} catch (Exception e) {e.printStackTrace();}return objectList;}

完整代码

@Overridepublic void download(HttpServletResponse response, HighSearchVO highSearchVO) throws UnsupportedEncodingException {String tableName = highSearchVO.getTableName();// 这里注意 有同学反应使用swagger 会导致各种问题,请直接用浏览器或者用postmanresponse.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");response.setCharacterEncoding("utf-8");// 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系String fileName = URLEncoder.encode("测试", "UTF-8").replaceAll("\\+", "%20");response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");try {Class classForTableName = TableObjectEnum.getClassForTableName(tableName);// 查询数据List<Map<String, Object>> dataList = getData(highSearchVO);List list = convertData(dataList, classForTableName);// 忽略字段Set<String> excludeColumnFiledNames = new HashSet<String>();
//            excludeColumnFiledNames.add("pdwId");EasyExcel.write(response.getOutputStream(), classForTableName).excludeColumnFieldNames(excludeColumnFiledNames)
//                    .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()) // 自动列宽.sheet("模板").doWrite(list);} catch (ClassNotFoundException | IOException e) {e.printStackTrace();}}

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

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

相关文章

list转map(根据某个或多个属性分组)

需要将对应的list换成本地list&#xff0c;和对象换成本地对象 1、List转Map<String,List> // 根据一个字段分组 Map<String, List<String>> map objectLists.stream().collect(Collectors.groupingBy(Object::getName,Collectors.mapping(Object::getId, …

【小技巧】MyBatis 中 SQL 写法技巧小总结

最近有个兄弟在搞mybatis&#xff0c;问我怎么写sql &#xff0c;说简单一点mybatis就是写原生sql&#xff0c;官方都说了 mybatis 的动态sql语句是基于 OGNL表达式的。可以方便的在 sql 语句中实现某些逻辑. 总体说来mybatis 动态SQL 语句主要有以下几类: if 语句 (简单的条件…

r语言plot函数

R语言中的plot()函数是一个用于创建各种类型的图形的基本绘图函数。它可以用来绘制散点图、线图、直方图、箱线图、饼图等多种图形。以下是plot()函数的基本语法和一些示例用法&#xff1a; 基本语法: plot(x, y, type "p", ...) 参数说明: x: 用于绘图的x轴数据&a…

分形简单版

我的代码&#xff1a; #include<bits/stdc.h> using namespace std; const int N1000; int n; char s[N][N]; void work(int x) {if(x1) {s[0][0]*;return;}work(x-1);for(int i0;i<(1<<x-2);i)for(int j(1<<x-2);j<(1<<x-1);j) s[i][j]s[i][j-(…

Java的IO流-打印流

打印流 PrintStream public void println&#xff08;&#xff09;自动换行 PrintWriter package com.itheima.println;import java.io.FileInputStream; import java.io.PrintStream; import java.io.PrintWriter;public class Test2 {public static void main(String[] arg…

MSSQL-逻辑级常用命令

--SQL Server 查询表的记录数 --one: 使用系统表. SELECT object_name (i.id) TableName, rows as RowCnt FROM sysindexes i INNER JOIN sysObjects o ON (o.id i.id AND o.xType U ) WHERE indid < 2 ORDER BY rows desc ————————————…

【Linux】第十九站:进程替换

文章目录 一、单进程版---最简单的程序替换二、进程替换的原理三、多进程的程序替换1.多进程的程序替换实例2.那么程序在替换时候有没有创建子进程呢3.再谈原理4.一个现象5.我们的CPU如何得知程序的入口地址&#xff1f; 四、各个接口的介绍1.execl2.execlp3.execv4.execvp5.ex…

【Spring Boot】使用WebSocket协议完成来单提醒及客户催单功能

1 WebSocket介绍 WebSocket 是基于 TCP 的一种新的网络协议。它实现了浏览器与服务器全双工通信(双向传输)——浏览器和服务器只需要完成一次握手&#xff0c;两者之间就可以创建持久性的连接&#xff0c; 并进行双向数据传输。 1.1 HTTP协议和WebSocket协议对比 1、HTTP是短…

SMB over QUIC帮助实现文件服务器在公网安全共享

要在Internet边缘服务器提供安全、可靠的共享连接&#xff0c;可以通过安全的SMB over QUIC来取代传统的TCP网络传输。 QUIC 是 IETF 标准化协议&#xff0c;与 TCP 相比具有许多优势&#xff1a; 所有数据包始终加密&#xff0c;握手使用 TLS 1.3 进行身份验证可靠和不可靠应…

Linux常用命令亲测总结

在实际开发中&#xff0c;经常会进行下位机的搭建&#xff0c;在搭建过程中&#xff0c;对于常用的LInux命令进行总结&#xff0c;方便自己使用 1.rm -rf 删除对应文件&#xff08;字节小的&#xff09; 2、ln -s 文件关联&#xff08;长的关联短的。三个则关联两次&#xff0…

基于SpringBoot+Redis的前后端分离外卖项目-苍穹外卖(六)

新增菜品 1.1 需求分析与设计1.1.1 产品原型1.1.2 接口设计1.1.3 表设计 2.2 代码开发2.2.1 文件上传实现2.2.2 新增菜品实现 2.3 功能测试 1.1 需求分析与设计 1.1.1 产品原型 后台系统中可以管理菜品信息&#xff0c;通过 新增功能来添加一个新的菜品&#xff0c;在添加菜品…

vue使用本地图片设置为默认图

一、引用 import imgSrc /assets/common/image/xxx.png 二、赋值给变量 defaultImg:imgSrc, 三、将变量给img标签 <img :src"defaultImg:imgSrc" alt"icon"> 注意&#xff1a;这里直接使用路径给变量是无法实现的哟

解决ubuntu23.10 virtualbox 启动错误modprobe vboxdrv, Kernel driver not installed

- 参考视频&#xff1a;https://www.youtube.com/watch?vAKAq2LGu_zs sudo apt updatesudo apt install --reinstall linux-headers-$(uname -r) virtualbox-dkms dkms# 重启系统&#xff0c;然后再执行下面一条命令sudo modprobe vboxdrv

Ubuntu 下C++数字雨

以前写过一个Window下的数字雨&#xff0c;像黑客帝国里那样的01数字&#xff0c;现在补充一版Linux下的。使用了curses库&#xff0c;安装方法与使用方法参照 Linux下curses函数库的详细介绍_libcurses库-CSDN博客 5-linux学习笔记之-----curses-CSDN博客 效果如下&#xf…

JS删除对象的某个属性

JS中删除对象中的某个元素_笔记大全_设计学院 1、delete方法 2、...展开运算符

工作备忘录【react-native】

react-native 关闭全部黄色警告 index.js0.63之后 /*** format*/import {AppRegistry,LogBox} from react-native; import App from ./App; import {name as appName} from ./app.json; LogBox.ignoreAllLogs(true)//关闭全部黄色警告AppRegistry.registerComponent(appName…

拜托!佛系点,你只是给社区打工而已

社区人到年底了各种要写的东西很烦啊&#xff01;突然看到这个&#xff0c;真的谢谢啊&#xff01; 家人们谁懂啊&#xff1f;&#xff01;&#xff01;平时写个东西起码两三天&#xff0c;试了一下这东西&#xff01;输入需求&#xff0c;一键生成&#xff0c;写好了&#xf…

webpack快速上手之搭建cesium三维地球环境

前言 &#x1f4eb; 大家好&#xff0c;我是南木元元&#xff0c;热衷分享有趣实用的文章&#xff0c;希望大家多多支持&#xff0c;一起进步&#xff01; &#x1f345; 个人主页&#xff1a;南木元元 目录 Cesium介绍 初始化一个Cesium地球 ​编辑 Webpack的使用 Webpac…

汽车ECU的虚拟化技术初探(三)--U2A虚拟化辅助功能分析1

目录 1.基本概述 1.1 U2A虚拟化辅助功能 1.2 U2A虚拟化使能和资源分配 2. U2A架构概述 3. CPU运行模式 3.1 虚拟化模式 3.2 限制运行模式 3.3 权限运行模式 3.4 CPU运行模式小结 4.小结 1.基本概述 1.1 U2A虚拟化辅助功能 在汽车ECU的虚拟化技术初探(二)-CSDN博客中…

文心一言 VS 讯飞星火 VS chatgpt (139)-- 算法导论11.4 3题

三、用go语言&#xff0c;考虑一个采用均匀散列的开放寻址散列表。当装载因子为 3/4 和 7/8 时&#xff0c;试分别给出一次不成功查找和一次成功查找的探查期望数上界。 文心一言&#xff1a; 在开放寻址法中&#xff0c;当散列表的装载因子超过其阈值时&#xff0c;会触发重…