若依微服务版本代码生成对sqlserver的支持

5 篇文章 0 订阅
4 篇文章 0 订阅


前言

公司的业务数据库使用的sqlserver,所以原来的mysql数据库代码生成对我来说没多大意义,所以改造兼容一下.


提示:我使用的sqlserver版本为2012R2,其他版本可能会存在语法不一致问题,如有不一样的,自行处理即可

一、后端

1.pom依赖

<!-- sqlserver-->
    <dependency>
        <groupId>com.microsoft.sqlserver</groupId>
        <artifactId>mssql-jdbc</artifactId>
    </dependency>

2.yml配置配置数据源

  datasource:
      # 主库数据源
      master:
        driver-class-name: com.mysql.cj.jdbc.Driver
        url: jdbc:mysql://127.0.0.1:3306/test?allowMultiQueries=true&useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&serverTimezone=GMT%2b8
        username: root
        password: 123456
      # 从库数据源
      sqlserver:
        driver-class-name: com.microsoft.sqlserver.jdbc.SQLServerDriver
        url: jdbc:sqlserver://127.0.0.1:1433;databasename=DEMO
        username: admin
        password: 123456

3.新增service/impl

SqlServerGenTableColumnServiceImpl

package com.jovefast.gen.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.jovefast.common.core.text.Convert;
import com.jovefast.gen.domain.GenTableColumn;
import com.jovefast.gen.mapper.SqlServerGenTableColumnMapper;
import com.jovefast.gen.service.IGenTableColumnService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 业务字段 服务层实现
 * 
 * @author Acechengui
 */
@Service
@Primary
@DS("sqlserver")
public class SqlServerGenTableColumnServiceImpl implements IGenTableColumnService
{
	@Autowired
	private SqlServerGenTableColumnMapper genTableColumnMapper;

	/**
     * 查询业务字段列表
     * 
     * @param tableId 业务字段编号
     * @return 业务字段集合
     */
	@Override
	public List<GenTableColumn> selectGenTableColumnListByTableId(Long tableId)
	{
	    return genTableColumnMapper.selectGenTableColumnListByTableId(tableId);
	}
	
    /**
     * 新增业务字段
     * 
     * @param genTableColumn 业务字段信息
     * @return 结果
     */
	@Override
	public int insertGenTableColumn(GenTableColumn genTableColumn)
	{
	    return genTableColumnMapper.insertGenTableColumn(genTableColumn);
	}
	
	/**
     * 修改业务字段
     * 
     * @param genTableColumn 业务字段信息
     * @return 结果
     */
	@Override
	public int updateGenTableColumn(GenTableColumn genTableColumn)
	{
	    return genTableColumnMapper.updateGenTableColumn(genTableColumn);
	}

	/**
     * 删除业务字段对象
     * 
     * @param ids 需要删除的数据ID
     * @return 结果
     */
	@Override
	public int deleteGenTableColumnByIds(String ids)
	{
		return genTableColumnMapper.deleteGenTableColumnByIds(Convert.toLongArray(ids));
	}
}

SqlServerGenTableServiceImpl

package com.jovefast.gen.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.jovefast.common.core.constant.Constants;
import com.jovefast.common.core.constant.GenConstants;
import com.jovefast.common.core.exception.ServiceException;
import com.jovefast.common.core.text.CharsetKit;
import com.jovefast.common.core.utils.StringUtils;
import com.jovefast.common.security.utils.SecurityUtils;
import com.jovefast.gen.domain.GenTable;
import com.jovefast.gen.domain.GenTableColumn;
import com.jovefast.gen.mapper.SqlServerGenTableColumnMapper;
import com.jovefast.gen.mapper.SqlServerGenTableMapper;
import com.jovefast.gen.service.IGenTableService;
import com.jovefast.gen.util.GenUtils;
import com.jovefast.gen.util.VelocityInitializer;
import com.jovefast.gen.util.VelocityUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
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.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * 业务 服务层实现
 * 
 * @author Acechengui
 */
@Service
@Primary
@DS("sqlserver")
public class SqlServerGenTableServiceImpl implements IGenTableService
{
    private static final Logger log = LoggerFactory.getLogger(SqlServerGenTableServiceImpl.class);

    @Autowired
    private SqlServerGenTableMapper sqlServerGenTableMapper;

    @Autowired
    private SqlServerGenTableColumnMapper sqlServerGenTableColumnMapper;

    /**
     * 查询业务信息
     * 
     * @param id 业务ID
     * @return 业务信息
     */
    @Override
    public GenTable selectGenTableById(Long id)
    {
        GenTable genTable = sqlServerGenTableMapper.selectGenTableById(id);
        setTableFromOptions(genTable);
        return genTable;
    }

    /**
     * 查询业务列表
     * 
     * @param genTable 业务信息
     * @return 业务集合
     */
    @Override
    public List<GenTable> selectGenTableList(GenTable genTable)
    {
        return sqlServerGenTableMapper.selectGenTableList(genTable);
    }

    /**
     * 查询据库列表
     * 
     * @param genTable 业务信息
     * @return 数据库表集合
     */
    @Override
    public List<GenTable> selectDbTableList(GenTable genTable)
    {
        return sqlServerGenTableMapper.selectDbTableList(genTable);
    }

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

    /**
     * 查询所有表信息
     * 
     * @return 表信息集合
     */
    @Override
    public List<GenTable> selectGenTableAll()
    {
        return sqlServerGenTableMapper.selectGenTableAll();
    }

    /**
     * 修改业务
     * 
     * @param genTable 业务信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateGenTable(GenTable genTable)
    {
        String options = JSON.toJSONString(genTable.getParams());
        genTable.setOptions(options);
        int row = sqlServerGenTableMapper.updateGenTable(genTable);
        if (row > 0)
        {
            for (GenTableColumn cenTableColumn : genTable.getColumns())
            {
                sqlServerGenTableColumnMapper.updateGenTableColumn(cenTableColumn);
            }
        }
    }

    /**
     * 删除业务对象
     * 
     * @param tableIds 需要删除的数据ID
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteGenTableByIds(Long[] tableIds)
    {
        sqlServerGenTableMapper.deleteGenTableByIds(tableIds);
        sqlServerGenTableColumnMapper.deleteGenTableColumnByIds(tableIds);
    }

    /**
     * 导入表结构
     * 
     * @param tableList 导入表列表
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void importGenTable(List<GenTable> tableList)
    {
        String operName = SecurityUtils.getUsername();
        try
        {
            for (GenTable table : tableList)
            {
                String tableName = table.getTableName();
                GenUtils.initTable(table, operName);
                int row = sqlServerGenTableMapper.insertGenTable(table);
                if (row > 0)
                {
                    // 保存列信息
                    List<GenTableColumn> genTableColumns = sqlServerGenTableColumnMapper.selectDbTableColumnsByName(tableName);
                    for (GenTableColumn column : genTableColumns)
                    {
                        GenUtils.initColumnField(column, table);
                        sqlServerGenTableColumnMapper.insertGenTableColumn(column);
                    }
                }
            }
        }
        catch (Exception e)
        {
            throw new ServiceException("导入失败:" + e.getMessage());
        }
    }

    /**
     * 预览代码
     * 
     * @param tableId 表编号
     * @return 预览数据列表
     */
    @Override
    public Map<String, String> previewCode(Long tableId)
    {
        Map<String, String> dataMap = new LinkedHashMap<>();
        // 查询表信息
        GenTable table = sqlServerGenTableMapper.selectGenTableById(tableId);
        // 设置主子表信息
        setSubTable(table);
        // 设置主键列信息
        setPkColumn(table);
        VelocityInitializer.initVelocity();

        VelocityContext context = VelocityUtils.prepareContext(table);

        // 获取模板列表
        List<String> templates = VelocityUtils.getTemplateList(table.getTplCategory());
        for (String template : templates)
        {
            // 渲染模板
            StringWriter sw = new StringWriter();
            Template tpl = Velocity.getTemplate(template, Constants.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 表名称
     */
    @Override
    public void generatorCode(String tableName)
    {
        // 查询表信息
        GenTable table = sqlServerGenTableMapper.selectGenTableByName(tableName);
        // 设置主子表信息
        setSubTable(table);
        // 设置主键列信息
        setPkColumn(table);

        VelocityInitializer.initVelocity();

        VelocityContext context = VelocityUtils.prepareContext(table);

        // 获取模板列表
        List<String> templates = VelocityUtils.getTemplateList(table.getTplCategory());
        for (String template : templates)
        {
            if (!StringUtils.containsAny(template, "sql.vm", "api.js.vm", "index.vue.vm", "index-tree.vue.vm"))
            {
                // 渲染模板
                StringWriter sw = new StringWriter();
                Template tpl = Velocity.getTemplate(template, Constants.UTF8);
                tpl.merge(context, sw);
                try
                {
                    String path = getGenPath(table, template);
                    FileUtils.writeStringToFile(new File(path), sw.toString(), CharsetKit.UTF_8);
                }
                catch (IOException e)
                {
                    throw new ServiceException("渲染模板失败,表名:" + table.getTableName());
                }
            }
        }
    }

    /**
     * 同步数据库
     * 
     * @param tableName 表名称
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void synchDb(String tableName)
    {
        GenTable table = sqlServerGenTableMapper.selectGenTableByName(tableName);
        List<GenTableColumn> tableColumns = table.getColumns();
        Map<String, GenTableColumn> tableColumnMap = tableColumns.stream().collect(Collectors.toMap(GenTableColumn::getColumnName, Function.identity()));

        List<GenTableColumn> dbTableColumns = sqlServerGenTableColumnMapper.selectDbTableColumnsByName(tableName);
        if (StringUtils.isEmpty(dbTableColumns))
        {
            throw new ServiceException("同步数据失败,原表结构不存在");
        }
        List<String> dbTableColumnNames = dbTableColumns.stream().map(GenTableColumn::getColumnName).collect(Collectors.toList());

        dbTableColumns.forEach(column -> {
            GenUtils.initColumnField(column, table);
            if (tableColumnMap.containsKey(column.getColumnName()))
            {
                GenTableColumn prevColumn = tableColumnMap.get(column.getColumnName());
                column.setColumnId(prevColumn.getColumnId());
                if (column.isList())
                {
                    // 如果是列表,继续保留查询方式/字典类型选项
                    column.setDictType(prevColumn.getDictType());
                    column.setQueryType(prevColumn.getQueryType());
                }
                if (StringUtils.isNotEmpty(prevColumn.getIsRequired()) && !column.isPk()
                        && (column.isInsert() || column.isEdit())
                        && ((column.isUsableColumn()) || (!column.isSuperColumn())))
                {
                    // 如果是(新增/修改&非主键/非忽略及父属性),继续保留必填/显示类型选项
                    column.setIsRequired(prevColumn.getIsRequired());
                    column.setHtmlType(prevColumn.getHtmlType());
                }
                sqlServerGenTableColumnMapper.updateGenTableColumn(column);
            }
            else
            {
                sqlServerGenTableColumnMapper.insertGenTableColumn(column);
            }
        });

        List<GenTableColumn> delColumns = tableColumns.stream().filter(column -> !dbTableColumnNames.contains(column.getColumnName())).collect(Collectors.toList());
        if (StringUtils.isNotEmpty(delColumns))
        {
            sqlServerGenTableColumnMapper.deleteGenTableColumns(delColumns);
        }
    }

    /**
     * 批量生成代码(下载方式)
     * 
     * @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)
    {
        // 查询表信息
        GenTable table = sqlServerGenTableMapper.selectGenTableByName(tableName);
        // 设置主子表信息
        setSubTable(table);
        // 设置主键列信息
        setPkColumn(table);

        VelocityInitializer.initVelocity();

        VelocityContext context = VelocityUtils.prepareContext(table);

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

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

    /**
     * 设置主键列信息
     * 
     * @param table 业务表信息
     */
    public void setPkColumn(GenTable table)
    {
        for (GenTableColumn column : table.getColumns())
        {
            if (column.isPk())
            {
                table.setPkColumn(column);
                break;
            }
        }
        if (StringUtils.isNull(table.getPkColumn()))
        {
            table.setPkColumn(table.getColumns().get(0));
        }
        if (GenConstants.TPL_SUB.equals(table.getTplCategory()))
        {
            for (GenTableColumn column : table.getSubTable().getColumns())
            {
                if (column.isPk())
                {
                    table.getSubTable().setPkColumn(column);
                    break;
                }
            }
            if (StringUtils.isNull(table.getSubTable().getPkColumn()))
            {
                table.getSubTable().setPkColumn(table.getSubTable().getColumns().get(0));
            }
        }
    }

    /**
     * 设置主子表信息
     * 
     * @param table 业务表信息
     */
    public void setSubTable(GenTable table)
    {
        String subTableName = table.getSubTableName();
        if (StringUtils.isNotEmpty(subTableName))
        {
            table.setSubTable(sqlServerGenTableMapper.selectGenTableByName(subTableName));
        }
    }

    /**
     * 设置代码生成其他选项值
     * 
     * @param genTable 设置后的生成对象
     */
    public void setTableFromOptions(GenTable genTable)
    {
        JSONObject paramsObj = JSON.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(GenTable 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);
    }
}

注意

这里使用了@DS(“sqlserver”)注解用于切换自动切换数据源,而@Primary注解便是用于切换你是要用mysql代码生成,还是sqlserver代码生成

4.新增mapper接口

SqlServerGenTableColumnMapper

package com.jovefast.gen.mapper;

import com.jovefast.gen.domain.GenTableColumn;

import java.util.List;

/**
 * 业务字段 数据层
 * 
 * @author Acechengui
 */
public interface SqlServerGenTableColumnMapper
{
    /**
     * 根据表名称查询列信息
     * 
     * @param tableName 表名称
     * @return 列信息
     */
    List<GenTableColumn> selectDbTableColumnsByName(String tableName);

    /**
     * 查询业务字段列表
     * 
     * @param tableId 业务字段编号
     * @return 业务字段集合
     */
    List<GenTableColumn> selectGenTableColumnListByTableId(Long tableId);

    /**
     * 新增业务字段
     * 
     * @param genTableColumn 业务字段信息
     * @return 结果
     */
    int insertGenTableColumn(GenTableColumn genTableColumn);

    /**
     * 修改业务字段
     * 
     * @param genTableColumn 业务字段信息
     * @return 结果
     */
    int updateGenTableColumn(GenTableColumn genTableColumn);

    /**
     * 删除业务字段
     * 
     * @param genTableColumns 列数据
     * @return 结果
     */
    int deleteGenTableColumns(List<GenTableColumn> genTableColumns);

    /**
     * 批量删除业务字段
     * 
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    int deleteGenTableColumnByIds(Long[] ids);
}

SqlServerGenTableMapper

package com.jovefast.gen.mapper;

import com.jovefast.gen.domain.GenTable;

import java.util.List;

/**
 * 业务 数据层
 * 
 * @author Acechengui
 */
public interface SqlServerGenTableMapper
{
    /**
     * 查询业务列表
     * 
     * @param genTable 业务信息
     * @return 业务集合
     */
    List<GenTable> selectGenTableList(GenTable genTable);

    /**
     * 查询据库列表
     * 
     * @param genTable 业务信息
     * @return 数据库表集合
     */
    List<GenTable> selectDbTableList(GenTable genTable);

    /**
     * 查询据库列表
     * 
     * @param tableNames 表名称组
     * @return 数据库表集合
     */
    List<GenTable> selectDbTableListByNames(String[] tableNames);

    /**
     * 查询所有表信息
     * 
     * @return 表信息集合
     */
    List<GenTable> selectGenTableAll();

    /**
     * 查询表ID业务信息
     * 
     * @param id 业务ID
     * @return 业务信息
     */
    GenTable selectGenTableById(Long id);

    /**
     * 查询表名称业务信息
     * 
     * @param tableName 表名称
     * @return 业务信息
     */
    GenTable selectGenTableByName(String tableName);

    /**
     * 新增业务
     * 
     * @param genTable 业务信息
     * @return 结果
     */
    int insertGenTable(GenTable genTable);

    /**
     * 修改业务
     * 
     * @param genTable 业务信息
     * @return 结果
     */
    int updateGenTable(GenTable genTable);

    /**
     * 批量删除业务
     * 
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    int deleteGenTableByIds(Long[] ids);
}

5.新增xml

SqlServerGenTableMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.jovefast.gen.mapper.SqlServerGenTableMapper">

	<resultMap type="GenTable" id="GenTableResult">
	    <id     property="tableId"        column="table_id"          />
		<result property="tableName"      column="table_name"        />
		<result property="tableComment"   column="table_comment"     />
		<result property="subTableName"   column="sub_table_name"    />
		<result property="subTableFkName" column="sub_table_fk_name" />
		<result property="className"      column="class_name"        />
		<result property="tplCategory"    column="tpl_category"      />
		<result property="packageName"    column="package_name"      />
		<result property="moduleName"     column="module_name"       />
		<result property="businessName"   column="business_name"     />
		<result property="functionName"   column="function_name"     />
		<result property="functionAuthor" column="function_author"   />
		<result property="genType"        column="gen_type"          />
		<result property="genPath"        column="gen_path"          />
		<result property="options"        column="options"           />
		<result property="createBy"       column="create_by"         />
		<result property="createTime"     column="create_time"       />
		<result property="updateBy"       column="update_by"         />
		<result property="updateTime"     column="update_time"       />
		<result property="remark"         column="remark"            />
		<collection  property="columns"  javaType="java.util.List"  resultMap="GenTableColumnResult" />
	</resultMap>
	
	<resultMap type="GenTableColumn" id="GenTableColumnResult">
        <id     property="columnId"       column="column_id"      />
        <result property="tableId"        column="table_id"       />
        <result property="columnName"     column="column_name"    />
        <result property="columnComment"  column="column_comment" />
        <result property="columnType"     column="column_type"    />
        <result property="javaType"       column="java_type"      />
        <result property="javaField"      column="java_field"     />
        <result property="isPk"           column="is_pk"          />
        <result property="isIncrement"    column="is_increment"   />
        <result property="isRequired"     column="is_required"    />
        <result property="isInsert"       column="is_insert"      />
        <result property="isEdit"         column="is_edit"        />
        <result property="isList"         column="is_list"        />
        <result property="isQuery"        column="is_query"       />
        <result property="queryType"      column="query_type"     />
        <result property="htmlType"       column="html_type"      />
        <result property="dictType"       column="dict_type"      />
        <result property="sort"           column="sort"           />
        <result property="createBy"       column="create_by"      />
        <result property="createTime"     column="create_time"    />
        <result property="updateBy"       column="update_by"      />
        <result property="updateTime"     column="update_time"    />
    </resultMap>
	
	<sql id="selectGenTableVo">
        select table_id, table_name, table_comment, sub_table_name, sub_table_fk_name, class_name, tpl_category, package_name, module_name, business_name, function_name, function_author, gen_type, gen_path, options, create_by, create_time, update_by, update_time, remark from gen_table
    </sql>
    
    <select id="selectGenTableList" parameterType="GenTable" resultMap="GenTableResult">
		<include refid="selectGenTableVo"/>
		<where>
			<if test="tableName != null and tableName != ''">
				AND lower(table_name) like lower(concat('%', #{tableName}, '%'))
			</if>
			<if test="tableComment != null and tableComment != ''">
				AND lower(table_comment) like lower(concat('%', #{tableComment}, '%'))
			</if>
			<if test="params.beginTime != null and params.beginTime != ''"><!-- 开始时间检索 -->
				AND date_format(create_time,'%y%m%d') &gt;= date_format(#{params.beginTime},'%y%m%d')
			</if>
			<if test="params.endTime != null and params.endTime != ''"><!-- 结束时间检索 -->
				AND date_format(create_time,'%y%m%d') &lt;= date_format(#{params.endTime},'%y%m%d')
			</if>
		</where>
	</select>

	<select id="selectDbTableList" parameterType="GenTable" resultMap="GenTableResult">
		SELECT
		t.name AS table_name,
		CAST(ep.value AS NVARCHAR) AS table_comment,
		t.create_date AS create_time,
		t.modify_date AS update_time
		FROM
		sys.tables t
		LEFT JOIN
		sys.extended_properties ep ON ep.major_id = t.object_id AND ep.minor_id = 0 AND ep.name = 'MS_Description'
		where t.name NOT LIKE 'gen_%'
		<if test="tableName != null and tableName != ''">
			AND lower(t.name) like lower(concat('%', #{tableName}, '%'))
		</if>
		<if test="tableComment != null and tableComment != ''">
			AND lower(CAST(ep.value AS NVARCHAR)) like lower(concat('%', #{tableComment}, '%'))
		</if>
		<if test="params.beginTime != null and params.beginTime != ''"><!-- 开始时间检索 -->
			AND date_format(create_time,'%y%m%d') &gt;= date_format(#{params.beginTime},'%y%m%d')
		</if>
		<if test="params.endTime != null and params.endTime != ''"><!-- 结束时间检索 -->
			AND date_format(create_time,'%y%m%d') &lt;= date_format(#{params.endTime},'%y%m%d')
		</if>
		ORDER BY t.create_date desc
	</select>
	
	<select id="selectDbTableListByNames" resultMap="GenTableResult">
		SELECT
		t.name AS table_name,
		CAST(ep.value AS NVARCHAR) AS table_comment,
		t.create_date AS create_time,
		t.modify_date AS update_time
		FROM
		sys.tables t
		LEFT JOIN
		sys.extended_properties ep ON ep.major_id = t.object_id AND ep.minor_id = 0 AND ep.name = 'MS_Description'
		where t.name NOT LIKE 'gen_%'
		and t.name in
		<foreach collection="array" item="name" open="(" separator="," close=")">
			#{name}
		</foreach>
		ORDER BY
		t.name
	</select>
	
	<select id="selectTableByName" parameterType="String" resultMap="GenTableResult">
		SELECT
		t.name AS table_id,
		CAST(ep.value AS NVARCHAR) AS table_comment,
		t.create_date AS create_time,
		t.modify_date AS update_time
		FROM
		sys.tables t
		LEFT JOIN
		sys.extended_properties ep ON ep.major_id = t.object_id AND ep.minor_id = 0 AND ep.name = 'MS_Description'
		where CAST(ep.value AS NVARCHAR) <![CDATA[ <> ]]> ''
		  and t.name = #{tableName}
	</select>
	
	<select id="selectGenTableById" parameterType="Long" resultMap="GenTableResult">
	    SELECT t.table_id, t.table_name, t.table_comment, t.sub_table_name, t.sub_table_fk_name, t.class_name, t.tpl_category, t.package_name, t.module_name, t.business_name, t.function_name, t.function_author, t.gen_type, t.gen_path, t.options, t.remark,
			   c.column_id, c.column_name, c.column_comment, c.column_type, c.java_type, c.java_field, c.is_pk, c.is_increment, c.is_required, c.is_insert, c.is_edit, c.is_list, c.is_query, c.query_type, c.html_type, c.dict_type, c.sort
		FROM gen_table t
			 LEFT JOIN gen_table_column c ON t.table_id = c.table_id
		where t.table_id = #{tableId} order by c.sort
	</select>
	
	<select id="selectGenTableByName" parameterType="String" resultMap="GenTableResult">
	    SELECT t.table_id, t.table_name, t.table_comment, t.sub_table_name, t.sub_table_fk_name, t.class_name, t.tpl_category, t.package_name, t.module_name, t.business_name, t.function_name, t.function_author, t.gen_type, t.gen_path, t.options, t.remark,
			   c.column_id, c.column_name, c.column_comment, c.column_type, c.java_type, c.java_field, c.is_pk, c.is_increment, c.is_required, c.is_insert, c.is_edit, c.is_list, c.is_query, c.query_type, c.html_type, c.dict_type, c.sort
		FROM gen_table t
			 LEFT JOIN gen_table_column c ON t.table_id = c.table_id
		where t.table_name = #{tableName} order by c.sort
	</select>
	
	<select id="selectGenTableAll" parameterType="String" resultMap="GenTableResult">
	    SELECT t.table_id, t.table_name, t.table_comment, t.sub_table_name, t.sub_table_fk_name, t.class_name, t.tpl_category, t.package_name, t.module_name, t.business_name, t.function_name, t.function_author, t.options, t.remark,
			   c.column_id, c.column_name, c.column_comment, c.column_type, c.java_type, c.java_field, c.is_pk, c.is_increment, c.is_required, c.is_insert, c.is_edit, c.is_list, c.is_query, c.query_type, c.html_type, c.dict_type, c.sort
		FROM gen_table t
			 LEFT JOIN gen_table_column c ON t.table_id = c.table_id
		order by c.sort
	</select>
	
	<insert id="insertGenTable" parameterType="GenTable" useGeneratedKeys="true" keyProperty="tableId">
        insert into gen_table (
			<if test="tableName != null">table_name,</if>
			<if test="tableComment != null and tableComment != ''">table_comment,</if>
			<if test="className != null and className != ''">class_name,</if>
			<if test="tplCategory != null and tplCategory != ''">tpl_category,</if>
			<if test="packageName != null and packageName != ''">package_name,</if>
			<if test="moduleName != null and moduleName != ''">module_name,</if>
			<if test="businessName != null and businessName != ''">business_name,</if>
			<if test="functionName != null and functionName != ''">function_name,</if>
			<if test="functionAuthor != null and functionAuthor != ''">function_author,</if>
			<if test="genType != null and genType != ''">gen_type,</if>
			<if test="genPath != null and genPath != ''">gen_path,</if>
			<if test="remark != null and remark != ''">remark,</if>
 			<if test="createBy != null and createBy != ''">create_by,</if>
			create_time
         )values(
			<if test="tableName != null">#{tableName},</if>
			<if test="tableComment != null and tableComment != ''">#{tableComment},</if>
			<if test="className != null and className != ''">#{className},</if>
			<if test="tplCategory != null and tplCategory != ''">#{tplCategory},</if>
			<if test="packageName != null and packageName != ''">#{packageName},</if>
			<if test="moduleName != null and moduleName != ''">#{moduleName},</if>
			<if test="businessName != null and businessName != ''">#{businessName},</if>
			<if test="functionName != null and functionName != ''">#{functionName},</if>
			<if test="functionAuthor != null and functionAuthor != ''">#{functionAuthor},</if>
			<if test="genType != null and genType != ''">#{genType},</if>
			<if test="genPath != null and genPath != ''">#{genPath},</if>
			<if test="remark != null and remark != ''">#{remark},</if>
 			<if test="createBy != null and createBy != ''">#{createBy},</if>
			GETDATE()
         )
    </insert>
    
    <update id="updateGenTable" parameterType="GenTable">
        update gen_table
        <set>
            <if test="tableName != null">table_name = #{tableName},</if>
            <if test="tableComment != null and tableComment != ''">table_comment = #{tableComment},</if>
            <if test="subTableName != null">sub_table_name = #{subTableName},</if>
            <if test="subTableFkName != null">sub_table_fk_name = #{subTableFkName},</if>
            <if test="className != null and className != ''">class_name = #{className},</if>
            <if test="functionAuthor != null and functionAuthor != ''">function_author = #{functionAuthor},</if>
            <if test="genType != null and genType != ''">gen_type = #{genType},</if>
            <if test="genPath != null and genPath != ''">gen_path = #{genPath},</if>
            <if test="tplCategory != null and tplCategory != ''">tpl_category = #{tplCategory},</if>
            <if test="packageName != null and packageName != ''">package_name = #{packageName},</if>
            <if test="moduleName != null and moduleName != ''">module_name = #{moduleName},</if>
            <if test="businessName != null and businessName != ''">business_name = #{businessName},</if>
            <if test="functionName != null and functionName != ''">function_name = #{functionName},</if>
            <if test="options != null and options != ''">options = #{options},</if>
            <if test="updateBy != null and updateBy != ''">update_by = #{updateBy},</if>
            <if test="remark != null">remark = #{remark},</if>
            update_time = GETDATE()
        </set>
        where table_id = #{tableId}
    </update>
    
    <delete id="deleteGenTableByIds" parameterType="Long">
        delete from gen_table where table_id in 
        <foreach collection="array" item="tableId" open="(" separator="," close=")">
            #{tableId}
        </foreach>
    </delete>
</mapper>

SqlServerGenTableColumnMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.jovefast.gen.mapper.SqlServerGenTableColumnMapper">
    <resultMap type="GenTableColumn" id="GenTableColumnResult">
        <id     property="columnId"       column="column_id"      />
        <result property="tableId"        column="table_id"       />
        <result property="columnName"     column="column_name"    />
        <result property="columnComment"  column="column_comment" />
        <result property="columnType"     column="column_type"    />
        <result property="javaType"       column="java_type"      />
        <result property="javaField"      column="java_field"     />
        <result property="isPk"           column="is_pk"          />
        <result property="isIncrement"    column="is_increment"   />
        <result property="isRequired"     column="is_required"    />
        <result property="isInsert"       column="is_insert"      />
        <result property="isEdit"         column="is_edit"        />
        <result property="isList"         column="is_list"        />
        <result property="isQuery"        column="is_query"       />
        <result property="queryType"      column="query_type"     />
        <result property="htmlType"       column="html_type"      />
        <result property="dictType"       column="dict_type"      />
        <result property="sort"           column="sort"           />
        <result property="createBy"       column="create_by"      />
        <result property="createTime"     column="create_time"    />
        <result property="updateBy"       column="update_by"      />
        <result property="updateTime"     column="update_time"    />
    </resultMap>
    <sql id="selectGenTableColumnVo">
        select column_id, table_id, column_name, column_comment, column_type, java_type, java_field, is_pk, is_increment, is_required, is_insert, is_edit, is_list, is_query, query_type, html_type, dict_type, sort, create_by, create_time, update_by, update_time from gen_table_column
    </sql>
    <select id="selectGenTableColumnListByTableId" parameterType="GenTableColumn" resultMap="GenTableColumnResult">
        <include refid="selectGenTableColumnVo"/>
        where table_id = #{tableId}
        order by sort
    </select>
    <select id="selectDbTableColumnsByName" parameterType="String" resultMap="GenTableColumnResult">
        SELECT
            COLUMN_NAME AS column_name,
            CASE
                WHEN IS_NULLABLE = 'NO' AND COLUMNPROPERTY(OBJECT_ID(TABLE_NAME), COLUMN_NAME, 'IsIdentity') = 0
                    THEN '1'
                ELSE NULL
                END AS is_required,
            CASE
                WHEN COLUMNPROPERTY(OBJECT_ID(TABLE_NAME), COLUMN_NAME, 'IsIdentity') = 1
                    THEN '1'
                ELSE '0'
                END AS is_pk,
            ORDINAL_POSITION AS sort,
            '' AS COLUMN_COMMENT,
            CASE
                WHEN COLUMNPROPERTY(OBJECT_ID(TABLE_NAME), COLUMN_NAME, 'IsIdentity') = 1
                    THEN '1'
                ELSE '0'
                END AS is_increment,
            DATA_TYPE +
            CASE
                WHEN CHARACTER_MAXIMUM_LENGTH IS NOT NULL
                    THEN '(' + CAST(CHARACTER_MAXIMUM_LENGTH AS VARCHAR) + ')'
                ELSE ''
                END AS column_type
        FROM
            INFORMATION_SCHEMA.COLUMNS
        WHERE
            TABLE_NAME = #{tableName}
        ORDER BY
            ORDINAL_POSITION
    </select>
    <insert id="insertGenTableColumn" parameterType="GenTableColumn" useGeneratedKeys="true" keyProperty="columnId">
        insert into gen_table_column (
        <if test="tableId != null and tableId != ''">table_id,</if>
        <if test="columnName != null and columnName != ''">column_name,</if>
        <if test="columnComment != null and columnComment != ''">column_comment,</if>
        <if test="columnType != null and columnType != ''">column_type,</if>
        <if test="javaType != null and javaType != ''">java_type,</if>
        <if test="javaField != null  and javaField != ''">java_field,</if>
        <if test="isPk != null and isPk != ''">is_pk,</if>
        <if test="isIncrement != null and isIncrement != ''">is_increment,</if>
        <if test="isRequired != null and isRequired != ''">is_required,</if>
        <if test="isInsert != null and isInsert != ''">is_insert,</if>
        <if test="isEdit != null and isEdit != ''">is_edit,</if>
        <if test="isList != null and isList != ''">is_list,</if>
        <if test="isQuery != null and isQuery != ''">is_query,</if>
        <if test="queryType != null and queryType != ''">query_type,</if>
        <if test="htmlType != null and htmlType != ''">html_type,</if>
        <if test="dictType != null and dictType != ''">dict_type,</if>
        <if test="sort != null">sort,</if>
        <if test="createBy != null and createBy != ''">create_by,</if>
        create_time
        )values(
        <if test="tableId != null and tableId != ''">#{tableId},</if>
        <if test="columnName != null and columnName != ''">#{columnName},</if>
        <if test="columnComment != null and columnComment != ''">#{columnComment},</if>
        <if test="columnType != null and columnType != ''">#{columnType},</if>
        <if test="javaType != null and javaType != ''">#{javaType},</if>
        <if test="javaField != null and javaField != ''">#{javaField},</if>
        <if test="isPk != null and isPk != ''">#{isPk},</if>
        <if test="isIncrement != null and isIncrement != ''">#{isIncrement},</if>
        <if test="isRequired != null and isRequired != ''">#{isRequired},</if>
        <if test="isInsert != null and isInsert != ''">#{isInsert},</if>
        <if test="isEdit != null and isEdit != ''">#{isEdit},</if>
        <if test="isList != null and isList != ''">#{isList},</if>
        <if test="isQuery != null and isQuery != ''">#{isQuery},</if>
        <if test="queryType != null and queryType != ''">#{queryType},</if>
        <if test="htmlType != null and htmlType != ''">#{htmlType},</if>
        <if test="dictType != null and dictType != ''">#{dictType},</if>
        <if test="sort != null">#{sort},</if>
        <if test="createBy != null and createBy != ''">#{createBy},</if>
        getdate()
        )
    </insert>
    <update id="updateGenTableColumn" parameterType="GenTableColumn">
        update gen_table_column
        <set>
            <if test="columnComment != null">column_comment = #{columnComment},</if>
            <if test="javaType != null">java_type = #{javaType},</if>
            <if test="javaField != null">java_field = #{javaField},</if>
            <if test="isInsert != null">is_insert = #{isInsert},</if>
            <if test="isEdit != null">is_edit = #{isEdit},</if>
            <if test="isList != null">is_list = #{isList},</if>
            <if test="isQuery != null">is_query = #{isQuery},</if>
            <if test="isRequired != null">is_required = #{isRequired},</if>
            <if test="queryType != null">query_type = #{queryType},</if>
            <if test="htmlType != null">html_type = #{htmlType},</if>
            <if test="dictType != null">dict_type = #{dictType},</if>
            <if test="sort != null">sort = #{sort},</if>
            <if test="updateBy != null">update_by = #{updateBy},</if>
            update_time = getdate()
        </set>
        where column_id = #{columnId}
    </update>
    <delete id="deleteGenTableColumnByIds" parameterType="Long">
        delete from gen_table_column where table_id in
        <foreach collection="array" item="tableId" open="(" separator="," close=")">
            #{tableId}
        </foreach>
    </delete>
    <delete id="deleteGenTableColumns">
        delete from gen_table_column where column_id in
        <foreach collection="list" item="item" open="(" separator="," close=")">
            #{item.columnId}
        </foreach>
    </delete>
</mapper>

二、数据库

在这里插入图片描述
哪个数据需要支持代码生成,对应的数据库,也要增加这两个表.

三、效果图

在这里插入图片描述

总结

增加以上代码与配置之后,想用哪个数据库的实现,就用@Primary标注切换即可,当然了,还可以更完善,比如在前端增加一个下拉选择,根据前端下拉选择来确定使用哪个的实现,这里就不展开了。

  • 10
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

辰鬼丫

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值