Java生成SQL文件,压缩包

package com.sinosoft.microservice.product.manage.basicinfo.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cxytiandi.encrypt.springboot.annotation.DecryptIgnore;
import com.cxytiandi.encrypt.springboot.annotation.EncryptIgnore;
import com.sinosoft.microservice.product.manage.basicinfo.mapper.PdPdInfoMapper;
import com.sinosoft.microservice.product.manage.basicinfo.mapper.PdProductCopyInfoMapper;
import com.sinosoft.microservice.product.manage.basicinfo.mapper.PdtempPdVerRlsMapper;
import com.sinosoft.microservice.product.manage.basicinfo.service.PdtempPdInfoService;
import com.sinosoft.microservice.product.manage.basicinfo.service.PdtempPdVerRlsService;
import com.sinosoft.microservice.product.manage.basicinfo.vo.PdProductCopyInfoVo;
import com.sinosoft.microservice.product.manage.config.common.sqlexecute.ExeSql;
import com.sinosoft.microservice.product.manage.config.dto.entry.BaseRequest;
import com.sinosoft.microservice.product.manage.config.utils.FileHttpUtil;
import com.sinosoft.microservice.product.manage.config.utils.PageHandler;
import com.sinosoft.microservice.product.manage.domain.basicinfo.PdPdInfo;
import com.sinosoft.microservice.product.manage.domain.basicinfo.PdtempPdAddAuditInfo;
import com.sinosoft.microservice.product.manage.domain.basicinfo.PdtempPdInfo;
import com.sinosoft.microservice.product.manage.domain.basicinfo.PdtempPdVerRls;
import com.sinosoft.microservice.product.manage.workflow.service.WorkFlowService;
import com.sinosoft.microservice.product.manage.workflow.vo.ProductReleaseInfoVo;
import com.sinosoft.microservice.product.manage.workflow.vo.TaskVo;
import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * 

* 服务实现类 *

* * @author chenganyuan * @since 2020-05-12 */ @Service public class PdtempPdVerRlsServiceImpl extends ServiceImpl implements PdtempPdVerRlsService { @Autowired private PdtempPdVerRlsMapper mapper; @Autowired private ExeSql exeSql; @Resource private WorkFlowService workFlowService; @Resource private PdProductCopyInfoMapper copyMapper; @Resource private SqlSession sqlSession; @Resource private PdtempPdInfoService pdtempPdInfoService; @Resource private PdPdInfoMapper pdPdInfoMapper; private List mFileList; private File zipFile; @Override public Long savePdtempPdVerRls(PdtempPdVerRls entity) { if (entity.getId() != null) { entity.updateById(); } else { entity.insert(); } return entity.getId(); } public Long updatePdtempPdVerRls(PdtempPdVerRls entity) { return savePdtempPdVerRls(entity); } @Override public void selectPdtempPdVerRlssByPage(Page page, QueryWrapper queryWrapper) { baseMapper.selectPage(page, queryWrapper); } @Override public void deletePdtempPdVerRlsById(Long id) { baseMapper.deleteById(id); } @Override public PdtempPdVerRls findPdtempPdVerRlsById(Long id) { return baseMapper.selectById(id); } //生成脚本文件入口方法 @Override @EncryptIgnore @Transactional(rollbackFor = Exception.class) public PdtempPdVerRls releInfo(HttpServletResponse response, PdtempPdVerRls input, int num) { try { String pdCode = input.getPdCode(); String pdEdition = input.getPdEdition(); PdtempPdInfo pdtempPdInfo = pdtempPdInfoService.findPdtempPdInfoByPdCodeAndPdEdition(pdCode, pdEdition); /*生成脚本*/ String sqlFileName = createSqlFile(pdCode,pdEdition,input,num); /* if (num == 2){ downloadFile(response,sqlFileName); }*/ /*temp 转数据 到 pd*/ copyDataFromTempToPd(pdtempPdInfo.getId(),pdtempPdInfo); /* 保存发布记录 */ savePdtempPdVerRls(input); } catch (Exception e) { TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//手动回滚 e.printStackTrace(); //throw new RuntimeException(); // 会自动回滚 } return input; } /* 生成脚本文件 */ /*1. 查询对应字段数据*/ public String createSqlFile(String pdCode, String pdEdition, PdtempPdVerRls input, int num) { String sqlFileName = ""; try { String fileName = baseMapper.getFileName(); SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd_HHmmss"); String date = formatter.format(new Date()); String path = "D:\\file\\template"; File file = new File(path); //判断文件夹是否存在 if (!file.exists()) { file.getParentFile().mkdirs(); } file = new File(path+"\\"+fileName+"_"+pdCode+"_"+date+".sql");// 脚本名称 input.setPdReleFilePath(path); // 存储文件生成路径 if (num == 2){ sqlFileName = file.getPath(); input.setPdReleFile(fileName + "_" + pdCode + "_" + date + ".sql"); //存储文件名称 }else if(num == 1){ mFileList = new ArrayList(); mFileList.add(file); String zipFileName = fileName+"_"+date; input.setPdReleFile(zipFileName+".zip"); //存储zip文件名称 zipFile = new File(path+"\\"+zipFileName+".zip"); //压缩包名称 } file.createNewFile();// 创建新文件 //准备好一个输出的对象,通过对象多态性,进行实例化 OutputStreamWriter outputStreamWriter = new OutputStreamWriter(new FileOutputStream(file), "UTF-8"); BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter); StringBuffer sColumn = new StringBuffer(); StringBuffer sCondition = new StringBuffer(); StringBuffer insSql = new StringBuffer(); StringBuffer delSql = new StringBuffer(); /* 获取所有要生成的表 */ List otherTableNames = baseMapper.getOtherTableNames(); for (int i = 0; i < otherTableNames.size(); i++) { //将StringBuffer清空 sColumn.setLength(0); sCondition.setLength(0); insSql.setLength(0); delSql.setLength(0); String othertablename = otherTableNames.get(i).toString(); //开始拼接sql sColumn.append("select "); sCondition.append(" where "); insSql.append("insert into "+othertablename+" ( "); delSql.append("delete from "+othertablename+" where ( "); List tableDatas = baseMapper.getTableDatas(othertablename); ArrayList condition = new ArrayList<>(); for (int j = 0; j tableNames = baseMapper.getTableNames(othertablename); for (int t = 0; t < tableNames.size(); t++) { if (t mapListData = exeSql.getMapListData(sql); /* 拼接插入sql */ String inssql = createInsSql(insSql,mapListData,tableDatas); /* 拼接删除sql */ String delsql = createDelSql(delSql,mapListData,tableDatas); bufferedWriter.write(delsql); bufferedWriter.newLine(); bufferedWriter.write(inssql); bufferedWriter.newLine(); bufferedWriter.newLine(); } bufferedWriter.flush(); //如果用于网络传输,记得强制刷新缓冲区,否则输出的数据只停留在缓冲区中,而无法进行网络传输 bufferedWriter.close(); // 关闭输出流 文件不存在会自动创建 outputStreamWriter.close(); // 关闭资源 } catch (IOException e) { e.printStackTrace(); } return sqlFileName; } /*拼接插入sql*/ private String createInsSql(StringBuffer insSql, List mapListData, List tableDatas) { for (int i = 0; i < mapListData.size(); i++) { Map map = mapListData.get(i); for (int j = 0; j < map.size(); j++) { if (j == map.size()-1){ insSql.append("'"+map.get(tableDatas.get(j).get("tablecolumn").toString().substring(2))+"');"); }else{ insSql.append("'"+map.get(tableDatas.get(j).get("tablecolumn").toString().substring(2))+"',"); } } } return insSql.toString(); } /*拼接删除sql*/ private String createDelSql(StringBuffer delSql, List mapListData, List tableDatas) { for (int i = 0; i < mapListData.size(); i++) { Map map = mapListData.get(i); for (int j = 0; j < map.size(); j++) { if (j == map.size()-1){ delSql.append(tableDatas.get(j).get("othertablecolumn")+" = '"+map.get(tableDatas.get(j).get("tablecolumn").toString().substring(2))+"');"); }else{ delSql.append(tableDatas.get(j).get("othertablecolumn")+" = '"+map.get(tableDatas.get(j).get("tablecolumn").toString().substring(2))+"' and "); } } } return delSql.toString(); } /*2. 将temp表数据转移到pd表,并删除temp表数据*/ @Transactional(rollbackFor = Exception.class) protected void copyDataFromTempToPd(Long pdInfoId, PdtempPdInfo pdtempPdInfo){ try { PdPdInfo pdPdInfo = new PdPdInfo(); BeanUtil.copyProperties(pdtempPdInfo,pdPdInfo); pdPdInfoMapper.deleteById(pdPdInfo.getId()); pdPdInfoMapper.insert(pdPdInfo); /*pdPdInfoMapper.deleteByMap(BeanUtil.beanToMap(pdPdInfo));*/ // 查询数据库获取需要复制的 pd 表 List copyInfoList = copyMapper.getAllPdProductCopyInfoVo(); for (PdProductCopyInfoVo pdProductCopyInfoVo : copyInfoList) { // 获取当前实体类的Mapper对象 String packagePath = pdProductCopyInfoVo.getPdtempPackagePath(); // 获取mapper文件路径 String mapperPackagePath = StrUtil.removeAll(packagePath, "domain.") + ".mapper"; // 获取实体类对象的类名, 根据pdtemp 获取 对应 的 pd类 String classPdName = "Pd"+StrUtil.cleanBlank(pdProductCopyInfoVo.getPdtempClassName()).substring(6); String classTempName = StrUtil.cleanBlank(pdProductCopyInfoVo.getPdtempClassName()); // 获取实体类对应的mapper文件 Class pdClass = Class.forName(mapperPackagePath + "." + classPdName + "Mapper"); //Class pdClass = Class.forName(packagePath + "." + classPdName); Class tempClass = Class.forName(mapperPackagePath + "." + classTempName + "Mapper"); Object currentPdMapper = sqlSession.getMapper(pdClass); Object currentTempMapper = sqlSession.getMapper(tempClass); String pdTableName = pdProductCopyInfoVo.getPdTableName().replaceFirst("pd_","pdtemp_"); String fullClassName = packagePath + "." + classPdName; Object o = ReflectUtil.newInstance(fullClassName); // 获取 pd 表中与该已发布产品相关的所有信息 List> productData = pdtempPdInfoService.getPdtempData(pdTableName, pdInfoId); for (Map map : productData) { String id = map.get("id").toString(); Object bean = BeanUtil.fillBeanWithMap(map, o, true); ReflectUtil.invoke(currentPdMapper, "deleteById", id); ReflectUtil.invoke(currentPdMapper, "insert", bean); /*ReflectUtil.invoke(currentTempMapper, "deleteByMap", map);*/ } } } catch (ClassNotFoundException e) { TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//手动回滚 e.printStackTrace(); } } //生成压缩包文件入口方法 @Override @EncryptIgnore public PdtempPdVerRls createZipFile(HttpServletResponse response, List selArr, PdtempPdVerRls pdtempPdVerRls) { for (int i = 0; i < selArr.size(); i++) { pdtempPdVerRls.setPdCode((String) selArr.get(i).get("pdCode")); pdtempPdVerRls.setPdInfoId(Long.valueOf( (selArr.get(i).get("pdInfoId")).toString())); pdtempPdVerRls.setPdVerId(Long.valueOf(selArr.get(i).get("pdVerId").toString())); pdtempPdVerRls.setPdEdition(selArr.get(i).get("pdEdition").toString()); pdtempPdVerRls.setPdReleType("全量发布"); releInfo(response, pdtempPdVerRls, 1); } createZipFiles(mFileList,zipFile); /* downloadFile(response,zipFile.getPath());*/ pdtempPdVerRls.setPdReleFile(zipFile.getName()); return pdtempPdVerRls; } //数据库执行入口方法 @Override public PdtempPdVerRls carryByConn(PdtempPdVerRls pdtempPdVerRls) { // 加载数据库驱动 try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException e) { e.printStackTrace(); return null; } // 声明数据库view的URL String url = "jdbc:mysql://localhost:3306/view?useUnicode=true&characterEncoding=utf-8&useSSL=false"; // 数据库用户名 String user = "root"; // 数据库密码 String password = "123456"; // 建立数据库连接,获得连接对象conn PreparedStatement ps = null; Connection conn = null; try { conn = DriverManager.getConnection(url, user, password); String pdCode = pdtempPdVerRls.getPdCode(); String pdEdition = pdtempPdVerRls.getPdEdition(); Map mMap = getSql(pdCode, pdEdition); for (int i = 0; i < mMap.size(); i++) { String delSql = mMap.get("del" + i); ps = conn.prepareStatement(delSql); ps.execute(); String insSql = mMap.get("ins" + i); ps = conn.prepareStatement(insSql); ps.execute(); } conn.commit(); } catch (SQLException e) { // TODO Auto-generated catch block try { conn.rollback(); } catch (SQLException throwables) { throwables.printStackTrace(); } e.printStackTrace(); }finally { // 关闭数据库连接对象 try { conn.close(); } catch (SQLException throwables) { throwables.printStackTrace(); } } return null; } /* 将生成的文件生成压缩包 */ private void createZipFiles(List srcFiles, File zipFile) { // 判断压缩后的文件存在不,不存在则创建 if (!zipFile.exists()) { try { zipFile.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } // 创建 FileInputStream 对象 FileInputStream fileInputStream = null; try { // 创建 实例化 FileOutputStream 对象 FileOutputStream fileStrem = new FileOutputStream(zipFile); // 创建 实例化 ZipOutputStream 对象 ZipOutputStream zipStream = new ZipOutputStream(fileStrem); // 创建 ZipEntry 对象 ZipEntry zipEntry = null; // 遍历源文件数组 for (int i = 0; i < srcFiles.size(); i++) { // 将源文件数组中的当前文件读入 FileInputStream 流中 fileInputStream = new FileInputStream(srcFiles.get(i)); // 实例化 ZipEntry 对象,源文件数组中的当前文件 zipEntry = new ZipEntry(srcFiles.get(i).getName()); zipStream.putNextEntry(zipEntry); // 该变量记录每次真正读的字节个数 int len; // 定义每次读取的字节数组 byte[] buffer = new byte[1024]; while ((len = fileInputStream.read(buffer)) > 0) { zipStream.write(buffer, 0, len); } } zipStream.closeEntry(); zipStream.close(); fileInputStream.close(); fileStrem.close(); for (int i = 0; i < srcFiles.size(); i++) { File file = srcFiles.get(i); if (file.exists() && file.isFile()){ final boolean delete = file.delete(); } } } catch (IOException e) { e.printStackTrace(); } } public Map getSql(String pdCode, String pdEdition) { Map sqlMap = new HashMap(); try { StringBuffer sColumn = new StringBuffer(); StringBuffer sCondition = new StringBuffer(); StringBuffer insSql = new StringBuffer(); StringBuffer delSql = new StringBuffer(); /* 获取所有要生成的表 */ List otherTableNames = baseMapper.getOtherTableNames(); for (int i = 0; i < otherTableNames.size(); i++) { //将StringBuffer清空 sColumn.setLength(0); sCondition.setLength(0); insSql.setLength(0); delSql.setLength(0); String othertablename = otherTableNames.get(i).toString(); //开始拼接sql sColumn.append("select "); sCondition.append(" where "); insSql.append("insert into "+othertablename+" ( "); delSql.append("delete from "+othertablename+" where ( "); List tableDatas = baseMapper.getTableDatas(othertablename); ArrayList condition = new ArrayList<>(); for (int j = 0; j tableNames = baseMapper.getTableNames(othertablename); for (int t = 0; t < tableNames.size(); t++) { if (t mapListData = exeSql.getMapListData(sql); /* 拼接插入sql */ String inssql = createInsSql(insSql,mapListData,tableDatas); /* 拼接删除sql */ String delsql = createDelSql(delSql,mapListData,tableDatas); sqlMap.put("del"+i,delsql); sqlMap.put("ins"+i,inssql); } } catch (Exception e) { e.printStackTrace(); } return sqlMap; } @EncryptIgnore @DecryptIgnore public void downloadFile(HttpServletResponse response, String filePath) { try { FileHttpUtil.downloadFile(response, filePath); } catch (Exception e) { e.printStackTrace(); } } }

 

你可能感兴趣的:(Java,java)