All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.beli.gen.service.impl.GenTableServiceImpl Maven / Gradle / Ivy

package com.beli.gen.service.impl;

import java.io.*;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import com.beli.common.enums.MyBoolean;
import com.beli.common.exceptions.BaseBusinessException;
import com.beli.common.pojos.vo.PageQueryVO;
import com.beli.common.services.BaseServiceImpl;
import com.beli.common.utils.DateUtil;
import com.beli.common.utils.SpringContextUtil;
import com.beli.gen.bo.GenTableBO;
import com.beli.gen.bo.GenTableColumnBO;
import com.beli.gen.consants.GenConstants;
import com.beli.gen.dao.GenTableDAO;
import com.beli.gen.po.GenTablePO;
import com.beli.gen.service.IGenTableColumnService;
import com.beli.gen.service.IGenTableService;
import com.beli.gen.text.CharsetKit;
import com.beli.gen.util.*;
import com.github.pagehelper.PageHelper;
import org.apache.commons.io.IOUtils;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.jdbc.ScriptRunner;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import tk.mybatis.mapper.entity.Example;

import javax.sql.DataSource;

/**
 * 业务 服务层实现
 *
 * @author beli
 */
@Service
public class GenTableServiceImpl extends BaseServiceImpl implements IGenTableService {
    private static final Logger log = LoggerFactory.getLogger(GenTableServiceImpl.class);

    @Autowired
    private IGenTableColumnService tableColumnService;

    private Example createExample(PageQueryVO queryVO) {
        Example example = new Example(GenTablePO.class);
        Example.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotBlank((String) queryVO.get("tableName"))) {
            criteria.andLike("tableName", "%" + StringUtils.lowerCase((String) queryVO.get("tableName")) + "%");
        }
        if (StringUtils.isNotBlank((String) queryVO.get("tableComment"))) {
            criteria.andLike("tableComment", "%" + StringUtils.lowerCase((String) queryVO.get("tableComment")) + "%");
        }
        if (StringUtils.isNotBlank((String) queryVO.get("createTime"))) {
            criteria.andGreaterThanOrEqualTo("createTime", DateUtil.getDate((String) queryVO.get("createTime")));
        }
        if (StringUtils.isNotBlank((String) queryVO.get("endTime"))) {
            criteria.andLessThanOrEqualTo("endTime", DateUtil.getDate((String) queryVO.get("endTime")));
        }
        return example;
    }

    @Override
    public List queryList(PageQueryVO queryVO) {
        Example example = createExample(queryVO);
        List poList = PageHelper.startPage(queryVO.getPage(), queryVO.getLimit()).doSelectPage(() -> dao.selectByExample(example));
        return toBOList(poList);
    }

    @Override
    public int queryDBTotal(PageQueryVO queryVO) {

        return dao.queryTotal(queryVO);
    }

    @Override
    public int queryTotal(PageQueryVO queryVO) {
        Example example = createExample(queryVO);
        return dao.selectCountByExample(example);
    }

    /**
     * 查询业务信息
     *
     * @param id 业务ID
     * @return 业务信息
     */
    @Override
    public GenTableBO selectGenTableById(Long id) {
        GenTableBO tableBO = (GenTableBO) queryObject(id);
        List columnBOList = tableColumnService.findByTableId(id);
        tableBO.setColumns(columnBOList);
        setTableFromOptions(tableBO);
        return tableBO;
    }

    /**
     * 查询业务信息
     *
     * @param tableName 表名
     * @return 业务信息
     */
    @Override
    public GenTableBO selectGenTableByTableName(String tableName) {
        Example example = new Example(GenTablePO.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("tableName", tableName);
        GenTablePO po = (GenTablePO) dao.selectOneByExample(example);
        if (po == null) throw new BaseBusinessException("表名" + tableName + "不存在");
        GenTableBO bo = (GenTableBO) po.toBO();
        List columnBOList = tableColumnService.findByTableId(bo.getId());
        bo.setColumns(columnBOList);
        setTableFromOptions(bo);
        return bo;
    }

    /**
     * 查询据库列表
     *
     * @param queryVO 业务信息
     * @return 数据库表集合
     */
    @Override
    public List selectDbTableList(PageQueryVO queryVO) {
        return PageHelper.startPage(queryVO.getPage(), queryVO.getLimit()).doSelectPage(() -> dao.selectDbTableList(queryVO));
    }

    /**
     * 查询据库列表
     *
     * @param tableNames 表名称组
     * @return 数据库表集合
     */
    @Override
    public List selectDbTableListByNames(String[] tableNames) {
        return dao.selectDbTableListByNames(tableNames);
    }

    /**
     * 修改业务
     *
     * @param genTable 业务信息
     * @return 结果
     */
    @Override
    @Transactional
    public void updateGenTable(GenTableBO genTable) {
        String options = JSON.toJSONString(genTable.getParams());
        genTable.setOptions(options);
        dao.updateGenTable(genTable);
        for (GenTableColumnBO cenTableColumn : genTable.getColumns()) {
            tableColumnService.updateGenTableColumn(cenTableColumn);
        }
    }

    /**
     * 删除业务对象
     *
     * @param tableIds 需要删除的数据ID
     * @return 结果
     */
    @Override
    @Transactional
    public void deleteGenTableByIds(Long[] tableIds) {
        deleteBatch(tableIds);
        tableColumnService.deleteBatch(tableIds);
    }

    /**
     * 导入表结构
     *
     * @param tableList 导入表列表
     */
    @Override
    @Transactional
    public void importGenTable(List> tableList, String operName) {
        try {
            for (Map table : tableList) {
                String tableName = (String) table.get("tableName");
                GenTableBO genTable = new GenTableBO();
                genTable.setTableName(tableName);
                genTable.setTableComment((String) table.get("tableComment"));
                GenUtils.initTable(genTable, operName);
                int row = dao.insertGenTable(genTable);
                if (row > 0) {
                    // 保存列信息
                    List genTableColumns = tableColumnService.selectDbTableColumnsByName(tableName);
                    for (GenTableColumnBO column : genTableColumns) {
                        GenUtils.initColumnField(column, genTable);
                        tableColumnService.insertGenTableColumn(column);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseBusinessException("导入失败:" + e.getMessage());
        }
    }

    /**
     * 预览代码
     *
     * @param tableId 表编号
     * @return 预览数据列表
     */
    @Override
    public Map previewCode(Long tableId) {
        Map dataMap = new LinkedHashMap<>();
        // 查询表信息
        GenTableBO table = selectGenTableById(tableId);
        // 查询列信息
        List columns = table.getColumns();
        setPkColumn(table, columns);
        VelocityInitializer.initVelocity();

        VelocityContext context = VelocityUtils.prepareContext(table);

        // 获取模板列表
        List templates = VelocityUtils.getTemplateList(table);
        for (String template : templates) {
            // 渲染模板
            StringWriter sw = new StringWriter();
            Template tpl = Velocity.getTemplate(template, GenConstants.UTF8);
            tpl.merge(context, sw);
            dataMap.put(template, sw.toString());
        }
        return dataMap;
    }

    /**
     * 生成代码(下载方式)
     *
     * @param tableName 表名称
     * @return 数据
     */
    @Override
    public byte[] downloadCode(String tableName) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ZipOutputStream zip = new ZipOutputStream(outputStream);
        generatorCode(tableName, zip);
        IOUtils.closeQuietly(zip);
        return outputStream.toByteArray();
    }

    /**
     * 生成代码(自定义路径)
     *
     * @param tableName 表名称
     * @return 数据
     */
    @Override
    public void generatorCode(String tableName) {
        GenTableBO table = selectGenTableByTableName(tableName);
        // 查询列信息
        setPkColumn(table, table.getColumns());

        VelocityInitializer.initVelocity();

        VelocityContext context = VelocityUtils.prepareContext(table);

        // 获取模板列表
        List templates = VelocityUtils.getTemplateList(table);
        for (String template : templates) {

            // 渲染模板
            StringWriter sw = new StringWriter();
            Template tpl = Velocity.getTemplate(template, GenConstants.UTF8);
            tpl.merge(context, sw);
            try {
                if (!StringUtils.containsAny(template, "sql.vm", "index.model.js.vm", "index.vue.vm", "edit.vue.vm", "index-tree.vue.vm","edit-activiti.vue.vm","editItem.vue.vm")) {
                    String path = getGenPath(table, template);
                    FileUtils.writeStringToFile(new File(path), sw.toString(), CharsetKit.UTF_8);
                }else if(!StringUtils.containsAny(template, "sql.vm", "index-tree.vue.vm") && !GenConstants.TPL_TREE.equals(table.getTplCategory())) {
                    String path = getGenVuePath(table, template);
                    FileUtils.writeStringToFile(new File(path), sw.toString(), CharsetKit.UTF_8);
                }else if(!StringUtils.containsAny(template, "sql.vm") && GenConstants.TPL_TREE.equals(table.getTplCategory())){
                    String path = getGenVuePath(table, template);
                    FileUtils.writeStringToFile(new File(path), sw.toString(), CharsetKit.UTF_8);
                }else if(StringUtils.containsAny(template, "sql.vm")){
                    if(table.getNeedRunSql()!=null&& MyBoolean.YES.getValue()==table.getNeedRunSql()){
                        runSql(sw.toString());
                    }
                }
            } catch (IOException e) {
                throw new BaseBusinessException("渲染模板失败,表名:" + table.getTableName());
            }

        }
    }

    private void runSql(String sql){
        DataSource dataSource = SpringContextUtil.getBean(DataSource.class);
        Connection connection = null;
        try {
            connection = dataSource.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        ScriptRunner runner=new ScriptRunner(connection);
        Reader resourceAsReader = new StringReader(sql);
        runner.runScript(resourceAsReader);
    }

    private String getGenVuePath(GenTableBO table, String template) {
        String genPath = table.getGenVuePath();
        if (StringUtils.equals(genPath, "/")) {
//            return System.getProperty("user.dir") + File.separator + "src" + File.separator + VelocityUtils.getFileName(template, table);
            throw new BaseBusinessException("请指定前端输出路径!");
        }
        return genPath + File.separator + VelocityUtils.getFileName(template, table);
    }

    /**
     * 批量生成代码(下载方式)
     *
     * @param tableNames 表数组
     * @return 数据
     */
    @Override
    public byte[] downloadCode(String[] tableNames) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ZipOutputStream zip = new ZipOutputStream(outputStream);
        for (String tableName : tableNames) {
            generatorCode(tableName, zip);
        }
        IOUtils.closeQuietly(zip);
        return outputStream.toByteArray();
    }

    /**
     * 查询表信息并生成代码
     */
    private void generatorCode(String tableName, ZipOutputStream zip) {
        // 查询表信息
        GenTableBO table = selectGenTableByTableName(tableName);
        table.setColumns(tableColumnService.findByTableId(table.getId()));
        // 查询列信息
        List columns = table.getColumns();
        setPkColumn(table, columns);

        VelocityInitializer.initVelocity();

        VelocityContext context = VelocityUtils.prepareContext(table);

        // 获取模板列表
        List templates = VelocityUtils.getTemplateList(table);
        for (String template : templates) {
            // 渲染模板
            StringWriter sw = new StringWriter();
            Template tpl = Velocity.getTemplate(template, GenConstants.UTF8);
            tpl.merge(context, sw);
            try {
                // 添加到zip
                zip.putNextEntry(new ZipEntry(VelocityUtils.getFileName(template, table)));
                IOUtils.write(sw.toString(), zip, GenConstants.UTF8);
                IOUtils.closeQuietly(sw);
                zip.flush();
                zip.closeEntry();
            } catch (IOException e) {
                log.error("渲染模板失败,表名:" + table.getTableName(), e);
            }
        }
    }

    /**
     * 修改保存参数校验
     *
     * @param genTable 业务信息
     */
    @Override
    public void validateEdit(GenTableBO genTable) {
        if (GenConstants.TPL_TREE.equals(genTable.getTplCategory())) {
            String options = JSON.toJSONString(genTable.getParams());
            JSONObject paramsObj = JSONObject.parseObject(options);
            if (StringUtils.isEmpty(paramsObj.getString(GenConstants.TREE_CODE))) {
                throw new BaseBusinessException("树编码字段不能为空");
            } else if (StringUtils.isEmpty(paramsObj.getString(GenConstants.TREE_PARENT_CODE))) {
                throw new BaseBusinessException("树父编码字段不能为空");
            } else if (StringUtils.isEmpty(paramsObj.getString(GenConstants.TREE_NAME))) {
                throw new BaseBusinessException("树名称字段不能为空");
            }
        }
    }

    /**
     * 设置主键列信息
     *
     * @param table   业务表信息
     * @param columns 业务字段列表
     */
    public void setPkColumn(GenTableBO table, List columns) {
        for (GenTableColumnBO column : columns) {
            if (column.isPk()) {
                table.setPkColumn(column);
                break;
            }
        }
        if (StringUtils.isNull(table.getPkColumn())) {
            table.setPkColumn(columns.get(0));
        }
    }

    /**
     * 设置代码生成其他选项值
     *
     * @param genTable 设置后的生成对象
     */
    public void setTableFromOptions(GenTableBO genTable) {
        JSONObject paramsObj = JSONObject.parseObject(genTable.getOptions());
        if (StringUtils.isNotNull(paramsObj)) {
            String treeCode = paramsObj.getString(GenConstants.TREE_CODE);
            String treeParentCode = paramsObj.getString(GenConstants.TREE_PARENT_CODE);
            String treeName = paramsObj.getString(GenConstants.TREE_NAME);
            String parentMenuId = paramsObj.getString(GenConstants.PARENT_MENU_ID);
            String parentMenuName = paramsObj.getString(GenConstants.PARENT_MENU_NAME);

            genTable.setTreeCode(treeCode);
            genTable.setTreeParentCode(treeParentCode);
            genTable.setTreeName(treeName);
            genTable.setParentMenuId(parentMenuId);
            genTable.setParentMenuName(parentMenuName);
        }
    }

    /**
     * 获取代码生成地址
     *
     * @param table    业务表信息
     * @param template 模板文件路径
     * @return 生成地址
     */
    public static String getGenPath(GenTableBO table, String template) {
        String genPath = table.getGenPath();
        if (StringUtils.equals(genPath, "/")) {
            return System.getProperty("user.dir") + File.separator + "src" + File.separator + VelocityUtils.getFileName(template, table);
        }
        return genPath + File.separator + VelocityUtils.getFileName(template, table);
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy