✨ Introducing new features. #2151 【代码生成】 支持ORACEL / SQL SERVER /PG 等其他数据源类型代码生成

This commit is contained in:
lengleng committed 2020-12-14 21:36:15 +08:00
1 parent 193a1f478b
commit e69a50c5ee
34 files changed
+826 -193

No files matched your search

@@ -17,7 +17,6 @@
package com.pig4cloud.pigx.common.data.mybatis;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.TenantLineInnerInterceptor;
@@ -83,7 +82,7 @@ public class MybatisPlusConfiguration implements WebMvcConfigurer {
dataScopeInnerInterceptor.setDataScopeHandle(dataScopeHandle());
interceptor.addInnerInterceptor(dataScopeInnerInterceptor);
// 分页支持
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
interceptor.addInnerInterceptor(new PaginationInnerInterceptor());
return interceptor;
}
@@ -32,5 +32,10 @@
<artifactId>druid-spring-boot-starter</artifactId>
<scope>provided</scope>
</dependency>
<!--拦截器依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
</dependency>
</dependencies>
</project>
@@ -22,6 +22,7 @@ import com.baomidou.dynamic.datasource.provider.DynamicDataSourceProvider;
import com.pig4cloud.pigx.common.datasource.config.DruidDataSourceProperties;
import com.pig4cloud.pigx.common.datasource.config.JdbcDynamicDataSourceProvider;
import com.pig4cloud.pigx.common.datasource.config.LastParamDsProcessor;
import com.pig4cloud.pigx.common.datasource.config.WebMvcConfig;
import lombok.AllArgsConstructor;
import org.jasypt.encryption.StringEncryptor;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
@@ -29,6 +30,7 @@ import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* @author lengleng
@@ -56,4 +58,9 @@ public class DynamicDataSourceAutoConfiguration {
return new LastParamDsProcessor();
}
@Bean
public WebMvcConfigurer webMvcConfigurer() {
return new WebMvcConfig();
}
}
@@ -0,0 +1,29 @@
package com.pig4cloud.pigx.common.datasource.config;
import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @author lengleng
* @date 2020/12/11
* <p>
* 清空上文的DS 设置避免污染当前线程
*/
public class ClearTtlDsInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
DynamicDataSourceContextHolder.clear();
return true;
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
Exception ex) {
DynamicDataSourceContextHolder.clear();
}
}
@@ -20,6 +20,8 @@ package com.pig4cloud.pigx.common.datasource.config;
import com.baomidou.dynamic.datasource.provider.AbstractJdbcDataSourceProvider;
import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DataSourceProperty;
import com.pig4cloud.pigx.common.datasource.support.DataSourceConstants;
import com.pig4cloud.pigx.common.datasource.util.DsConfTypeEnum;
import com.pig4cloud.pigx.common.datasource.util.DsJdbcUrlEnum;
import org.jasypt.encryption.StringEncryptor;
import java.sql.ResultSet;
@@ -61,9 +63,30 @@ public class JdbcDynamicDataSourceProvider extends AbstractJdbcDataSourceProvide
String name = rs.getString(DataSourceConstants.DS_NAME);
String username = rs.getString(DataSourceConstants.DS_USER_NAME);
String password = rs.getString(DataSourceConstants.DS_USER_PWD);
String url = rs.getString(DataSourceConstants.DS_JDBC_URL);
Integer confType = rs.getInt(DataSourceConstants.DS_CONFIG_TYPE);
String dsType = rs.getString(DataSourceConstants.DS_TYPE);
String url;
// JDBC 配置形式
DsJdbcUrlEnum urlEnum = DsJdbcUrlEnum.get(dsType);
if (DsConfTypeEnum.JDBC.getType().equals(confType)) {
url = rs.getString(DataSourceConstants.DS_JDBC_URL);
}
else if (DsJdbcUrlEnum.MSSQL.getDbName().equals(dsType)) {
String host = rs.getString(DataSourceConstants.DS_HOST);
String port = rs.getString(DataSourceConstants.DS_PORT);
String dsName = rs.getString(DataSourceConstants.DS_NAME);
String instance = rs.getString(DataSourceConstants.DS_INSTANCE);
url = String.format(urlEnum.getUrl(), host, instance, port, dsName);
}
else {
String host = rs.getString(DataSourceConstants.DS_HOST);
String port = rs.getString(DataSourceConstants.DS_PORT);
String dsName = rs.getString(DataSourceConstants.DS_NAME);
url = String.format(urlEnum.getUrl(), host, port, dsName);
}
DataSourceProperty property = new DataSourceProperty();
property.setDriverClassName(DataSourceConstants.DS_DRIVER);
property.setUsername(username);
property.setPassword(stringEncryptor.decrypt(password));
property.setUrl(url);
@@ -75,7 +98,6 @@ public class JdbcDynamicDataSourceProvider extends AbstractJdbcDataSourceProvide
property.setUsername(properties.getUsername());
property.setPassword(properties.getPassword());
property.setUrl(properties.getUrl());
property.setDriverClassName(DataSourceConstants.DS_DRIVER);
map.put(DataSourceConstants.DS_MASTER, property);
return map;
}
@@ -0,0 +1,17 @@
package com.pig4cloud.pigx.common.datasource.config;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* @author lengleng
* @date 2020/12/11
*/
public class WebMvcConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new ClearTtlDsInterceptor()).addPathPatterns("/**");
}
}
@@ -23,6 +23,11 @@ public interface DataSourceConstants {
*/
String DS_JDBC_URL = "url";
/**
* 配置类型
*/
String DS_CONFIG_TYPE = "conf_type";
/**
* 用户名
*/
@@ -34,8 +39,23 @@ public interface DataSourceConstants {
String DS_USER_PWD = "password";
/**
* 默认驱动名称
* 数据库类型
*/
String DS_DRIVER = "com.mysql.cj.jdbc.Driver";
String DS_TYPE = "ds_type";
/**
* 主机类型
*/
String DS_HOST = "host";
/**
* 端口
*/
String DS_PORT = "port";
/**
* 实例名称
*/
String DS_INSTANCE = "instance";
}
@@ -0,0 +1,30 @@
package com.pig4cloud.pigx.common.datasource.util;
import lombok.AllArgsConstructor;
import lombok.Getter;
/**
* @author lengleng
* @date 2020/12/11
* <p>
* 数据源配置类型
*/
@Getter
@AllArgsConstructor
public enum DsConfTypeEnum {
/**
* 主机链接
*/
HOST(0, "主机链接"),
/**
* JDBC链接
*/
JDBC(1, "JDBC链接");
private final Integer type;
private final String description;
}
@@ -0,0 +1,53 @@
package com.pig4cloud.pigx.common.datasource.util;
import lombok.AllArgsConstructor;
import lombok.Getter;
import java.util.Arrays;
/**
* @author lengleng
* @date 2020/12/11
* <p>
* jdbc-url
*/
@Getter
@AllArgsConstructor
public enum DsJdbcUrlEnum {
/**
* mysql 数据库
*/
MYSQL("mysql",
"jdbc:mysql://%s:%s/%s?characterEncoding=utf8"
+ "&zeroDateTimeBehavior=convertToNull&useSSL=false&useJDBCCompliantTimezoneShift=true"
+ "&useLegacyDatetimeCode=false&allowMultiQueries=true&allowPublicKeyRetrieval=true",
"mysql8 链接"),
/**
* pg 数据库
*/
PG("pg", "jdbc:postgresql://%s:%s/%s", "postgresql 链接"),
/**
* SQL SERVER
*/
MSSQL("mssql", "jdbc:sqlserver://%s\\%s:%s;database=%s;characterEncoding=UTF-8", "sqlserver 链接"),
/**
* oracle
*/
ORACLE("oracle", "jdbc:oracle:thin:@%s:%s:%s", "oracle 链接");
private final String dbName;
private final String url;
private final String description;
public static DsJdbcUrlEnum get(String dsType) {
return Arrays.stream(DsJdbcUrlEnum.values()).filter(dsJdbcUrlEnum -> dsType.equals(dsJdbcUrlEnum.getDbName()))
.findFirst().get();
}
}
@@ -62,10 +62,11 @@ public class SwaggerProvider implements SwaggerResourcesProvider {
.filter(predicateDefinition -> !swaggerProperties.getIgnoreProviders()
.contains(routeDefinition.getId()))
.map(predicateDefinition -> swaggerResource(routeDefinition.getId(),
predicateDefinition.getArgs()
.get(NameUtils.GENERATED_NAME_PREFIX + "0").replace("/**", API_URI))))
predicateDefinition.getArgs().get(NameUtils.GENERATED_NAME_PREFIX + "0").replace("/**",
API_URI))))
// 只显示注册中心 内已经正确启动的服务
.filter(swaggerResource -> discoveryClient.getServices().stream().anyMatch(s -> s.equals(swaggerResource.getName())))
.filter(swaggerResource -> discoveryClient.getServices().stream()
.anyMatch(s -> s.equals(swaggerResource.getName())))
.collect(Collectors.toList());
}
@@ -49,8 +49,7 @@ public class SysFileController {
/**
* 分页查询
*
* @param page 分页对象
* @param page 分页对象
* @param sysFile 文件管理
* @return
*/
@@ -62,7 +61,6 @@ public class SysFileController {
/**
* 通过id删除文件管理
*
* @param id id
* @return R
*/
@@ -76,7 +74,6 @@ public class SysFileController {
/**
* 上传文件 文件名采用uuid,避免原始文件名中带"-"符号导致下载的时候解析出现异常
*
* @param file 资源
* @return R(/ admin / bucketName / filename)
*/
@@ -87,8 +84,7 @@ public class SysFileController {
/**
* 获取文件
*
* @param bucket 桶名称
* @param bucket 桶名称
* @param fileName 文件空间/名称
* @param response
* @return
+22
View File
@@ -14,6 +14,11 @@
<description>代码生成模块</description>
<properties>
<sqlserver.version>4.0</sqlserver.version>
<oracle.version>12.1.0.1-atlassian-hosted</oracle.version>
</properties>
<dependencies>
<!--注册中心客户端-->
<dependency>
@@ -44,6 +49,23 @@
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- postgresql 驱动 -->
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
</dependency>
<!-- oracle 驱动 -->
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc6</artifactId>
<version>${oracle.version}</version>
</dependency>
<!-- sqlserver 驱动 -->
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>sqljdbc4</artifactId>
<version>${sqlserver.version}</version>
</dependency>
<!-- druid 连接池 -->
<dependency>
<groupId>com.alibaba</groupId>
@@ -50,10 +50,40 @@ public class GenDatasourceConf extends Model<GenDatasourceConf> {
private String name;
/**
* jdbcurl
* 数据库类型
*/
private String dsType;
/**
* 配置类型 (0 主机形式 | 1 url形式)
*/
private Integer confType;
/**
* 主机地址
*/
private String host;
/**
* 端口
*/
private Integer port;
/**
* jdbc-url
*/
private String url;
/**
* 实例
*/
private String instance;
/**
* 数据库名称
*/
private String dsName;
/**
* 用户名
*/
@@ -80,9 +110,4 @@ public class GenDatasourceConf extends Model<GenDatasourceConf> {
@TableLogic
private String delFlag;
/**
* 租户ID
*/
private Integer tenantId;
}
@@ -58,4 +58,9 @@ public class TableEntity {
*/
private String lowerClassName;
/**
* 数据库类型 (用于根据数据库个性化)
*/
private String dbType;
}
@@ -1,50 +0,0 @@
package com.pig4cloud.pigx.codegen.mapper;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pig4cloud.pigx.codegen.entity.ColumnEntity;
import com.pig4cloud.pigx.common.data.datascope.PigxBaseMapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
import java.util.Map;
/**
* @author lengleng
* @date 2020/5/18
*/
@Mapper
public interface GenTableColumnMapper extends PigxBaseMapper<ColumnEntity> {
/**
* 分页查询表分页信息
* @param page
* @param tableName
* @param dsName
* @return
*/
@DS("#last")
IPage<ColumnEntity> selectTableColumn(Page page, @Param("tableName") String tableName,
@Param("dsName") String dsName);
/**
* 查询表全部列信息
* @param tableName
* @param dsName
* @return
*/
@DS("#last")
List<ColumnEntity> selectTableColumn(@Param("tableName") String tableName, @Param("dsName") String dsName);
/**
* 查询表全部列信息
* @param tableName 表名称
* @param dsName 数据源名称
* @return
*/
@DS("#last")
List<Map<String, String>> selectMapTableColumn(@Param("tableName") String tableName, String dsName);
}
@@ -20,7 +20,8 @@ package com.pig4cloud.pigx.codegen.mapper;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.ibatis.annotations.Mapper;
import com.pig4cloud.pigx.codegen.entity.ColumnEntity;
import com.pig4cloud.pigx.common.data.datascope.PigxBaseMapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
@@ -32,8 +33,7 @@ import java.util.Map;
* @author lengleng
* @date 2018-07-30
*/
@Mapper
public interface GeneratorMapper {
public interface GeneratorMapper extends PigxBaseMapper<ColumnEntity> {
/**
* 分页查询表格
@@ -41,7 +41,7 @@ public interface GeneratorMapper {
* @param tableName 表名称
* @return
*/
IPage<List<Map<String, Object>>> queryList(Page page, @Param("tableName") String tableName);
IPage<List<Map<String, Object>>> queryTable(Page page, @Param("tableName") String tableName);
/**
* 查询表信息
@@ -52,4 +52,33 @@ public interface GeneratorMapper {
@DS("#last")
Map<String, String> queryTable(@Param("tableName") String tableName, String dsName);
/**
* 分页查询表分页信息
* @param page
* @param tableName
* @param dsName
* @return
*/
@DS("#last")
IPage<ColumnEntity> selectTableColumn(Page page, @Param("tableName") String tableName,
@Param("dsName") String dsName);
/**
* 查询表全部列信息
* @param tableName
* @param dsName
* @return
*/
@DS("#last")
List<ColumnEntity> selectTableColumn(@Param("tableName") String tableName, @Param("dsName") String dsName);
/**
* 查询表全部列信息
* @param tableName 表名称
* @param dsName 数据源名称
* @return
*/
@DS("#last")
List<Map<String, String>> selectMapTableColumn(@Param("tableName") String tableName, String dsName);
}
@@ -0,0 +1,31 @@
/*
* Copyright (c) 2018-2025, lengleng All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* Neither the name of the pig4cloud.com developer nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
* Author: lengleng (wangiegie@gmail.com)
*/
package com.pig4cloud.pigx.codegen.mapper;
import org.apache.ibatis.annotations.Mapper;
/**
* 支持 SQL SERVER 代码生成器
*
* @author lengleng
* @date 2020-12-11
*/
@Mapper
public interface GeneratorMssqlMapper extends GeneratorMapper {
}
@@ -0,0 +1,31 @@
/*
* Copyright (c) 2018-2025, lengleng All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* Neither the name of the pig4cloud.com developer nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
* Author: lengleng (wangiegie@gmail.com)
*/
package com.pig4cloud.pigx.codegen.mapper;
import org.apache.ibatis.annotations.Mapper;
/**
* 支持 MySql 代码生成器
*
* @author lengleng
* @date 2020-12-11
*/
@Mapper
public interface GeneratorMySqlMapper extends GeneratorMapper {
}
@@ -0,0 +1,31 @@
/*
* Copyright (c) 2018-2025, lengleng All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* Neither the name of the pig4cloud.com developer nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
* Author: lengleng (wangiegie@gmail.com)
*/
package com.pig4cloud.pigx.codegen.mapper;
import org.apache.ibatis.annotations.Mapper;
/**
* 支持 Oracle 代码生成器
*
* @author lengleng
* @date 2020-12-11
*/
@Mapper
public interface GeneratorOracleMapper extends GeneratorMapper {
}
@@ -0,0 +1,31 @@
/*
* Copyright (c) 2018-2025, lengleng All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* Neither the name of the pig4cloud.com developer nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
* Author: lengleng (wangiegie@gmail.com)
*/
package com.pig4cloud.pigx.codegen.mapper;
import org.apache.ibatis.annotations.Mapper;
/**
* 支持 PostgreSQL 代码生成器
*
* @author lengleng
* @date 2020-12-11
*/
@Mapper
public interface GeneratorPgMapper extends GeneratorMapper {
}
@@ -19,7 +19,6 @@ package com.pig4cloud.pigx.codegen.service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.pig4cloud.pigx.codegen.entity.ColumnEntity;
import com.pig4cloud.pigx.codegen.entity.GenConfig;
@@ -29,7 +28,7 @@ import com.pig4cloud.pigx.codegen.entity.GenConfig;
* @author lengleng
* @date 2020-05-18
*/
public interface GenTableColumnService extends IService<ColumnEntity> {
public interface GenTableColumnService {
/**
* 查询表的字段信息
@@ -25,6 +25,8 @@ import com.pig4cloud.pigx.codegen.entity.GenDatasourceConf;
import com.pig4cloud.pigx.codegen.mapper.GenDatasourceConfMapper;
import com.pig4cloud.pigx.codegen.service.GenDatasourceConfService;
import com.pig4cloud.pigx.common.core.util.SpringContextHolder;
import com.pig4cloud.pigx.common.datasource.util.DsConfTypeEnum;
import com.pig4cloud.pigx.common.datasource.util.DsJdbcUrlEnum;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.jasypt.encryption.StringEncryptor;
@@ -134,8 +136,24 @@ public class GenDatasourceConfServiceImpl extends ServiceImpl<GenDatasourceConfM
*/
@Override
public Boolean checkDataSource(GenDatasourceConf conf) {
try (Connection connection = DriverManager.getConnection(conf.getUrl(), conf.getUsername(),
conf.getPassword())) {
String url;
// JDBC 配置形式
if (DsConfTypeEnum.JDBC.getType().equals(conf.getConfType())) {
url = conf.getUrl();
}
else if (DsJdbcUrlEnum.MSSQL.getDbName().equals(conf.getDsType())) {
// 主机形式 sql server 特殊处理
DsJdbcUrlEnum urlEnum = DsJdbcUrlEnum.get(conf.getDsType());
url = String.format(urlEnum.getUrl(), conf.getHost(), conf.getInstance(), conf.getPort(), conf.getDsName());
}
else {
DsJdbcUrlEnum urlEnum = DsJdbcUrlEnum.get(conf.getDsType());
url = String.format(urlEnum.getUrl(), conf.getHost(), conf.getPort(), conf.getDsName());
}
conf.setUrl(url);
try (Connection connection = DriverManager.getConnection(url, conf.getUsername(), conf.getPassword())) {
}
catch (SQLException e) {
log.error("数据源配置 {} , 获取链接失败", conf.getName(), e);
@@ -23,7 +23,7 @@ import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pig4cloud.pigx.codegen.entity.ColumnEntity;
import com.pig4cloud.pigx.codegen.entity.GenFormConf;
import com.pig4cloud.pigx.codegen.mapper.GenFormConfMapper;
import com.pig4cloud.pigx.codegen.mapper.GenTableColumnMapper;
import com.pig4cloud.pigx.codegen.mapper.GeneratorMapper;
import com.pig4cloud.pigx.codegen.service.GenFormConfService;
import com.pig4cloud.pigx.codegen.util.GenUtils;
import lombok.AllArgsConstructor;
@@ -50,8 +50,6 @@ import java.util.Properties;
@AllArgsConstructor
public class GenFormConfServiceImpl extends ServiceImpl<GenFormConfMapper, GenFormConf> implements GenFormConfService {
private final GenTableColumnMapper tableColumnMapper;
/**
* 1. 根据数据源、表名称,查询已配置表单信息 2. 不存在调用模板生成
* @param dsName 数据源ID
@@ -68,7 +66,8 @@ public class GenFormConfServiceImpl extends ServiceImpl<GenFormConfMapper, GenFo
return form.getFormInfo();
}
List<ColumnEntity> columns = tableColumnMapper.selectTableColumn(tableName, dsName);
GeneratorMapper mapper = GenUtils.getMapper(dsName);
List<ColumnEntity> columns = mapper.selectTableColumn(tableName, dsName);
// 设置velocity资源加载器
Properties prop = new Properties();
prop.put("file.resource.loader.class", ClasspathResourceLoader.class.getName());
@@ -79,8 +78,15 @@ public class GenFormConfServiceImpl extends ServiceImpl<GenFormConfMapper, GenFo
List<ColumnEntity> columnList = new ArrayList<>();
for (ColumnEntity column : columns) {
ColumnEntity columnEntity = new ColumnEntity();
columnEntity.setComments(column.getComments());
columnEntity.setLowerAttrName(StringUtils.uncapitalize(GenUtils.columnToJava(column.getColumnName())));
// 判断注释是否为空
if (StrUtil.isNotBlank(column.getComments())) {
columnEntity.setComments(column.getComments());
}
else {
columnEntity.setComments(columnEntity.getLowerAttrName());
}
columnList.add(columnEntity);
}
context.put("columns", columnList);
@@ -2,13 +2,12 @@ package com.pig4cloud.pigx.codegen.service.impl;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pig4cloud.pigx.codegen.entity.ColumnEntity;
import com.pig4cloud.pigx.codegen.entity.GenConfig;
import com.pig4cloud.pigx.codegen.mapper.GenTableColumnMapper;
import com.pig4cloud.pigx.codegen.mapper.GeneratorMapper;
import com.pig4cloud.pigx.codegen.service.GenTableColumnService;
import com.pig4cloud.pigx.codegen.util.GenUtils;
import lombok.AllArgsConstructor;
import lombok.RequiredArgsConstructor;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
@@ -20,13 +19,13 @@ import org.springframework.stereotype.Service;
* @date 2020/5/18
*/
@Service
@AllArgsConstructor
public class GenTableColumnServiceImpl extends ServiceImpl<GenTableColumnMapper, ColumnEntity>
implements GenTableColumnService {
@RequiredArgsConstructor
public class GenTableColumnServiceImpl implements GenTableColumnService {
@Override
public IPage<ColumnEntity> listTable(Page page, GenConfig genConfig) {
IPage<ColumnEntity> columnPage = baseMapper.selectTableColumn(page, genConfig.getTableName(),
GeneratorMapper mapper = GenUtils.getMapper(genConfig.getDsName());
IPage<ColumnEntity> columnPage = mapper.selectTableColumn(page, genConfig.getTableName(),
genConfig.getDsName());
// 处理 数据库类型和 Java 类型关系
@@ -21,14 +21,13 @@ import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pig4cloud.pigx.codegen.entity.GenConfig;
import com.pig4cloud.pigx.codegen.entity.GenFormConf;
import com.pig4cloud.pigx.codegen.mapper.GenFormConfMapper;
import com.pig4cloud.pigx.codegen.mapper.GenTableColumnMapper;
import com.pig4cloud.pigx.codegen.mapper.GeneratorMapper;
import com.pig4cloud.pigx.codegen.service.GeneratorService;
import com.pig4cloud.pigx.codegen.util.GenUtils;
@@ -50,10 +49,6 @@ import java.util.zip.ZipOutputStream;
@AllArgsConstructor
public class GeneratorServiceImpl implements GeneratorService {
private final GenTableColumnMapper tableColumnMapper;
private final GeneratorMapper generatorMapper;
private final GenFormConfMapper genFormConfMapper;
/**
@@ -63,9 +58,11 @@ public class GeneratorServiceImpl implements GeneratorService {
* @return
*/
@Override
@DS("#last")
public IPage<List<Map<String, Object>>> getPage(Page page, String tableName, String dsName) {
return generatorMapper.queryList(page, tableName);
GeneratorMapper mapper = GenUtils.getMapper(dsName);
// 手动切换数据源
DynamicDataSourceContextHolder.push(dsName);
return mapper.queryTable(page, tableName);
}
@Override
@@ -75,12 +72,14 @@ public class GeneratorServiceImpl implements GeneratorService {
.eq(GenFormConf::getTableName, genConfig.getTableName()).orderByDesc(GenFormConf::getCreateTime));
String tableNames = genConfig.getTableName();
String dsName = genConfig.getDsName();
GeneratorMapper mapper = GenUtils.getMapper(genConfig.getDsName());
for (String tableName : StrUtil.split(tableNames, StrUtil.DASHED)) {
// 查询表信息
Map<String, String> table = generatorMapper.queryTable(tableName, genConfig.getDsName());
Map<String, String> table = mapper.queryTable(tableName, dsName);
// 查询列信息
List<Map<String, String>> columns = tableColumnMapper.selectMapTableColumn(tableName,
genConfig.getDsName());
List<Map<String, String>> columns = mapper.selectMapTableColumn(tableName, dsName);
// 生成代码
if (CollUtil.isNotEmpty(formConfList)) {
return GenUtils.generatorCode(genConfig, table, columns, null, formConfList.get(0));
@@ -107,12 +106,14 @@ public class GeneratorServiceImpl implements GeneratorService {
ZipOutputStream zip = new ZipOutputStream(outputStream);
String tableNames = genConfig.getTableName();
String dsName = genConfig.getDsName();
GeneratorMapper mapper = GenUtils.getMapper(dsName);
for (String tableName : StrUtil.split(tableNames, StrUtil.DASHED)) {
// 查询表信息
Map<String, String> table = generatorMapper.queryTable(tableName, genConfig.getDsName());
Map<String, String> table = mapper.queryTable(tableName, dsName);
// 查询列信息
List<Map<String, String>> columns = tableColumnMapper.selectMapTableColumn(tableName,
genConfig.getDsName());
List<Map<String, String>> columns = mapper.selectMapTableColumn(tableName, dsName);
// 生成代码
if (CollUtil.isNotEmpty(formConfList)) {
GenUtils.generatorCode(genConfig, table, columns, zip, formConfList.get(0));
@@ -21,13 +21,15 @@ import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import com.pig4cloud.pigx.codegen.entity.ColumnEntity;
import com.pig4cloud.pigx.codegen.entity.GenConfig;
import com.pig4cloud.pigx.codegen.entity.GenFormConf;
import com.pig4cloud.pigx.codegen.entity.TableEntity;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.pig4cloud.pigx.codegen.entity.*;
import com.pig4cloud.pigx.codegen.mapper.GenDatasourceConfMapper;
import com.pig4cloud.pigx.codegen.mapper.GeneratorMapper;
import com.pig4cloud.pigx.common.core.constant.CommonConstants;
import com.pig4cloud.pigx.common.core.constant.enums.StyleTypeEnum;
import com.pig4cloud.pigx.common.core.exception.CheckedException;
import com.pig4cloud.pigx.common.core.util.SpringContextHolder;
import com.pig4cloud.pigx.common.datasource.util.DsJdbcUrlEnum;
import lombok.SneakyThrows;
import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;
@@ -39,6 +41,7 @@ import org.apache.commons.lang.WordUtils;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.springframework.context.ApplicationContext;
import java.io.File;
import java.io.IOException;
@@ -133,6 +136,8 @@ public class GenUtils {
tableEntity.setComments(table.get("tableComment"));
}
tableEntity.setDbType(table.get("dbType"));
String tablePrefix;
if (StrUtil.isNotBlank(genConfig.getTablePrefix())) {
tablePrefix = genConfig.getTablePrefix();
@@ -153,7 +158,6 @@ public class GenUtils {
ColumnEntity columnEntity = new ColumnEntity();
columnEntity.setColumnName(column.get("columnName"));
columnEntity.setDataType(column.get("dataType"));
columnEntity.setComments(column.get("comments"));
columnEntity.setExtra(column.get("extra"));
columnEntity.setNullable("NO".equals(column.get("isNullable")));
columnEntity.setColumnType(column.get("columnType"));
@@ -169,6 +173,14 @@ public class GenUtils {
columnEntity.setCaseAttrName(attrName);
columnEntity.setLowerAttrName(StringUtils.uncapitalize(attrName));
// 判断注释是否为空
if (StrUtil.isNotBlank(column.get("comments"))) {
columnEntity.setComments(column.get("comments"));
}
else {
columnEntity.setComments(columnEntity.getLowerAttrName());
}
// 列的数据类型,转换成Java类型
String attrType = config.getString(columnEntity.getDataType(), "unknowType");
columnEntity.setAttrType(attrType);
@@ -389,4 +401,38 @@ public class GenUtils {
return null;
}
/**
* 根据目标数据源名称动态匹配Mapper
* @param dsName
* @return
*/
public GeneratorMapper getMapper(String dsName) {
// 获取目标数据源数据库类型
GenDatasourceConfMapper datasourceConfMapper = SpringContextHolder.getBean(GenDatasourceConfMapper.class);
GenDatasourceConf datasourceConf = datasourceConfMapper
.selectOne(Wrappers.<GenDatasourceConf>lambdaQuery().eq(GenDatasourceConf::getName, dsName));
String dbConfType;
// 默认MYSQL 数据源
if (datasourceConf == null) {
dbConfType = DsJdbcUrlEnum.MYSQL.getDbName();
}
else {
dbConfType = datasourceConf.getDsType();
}
// 获取全部数据实现
ApplicationContext context = SpringContextHolder.getApplicationContext();
Map<String, GeneratorMapper> beansOfType = context.getBeansOfType(GeneratorMapper.class);
// 根据数据类型选择mapper
for (String key : beansOfType.keySet()) {
if (StrUtil.containsIgnoreCase(key, dbConfType)) {
return beansOfType.get(key);
}
}
throw new IllegalArgumentException("dsName 不合法: " + dsName);
}
}
@@ -1,37 +1,59 @@
#\u4EE3\u7801\u751F\u6210\u5668\uFF0C\u914D\u7F6E\u4FE1\u606F
mainPath=com.pig4cloud.pigx
#\u5305\u540D
package=com.pig4cloud.pigx
moduleName=generator
#\u4F5C\u8005
author=pigx code generator
#\u8868\u524D\u7F00(\u7C7B\u540D\u4E0D\u4F1A\u5305\u542B\u8868\u524D\u7F00)
tablePrefix=tb_
# hidden columns in Swagger Models
hiddenColumn=tenant_id
#\u7C7B\u578B\u8F6C\u6362\uFF0C\u914D\u7F6E\u4FE1\u606F
#MYSQL \u7C7B\u578B\u8F6C\u6362
tinyint=Integer
smallint=Integer
mediumint=Integer
int=Integer
int=Integer
integer=Integer
bigint=Long
float=Float
double=Double
decimal=BigDecimal
bit=Boolean
char=String
varchar=String
tinytext=String
text=String
mediumtext=String
longtext=String
date=LocalDateTime
datetime=LocalDateTime
timestamp=LocalDateTime
# hidden columns in Swagger Models
hiddenColumn=tenant_id
# PG \u7C7B\u578B\u8F6C\u5316\u89C4\u5219
int2=Integer
int4=Integer
int8=Long
#ORACLE \u7279\u6B8A\u7C7B\u578B\u8F6C\u6362\u89C4\u5219
INT=Integer
INTEGER=Integer
LONG=LONG
NUMBER=Integer
BINARY_INTEGER=Integer
FLOAT=Float
BINARY_FLOAT=Float
DOUBLE=Double
BINARY_DOUBLE=Double
DECIMAL=BigDecimal
CHAR=String
VARCHAR=String
VARCHAR2=String
NVARCHAR=String
NVARCHAR2=String
DATE=LocalDateTime
DATETIME=LocalDateTime
TIMESTAMP=LocalDateTime
CLOB=String
BLOB=String
@@ -1,47 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2018-2025, lengleng All rights reserved.
~
~ Redistribution and use in source and binary forms, with or without
~ modification, are permitted provided that the following conditions are met:
~
~ Redistributions of source code must retain the above copyright notice,
~ this list of conditions and the following disclaimer.
~ Redistributions in binary form must reproduce the above copyright
~ notice, this list of conditions and the following disclaimer in the
~ documentation and/or other materials provided with the distribution.
~ Neither the name of the pig4cloud.com developer nor the names of its
~ contributors may be used to endorse or promote products derived from
~ this software without specific prior written permission.
~ Author: lengleng (wangiegie@gmail.com)
-->
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.pig4cloud.pigx.codegen.mapper.GenTableColumnMapper">
<sql id="queryColumn">
SELECT
column_name columnName,
data_type dataType,
column_comment comments,
column_key columnKey,
extra,
is_nullable AS isNullable,
column_type AS columnType
FROM
information_schema.COLUMNS
WHERE
table_name = #{tableName} and table_schema = (select database()) order by ordinal_position
</sql>
<select id="selectTableColumn" resultType="com.pig4cloud.pigx.codegen.entity.ColumnEntity">
<include refid="queryColumn"/>
</select>
<select id="selectMapTableColumn" resultType="map">
<include refid="queryColumn"/>
</select>
</mapper>
@@ -1,19 +0,0 @@
<?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.pig4cloud.pigx.codegen.mapper.GeneratorMapper">
<select id="queryList" resultType="map">
select table_name tableName, engine, table_comment tableComment, table_collation tableCollation, create_time createTime from information_schema.tables
where table_schema = (select database())
<if test="tableName != null and tableName.trim() != ''">
and table_name like concat('%', #{tableName}, '%')
</if>
order by create_time desc
</select>
<select id="queryTable" resultType="map">
select table_name tableName, engine, table_comment tableComment, create_time createTime from information_schema.tables
where table_schema = (select database()) and table_name = #{tableName}
</select>
</mapper>
@@ -0,0 +1,87 @@
<?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.pig4cloud.pigx.codegen.mapper.GeneratorMssqlMapper">
<select id="queryTable" resultType="map">
SELECT *
FROM (
SELECT CAST
(so.NAME AS nvarchar(500)) AS tableName,
CAST(sep.VALUE AS nvarchar(500)) AS tableComment
FROM sysobjects so
LEFT JOIN sys.extended_properties sep ON sep.major_id = so.ID
AND sep.minor_id = 0
WHERE (xtype = 'U' OR xtype = 'v')
) T
<where>
<if test="tableName != null and tableName.trim() != ''">
and T.tableName like concat('%', #{tableName}, '%')
</if>
</where>
ORDER BY T.tableName
</select>
<sql id="queryColumn">
SELECT
'mssql' AS dbType,
CAST ( b.NAME AS NVARCHAR ( 500 ) ) AS columnName,
CAST ( sys.types.NAME AS NVARCHAR ( 500 ) ) AS dataType,
CAST ( sys.types.NAME AS NVARCHAR ( 500 ) ) AS columnType,
CAST ( c.VALUE AS NVARCHAR ( 500 ) ) AS comments,
(
SELECT
CASE
COUNT
( 1 )
WHEN 1 THEN
'PRI' ELSE ''
END
FROM
syscolumns,
sysobjects,
sysindexes,
sysindexkeys,
systypes
WHERE
syscolumns.xusertype = systypes.xusertype
AND syscolumns.id = object_id( A.NAME )
AND sysobjects.xtype = 'PK'
AND sysobjects.parent_obj = syscolumns.id
AND sysindexes.id = syscolumns.id
AND sysobjects.NAME = sysindexes.NAME
AND sysindexkeys.id = syscolumns.id
AND sysindexkeys.indid = sysindexes.indid
AND syscolumns.colid = sysindexkeys.colid
AND syscolumns.NAME = B.NAME
) AS columnKey,
'' AS extra
FROM
(
SELECT
name,
object_id
FROM
sys.tables UNION ALL
SELECT
name,
object_id
FROM
sys.views
) a
INNER JOIN sys.COLUMNS b ON b.object_id = a.object_id
LEFT JOIN sys.types ON b.user_type_id = sys.types.user_type_id
LEFT JOIN sys.extended_properties c ON c.major_id = b.object_id
AND c.minor_id = b.column_id
WHERE a.NAME = #{tableName} and sys.types.NAME != 'sysname'
</sql>
<select id="selectTableColumn" resultType="com.pig4cloud.pigx.codegen.entity.ColumnEntity">
<include refid="queryColumn"/>
</select>
<select id="selectMapTableColumn" resultType="map">
<include refid="queryColumn"/>
</select>
</mapper>
@@ -0,0 +1,49 @@
<?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.pig4cloud.pigx.codegen.mapper.GeneratorMySqlMapper">
<select id="queryTable" resultType="map">
SELECT
'mysql' AS dbType,
table_name AS tableName,
ENGINE,
table_comment AS tableComment,
create_time AS createTime
FROM
information_schema.TABLES
WHERE
table_schema = (
SELECT DATABASE
())
<if test="tableName != null and tableName.trim() != ''">
and table_name like concat('%', #{tableName}, '%')
</if>
order by create_time desc
</select>
<sql id="queryColumn">
SELECT
column_name columnName,
data_type dataType,
column_comment comments,
column_key columnKey,
extra,
is_nullable AS isNullable,
column_type AS columnType
FROM
information_schema.COLUMNS
WHERE
table_name = #{tableName} and table_schema = (select database()) order by ordinal_position
</sql>
<select id="selectTableColumn" resultType="com.pig4cloud.pigx.codegen.entity.ColumnEntity">
<include refid="queryColumn"/>
</select>
<select id="selectMapTableColumn" resultType="map">
<include refid="queryColumn"/>
</select>
</mapper>
@@ -0,0 +1,72 @@
<?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.pig4cloud.pigx.codegen.mapper.GeneratorOracleMapper">
<select id="queryTable" resultType="map">
SELECT
ut.TABLE_NAME AS "tableName",
utc.comments AS "tableComment"
FROM
user_tables ut,
user_tab_comments utc
WHERE
ut.TABLE_NAME = utc.TABLE_NAME
<if test="tableName != null and tableName.trim() != ''">
and ut.TABLE_NAME = UPPER ( #{tableName} )
</if>
ORDER BY ut.TABLE_NAME
</select>
<sql id="queryColumn">
SELECT
'oracle' AS "dbType",
TEMP.COLUMN_NAME AS "columnName",
TEMP.data_type AS "columnType",
TEMP.data_type AS "dataType",
TEMP.comments AS comments,
CASE
TEMP.constraint_type
WHEN 'P' THEN
'PRI'
WHEN 'C' THEN
'UNI' ELSE''
END "COLUMNKEY"
FROM
(
SELECT
col.column_id,
col.COLUMN_NAME,
col.data_type,
colc.comments,
uc.constraint_type,
ROW_NUMBER ( ) OVER (
PARTITION BY col.COLUMN_NAME
ORDER BY
uc.constraint_type DESC
) AS row_flg
FROM
user_tab_columns col
LEFT JOIN user_col_comments colc ON colc.TABLE_NAME = col.TABLE_NAME
AND colc.COLUMN_NAME = col.
COLUMN_NAME LEFT JOIN user_cons_columns ucc ON ucc.TABLE_NAME = col.TABLE_NAME
AND ucc.COLUMN_NAME = col.
COLUMN_NAME LEFT JOIN user_constraints uc ON uc.CONSTRAINT_NAME = ucc.CONSTRAINT_NAME
WHERE
col.TABLE_NAME = UPPER ( #{tableName} )
) TEMP
WHERE
TEMP.row_flg = 1
ORDER BY
TEMP.column_id
</sql>
<select id="selectTableColumn" resultType="com.pig4cloud.pigx.codegen.entity.ColumnEntity">
<include refid="queryColumn"/>
</select>
<select id="selectMapTableColumn" resultType="map">
<include refid="queryColumn"/>
</select>
</mapper>
@@ -0,0 +1,57 @@
<?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.pig4cloud.pigx.codegen.mapper.GeneratorPgMapper">
<select id="queryTable" resultType="map">
SELECT
relname AS "tableName",
obj_description ( oid ) AS "tableComment"
FROM
pg_class pc
WHERE
relkind = 'r'
AND relname NOT LIKE'pg_%'
AND relname NOT LIKE'sql_%'
AND relchecks = 0
<if test="tableName != null and tableName.trim() != ''">
and pc.relname like concat('%', #{tableName}, '%')
</if>
ORDER BY relname
</select>
<sql id="queryColumn">
SELECT
'pg' AS "dbType",
pa.attname AS "columnName",
pg_type.typname AS "columnType",
pg_type.typname AS "dataType",
col_description ( pa.attrelid, pa.attnum ) AS "comments",
(
CASE
pcon.contype
WHEN 'p' THEN
'PRI' ELSE''
END
) AS "columnKey"
FROM
pg_class AS pc,
pg_attribute AS pa
INNER JOIN pg_type ON pg_type.oid = pa.atttypid
LEFT JOIN pg_constraint pcon ON pa.attnum = pcon.conkey[1]
AND pa.attrelid = pcon.conrelid
WHERE
pc.relname = #{ tableName }
AND pa.attrelid = pc.oid
AND pa.attnum > 0;
</sql>
<select id="selectTableColumn" resultType="com.pig4cloud.pigx.codegen.entity.ColumnEntity">
<include refid="queryColumn"/>
</select>
<select id="selectMapTableColumn" resultType="map">
<include refid="queryColumn"/>
</select>
</mapper>
@@ -17,6 +17,9 @@
package ${package}.${moduleName}.entity;
#if($dbType != "mysql")
import com.baomidou.mybatisplus.annotation.IdType;
#end
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.extension.activerecord.Model;
@@ -41,16 +44,22 @@ import java.time.LocalDateTime;
@EqualsAndHashCode(callSuper = true)
@ApiModel(value = "${comments}")
public class ${className} extends Model<${className}> {
private static final long serialVersionUID = 1L;
#foreach ($column in $columns)
/**
private static final long serialVersionUID = 1L;
#foreach ($column in $columns)
/**
* $column.comments
*/
#if($column.columnName == $pk.columnName)
@TableId
#end
@ApiModelProperty(value="$column.comments"#if($column.hidden),hidden=$column.hidden#end)
#if($column.columnName == $pk.columnName)
#if($dbType == "mysql")
@TableId
#else
@TableId(type = IdType.ASSIGN_ID)
#end
#end
@ApiModelProperty(value="$column.comments"#if($column.hidden),hidden=$column.hidden#end)
private $column.attrType $column.lowerAttrName;
#end
#end
}