Merge remote-tracking branch 'origin/liuyes_dev' into leng_feat_dy_ds

This commit is contained in:
冷冷 committed 2020-02-06 17:32:00 +08:00
commit d0716c22f0
51 files changed
+3149

No files matched your search

+15
View File
@@ -0,0 +1,15 @@
FROM anapsix/alpine-java:8_server-jre_unlimited
MAINTAINER wangiegie@gmail.com
RUN ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
RUN mkdir -p /pigx-code
WORKDIR /pigx-code
EXPOSE 5003
ADD ./pigx-visual/pigx-code/target/pigx-code.jar ./
CMD sleep 120;java -Xms128m -Xmx256m -Djava.security.egd=file:/dev/./urandom -jar pigx-code.jar
+90
View File
@@ -0,0 +1,90 @@
## 使用说明
```
本模块是pigx-codegen的重写版本,使用dynamic-datasource实现,去除pigx-common-datasource依赖,功能未做扩展。
```
### pigx-code-dev.yml
```
## spring security 配置
security:
oauth2:
client:
client-id: ENC(gPFcUOmJm8WqM3k3eSqS0Q==)
client-secret: ENC(gPFcUOmJm8WqM3k3eSqS0Q==)
scope: server
resources:
static-locations: classpath:/static/,classpath:/views/
# 数据源
spring:
datasource:
dynamic:
username: ${MYSQL-USER:root}
password: ${MYSQL-USER:root}
url: jdbc:mysql://${MYSQL-HOST:pigx-mysql}:${MYSQL-PORT:3306}/pigxx_codegen?characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=GMT%2B8&allowMultiQueries=true&allowPublicKeyRetrieval=true
driverClassName: com.mysql.cj.jdbc.Driver
sql: select * from gen_datasource_conf
pigx:
tenant:
column: tenant_id
tables:
- sys_datasource_conf
```
### 示例中的pigxx_codegen数据库及sql说明
```
pigxx_codegen数据库中gen_datasource_conf表必须存在一个name为master的数据库连接配置
INSERT INTO `gen_datasource_conf` VALUES ('8', 'master', 'jdbc:mysql://pigx-mysql:3306/pigxx_codegen?characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=GMT%2B8&allowMultiQueries=true', 'root', 'ZkxR9PxP6sWvasdc9CG9Ww==', '2019-09-18 09:44:55', '2019-12-17 17:07:17', '0', null);
```
### 修改菜单的url
```
开发平台菜单下的/gen全部改为/code
如 /gen/datasource 改为 /code/datasource
```
### 修改动态路由
```
{
"routeId": "pigx-codegen",
"routeName": "代码生成模块",
"predicates": [
{
"args": {
"_genkey_0": "/gen/**"
},
"name": "Path"
}
],
"filters": [],
"uri": "lb://pigx-codegen",
"order": 0,
"createTime": "2019-10-16 16:44:41",
"updateTime": "2019-11-05 22:36:58",
"delFlag": "0"
},
改为
{
"routeId": "pigx-code",
"routeName": "多数据源代码生成模块",
"predicates": [
{
"args": {
"_genkey_0": "/code/**"
},
"name": "Path"
}
],
"filters": [],
"uri": "lb://pigx-code",
"order": 0,
"createTime": "2019-10-16 16:44:41",
"updateTime": "2019-11-05 22:36:58",
"delFlag": "0"
},
```
### yml配置文件切换数据源
```
请参考:https://git.pig4cloud.com/pigx/pigx/src/liuyes_dev/pigx-visual/pigx-dynamic-datasource
```
### 联系我
QQ:55215085
+107
View File
@@ -0,0 +1,107 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.pig4cloud</groupId>
<artifactId>pigx-visual</artifactId>
<version>3.5.0</version>
</parent>
<artifactId>pigx-code</artifactId>
<packaging>jar</packaging>
<description>多数据源代码生成模块</description>
<dependencies>
<!--注册中心客户端-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<!--配置中心客户端-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>
<!--必备: 操作数据源相关-->
<dependency>
<groupId>com.pig4cloud</groupId>
<artifactId>pigx-common-data</artifactId>
</dependency>
<!-- 动态数据源 数据操作 -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>dynamic-datasource-spring-boot-starter</artifactId>
<version>2.5.6</version>
</dependency>
<!--mybatis-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- druid 连接池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
</dependency>
<!--common-->
<dependency>
<groupId>com.pig4cloud</groupId>
<artifactId>pigx-common-core</artifactId>
</dependency>
<!--swagger-->
<dependency>
<groupId>com.pig4cloud</groupId>
<artifactId>pigx-common-swagger</artifactId>
</dependency>
<!--安全模块-->
<dependency>
<groupId>com.pig4cloud</groupId>
<artifactId>pigx-common-security</artifactId>
</dependency>
<!--必备: sentinel 依赖-->
<dependency>
<groupId>com.pig4cloud</groupId>
<artifactId>pigx-common-sentinel</artifactId>
</dependency>
<dependency>
<groupId>com.pig4cloud</groupId>
<artifactId>pigx-common-log</artifactId>
</dependency>
<!--代码生成模板引擎-->
<dependency>
<artifactId>velocity</artifactId>
<groupId>org.apache.velocity</groupId>
<version>${velocity.version}</version>
</dependency>
<!--web 模块-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--undertow容器-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-undertow</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>com.spotify</groupId>
<artifactId>docker-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
@@ -0,0 +1,44 @@
/*
* 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.code;
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceAutoConfigure;
import com.pig4cloud.pigx.common.security.annotation.EnablePigxFeignClients;
import com.pig4cloud.pigx.common.security.annotation.EnablePigxResourceServer;
import com.pig4cloud.pigx.common.swagger.annotation.EnablePigxSwagger2;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.cloud.client.SpringCloudApplication;
/**
* @author lengleng
* @date 2018/07/29
* 代码生成模块
*/
@EnablePigxSwagger2
@SpringCloudApplication
@EnablePigxFeignClients
@EnablePigxResourceServer
@EnableAutoConfiguration(exclude={DruidDataSourceAutoConfigure.class})
public class PigxCodeApplication {
public static void main(String[] args) {
SpringApplication.run(PigxCodeApplication.class, args);
}
}
@@ -0,0 +1,21 @@
package com.pig4cloud.pigx.code.config;
import lombok.AllArgsConstructor;
import lombok.Data;
import org.jasypt.encryption.StringEncryptor;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
@Data
@Component
@ConfigurationProperties("spring.datasource.dynamic")
public class JdbcDynamicDataSourceProperties {
private final StringEncryptor stringEncryptor;
private String username;
private String password;
private String url;
private String driverClassName;
private String sql;
}
@@ -0,0 +1,47 @@
package com.pig4cloud.pigx.code.config;
import com.baomidou.dynamic.datasource.provider.AbstractJdbcDataSourceProvider;
import com.baomidou.dynamic.datasource.provider.DynamicDataSourceProvider;
import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DataSourceProperty;
import lombok.AllArgsConstructor;
import org.jasypt.encryption.StringEncryptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Map;
@Configuration
@AllArgsConstructor
public class JdbcDynamicDataSourceProvider {
private final StringEncryptor stringEncryptor;
private final JdbcDynamicDataSourceProperties properties;
@Bean
public DynamicDataSourceProvider dynamicDataSourceProvider() {
return new AbstractJdbcDataSourceProvider(properties.getDriverClassName(), properties.getUrl(), properties.getUsername(), properties.getPassword()) {
@Override
protected Map<String, DataSourceProperty> executeStmt(Statement statement) throws SQLException {
Map<String, DataSourceProperty> map = new HashMap<>();
ResultSet rs = statement.executeQuery(properties.getSql());
while (rs.next()) {
String name = rs.getString("name");
String username = rs.getString("username");
String password = rs.getString("password");
String url = rs.getString("url");
// String driver = rs.getString("driver");
DataSourceProperty property = new DataSourceProperty();
property.setUsername(username);
property.setPassword(stringEncryptor.decrypt(password));
property.setUrl(url);
// property.setDriverClassName(driver);
map.put(name, property);
}
return map;
}
};
}
}
@@ -0,0 +1,141 @@
/*
* 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.code.controller;
import com.baomidou.dynamic.datasource.DynamicDataSourceCreator;
import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DataSourceProperty;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pig4cloud.pigx.code.entity.GenDatasourceConf;
import com.pig4cloud.pigx.code.service.GenDatasourceConfService;
import com.pig4cloud.pigx.common.core.util.R;
import com.pig4cloud.pigx.common.log.annotation.SysLog;
import lombok.AllArgsConstructor;
import org.jasypt.encryption.StringEncryptor;
import org.springframework.web.bind.annotation.*;
import javax.sql.DataSource;
/**
* 数据源管理
*
* @author lengleng
* @date 2019-03-31 16:00:20
*/
@RestController
@AllArgsConstructor
@RequestMapping("/dsconf")
public class GenDsConfController {
private final GenDatasourceConfService datasourceConfService;
private final StringEncryptor stringEncryptor;
private DataSource dataSource;
private DynamicDataSourceCreator dataSourceCreator;
/**
* 分页查询
*
* @param page 分页对象
* @param datasourceConf 数据源表
* @return
*/
@GetMapping("/page")
public R getSysDatasourceConfPage(Page page, GenDatasourceConf datasourceConf) {
return R.ok(datasourceConfService.page(page, Wrappers.query(datasourceConf)));
}
/**
* 查询全部数据源
*
* @return
*/
@GetMapping("/list")
public R list() {
return R.ok(datasourceConfService.list());
}
/**
* 通过id查询数据源表
*
* @param id id
* @return R
*/
@GetMapping("/{id}")
public R getById(@PathVariable("id") Integer id) {
return R.ok(datasourceConfService.getById(id));
}
/**
* 新增数据源表
*
* @param datasourceConf 数据源表
* @return R
*/
@SysLog("新增数据源表")
@PostMapping
public R save(@RequestBody GenDatasourceConf datasourceConf) {
DynamicRoutingDataSource ds = (DynamicRoutingDataSource) dataSource;
DataSourceProperty dataSourceProperty = new DataSourceProperty();
dataSourceProperty.setPollName(datasourceConf.getName());
dataSourceProperty.setUrl(datasourceConf.getUrl());
dataSourceProperty.setUsername(datasourceConf.getUsername());
dataSourceProperty.setPassword(datasourceConf.getPassword());
DataSource dataSource = dataSourceCreator.createDataSource(dataSourceProperty);
ds.addDataSource(dataSourceProperty.getPollName(), dataSource);
return R.ok(datasourceConfService.saveDsByEnc(datasourceConf));
}
/**
* 修改数据源表
*
* @param sysDatasourceConf 数据源表
* @return R
*/
@SysLog("修改数据源表")
@PutMapping
public R updateById(@RequestBody GenDatasourceConf sysDatasourceConf) {
DynamicRoutingDataSource ds = (DynamicRoutingDataSource) dataSource;
//先移除
ds.removeDataSource(datasourceConfService.getById(sysDatasourceConf.getId()).getName());
//再添加
DataSourceProperty dataSourceProperty = new DataSourceProperty();
dataSourceProperty.setPollName(sysDatasourceConf.getName());
dataSourceProperty.setUrl(sysDatasourceConf.getUrl());
dataSourceProperty.setUsername(sysDatasourceConf.getUsername());
dataSourceProperty.setPassword(sysDatasourceConf.getPassword());
DataSource dataSource = dataSourceCreator.createDataSource(dataSourceProperty);
ds.addDataSource(dataSourceProperty.getPollName(), dataSource);
return R.ok(datasourceConfService.updateDsByEnc(sysDatasourceConf));
}
/**
* 通过id删除数据源表
*
* @param id id
* @return R
*/
@SysLog("删除数据源表")
@DeleteMapping("/{id}")
public R removeById(@PathVariable Integer id) {
DynamicRoutingDataSource ds = (DynamicRoutingDataSource) dataSource;
ds.removeDataSource(datasourceConfService.getById(id).getName());
return R.ok(datasourceConfService.removeById(id));
}
}
@@ -0,0 +1,127 @@
/*
* 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.code.controller;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pig4cloud.pigx.code.entity.GenFormConf;
import com.pig4cloud.pigx.code.service.GenFormConfService;
import com.pig4cloud.pigx.common.core.util.R;
import com.pig4cloud.pigx.common.log.annotation.SysLog;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
/**
* 表单管理
*
* @author lengleng
* @date 2019-08-12 15:55:35
*/
@RestController
@AllArgsConstructor
@RequestMapping("/form")
@Api(value = "form", tags = "表单管理")
public class GenFormConfController {
private final GenFormConfService genRecordService;
/**
* 分页查询
*
* @param page 分页对象
* @param formConf 生成记录
* @return
*/
@ApiOperation(value = "分页查询", notes = "分页查询")
@GetMapping("/page")
public R getGenFormConfPage(Page page, GenFormConf formConf) {
return R.ok(genRecordService.page(page, Wrappers.query(formConf)));
}
/**
* 通过id查询生成记录
*
* @param id id
* @return R
*/
@ApiOperation(value = "通过id查询", notes = "通过id查询")
@GetMapping("/{id}")
public R getById(@PathVariable("id") Integer id) {
return R.ok(genRecordService.getById(id));
}
/**
* 通过id查询生成记录
*
* @param dsId 数据源ID
* @param tableName tableName
* @return R
*/
@ApiOperation(value = "通过tableName查询表单信息")
@GetMapping("/info")
public R form(Integer dsId, String tableName) {
return R.ok(genRecordService.getForm(dsId, tableName));
}
/**
* 新增生成记录
*
* @param formConf 生成记录
* @return R
*/
@ApiOperation(value = "新增生成记录", notes = "新增生成记录")
@SysLog("新增生成记录")
@PostMapping
@PreAuthorize("@pms.hasPermission('gen_form_add')")
public R save(@RequestBody GenFormConf formConf) {
return R.ok(genRecordService.save(formConf));
}
/**
* 修改生成记录
*
* @param formConf 生成记录
* @return R
*/
@ApiOperation(value = "修改生成记录", notes = "修改生成记录")
@SysLog("修改生成记录")
@PutMapping
@PreAuthorize("@pms.hasPermission('gen_form_edit')")
public R updateById(@RequestBody GenFormConf formConf) {
return R.ok(genRecordService.updateById(formConf));
}
/**
* 通过id删除生成记录
*
* @param id id
* @return R
*/
@ApiOperation(value = "通过id删除生成记录", notes = "通过id删除生成记录")
@SysLog("通过id删除生成记录")
@DeleteMapping("/{id}")
@PreAuthorize("@pms.hasPermission('gen_form_del')")
public R removeById(@PathVariable Integer id) {
return R.ok(genRecordService.removeById(id));
}
}
@@ -0,0 +1,74 @@
/*
* 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.code.controller;
import cn.hutool.core.io.IoUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pig4cloud.pigx.code.entity.GenConfig;
import com.pig4cloud.pigx.code.service.GeneratorService;
import com.pig4cloud.pigx.common.core.util.R;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 代码生成器
*
* @author lengleng
* @date 2018-07-30
*/
@RestController
@AllArgsConstructor
@RequestMapping("/generator")
public class GeneratorController {
private final GeneratorService generatorService;
/**
* 列表
*
* @param tableName 参数集
* @param id 数据源编号
* @return 数据库表
*/
@GetMapping("/page")
public R getPage(Page page, String tableName, String name, HttpServletRequest request) {
name = StringUtils.isEmpty(name) ? "master" : name;
request.getSession().setAttribute("dataSourceName", name);
return R.ok(generatorService.getPage(page, tableName));
}
/**
* 生成代码
*/
@SneakyThrows
@PostMapping("/code")
public void generatorCode(@RequestBody GenConfig genConfig, HttpServletResponse response) {
byte[] data = generatorService.generatorCode(genConfig);
response.reset();
response.setHeader(HttpHeaders.CONTENT_DISPOSITION, String.format("attachment; filename=%s.zip", genConfig.getTableName()));
response.addHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(data.length));
response.setContentType("application/octet-stream; charset=UTF-8");
IoUtil.write(response.getOutputStream(), Boolean.TRUE, data);
}
}
@@ -0,0 +1,70 @@
/*
* 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.code.entity;
import lombok.Data;
/**
* @author lengleng
* @date 2018/07/29
* 列属性: https://blog.csdn.net/lkforce/article/details/79557482
*/
@Data
public class ColumnEntity {
/**
* 列表
*/
private String columnName;
/**
* 数据类型
*/
private String dataType;
/**
* 备注
*/
private String comments;
/**
* 驼峰属性
*/
private String caseAttrName;
/**
* 普通属性
*/
private String lowerAttrName;
/**
* 属性类型
*/
private String attrType;
/**
* 其他信息
*/
private String extra;
/**
* 字段类型
*/
private String columnType;
/**
* 是否可以为空
*/
private Boolean nullable;
/**
* 是否隐藏
*/
private Boolean hidden;
}
@@ -0,0 +1,59 @@
/*
* 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.code.entity;
import lombok.Data;
/**
* @author lengleng
* @date 2018/8/2
* 生成配置
*/
@Data
public class GenConfig {
/**
* 数据源ID
*/
private Integer id;
/**
* 包名
*/
private String packageName;
/**
* 作者
*/
private String author;
/**
* 模块名称
*/
private String moduleName;
/**
* 表前缀
*/
private String tablePrefix;
/**
* 表名称
*/
private String tableName;
/**
* 表备注
*/
private String comments;
}
@@ -0,0 +1,79 @@
/*
* 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.code.entity;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableLogic;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.extension.activerecord.Model;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.time.LocalDateTime;
/**
* 数据源表
*
* @author lengleng
* @date 2019-03-31 16:00:20
*/
@Data
@TableName("gen_datasource_conf")
@EqualsAndHashCode(callSuper = true)
public class GenDatasourceConf extends Model<GenDatasourceConf> {
private static final long serialVersionUID = 1L;
/**
* 主键
*/
@TableId
private Integer id;
/**
* 名称
*/
private String name;
/**
* jdbcurl
*/
private String url;
/**
* 用户名
*/
private String username;
/**
* 密码
*/
private String password;
/**
* 创建时间
*/
private LocalDateTime createDate;
/**
* 更新
*/
private LocalDateTime updateDate;
/**
* 删除标记
*/
@TableLogic
private String delFlag;
/**
* 租户ID
*/
private Integer tenantId;
}
@@ -0,0 +1,79 @@
/*
* 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.code.entity;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.extension.activerecord.Model;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.time.LocalDateTime;
/**
* 生成记录
*
* @author lengleng
* @date 2019-08-12 15:55:35
*/
@Data
@TableName("gen_form_conf")
@EqualsAndHashCode(callSuper = true)
@ApiModel(value = "生成记录")
public class GenFormConf extends Model<GenFormConf> {
private static final long serialVersionUID = 1L;
/**
* ID
*/
@TableId
@ApiModelProperty(value = "ID")
private Integer id;
/**
* 表名称
*/
@ApiModelProperty(value = "表名称")
private String tableName;
/**
* 表单信息
*/
@ApiModelProperty(value = "表单信息")
private String formInfo;
/**
* 创建时间
*/
@ApiModelProperty(value = "创建时间")
private LocalDateTime createTime;
/**
* 修改时间
*/
@ApiModelProperty(value = "修改时间")
private LocalDateTime updateTime;
/**
* 删除标记
*/
@ApiModelProperty(value = "删除标记")
private String delFlag;
/**
* 所属租户
*/
@ApiModelProperty(value = "所属租户", hidden = true)
private Integer tenantId;
}
@@ -0,0 +1,55 @@
/*
* 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.code.entity;
import lombok.Data;
import java.util.List;
/**
* @author lengleng
* @date 2018/07/29
* 表属性: https://blog.csdn.net/lkforce/article/details/79557482
*/
@Data
public class TableEntity {
/**
* 名称
*/
private String tableName;
/**
* 备注
*/
private String comments;
/**
* 主键
*/
private ColumnEntity pk;
/**
* 列名
*/
private List<ColumnEntity> columns;
/**
* 驼峰类型
*/
private String caseClassName;
/**
* 普通类型
*/
private String lowerClassName;
}
@@ -0,0 +1,30 @@
/*
* 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.code.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.pig4cloud.pigx.code.entity.GenDatasourceConf;
/**
* 数据源表
*
* @author lengleng
* @date 2019-03-31 16:00:20
*/
public interface GenDatasourceConfMapper extends BaseMapper<GenDatasourceConf> {
}
@@ -0,0 +1,33 @@
/*
* 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.code.mapper;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.pig4cloud.pigx.code.entity.GenFormConf;
/**
* 生成记录
*
* @author lengleng
* @date 2019-08-12 15:55:35
*/
@DS("master")
public interface GenFormConfMapper extends BaseMapper<GenFormConf> {
}
@@ -0,0 +1,59 @@
/*
* 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.code.mapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.ibatis.annotations.Param;
import java.util.List;
import java.util.Map;
/**
* 代码生成器
*
* @author lengleng
* @date 2018-07-30
*/
public interface GeneratorMapper {
/**
* 分页查询表格
*
* @param page
* @param tableName
* @return
*/
IPage<List<Map<String, Object>>> queryList(Page page, @Param("tableName") String tableName);
/**
* 查询表信息
*
* @param tableName 表名称
* @return
*/
Map<String, String> queryTable(String tableName);
/**
* 查询表列信息
*
* @param tableName 表名称
* @return
*/
List<Map<String, String>> queryColumns(String tableName);
}
@@ -0,0 +1,44 @@
/*
* 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.code.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.pig4cloud.pigx.code.entity.GenDatasourceConf;
/**
* 数据源表
*
* @author lengleng
* @date 2019-03-31 16:00:20
*/
public interface GenDatasourceConfService extends IService<GenDatasourceConf> {
/**
* 保存数据源并且加密
*
* @param genDatasourceConf
* @return
*/
Boolean saveDsByEnc(GenDatasourceConf genDatasourceConf);
/**
* 更新数据源
*
* @param genDatasourceConf
* @return
*/
Boolean updateDsByEnc(GenDatasourceConf genDatasourceConf);
}
@@ -0,0 +1,40 @@
/*
* 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.code.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.pig4cloud.pigx.code.entity.GenFormConf;
/**
* 表单管理
*
* @author lengleng
* @date 2019-08-12 15:55:35
*/
public interface GenFormConfService extends IService<GenFormConf> {
/**
* 获取表单信息
*
* @param dsId 数据源ID
* @param tableName 表名称
* @return
*/
String getForm(Integer dsId, String tableName);
}
@@ -0,0 +1,48 @@
/*
* 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.code.service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pig4cloud.pigx.code.entity.GenConfig;
import java.util.List;
import java.util.Map;
/**
* @author lengleng
* @date 2018/7/29
*/
public interface GeneratorService {
/**
* 生成代码
*
* @param tableNames 表名称
* @return
*/
byte[] generatorCode(GenConfig tableNames);
/**
* 分页查询表
*
* @param page 分页信息
* @param tableName 表名
* @return
*/
IPage<List<Map<String, Object>>> getPage(Page page, String tableName);
}
@@ -0,0 +1,68 @@
/*
* 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.code.service.impl;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pig4cloud.pigx.code.entity.GenDatasourceConf;
import com.pig4cloud.pigx.code.mapper.GenDatasourceConfMapper;
import com.pig4cloud.pigx.code.service.GenDatasourceConfService;
import lombok.AllArgsConstructor;
import org.jasypt.encryption.StringEncryptor;
import org.springframework.stereotype.Service;
/**
* 数据源表
*
* @author lengleng
* @date 2019-03-31 16:00:20
*/
@Service
@AllArgsConstructor
public class GenDatasourceConfServiceImpl extends ServiceImpl<GenDatasourceConfMapper, GenDatasourceConf> implements GenDatasourceConfService {
private final StringEncryptor stringEncryptor;
/**
* 保存数据源并且加密
*
* @param genDatasourceConf
* @return
*/
@Override
public Boolean saveDsByEnc(GenDatasourceConf genDatasourceConf) {
genDatasourceConf.setPassword(stringEncryptor.encrypt(genDatasourceConf.getPassword()));
this.baseMapper.insert(genDatasourceConf);
return true;
// return dynamicDataSourceConfig.reload();
}
/**
* 更新数据源
*
* @param genDatasourceConf
* @return
*/
@Override
public Boolean updateDsByEnc(GenDatasourceConf genDatasourceConf) {
if (StrUtil.isNotBlank(genDatasourceConf.getPassword())) {
genDatasourceConf.setPassword(stringEncryptor.encrypt(genDatasourceConf.getPassword()));
}
this.baseMapper.updateById(genDatasourceConf);
return true;
// return dynamicDataSourceConfig.reload();
}
}
@@ -0,0 +1,98 @@
/*
* 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.code.service.impl;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pig4cloud.pigx.code.entity.ColumnEntity;
import com.pig4cloud.pigx.code.entity.GenFormConf;
import com.pig4cloud.pigx.code.mapper.GenFormConfMapper;
import com.pig4cloud.pigx.code.mapper.GeneratorMapper;
import com.pig4cloud.pigx.code.service.GenFormConfService;
import com.pig4cloud.pigx.code.util.GenUtils;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import org.apache.commons.lang.StringUtils;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader;
import org.springframework.stereotype.Service;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
/**
* 表单管理
*
* @author lengleng
* @date 2019-08-12 15:55:35
*/
@Service
@AllArgsConstructor
public class GenFormConfServiceImpl extends ServiceImpl<GenFormConfMapper, GenFormConf> implements GenFormConfService {
private final GeneratorMapper generatorMapper;
/**
* 1. 根据数据源、表名称,查询已配置表单信息
* 2. 不存在调用模板生成
*
* @param dsId 数据源ID
* @param tableName 表名称
* @return
*/
@DS("pigxx")
@Override
@SneakyThrows
public String getForm(Integer dsId, String tableName) {
GenFormConf form = getOne(Wrappers.<GenFormConf>lambdaQuery()
.eq(GenFormConf::getTableName, tableName)
.orderByDesc(GenFormConf::getCreateTime), false);
if (form != null) {
return form.getFormInfo();
}
// DynamicDataSourceContextHolder.setDataSourceType(dsId);
List<Map<String, String>> columns = generatorMapper.queryColumns(tableName);
//设置velocity资源加载器
Properties prop = new Properties();
prop.put("file.resource.loader.class", ClasspathResourceLoader.class.getName());
Velocity.init(prop);
Template template = Velocity.getTemplate("template/crud.js.vm", CharsetUtil.UTF_8);
VelocityContext context = new VelocityContext();
List<ColumnEntity> columnList = new ArrayList<>();
for (Map<String, String> column : columns) {
ColumnEntity columnEntity = new ColumnEntity();
columnEntity.setComments(column.get("columnComment"));
columnEntity.setLowerAttrName(StringUtils.uncapitalize(GenUtils.columnToJava(column.get("columnName"))));
columnList.add(columnEntity);
}
context.put("columns", columnList);
StringWriter writer = new StringWriter();
template.merge(context, writer);
return StrUtil.trim(StrUtil.removePrefix(writer.toString(), GenUtils.CRUD_PREFIX));
}
}
@@ -0,0 +1,106 @@
/*
* 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.code.service.impl;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
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.code.entity.GenConfig;
import com.pig4cloud.pigx.code.entity.GenFormConf;
import com.pig4cloud.pigx.code.mapper.GenFormConfMapper;
import com.pig4cloud.pigx.code.mapper.GeneratorMapper;
import com.pig4cloud.pigx.code.service.GeneratorService;
import com.pig4cloud.pigx.code.util.GenUtils;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import java.io.ByteArrayOutputStream;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipOutputStream;
/**
* @author lengleng
* @date 2018-07-30
* <p>
* 代码生成器
*/
@Service
@AllArgsConstructor
public class GeneratorServiceImpl implements GeneratorService {
private final GeneratorMapper generatorMapper;
private final GenFormConfMapper genFormConfMapper;
/**
* 分页查询表
*
* @param tableName 查询条件
* @return
*/
@DS("#session.dataSourceName")
@Override
public IPage<List<Map<String, Object>>> getPage(Page page, String tableName) {
return generatorMapper.queryList(page, tableName);
}
/**
* 生成代码
*
* @param genConfig 生成配置
* @return
*/
@DS("#session.dataSourceName")
@Override
public byte[] generatorCode(GenConfig genConfig) {
//根据tableName 查询最新的表单配置
List<GenFormConf> formConfList = genFormConfMapper.selectList(Wrappers.<GenFormConf>lambdaQuery()
.eq(GenFormConf::getTableName, genConfig.getTableName())
.orderByDesc(GenFormConf::getCreateTime));
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ZipOutputStream zip = new ZipOutputStream(outputStream);
String tableNames = genConfig.getTableName();
for (String tableName : StrUtil.split(tableNames, StrUtil.DASHED)) {
//查询表信息
Map<String, String> table = queryTable(tableName);
//查询列信息
List<Map<String, String>> columns = queryColumns(tableName);
//生成代码
if (CollUtil.isNotEmpty(formConfList)) {
GenUtils.generatorCode(genConfig, table, columns, zip, formConfList.get(0));
} else {
GenUtils.generatorCode(genConfig, table, columns, zip, null);
}
}
IoUtil.close(zip);
return outputStream.toByteArray();
}
private Map<String, String> queryTable(String tableName) {
return generatorMapper.queryTable(tableName);
}
private List<Map<String, String>> queryColumns(String tableName) {
return generatorMapper.queryColumns(tableName);
}
}
@@ -0,0 +1,312 @@
/*
* 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.code.util;
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.code.entity.ColumnEntity;
import com.pig4cloud.pigx.code.entity.GenConfig;
import com.pig4cloud.pigx.code.entity.GenFormConf;
import com.pig4cloud.pigx.code.entity.TableEntity;
import com.pig4cloud.pigx.common.core.constant.CommonConstants;
import com.pig4cloud.pigx.common.core.exception.CheckedException;
import lombok.SneakyThrows;
import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.WordUtils;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import java.io.File;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
* 代码生成器 工具类
*
* @author lengleng
* @date 2018-07-30
*/
@Slf4j
@UtilityClass
public class GenUtils {
public final String CRUD_PREFIX = "export const tableOption =";
private final String ENTITY_JAVA_VM = "Entity.java.vm";
private final String MAPPER_JAVA_VM = "Mapper.java.vm";
private final String SERVICE_JAVA_VM = "Service.java.vm";
private final String SERVICE_IMPL_JAVA_VM = "ServiceImpl.java.vm";
private final String CONTROLLER_JAVA_VM = "Controller.java.vm";
private final String MAPPER_XML_VM = "Mapper.xml.vm";
private final String MENU_SQL_VM = "menu.sql.vm";
private final String INDEX_VUE_VM = "index.vue.vm";
private final String API_JS_VM = "api.js.vm";
private final String CRUD_JS_VM = "crud.js.vm";
private List<String> getTemplates() {
List<String> templates = new ArrayList<>();
templates.add("template/Entity.java.vm");
templates.add("template/Mapper.java.vm");
templates.add("template/Mapper.xml.vm");
templates.add("template/Service.java.vm");
templates.add("template/ServiceImpl.java.vm");
templates.add("template/Controller.java.vm");
templates.add("template/menu.sql.vm");
templates.add("template/index.vue.vm");
templates.add("template/api.js.vm");
templates.add("template/crud.js.vm");
return templates;
}
/**
* 生成代码
*/
@SneakyThrows
public void generatorCode(GenConfig genConfig, Map<String, String> table,
List<Map<String, String>> columns, ZipOutputStream zip, GenFormConf formConf) {
//配置信息
Configuration config = getConfig();
boolean hasBigDecimal = false;
//表信息
TableEntity tableEntity = new TableEntity();
tableEntity.setTableName(table.get("tableName"));
if (StrUtil.isNotBlank(genConfig.getComments())) {
tableEntity.setComments(genConfig.getComments());
} else {
tableEntity.setComments(table.get("tableComment"));
}
String tablePrefix;
if (StrUtil.isNotBlank(genConfig.getTablePrefix())) {
tablePrefix = genConfig.getTablePrefix();
} else {
tablePrefix = config.getString("tablePrefix");
}
//表名转换成Java类名
String className = tableToJava(tableEntity.getTableName(), tablePrefix);
tableEntity.setCaseClassName(className);
tableEntity.setLowerClassName(StringUtils.uncapitalize(className));
//获取需要在swagger文档中隐藏的属性字段
List<Object> hiddenColumns = config.getList("hiddenColumn");
//列信息
List<ColumnEntity> columnList = new ArrayList<>();
for (Map<String, String> column : columns) {
ColumnEntity columnEntity = new ColumnEntity();
columnEntity.setColumnName(column.get("columnName"));
columnEntity.setDataType(column.get("dataType"));
columnEntity.setComments(column.get("columnComment"));
columnEntity.setExtra(column.get("extra"));
columnEntity.setNullable("NO".equals(column.get("isNullable")));
columnEntity.setColumnType(column.get("columnType"));
//隐藏不需要的在接口文档中展示的字段
if (hiddenColumns.contains(column.get("columnName"))) {
columnEntity.setHidden(Boolean.TRUE);
} else {
columnEntity.setHidden(Boolean.FALSE);
}
//列名转换成Java属性名
String attrName = columnToJava(columnEntity.getColumnName());
columnEntity.setCaseAttrName(attrName);
columnEntity.setLowerAttrName(StringUtils.uncapitalize(attrName));
//列的数据类型,转换成Java类型
String attrType = config.getString(columnEntity.getDataType(), "unknowType");
columnEntity.setAttrType(attrType);
if (!hasBigDecimal && "BigDecimal".equals(attrType)) {
hasBigDecimal = true;
}
//是否主键
if ("PRI".equalsIgnoreCase(column.get("columnKey")) && tableEntity.getPk() == null) {
tableEntity.setPk(columnEntity);
}
columnList.add(columnEntity);
}
tableEntity.setColumns(columnList);
//没主键,则第一个字段为主键
if (tableEntity.getPk() == null) {
tableEntity.setPk(tableEntity.getColumns().get(0));
}
//设置velocity资源加载器
Properties prop = new Properties();
prop.put("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
Velocity.init(prop);
//封装模板数据
Map<String, Object> map = new HashMap<>(16);
map.put("tableName", tableEntity.getTableName());
map.put("pk", tableEntity.getPk());
map.put("className", tableEntity.getCaseClassName());
map.put("classname", tableEntity.getLowerClassName());
map.put("pathName", tableEntity.getLowerClassName().toLowerCase());
map.put("columns", tableEntity.getColumns());
map.put("hasBigDecimal", hasBigDecimal);
map.put("datetime", DateUtil.now());
if (StrUtil.isNotBlank(genConfig.getComments())) {
map.put("comments", genConfig.getComments());
} else {
map.put("comments", tableEntity.getComments());
}
if (StrUtil.isNotBlank(genConfig.getAuthor())) {
map.put("author", genConfig.getAuthor());
} else {
map.put("author", config.getString("author"));
}
if (StrUtil.isNotBlank(genConfig.getModuleName())) {
map.put("moduleName", genConfig.getModuleName());
} else {
map.put("moduleName", config.getString("moduleName"));
}
if (StrUtil.isNotBlank(genConfig.getPackageName())) {
map.put("package", genConfig.getPackageName());
map.put("mainPath", genConfig.getPackageName());
} else {
map.put("package", config.getString("package"));
map.put("mainPath", config.getString("mainPath"));
}
VelocityContext context = new VelocityContext(map);
//获取模板列表
List<String> templates = getTemplates();
for (String template : templates) {
// 如果是crud
if (template.contains(CRUD_JS_VM) && formConf != null) {
zip.putNextEntry(new ZipEntry(Objects
.requireNonNull(getFileName(template, tableEntity.getCaseClassName()
, map.get("package").toString(), map.get("moduleName").toString()))));
IoUtil.write(zip, StandardCharsets.UTF_8, false, CRUD_PREFIX + formConf.getFormInfo());
zip.closeEntry();
continue;
}
//渲染模板
StringWriter sw = new StringWriter();
Template tpl = Velocity.getTemplate(template, CharsetUtil.UTF_8);
tpl.merge(context, sw);
//添加到zip
zip.putNextEntry(new ZipEntry(Objects
.requireNonNull(getFileName(template, tableEntity.getCaseClassName()
, map.get("package").toString(), map.get("moduleName").toString()))));
IoUtil.write(zip, StandardCharsets.UTF_8, false, sw.toString());
IoUtil.close(sw);
zip.closeEntry();
}
}
/**
* 列名转换成Java属性名
*/
public String columnToJava(String columnName) {
return WordUtils.capitalizeFully(columnName, new char[]{'_'}).replace("_", "");
}
/**
* 表名转换成Java类名
*/
private String tableToJava(String tableName, String tablePrefix) {
if (StringUtils.isNotBlank(tablePrefix)) {
tableName = tableName.replaceFirst(tablePrefix, "");
}
return columnToJava(tableName);
}
/**
* 获取配置信息
*/
private Configuration getConfig() {
try {
return new PropertiesConfiguration("generator.properties");
} catch (ConfigurationException e) {
throw new CheckedException("获取配置文件失败,", e);
}
}
/**
* 获取文件名
*/
private String getFileName(String template, String className, String packageName, String moduleName) {
String packagePath = CommonConstants.BACK_END_PROJECT + File.separator + "src" + File.separator + "main" + File.separator + "java" + File.separator;
if (StringUtils.isNotBlank(packageName)) {
packagePath += packageName.replace(".", File.separator) + File.separator + moduleName + File.separator;
}
if (template.contains(ENTITY_JAVA_VM)) {
return packagePath + "entity" + File.separator + className + ".java";
}
if (template.contains(MAPPER_JAVA_VM)) {
return packagePath + "mapper" + File.separator + className + "Mapper.java";
}
if (template.contains(SERVICE_JAVA_VM)) {
return packagePath + "service" + File.separator + className + "Service.java";
}
if (template.contains(SERVICE_IMPL_JAVA_VM)) {
return packagePath + "service" + File.separator + "impl" + File.separator + className + "ServiceImpl.java";
}
if (template.contains(CONTROLLER_JAVA_VM)) {
return packagePath + "controller" + File.separator + className + "Controller.java";
}
if (template.contains(MAPPER_XML_VM)) {
return CommonConstants.BACK_END_PROJECT + File.separator + "src" + File.separator + "main" + File.separator + "resources" + File.separator + "mapper" + File.separator + className + "Mapper.xml";
}
if (template.contains(MENU_SQL_VM)) {
return className.toLowerCase() + "_menu.sql";
}
if (template.contains(INDEX_VUE_VM)) {
return CommonConstants.FRONT_END_PROJECT + File.separator + "src" + File.separator + "views" +
File.separator + moduleName + File.separator + className.toLowerCase() + File.separator + "index.vue";
}
if (template.contains(API_JS_VM)) {
return CommonConstants.FRONT_END_PROJECT + File.separator + "src" + File.separator + "api" + File.separator + className.toLowerCase() + ".js";
}
if (template.contains(CRUD_JS_VM)) {
return CommonConstants.FRONT_END_PROJECT + File.separator + "src" + File.separator + "const" +
File.separator + "crud" + File.separator + className.toLowerCase() + ".js";
}
return null;
}
}
@@ -0,0 +1,16 @@
server:
port: 5003
spring:
application:
name: @artifactId@
cloud:
nacos:
discovery:
server-addr: ${NACOS-HOST:pigx-register}:${NACOS-PORT:8848}
config:
server-addr: ${spring.cloud.nacos.discovery.server-addr}
file-extension: yml
shared-dataids: application-${spring.profiles.active}.${spring.cloud.nacos.config.file-extension}
profiles:
active: @profiles.active@
@@ -0,0 +1,37 @@
#\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_
#\u7C7B\u578B\u8F6C\u6362\uFF0C\u914D\u7F6E\u4FE1\u606F
tinyint=Integer
smallint=Integer
mediumint=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
@@ -0,0 +1,33 @@
<?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.code.mapper.GenFormConfMapper">
<resultMap id="genRecordMap" type="com.pig4cloud.pigx.code.entity.GenFormConf">
<id property="id" column="id"/>
<result property="tableName" column="table_name"/>
<result property="formInfo" column="form_info"/>
<result property="createTime" column="create_time"/>
<result property="updateTime" column="update_time"/>
<result property="delFlag" column="del_flag"/>
<result property="tenantId" column="tenant_id"/>
</resultMap>
</mapper>
@@ -0,0 +1,23 @@
<?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.code.mapper.GeneratorMapper">
<select id="queryList" resultType="map">
select table_name tableName, engine, table_comment tableComment, 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>
<select id="queryColumns" resultType="map">
select column_name columnName, data_type dataType, column_comment columnComment, 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
</select>
</mapper>
@@ -0,0 +1,110 @@
/*
* 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 ${package}.${moduleName}.controller;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pig4cloud.pigx.common.core.util.R;
import com.pig4cloud.pigx.common.log.annotation.SysLog;
import ${package}.${moduleName}.entity.${className};
import ${package}.${moduleName}.service.${className}Service;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;
/**
* ${comments}
*
* @author ${author}
* @date ${datetime}
*/
@RestController
@AllArgsConstructor
@RequestMapping("/${pathName}" )
@Api(value = "${pathName}", tags = "${comments}管理")
public class ${className}Controller {
private final ${className}Service ${classname}Service;
/**
* 分页查询
* @param page 分页对象
* @param ${classname} ${comments}
* @return
*/
@ApiOperation(value = "分页查询", notes = "分页查询")
@GetMapping("/page" )
public R get${className}Page(Page page, ${className} ${classname}) {
return R.ok(${classname}Service.page(page, Wrappers.query(${classname})));
}
/**
* 通过id查询${comments}
* @param ${pk.lowerAttrName} id
* @return R
*/
@ApiOperation(value = "通过id查询", notes = "通过id查询")
@GetMapping("/{${pk.lowerAttrName}}" )
public R getById(@PathVariable("${pk.lowerAttrName}" ) ${pk.attrType} ${pk.lowerAttrName}) {
return R.ok(${classname}Service.getById(${pk.lowerAttrName}));
}
/**
* 新增${comments}
* @param ${classname} ${comments}
* @return R
*/
@ApiOperation(value = "新增${comments}", notes = "新增${comments}")
@SysLog("新增${comments}" )
@PostMapping
@PreAuthorize("@pms.hasPermission('${moduleName}_${pathName}_add')" )
public R save(@RequestBody ${className} ${classname}) {
return R.ok(${classname}Service.save(${classname}));
}
/**
* 修改${comments}
* @param ${classname} ${comments}
* @return R
*/
@ApiOperation(value = "修改${comments}", notes = "修改${comments}")
@SysLog("修改${comments}" )
@PutMapping
@PreAuthorize("@pms.hasPermission('${moduleName}_${pathName}_edit')" )
public R updateById(@RequestBody ${className} ${classname}) {
return R.ok(${classname}Service.updateById(${classname}));
}
/**
* 通过id删除${comments}
* @param ${pk.lowerAttrName} id
* @return R
*/
@ApiOperation(value = "通过id删除${comments}", notes = "通过id删除${comments}")
@SysLog("通过id删除${comments}" )
@DeleteMapping("/{${pk.lowerAttrName}}" )
@PreAuthorize("@pms.hasPermission('${moduleName}_${pathName}_del')" )
public R removeById(@PathVariable ${pk.attrType} ${pk.lowerAttrName}) {
return R.ok(${classname}Service.removeById(${pk.lowerAttrName}));
}
}
@@ -0,0 +1,56 @@
/*
* 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 ${package}.${moduleName}.entity;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.extension.activerecord.Model;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
#if(${hasBigDecimal})
import java.math.BigDecimal;
#end
import java.io.Serializable;
import java.time.LocalDateTime;
/**
* ${comments}
*
* @author ${author}
* @date ${datetime}
*/
@Data
@TableName("${tableName}")
@EqualsAndHashCode(callSuper = true)
@ApiModel(value = "${comments}")
public class ${className} extends Model<${className}> {
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)
private $column.attrType $column.lowerAttrName;
#end
}
@@ -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 ${package}.${moduleName}.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import ${package}.${moduleName}.entity.${className};
/**
* ${comments}
*
* @author ${author}
* @date ${datetime}
*/
public interface ${className}Mapper extends BaseMapper<${className}> {
}
@@ -0,0 +1,35 @@
<?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="${package}.${moduleName}.mapper.${className}Mapper">
<resultMap id="${classname}Map" type="${package}.${moduleName}.entity.${className}">
#foreach($column in $columns)
#if($column.lowerAttrName==$pk.lowerAttrName)
<id property="${pk.lowerAttrName}" column="${pk.columnName}"/>
#else
<result property="${column.lowerAttrName}" column="${column.columnName}"/>
#end
#end
</resultMap>
</mapper>
@@ -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 ${package}.${moduleName}.service;
import com.baomidou.mybatisplus.extension.service.IService;
import ${package}.${moduleName}.entity.${className};
/**
* ${comments}
*
* @author ${author}
* @date ${datetime}
*/
public interface ${className}Service extends IService<${className}> {
}
@@ -0,0 +1,34 @@
/*
* 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 ${package}.${moduleName}.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import ${package}.${moduleName}.entity.${className};
import ${package}.${moduleName}.mapper.${className}Mapper;
import ${package}.${moduleName}.service.${className}Service;
import org.springframework.stereotype.Service;
/**
* ${comments}
*
* @author ${author}
* @date ${datetime}
*/
@Service
public class ${className}ServiceImpl extends ServiceImpl<${className}Mapper, ${className}> implements ${className}Service {
}
@@ -0,0 +1,56 @@
/*
* 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)
*/
import request from '@/router/axios'
export function fetchList(query) {
return request({
url: '/${moduleName}/${pathName}/page',
method: 'get',
params: query
})
}
export function addObj(obj) {
return request({
url: '/${moduleName}/${pathName}',
method: 'post',
data: obj
})
}
export function getObj(id) {
return request({
url: '/${moduleName}/${pathName}/' + id,
method: 'get'
})
}
export function delObj(id) {
return request({
url: '/${moduleName}/${pathName}/' + id,
method: 'delete'
})
}
export function putObj(obj) {
return request({
url: '/${moduleName}/${pathName}',
method: 'put',
data: obj
})
}
@@ -0,0 +1,17 @@
export const tableOption = {
"border": true,
"index": true,
"indexLabel": "序号",
"stripe": true,
"menuAlign": "center",
"align": "center",
"column": [
#foreach ($column in $columns)
{
"type": "input",
"label": "$column.comments",
"prop": "$column.lowerAttrName"
}#if($foreach.hasNext),#end
#end
]
}
@@ -0,0 +1,121 @@
<!--
- 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)
-->
<template>
<div class="execution">
<basic-container>
<avue-crud ref="crud"
:page="page"
:data="tableData"
:permission="permissionList"
:table-loading="tableLoading"
:option="tableOption"
@on-load="getList"
@search-change="searchChange"
@refresh-change="refreshChange"
@row-update="handleUpdate"
@row-save="handleSave"
@row-del="rowDel">
</avue-crud>
</basic-container>
</div>
</template>
<script>
import {fetchList, getObj, addObj, putObj, delObj} from '@/api/${pathName}'
import {tableOption} from '@/const/crud/${pathName}'
import {mapGetters} from 'vuex'
export default {
name: '${pathName}',
data() {
return {
searchForm: {},
tableData: [],
page: {
total: 0, // 总页数
currentPage: 1, // 当前页数
pageSize: 20 // 每页显示多少条
},
tableLoading: false,
tableOption: tableOption
}
},
computed: {
...mapGetters(['permissions']),
permissionList() {
return {
addBtn: this.vaildData(this.permissions.${moduleName}_${pathName}_add, false),
delBtn: this.vaildData(this.permissions.${moduleName}_${pathName}_del, false),
editBtn: this.vaildData(this.permissions.${moduleName}_${pathName}_edit, false)
};
}
},
methods: {
getList(page, params) {
this.tableLoading = true
fetchList(Object.assign({
current: page.currentPage,
size: page.pageSize
}, params, this.searchForm )).then(response => {
this.tableData = response.data.data.records
this.page.total = response.data.data.total
this.tableLoading = false
}).catch(() => {
this.tableLoading=false
})
},
rowDel: function (row, index) {
var _this = this
this.$confirm('是否确认删除ID为' + row.$pk.lowerAttrName, '提示', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning'
}).then(function () {
return delObj(row.$pk.lowerAttrName)
}).then(data => {
_this.$message.success('删除成功')
this.getList(this.page)
})
},
handleUpdate: function (row, index, done,loading) {
putObj(row).then(data => {
this.$message.success('修改成功')
done()
this.getList(this.page)
}).catch(() => {
loading();
});
},
handleSave: function (row, done,loading) {
addObj(row).then(data => {
this.$message.success('添加成功')
done()
this.getList(this.page)
}).catch(() => {
loading();
});
},
searchChange(form) {
this.searchForm = form
this.getList(this.page, form)
},
refreshChange() {
this.getList(this.page)
}
}
}
</script>
@@ -0,0 +1,16 @@
-- 该脚本不要直接执行, 注意维护菜单的父节点ID 默认 父节点1000
-- 菜单SQL
insert into `sys_menu` ( `parent_id`, `path`, `permission`, `type`, `icon`, `del_flag`, `create_time`, `sort`, `update_time`, `name`)
values ( '1000', '/${moduleName}/${pathName}/index', '', '0', 'icon-bangzhushouji', '0', '2018-01-20 13:17:19', '8', '2018-07-29 13:38:19', '${comments}管理');
-- 按钮父菜单ID
set @parentId = @@identity;
-- 菜单对应按钮SQL
insert into `sys_menu` ( `parent_id`, `permission`, `type`, `path`, `icon`, `del_flag`, `create_time`, `sort`, `update_time`, `name`)
SELECT @parentId, '${moduleName}_${pathName}_add', '1', null, '1', '0', '2018-05-15 21:35:18', '0', '2018-07-29 13:38:59', '${comments}新增';
insert into `sys_menu` ( `parent_id`, `permission`, `type`, `path`, `icon`, `del_flag`, `create_time`, `sort`, `update_time`, `name`)
SELECT @parentId, '${moduleName}_${pathName}_edit', '1', null, '1', '0', '2018-05-15 21:35:18', '1', '2018-07-29 13:38:59', '${comments}修改';
insert into `sys_menu` ( `parent_id`, `permission`, `type`, `path`, `icon`, `del_flag`, `create_time`, `sort`, `update_time`, `name`)
SELECT @parentId, '${moduleName}_${pathName}_del', '1', null, '1', '0', '2018-05-15 21:35:18', '2', '2018-07-29 13:38:59', '${comments}删除';
@@ -0,0 +1,94 @@
## 快速入门
### 创建测试数据库
```
create database `test1` default character set utf8mb4 collate utf8mb4_general_ci;
create database `test2` default character set utf8mb4 collate utf8mb4_general_ci;
create database `test3` default character set utf8mb4 collate utf8mb4_general_ci;
```
### 创建测试表
```
CREATE TABLE `user` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'id',
`username` varchar(255) DEFAULT NULL COMMENT '用户名',
`password` varchar(255) DEFAULT NULL COMMENT '密码',
PRIMARY KEY (`id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=40 DEFAULT CHARSET=utf8mb4 COMMENT='用户测试表';
```
### 插入测试数据
```
use test1;
BEGIN;
INSERT INTO `user` VALUES (1, 'test1测试一', '123');
INSERT INTO `user` VALUES (2, 'test1测试二', '123');
INSERT INTO `user` VALUES (3, 'test1测试三', '123');
COMMIT;
use test2;
BEGIN;
INSERT INTO `user` VALUES (1, 'test2测试一', '123');
INSERT INTO `user` VALUES (2, 'test2测试二', '123');
INSERT INTO `user` VALUES (3, 'test2测试三', '123');
COMMIT;
use test3;
BEGIN;
INSERT INTO `user` VALUES (1, 'test3测试一', '123');
INSERT INTO `user` VALUES (2, 'test3测试二', '123');
INSERT INTO `user` VALUES (3, 'test3测试三', '123');
COMMIT;
```
### Nocas新增配置
```
## pigx-dynamic-datasource-biz.yml
## spring security 配置
security:
oauth2:
client:
client-id: ENC(ltJPpR50wT0oIY9kfOe1Iw==)
client-secret: ENC(ltJPpR50wT0oIY9kfOe1Iw==)
scope: server
# 数据源
spring:
datasource:
dynamic:
primary: test1 #设置默认的数据源
druid:
filters: stat
datasource:
test1:
username: ${MYSQL-USER:root}
password: ${MYSQL-USER:root}
url: jdbc:mysql://${MYSQL-HOST:pigx-mysql}:${MYSQL-PORT:3306}/test1?characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=GMT%2B8&allowMultiQueries=true&allowPublicKeyRetrieval=true
driver-class-name: com.mysql.cj.jdbc.Driver
test2:
username: ${MYSQL-USER:root}
password: ${MYSQL-USER:root}
url: jdbc:mysql://${MYSQL-HOST:pigx-mysql}:${MYSQL-PORT:3306}/test2?characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=GMT%2B8&allowMultiQueries=true&allowPublicKeyRetrieval=true
driver-class-name: com.mysql.cj.jdbc.Driver
test3:
username: ${MYSQL-USER:root}
password: ${MYSQL-USER:root}
url: jdbc:mysql://${MYSQL-HOST:pigx-mysql}:${MYSQL-PORT:3306}/test3?characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=GMT%2B8&allowMultiQueries=true&allowPublicKeyRetrieval=true
driver-class-name: com.mysql.cj.jdbc.Driver
```
### 启动以下应用
+ PigxNacosApplication
+ PigxSentinelApplication
+ PigxAuthApplication
+ PigxAdminApplication
+ PigxGatewayApplication
+ PigxDynamicDatasourceApplication
### Postman看效果
```
http://localhost:6060/test/getTest1
http://localhost:6060/test/getTest2?current=1&size=5
http://localhost:6060/test/getTest3?current=1&size=5
```
![test1数据库](http://i1.fuimg.com/704023/83e168e45242e135.png "test1数据库")
![test2数据库](http://i1.fuimg.com/704023/cf8c42fbc3512c32.png "test2数据库")
![test3数据库](http://i1.fuimg.com/704023/534483515e3f7cd0.png "test3数据库")
### 切换数据源
```
请参考:com/pig4cloud/pigx/dynamic/mapper/TestMapper.java
```
### 联系我
QQ:55215085
@@ -0,0 +1,27 @@
<?xml version="1.0"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.pig4cloud</groupId>
<artifactId>pigx-dynamic-datasource</artifactId>
<version>3.5.0</version>
</parent>
<artifactId>pigx-dynamic-datasource-api</artifactId>
<dependencies>
<!--core 工具类-->
<dependency>
<groupId>com.pig4cloud</groupId>
<artifactId>pigx-common-core</artifactId>
</dependency>
<!--mybatis plus extension,包含了mybatis plus core-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-extension</artifactId>
</dependency>
</dependencies>
</project>
@@ -0,0 +1,6 @@
/*
@author pigx archetype
* <p>
* feign client 存放目录,注意 @EnablePigxFeignClients 的扫描范围
*/
package com.pig4cloud.pigx.dynamic.feign;
@@ -0,0 +1,99 @@
<?xml version="1.0"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.pig4cloud</groupId>
<artifactId>pigx-dynamic-datasource</artifactId>
<version>3.5.0</version>
</parent>
<artifactId>pigx-dynamic-datasource-biz</artifactId>
<dependencies>
<!--必备: undertow容器-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-undertow</artifactId>
</dependency>
<!--必备: spring boot web-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--必备: 注册中心客户端-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<!--必备: 配置中心客户端-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>
<!--必备: 操作数据源相关-->
<dependency>
<groupId>com.pig4cloud</groupId>
<artifactId>pigx-common-data</artifactId>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
</dependency>
<dependency>
<artifactId>druid-spring-boot-starter</artifactId>
<groupId>com.alibaba</groupId>
<version>1.1.20</version>
</dependency>
<!-- 动态数据源 数据操作 -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>dynamic-datasource-spring-boot-starter</artifactId>
<version>2.5.6</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>com.pig4cloud</groupId>
<artifactId>pigx-common-log</artifactId>
</dependency>
<!--必备:pigx安全模块-->
<dependency>
<groupId>com.pig4cloud</groupId>
<artifactId>pigx-common-security</artifactId>
</dependency>
<!--必备: sentinel 依赖-->
<dependency>
<groupId>com.pig4cloud</groupId>
<artifactId>pigx-common-sentinel</artifactId>
</dependency>
<!--必备: 依赖api模块-->
<dependency>
<groupId>com.pig4cloud</groupId>
<artifactId>pigx-dynamic-datasource-api</artifactId>
<version>3.5.0</version>
</dependency>
<!--选配: swagger文档-->
<dependency>
<groupId>com.pig4cloud</groupId>
<artifactId>pigx-common-swagger</artifactId>
</dependency>
<!--测试: spring boot test-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
@@ -0,0 +1,25 @@
package com.pig4cloud.pigx.dynamic;
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceAutoConfigure;
import com.pig4cloud.pigx.common.security.annotation.EnablePigxFeignClients;
import com.pig4cloud.pigx.common.security.annotation.EnablePigxResourceServer;
import com.pig4cloud.pigx.common.swagger.annotation.EnablePigxSwagger2;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.cloud.client.SpringCloudApplication;
/**
* @author pigx archetype
* <p>
* 项目启动类
*/
@EnablePigxSwagger2
@SpringCloudApplication
@EnablePigxFeignClients
@EnablePigxResourceServer
@EnableAutoConfiguration(exclude={DruidDataSourceAutoConfigure.class})
public class PigxDynamicDatasourceApplication {
public static void main(String[] args) {
SpringApplication.run(PigxDynamicDatasourceApplication.class, args);
}
}
@@ -0,0 +1,96 @@
/*
*
* 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.dynamic.controller;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pig4cloud.pigx.common.core.util.R;
import com.pig4cloud.pigx.common.log.annotation.SysLog;
import com.pig4cloud.pigx.dynamic.mapper.TestMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.Map;
/**
* @author liuyes
* @date 2019/11/19
*/
@RestController
@AllArgsConstructor
@RequestMapping("/test")
@Api(value = "test", tags = "动态多数据源示例模块")
public class TestController {
private TestMapper testMapper;
/**
* 获取test1数据库用户信息
*
* @return 用户信息
*/
@ApiOperation(value = "查询test1数据库用户信息", notes = "查询test1数据库用户信息")
@SysLog("查询test1数据库用户信息" )
@PostMapping("/getTest1")
public R getTest1() {
List<Map<String, Object>> list = testMapper.getTest1();
if (list == null) {
return R.failed(null, "查询失败!");
}
return R.ok(list,"操作成功!");
}
/**
* 获取test2数据库用户信息
*
* @return 用户信息
*/
@ApiOperation(value = "查询test2数据库用户信息", notes = "查询test2数据库用户信息")
@SysLog("查询test2数据库用户信息" )
@PostMapping("/getTest2")
public R getTest2(Page page) {
IPage<List<Map<String, Object>>> list = testMapper.getTest2(page);
if (list == null) {
return R.failed(null, "查询失败!");
}
return R.ok(list,"操作成功!");
}
/**
* 获取test3数据库用户信息
*
* @return 用户信息
*/
@ApiOperation(value = "查询test3数据库用户信息", notes = "查询test3数据库用户信息")
@SysLog("查询test3数据库用户信息" )
@PostMapping("/getTest3")
public R getTest3(Page page) {
IPage<List<Map<String, Object>>> list = testMapper.getTest3(page);
if (list == null) {
return R.failed(null, "查询失败!");
}
return R.ok(list,"操作成功!");
}
}
@@ -0,0 +1,50 @@
/*
*
* 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.dynamic.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.Select;
import java.util.List;
import java.util.Map;
/**
* <p>
* test Mapper 接口
* </p>
*
* @author liuyes
* @date 2019/11/19
*/
public interface TestMapper {
@Select("SELECT * FROM user")
@DS("test1")
List<Map<String, Object>> getTest1();
@DS("test2")
IPage<List<Map<String, Object>>> getTest2(Page page);
@DS("test3")
IPage<List<Map<String, Object>>> getTest3(Page page);
}
@@ -0,0 +1,10 @@
package com.pig4cloud.pigx.dynamic.vo;
import lombok.Data;
@Data
public class UserVO {
private Integer id;
private String username;
private String password;
}
@@ -0,0 +1,16 @@
server:
port: 6060
spring:
application:
name: @artifactId@
cloud:
nacos:
discovery:
server-addr: ${NACOS-HOST:pigx-register}:${NACOS-PORT:8848}
config:
server-addr: ${spring.cloud.nacos.discovery.server-addr}
file-extension: yml
shared-dataids: application-${spring.profiles.active}.${spring.cloud.nacos.config.file-extension}
profiles:
active: dev
@@ -0,0 +1,70 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
小技巧: 在根pom里面设置统一存放路径,统一管理方便维护
<properties>
<log-path>/Users/lengleng</log-path>
</properties>
1. 其他模块加日志输出,直接copy本文件放在resources 目录即可
2. 注意修改 <property name="${log-path}/log.path" value=""/> 的value模块
-->
<configuration debug="false" scan="false">
<property name="log.path" value="logs/${project.artifactId}"/>
<!-- 彩色日志格式 -->
<property name="CONSOLE_LOG_PATTERN"
value="${CONSOLE_LOG_PATTERN:-%clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){faint} %clr(${LOG_LEVEL_PATTERN:-%5p}) %clr(${PID:- }){magenta} %clr(---){faint} %clr([%15.15t]){faint} %clr(%-40.40logger{39}){cyan} %clr(:){faint} %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}}"/>
<!-- 彩色日志依赖的渲染类 -->
<conversionRule conversionWord="clr" converterClass="org.springframework.boot.logging.logback.ColorConverter"/>
<conversionRule conversionWord="wex"
converterClass="org.springframework.boot.logging.logback.WhitespaceThrowableProxyConverter"/>
<conversionRule conversionWord="wEx"
converterClass="org.springframework.boot.logging.logback.ExtendedWhitespaceThrowableProxyConverter"/>
<!-- Console log output -->
<appender name="console" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>${CONSOLE_LOG_PATTERN}</pattern>
</encoder>
</appender>
<!-- Log file debug output -->
<appender name="debug" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${log.path}/debug.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<fileNamePattern>${log.path}/%d{yyyy-MM, aux}/debug.%d{yyyy-MM-dd}.%i.log.gz</fileNamePattern>
<maxFileSize>50MB</maxFileSize>
<maxHistory>30</maxHistory>
</rollingPolicy>
<encoder>
<pattern>%date [%thread] %-5level [%logger{50}] %file:%line - %msg%n</pattern>
</encoder>
</appender>
<!-- Log file error output -->
<appender name="error" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${log.path}/error.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<fileNamePattern>${log.path}/%d{yyyy-MM}/error.%d{yyyy-MM-dd}.%i.log.gz</fileNamePattern>
<maxFileSize>50MB</maxFileSize>
<maxHistory>30</maxHistory>
</rollingPolicy>
<encoder>
<pattern>%date [%thread] %-5level [%logger{50}] %file:%line - %msg%n</pattern>
</encoder>
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>ERROR</level>
</filter>
</appender>
<logger name="org.activiti.engine.impl.db" level="DEBUG">
<appender-ref ref="debug"/>
</logger>
<!--nacos 心跳 INFO 屏蔽-->
<logger name="com.alibaba.nacos" level="OFF">
<appender-ref ref="error"/>
</logger>
<!-- Level: FATAL 0 ERROR 3 WARN 4 INFO 6 DEBUG 7 -->
<root level="INFO">
<appender-ref ref="console"/>
<appender-ref ref="debug"/>
</root>
</configuration>
@@ -0,0 +1,13 @@
<?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.dynamic.mapper.TestMapper">
<select id="getTest2" resultType="com.pig4cloud.pigx.dynamic.vo.UserVO">
SELECT * FROM user
</select>
<select id="getTest3" resultType="com.pig4cloud.pigx.dynamic.vo.UserVO">
SELECT * FROM user
</select>
</mapper>
+179
View File
@@ -0,0 +1,179 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>pigx-visual</artifactId>
<groupId>com.pig4cloud</groupId>
<version>3.5.0</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>pigx-dynamic-datasource</artifactId>
<packaging>pom</packaging>
<name>pigx-dynamic-datasource</name>
<properties>
<spring-boot.version>2.1.10.RELEASE</spring-boot.version>
<spring-cloud.version>Greenwich.SR3</spring-cloud.version>
<spring-cloud-alibaba.version>2.1.0.RELEASE</spring-cloud-alibaba.version>
<spring-platform.version>Cairo-SR8</spring-platform.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<hutool.version>5.0.5</hutool.version>
<pigx.bom.version>3.5.0</pigx.bom.version>
<kaptcha.version>0.0.9</kaptcha.version>
<jasypt.version>2.1.1</jasypt.version>
<ttl.version>2.10.2</ttl.version>
<spring-boot-admin.version>2.1.6</spring-boot-admin.version>
<security.oauth.version>2.3.6.RELEASE</security.oauth.version>
</properties>
<!--项目子模块-->
<modules>
<module>pigx-dynamic-datasource-api</module>
<module>pigx-dynamic-datasource-biz</module>
</modules>
<dependencies>
<!--配置文件处理器-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<!--jasypt配置文件加解密-->
<dependency>
<groupId>com.github.ulisesbocchio</groupId>
<artifactId>jasypt-spring-boot-starter</artifactId>
<version>${jasypt.version}</version>
</dependency>
<!--监控-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<!--监控客户端-->
<dependency>
<groupId>de.codecentric</groupId>
<artifactId>spring-boot-admin-starter-client</artifactId>
<version>${spring-boot-admin.version}</version>
</dependency>
<!--Lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<scope>provided</scope>
</dependency>
<!--测试依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>${spring-boot.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>io.spring.platform</groupId>
<artifactId>platform-bom</artifactId>
<version>${spring-platform.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>com.pig4cloud</groupId>
<artifactId>pigx-common-bom</artifactId>
<version>${pigx.bom.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<!--spring cloud alibaba-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
<version>${spring-cloud-alibaba.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<!--稳定版本,替代spring security bom内置-->
<dependency>
<groupId>org.springframework.security.oauth</groupId>
<artifactId>spring-security-oauth2</artifactId>
<version>${security.oauth.version}</version>
</dependency>
<!--web 模块-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>${spring-boot.version}</version>
<exclusions>
<!--排除tomcat依赖-->
<exclusion>
<artifactId>spring-boot-starter-tomcat</artifactId>
<groupId>org.springframework.boot</groupId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<finalName>${project.name}</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>${spring-boot.version}</version>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</pluginManagement>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
<configuration>
<target>${maven.compiler.target}</target>
<source>${maven.compiler.source}</source>
<encoding>UTF-8</encoding>
<skip>true</skip>
</configuration>
</plugin>
<plugin>
<groupId>pl.project13.maven</groupId>
<artifactId>git-commit-id-plugin</artifactId>
<version>2.2.5</version>
</plugin>
</plugins>
</build>
</project>
+2
View File
@@ -42,5 +42,7 @@
<module>pigx-sso-client-demo</module>
<module>pigx-sentinel-dashboard</module>
<module>pigx-tx-manager</module>
<module>pigx-dynamic-datasource</module>
<module>pigx-code</module>
</modules>
</project>