Commit 12c220d7 authored by 林洋洋's avatar 林洋洋

代码调整

parent 581a2e6e
...@@ -13,7 +13,7 @@ USE `pig`; ...@@ -13,7 +13,7 @@ USE `pig`;
-- ---------------------------- -- ----------------------------
DROP TABLE IF EXISTS `sys_dept`; DROP TABLE IF EXISTS `sys_dept`;
CREATE TABLE `sys_dept` ( CREATE TABLE `sys_dept` (
`dept_id` bigint NOT NULL COMMENT '部门ID', `dept_id` bigserial NOT NULL COMMENT '部门ID',
`name` varchar(50) DEFAULT NULL COMMENT '部门名称', `name` varchar(50) DEFAULT NULL COMMENT '部门名称',
`sort_order` int NOT NULL DEFAULT '0' COMMENT '排序', `sort_order` int NOT NULL DEFAULT '0' COMMENT '排序',
`create_by` varchar(64) NOT NULL DEFAULT ' ' COMMENT '创建人', `create_by` varchar(64) NOT NULL DEFAULT ' ' COMMENT '创建人',
......
...@@ -42,18 +42,6 @@ ...@@ -42,18 +42,6 @@
<artifactId>pig-upms-biz</artifactId> <artifactId>pig-upms-biz</artifactId>
<version>${revision}</version> <version>${revision}</version>
</dependency> </dependency>
<!--可选:代码生成模块-->
<dependency>
<groupId>com.pig4cloud</groupId>
<artifactId>pig-codegen</artifactId>
<version>${revision}</version>
</dependency>
<!--可选:定时任务模块-->
<dependency>
<groupId>com.pig4cloud</groupId>
<artifactId>pig-quartz</artifactId>
<version>${revision}</version>
</dependency>
<!--安全模块--> <!--安全模块-->
<dependency> <dependency>
<groupId>com.pig4cloud</groupId> <groupId>com.pig4cloud</groupId>
......
...@@ -3,13 +3,16 @@ spring: ...@@ -3,13 +3,16 @@ spring:
type: redis # 缓存类型 Redis type: redis # 缓存类型 Redis
data: data:
redis: redis:
host: 127.0.0.1 # Redis地址 database: 5
host: 81.70.183.25
port: 16379
password: '123qwe!@#'
# 数据库相关配置 # 数据库相关配置
datasource: datasource:
driver-class-name: com.mysql.cj.jdbc.Driver driver-class-name: org.postgresql.Driver
username: root username: postgres
password: root password: postgres123
url: jdbc:mysql://127.0.0.1:3306/pig?characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=GMT%2B8&allowMultiQueries=true&nullCatalogMeansCurrent=true url: jdbc:postgresql://81.70.183.25:25432/ask_data_ai_db
# 本地文件系统 # 本地文件系统
file: file:
......
server: server:
port: 9999 # 项目端口 port: 19999 # 项目端口
servlet: servlet:
context-path: /admin # 项目访问路径 context-path: /admin # 项目访问路径
......
...@@ -16,6 +16,7 @@ ...@@ -16,6 +16,7 @@
<properties> <properties>
<!-- 项目版本号 --> <!-- 项目版本号 -->
<revision>3.9.0</revision> <revision>3.9.0</revision>
<postgresql.version>42.6.2</postgresql.version>
<spring-boot.version>3.5.0</spring-boot.version> <spring-boot.version>3.5.0</spring-boot.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>17</maven.compiler.source> <maven.compiler.source>17</maven.compiler.source>
...@@ -25,7 +26,6 @@ ...@@ -25,7 +26,6 @@
<springdoc.version>2.8.8</springdoc.version> <springdoc.version>2.8.8</springdoc.version>
<swagger.core.version>2.2.32</swagger.core.version> <swagger.core.version>2.2.32</swagger.core.version>
<mybatis-plus.version>3.5.12</mybatis-plus.version> <mybatis-plus.version>3.5.12</mybatis-plus.version>
<mysql.version>9.2.0</mysql.version>
<dynamic-ds.version>4.3.1</dynamic-ds.version> <dynamic-ds.version>4.3.1</dynamic-ds.version>
<seata.version>1.7.0</seata.version> <seata.version>1.7.0</seata.version>
<excel.version>3.4.2</excel.version> <excel.version>3.4.2</excel.version>
...@@ -98,11 +98,11 @@ ...@@ -98,11 +98,11 @@
<artifactId>pig-upms-api</artifactId> <artifactId>pig-upms-api</artifactId>
<version>${revision}</version> <version>${revision}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.mysql</groupId> <groupId>org.postgresql</groupId>
<artifactId>mysql-connector-j</artifactId> <artifactId>postgresql</artifactId>
<version>${mysql.version}</version> <version>${postgresql.version}</version>
</dependency> </dependency>
<!--springdoc --> <!--springdoc -->
<dependency> <dependency>
<groupId>org.springdoc</groupId> <groupId>org.springdoc</groupId>
......
...@@ -38,5 +38,9 @@ ...@@ -38,5 +38,9 @@
<groupId>jakarta.servlet</groupId> <groupId>jakarta.servlet</groupId>
<artifactId>jakarta.servlet-api</artifactId> <artifactId>jakarta.servlet-api</artifactId>
</dependency> </dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
</dependency>
</dependencies> </dependencies>
</project> </project>
FROM registry.cn-hangzhou.aliyuncs.com/dockerhub_mirror/java:21-anolis
WORKDIR /pig-gateway
ARG JAR_FILE=target/pig-gateway.jar
COPY ${JAR_FILE} app.jar
EXPOSE 9999
ENV TZ=Asia/Shanghai JAVA_OPTS="-Xms128m -Xmx256m -Djava.security.egd=file:/dev/./urandom"
CMD sleep 60; java $JAVA_OPTS -jar app.jar
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2020 pig4cloud Authors. All Rights Reserved.
~
~ Licensed under the Apache License, Version 2.0 (the "License");
~ you may not use this file except in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing, software
~ distributed under the License is distributed on an "AS IS" BASIS,
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
~ See the License for the specific language governing permissions and
~ limitations under the License.
-->
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
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>pig</artifactId>
<version>${revision}</version>
</parent>
<artifactId>pig-gateway</artifactId>
<packaging>jar</packaging>
<description>pig 服务网关,基于 spring cloud gateway</description>
<dependencies>
<!--gateway 网关依赖,内置webflux 依赖-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway-server-webflux</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis-reactive</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>
<!-- LB 扩展 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-loadbalancer</artifactId>
</dependency>
<!--caffeine 替换LB 默认缓存实现-->
<dependency>
<groupId>com.github.ben-manes.caffeine</groupId>
<artifactId>caffeine</artifactId>
</dependency>
<!-- 工具包依赖 -->
<dependency>
<groupId>com.pig4cloud</groupId>
<artifactId>pig-common-core</artifactId>
</dependency>
<!--接口文档-->
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-starter-webflux-ui</artifactId>
</dependency>
<!--引入Knife4j的官方ui包-->
<dependency>
<groupId>io.springboot</groupId>
<artifactId>knife4j-openapi3-ui</artifactId>
<version>${knife4j.version}</version>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-crypto</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>io.fabric8</groupId>
<artifactId>docker-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
/*
* Copyright (c) 2020 pig4cloud Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.pig4cloud.pig.gateway;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
/**
* 网关应用
*
* @author lengleng
* @date 2025/05/30
*/
@EnableDiscoveryClient
@SpringBootApplication
public class PigGatewayApplication {
public static void main(String[] args) {
SpringApplication.run(PigGatewayApplication.class, args);
}
}
package com.pig4cloud.pig.gateway.config;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.pig4cloud.pig.gateway.filter.PigRequestGlobalFilter;
import com.pig4cloud.pig.gateway.handler.GlobalExceptionHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* 网关配置类
*
* @author lengleng
* @date 2025/05/30
*/
@Configuration(proxyBeanMethods = false)
public class GatewayConfiguration {
/**
* 创建PigRequest全局过滤器
* @return PigRequest全局过滤器
*/
@Bean
public PigRequestGlobalFilter pigRequestGlobalFilter() {
return new PigRequestGlobalFilter();
}
/**
* 创建全局异常处理程序
* @param objectMapper 对象映射器
* @return 全局异常处理程序
*/
@Bean
public GlobalExceptionHandler globalExceptionHandler(ObjectMapper objectMapper) {
return new GlobalExceptionHandler(objectMapper);
}
}
/*
* Copyright (c) 2020 pig4cloud Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.pig4cloud.pig.gateway.config;
import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import reactor.core.publisher.Mono;
import java.util.Objects;
/**
* 路由限流配置类
*
* @author lengleng
* @date 2019/2/1
*/
@Configuration(proxyBeanMethods = false)
public class RateLimiterConfiguration {
/**
* 创建基于远程地址的KeyResolver实例
* @return 根据请求的远程地址生成限流key的KeyResolver
* @see <a href=
* "https://docs.spring.io/spring-cloud-gateway/docs/current/reference/html/#the-requestratelimiter-gatewayfilter-factory">Spring
* Cloud Gateway文档</a>
*/
@Bean
public KeyResolver remoteAddrKeyResolver() {
return exchange -> Mono
.just(Objects.requireNonNull(Objects.requireNonNull(exchange.getRequest().getRemoteAddress()))
.getAddress()
.getHostAddress());
}
}
package com.pig4cloud.pig.gateway.config;
import com.alibaba.nacos.client.naming.event.InstancesChangeEvent;
import com.alibaba.nacos.common.notify.Event;
import com.alibaba.nacos.common.notify.NotifyCenter;
import com.alibaba.nacos.common.notify.listener.Subscriber;
import com.alibaba.nacos.common.utils.StringUtils;
import lombok.RequiredArgsConstructor;
import org.springdoc.core.properties.AbstractSwaggerUiConfigProperties;
import org.springdoc.core.properties.SwaggerUiConfigProperties;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.context.annotation.Configuration;
import java.util.Set;
import java.util.stream.Collectors;
/**
* SpringDoc配置类,实现InitializingBean接口,用于Swagger 3.0文档展示
*
* @author lengleng
* @date 2025/05/30
*/
@RequiredArgsConstructor
@Configuration(proxyBeanMethods = false)
@ConditionalOnProperty(value = "springdoc.api-docs.enabled", matchIfMissing = true)
public class SpringDocConfiguration implements InitializingBean {
private final SwaggerUiConfigProperties swaggerUiConfigProperties;
private final DiscoveryClient discoveryClient;
/**
* 在初始化后调用的方法,用于注册SwaggerDocRegister订阅器
*/
@Override
public void afterPropertiesSet() {
NotifyCenter.registerSubscriber(new SwaggerDocRegister(swaggerUiConfigProperties, discoveryClient));
}
}
/**
* Swagger文档注册器,用于处理服务实例变更事件并更新Swagger UI配置
*
* @author lengleng
* @date 2025/05/30
*/
@RequiredArgsConstructor
class SwaggerDocRegister extends Subscriber<InstancesChangeEvent> {
private final SwaggerUiConfigProperties swaggerUiConfigProperties;
private final DiscoveryClient discoveryClient;
/**
* 处理服务实例变更事件
* @param event 服务实例变更事件对象
*/
@Override
public void onEvent(InstancesChangeEvent event) {
Set<AbstractSwaggerUiConfigProperties.SwaggerUrl> swaggerUrlSet = discoveryClient.getServices()
.stream()
.flatMap(serviceId -> discoveryClient.getInstances(serviceId).stream())
.filter(instance -> StringUtils.isNotBlank(instance.getMetadata().get("spring-doc")))
.map(instance -> {
AbstractSwaggerUiConfigProperties.SwaggerUrl swaggerUrl = new AbstractSwaggerUiConfigProperties.SwaggerUrl();
swaggerUrl.setName(instance.getServiceId());
swaggerUrl.setUrl(String.format("/%s/v3/api-docs", instance.getMetadata().get("spring-doc")));
return swaggerUrl;
})
.collect(Collectors.toSet());
swaggerUiConfigProperties.setUrls(swaggerUrlSet);
}
/**
* 订阅类型方法,返回订阅的事件类型
* @return 订阅的事件类型
*/
@Override
public Class<? extends Event> subscribeType() {
return InstancesChangeEvent.class;
}
}
/*
* Copyright (c) 2020 pig4cloud Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.pig4cloud.pig.gateway.filter;
import com.pig4cloud.pig.common.core.constant.CommonConstants;
import com.pig4cloud.pig.common.core.constant.SecurityConstants;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import java.util.Arrays;
import java.util.Collections;
import java.util.stream.Collectors;
import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR;
import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.addOriginalRequestUrl;
/**
* 全局拦截器,作用于所有微服务
* <p>
* 1. 清洗请求头中的from参数 2. 重写StripPrefix = 1,支持全局路由
*
* @author lengleng
* @date 2025/05/30
*/
public class PigRequestGlobalFilter implements GlobalFilter, Ordered {
/**
* 处理Web请求并(可选地)通过给定的网关过滤器链委托给下一个过滤器
* @param exchange 当前服务器交换对象
* @param chain 提供委托给下一个过滤器的方式
* @return {@code Mono<Void>} 表示请求处理完成
*/
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
// 1. 清洗请求头中from 参数
ServerHttpRequest request = exchange.getRequest().mutate().headers(httpHeaders -> {
httpHeaders.remove(SecurityConstants.FROM);
// 设置请求时间
httpHeaders.put(CommonConstants.REQUEST_START_TIME,
Collections.singletonList(String.valueOf(System.currentTimeMillis())));
}).build();
// 2. 重写StripPrefix
addOriginalRequestUrl(exchange, request.getURI());
String rawPath = request.getURI().getRawPath();
String newPath = "/" + Arrays.stream(StringUtils.tokenizeToStringArray(rawPath, "/"))
.skip(1L)
.collect(Collectors.joining("/"));
ServerHttpRequest newRequest = request.mutate().path(newPath).build();
exchange.getAttributes().put(GATEWAY_REQUEST_URL_ATTR, newRequest.getURI());
return chain.filter(exchange.mutate().request(newRequest.mutate().build()).build());
}
@Override
public int getOrder() {
return 10;
}
}
/*
* Copyright (c) 2020 pig4cloud Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.pig4cloud.pig.gateway.handler;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.pig4cloud.pig.common.core.util.R;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
/**
* 网关异常通用处理器,作用于WebFlux环境,优先级低于ResponseStatusExceptionHandler
*
* @author lengleng
* @date 2025/05/30
*/
@Slf4j
@Order(-1)
@RequiredArgsConstructor
public class GlobalExceptionHandler implements ErrorWebExceptionHandler {
/**
* 对象映射器,用于JSON序列化与反序列化
*/
private final ObjectMapper objectMapper;
/**
* @param exchange 服务器网络交换对象
* @param ex 抛出的异常
* @return Mono<Void> 异步处理结果
*/
@Override
public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
ServerHttpResponse response = exchange.getResponse();
if (response.isCommitted()) {
return Mono.error(ex);
}
// header set
response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
if (ex instanceof ResponseStatusException) {
response.setStatusCode(((ResponseStatusException) ex).getStatusCode());
}
return response.writeWith(Mono.fromSupplier(() -> {
DataBufferFactory bufferFactory = response.bufferFactory();
try {
log.debug("Error Spring Cloud Gateway : {} {}", exchange.getRequest().getPath(), ex.getMessage());
return bufferFactory.wrap(objectMapper.writeValueAsBytes(R.failed(ex.getMessage())));
}
catch (JsonProcessingException e) {
log.error("Error writing response", ex);
return bufferFactory.wrap(new byte[0]);
}
}));
}
}
server:
port: 9999
spring:
application:
name: @artifactId@
cloud:
nacos:
username: @nacos.username@
password: @nacos.password@
discovery:
server-addr: ${NACOS_HOST:127.0.0.1}:${NACOS_PORT:8848}
watch:
enabled: true
watch-delay: 1000
config:
server-addr: ${spring.cloud.nacos.discovery.server-addr}
config:
import:
- optional:nacos:application-@profiles.active@.yml
- optional:nacos:${spring.application.name}-@profiles.active@.yml
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2020 pig4cloud Authors. All Rights Reserved.
~
~ Licensed under the Apache License, Version 2.0 (the "License");
~ you may not use this file except in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing, software
~ distributed under the License is distributed on an "AS IS" BASIS,
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
~ See the License for the specific language governing permissions and
~ limitations under the License.
-->
<configuration debug="false" scan="false">
<springProperty scop="context" name="spring.application.name" source="spring.application.name" defaultValue=""/>
<property name="log.path" value="logs/${spring.application.name}"/>
<!-- 彩色日志格式 -->
<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}}"/>
<property name="FILE_LOG_PATTERN" value=":%d{yyyy-MM-dd HH:mm:ss.SSS} %5p %t %c{1}: %m%n"/>
<!-- 彩色日志依赖的渲染类 -->
<conversionRule conversionWord="clr" class="org.springframework.boot.logging.logback.ColorConverter"/>
<conversionRule conversionWord="wex"
class="org.springframework.boot.logging.logback.WhitespaceThrowableProxyConverter"/>
<conversionRule conversionWord="wEx"
class="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>${FILE_LOG_PATTERN}</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>${FILE_LOG_PATTERN}</pattern>
</encoder>
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>ERROR</level>
</filter>
</appender>
<!--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"/>
<appender-ref ref="error"/>
</root>
</configuration>
FROM registry.cn-hangzhou.aliyuncs.com/dockerhub_mirror/java:21-anolis
WORKDIR /pig-register
ARG JAR_FILE=target/pig-register.jar
COPY ${JAR_FILE} app.jar
EXPOSE 8848 9848 8080
ENV TZ=Asia/Shanghai JAVA_OPTS="-Xms128m -Xmx256m -Djava.security.egd=file:/dev/./urandom"
CMD sleep 30; java $JAVA_OPTS -jar app.jar
<?xml version="1.0" encoding="UTF-8"?>
<!--
Copyright 1999-2018 Alibaba Group Holding Ltd.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<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>pig</artifactId>
<version>${revision}</version>
</parent>
<artifactId>pig-register</artifactId>
<packaging>jar</packaging>
<name>pig-register</name>
<description>nacos 注册配置中心</description>
<properties>
<nacos.version>3.0.0</nacos.version>
</properties>
<dependencies>
<dependency>
<groupId>io.github.pig-mesh.nacos</groupId>
<artifactId>nacos-console</artifactId>
<version>${nacos.version}</version>
</dependency>
<dependency>
<groupId>io.github.pig-mesh.nacos</groupId>
<artifactId>nacos-server</artifactId>
<version>${nacos.version}</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>io.fabric8</groupId>
<artifactId>docker-maven-plugin</artifactId>
</plugin>
</plugins>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
<excludes>
<exclude>**/*.woff</exclude>
<exclude>**/*.woff2</exclude>
<exclude>**/*.ttf</exclude>
<exclude>**/*.eot</exclude>
</excludes>
</resource>
<resource>
<directory>src/main/resources</directory>
<filtering>false</filtering>
<includes>
<include>**/*.woff</include>
<include>**/*.woff2</include>
<include>**/*.ttf</include>
<include>**/*.eot</include>
</includes>
</resource>
</resources>
</build>
</project>
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.bootstrap;
import com.alibaba.nacos.NacosServerBasicApplication;
import com.alibaba.nacos.NacosServerWebApplication;
import com.alibaba.nacos.console.NacosConsole;
import com.alibaba.nacos.core.listener.startup.NacosStartUp;
import com.alibaba.nacos.core.listener.startup.NacosStartUpManager;
import com.alibaba.nacos.sys.env.Constants;
import com.alibaba.nacos.sys.env.DeploymentType;
import com.alibaba.nacos.sys.env.EnvUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.WebApplicationType;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.context.ConfigurableApplicationContext;
import static org.springframework.boot.context.logging.LoggingApplicationListener.CONFIG_PROPERTY;
import static org.springframework.core.io.ResourceLoader.CLASSPATH_URL_PREFIX;
/**
* @author nacos
* <p>
* nacos console 源码运行,方便开发 生产从官网下载zip最新版集群配置运行
*/
@Slf4j
public class PigNacosApplication {
/**
* 独立模式系统属性名称
*/
private static String STANDALONE_MODE = "nacos.standalone";
public static void main(String[] args) {
System.setProperty(STANDALONE_MODE, "true");
System.setProperty(CONFIG_PROPERTY, CLASSPATH_URL_PREFIX + "logback-spring.xml");
String type = System.getProperty(Constants.NACOS_DEPLOYMENT_TYPE, Constants.NACOS_DEPLOYMENT_TYPE_MERGED);
DeploymentType deploymentType = DeploymentType.getType(type);
EnvUtil.setDeploymentType(deploymentType);
// Start Core Context
NacosStartUpManager.start(NacosStartUp.CORE_START_UP_PHASE);
ConfigurableApplicationContext coreContext = new SpringApplicationBuilder(NacosServerBasicApplication.class)
.web(WebApplicationType.NONE)
.run(args);
// Start Server Web Context
NacosStartUpManager.start(NacosStartUp.WEB_START_UP_PHASE);
ConfigurableApplicationContext serverWebContext = new SpringApplicationBuilder(NacosServerWebApplication.class)
.parent(coreContext)
.run(args);
// Start Console Context
NacosStartUpManager.start(NacosStartUp.CONSOLE_START_UP_PHASE);
ConfigurableApplicationContext consoleContext = new SpringApplicationBuilder(NacosConsole.class)
.parent(coreContext)
.run(args);
}
}
# Nacos \u63A7\u5236\u53F0\u7AEF\u53E3\uFF0C\u8BF7\u6CE8\u610F\u8BBF\u95EE\u7684 IP:8080
nacos.console.port=8080
# Nacos \u670D\u52A1\u7AEF\u4E3B\u7AEF\u53E3
nacos.server.main.port=8848
# \u6570\u636E\u5E93\u8BBE\u7F6E
spring.sql.init.platform=mysql
db.num=1
db.url.0=jdbc:mysql://${MYSQL_HOST:pig-mysql}:${MYSQL_PORT:3306}/${MYSQL_DB:pig_config}?characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=GMT%2B8&nullCatalogMeansCurrent=true&allowPublicKeyRetrieval=true
db.user=root
db.password=root
# nacos \u4F1A\u81EA\u52A8\u88C5\u914D\u6570\u636E\u6E90\uFF0C\u6240\u4EE5\u6392\u9664 spring.datasource \u81EA\u52A8\u914D\u7F6E
spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration
#*************** \u76D1\u63A7\u76F8\u5173\u914D\u7F6E ***************#
# Prometheus \u76D1\u63A7\u914D\u7F6E
#management.endpoints.web.exposure.include=prometheus
# ElasticSearch \u76D1\u63A7\u914D\u7F6E - \u5DF2\u7981\u7528
management.elastic.metrics.export.enabled=false
# InfluxDB \u76D1\u63A7\u914D\u7F6E - \u5DF2\u7981\u7528
management.influx.metrics.export.enabled=false
#*************** \u914D\u7F6E\u4E2D\u5FC3\u76F8\u5173 ***************#
# Nacos \u914D\u7F6E\u63A8\u9001\u6700\u5927\u91CD\u8BD5\u6B21\u6570
nacos.config.push.maxRetryTime=50
#*************** \u547D\u540D\u670D\u52A1\u76F8\u5173 ***************#
# \u7A7A\u670D\u52A1\u81EA\u52A8\u6E05\u7406
nacos.naming.empty-service.auto-clean=true
nacos.naming.empty-service.clean.initial-delay-ms=50000
nacos.naming.empty-service.clean.period-time-ms=30000
#*************** Nacos Web \u76F8\u5173\u914D\u7F6E ***************#
# Nacos \u670D\u52A1\u7AEF\u4E0A\u4E0B\u6587\u8DEF\u5F84
nacos.server.contextPath=/nacos
#*************** \u65E5\u5FD7\u76F8\u5173\u914D\u7F6E ***************#
# \u5F00\u542F\u8BBF\u95EE\u65E5\u5FD7
server.tomcat.accesslog.enabled=true
# \u8BBF\u95EE\u65E5\u5FD7\u4FDD\u7559\u5929\u6570\u914D\u7F6E
server.tomcat.accesslog.max-days=30
# \u8BBF\u95EE\u65E5\u5FD7\u683C\u5F0F
server.tomcat.accesslog.pattern=%h %l %u %t "%r" %s %b %D %{User-Agent}i %{Request-Source}i
# \u65E5\u5FD7\u57FA\u7840\u76EE\u5F55
server.tomcat.basedir=file:.
#*************** API \u9519\u8BEF\u5904\u7406 ***************#
# \u9519\u8BEF\u4FE1\u606F\u663E\u793A\u8BBE\u7F6E
server.error.include-message=ALWAYS
#*************** Nacos \u63A7\u5236\u53F0\u914D\u7F6E ***************#
# Nacos \u63A7\u5236\u53F0\u4E0A\u4E0B\u6587\u8DEF\u5F84
nacos.console.contextPath=
# Nacos \u63A7\u5236\u53F0\u8FDC\u7A0B\u670D\u52A1\u4E0A\u4E0B\u6587\u8DEF\u5F84
nacos.console.remote.server.context-path=/nacos
#*************** \u5B89\u5168\u76F8\u5173\u914D\u7F6E ***************#
# \u5B89\u5168\u5FFD\u7565 URL
nacos.security.ignore.urls=/,/error,/**/*.css,/**/*.js,/**/*.html,/**/*.map,/**/*.svg,/**/*.png,/**/*.ico,/console-ui/public/**,/v1/auth/**,/v1/console/health/**,/actuator/**,/v1/console/server/**
# \u8BA4\u8BC1\u7CFB\u7EDF\u7C7B\u578B
nacos.core.auth.system.type=nacos
# \u5F00\u542F\u8BA4\u8BC1
nacos.core.auth.enabled=true
# \u542F\u7528 API \u8BBF\u95EE\u6743\u9650
nacos.core.auth.admin.enabled=true
# \u542F\u7528\u63A7\u5236\u53F0 API \u8BA4\u8BC1
nacos.core.auth.console.enabled=true
# \u5F00\u542F\u8BA4\u8BC1\u7F13\u5B58
nacos.core.auth.caching.enabled=true
# \u670D\u52A1\u5668\u8EAB\u4EFD\u8BA4\u8BC1 (\u5F53 nacos.core.auth.enabled=true \u65F6\u751F\u6548)
nacos.core.auth.server.identity.key=VGhpc0lzTXlDdXN0b21TZWNyZXRLZXkwMTIzNDU2Nzg=
nacos.core.auth.server.identity.value=VGhpc0lzTXlDdXN0b21TZWNyZXRLZXkwMTIzNDU2Nzg=
# Nacos \u4EE4\u724C\u76F8\u5173\u914D\u7F6E
nacos.core.auth.plugin.nacos.token.cache.enable=false
nacos.core.auth.plugin.nacos.token.expire.seconds=18000
# \u8BA4\u8BC1\u5BC6\u94A5 (Base64 \u7F16\u7801)
nacos.core.auth.plugin.nacos.token.secret.key=VGhpc0lzTXlDdXN0b21TZWNyZXRLZXkwMTIzNDU2Nzg=
#*************** Istio \u670D\u52A1\u7F51\u683C\u914D\u7F6E ***************#
# MCP \u670D\u52A1\u652F\u6301 - \u5DF2\u7981\u7528
nacos.istio.mcp.server.enabled=false
#*************** K8s \u76F8\u5173\u914D\u7F6E ***************#
# K8s \u540C\u6B65\u652F\u6301 - \u5DF2\u7981\u7528
nacos.k8s.sync.enabled=false
#*************** \u90E8\u7F72\u6A21\u5F0F\u914D\u7F6E ***************#
# \u90E8\u7F72\u6A21\u5F0F: 'merged' \u6DF7\u5408\u6A21\u5F0F, 'server' \u670D\u52A1\u7AEF\u6A21\u5F0F, 'console' \u63A7\u5236\u53F0\u6A21\u5F0F
nacos.deployment.type=merged
#*************** \u6A21\u7CCA\u5339\u914D\u914D\u7F6E ***************#
# \u914D\u7F6E\u4E2D\u5FC3\u6A21\u7CCA\u5339\u914D\u6700\u5927\u503C
nacos.config.fuzzy.watch.max.pattern.count=20
nacos.config.fuzzy.watch.max.pattern.match.config.count=500
# \u670D\u52A1\u53D1\u73B0\u6A21\u7CCA\u5339\u914D\u6700\u5927\u503C
nacos.naming.fuzzy.watch.max.pattern.count=20
nacos.naming.fuzzy.watch.max.pattern.match.service.count=500
<?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)
-->
<!--
小技巧: 在根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" class="org.springframework.boot.logging.logback.ColorConverter"/>
<conversionRule conversionWord="wex"
class="org.springframework.boot.logging.logback.WhitespaceThrowableProxyConverter"/>
<conversionRule conversionWord="wEx"
class="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>
<!--AJ 验证码INFO 屏蔽-->
<logger name="com.anji.captcha" 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"/>
<appender-ref ref="error"/>
</root>
</configuration>
...@@ -65,9 +65,10 @@ ...@@ -65,9 +65,10 @@
<groupId>com.baomidou</groupId> <groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-spring-boot3-starter</artifactId> <artifactId>mybatis-plus-spring-boot3-starter</artifactId>
</dependency> </dependency>
<!-- PostgreSQL驱动 -->
<dependency> <dependency>
<groupId>com.mysql</groupId> <groupId>org.postgresql</groupId>
<artifactId>mysql-connector-j</artifactId> <artifactId>postgresql</artifactId>
</dependency> </dependency>
<!--注册中心客户端--> <!--注册中心客户端-->
<dependency> <dependency>
......
FROM registry.cn-hangzhou.aliyuncs.com/dockerhub_mirror/java:21-anolis
WORKDIR /pig-codegen
ARG JAR_FILE=target/pig-codegen.jar
COPY ${JAR_FILE} app.jar
EXPOSE 5002
ENV TZ=Asia/Shanghai JAVA_OPTS="-Xms128m -Xmx256m -Djava.security.egd=file:/dev/./urandom"
CMD sleep 60; java $JAVA_OPTS -jar app.jar
<?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>pig-visual</artifactId>
<version>${revision}</version>
</parent>
<artifactId>pig-codegen</artifactId>
<packaging>jar</packaging>
<description>代码生成模块</description>
<properties>
<screw.version>0.0.6</screw.version>
<anyline.version>8.7.2-jdk17-20240808</anyline.version>
</properties>
<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>pig-common-mybatis</artifactId>
</dependency>
<!--动态数据源 数据操作-->
<dependency>
<groupId>com.pig4cloud</groupId>
<artifactId>pig-common-datasource</artifactId>
</dependency>
<!--mybatis-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-spring-boot3-starter</artifactId>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
</dependency>
<!--anyline-->
<dependency>
<groupId>org.anyline</groupId>
<artifactId>anyline-environment-spring-data-jdbc</artifactId>
<version>${anyline.version}</version>
</dependency>
<dependency>
<groupId>org.anyline</groupId>
<artifactId>anyline-data-jdbc-mysql</artifactId>
<version>${anyline.version}</version>
</dependency>
<!--common-->
<dependency>
<groupId>com.pig4cloud</groupId>
<artifactId>pig-common-core</artifactId>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-json</artifactId>
</dependency>
<!--swagger-->
<dependency>
<groupId>com.pig4cloud</groupId>
<artifactId>pig-common-swagger</artifactId>
</dependency>
<!--安全模块-->
<dependency>
<groupId>com.pig4cloud</groupId>
<artifactId>pig-common-xss</artifactId>
</dependency>
<dependency>
<groupId>com.pig4cloud</groupId>
<artifactId>pig-common-security</artifactId>
</dependency>
<dependency>
<groupId>com.pig4cloud</groupId>
<artifactId>pig-common-log</artifactId>
</dependency>
<!--代码生成模板引擎-->
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>${velocity.version}</version>
</dependency>
<dependency>
<groupId>org.apache.velocity.tools</groupId>
<artifactId>velocity-tools-generic</artifactId>
<version>${velocity.tool.version}</version>
</dependency>
<!--生成文档-->
<dependency>
<groupId>group.springframework.plugin</groupId>
<artifactId>screw-spring-boot-starter</artifactId>
<version>${screw.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>
<profiles>
<profile>
<id>cloud</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
<configuration>
<loaderImplementation>CLASSIC</loaderImplementation>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>io.fabric8</groupId>
<artifactId>docker-maven-plugin</artifactId>
<configuration>
<skip>false</skip>
</configuration>
</plugin>
</plugins>
</build>
</profile>
<profile>
<id>boot</id>
</profile>
</profiles>
</project>
/*
* 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.pig.codegen;
import com.pig4cloud.pig.common.datasource.annotation.EnableDynamicDataSource;
import com.pig4cloud.pig.common.feign.annotation.EnablePigFeignClients;
import com.pig4cloud.pig.common.security.annotation.EnablePigResourceServer;
import com.pig4cloud.pig.common.swagger.annotation.EnablePigDoc;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
/**
* 代码生成模块应用启动类
*
* @author lengleng
* @date 2025/05/31
*/
@EnableDynamicDataSource
@EnablePigFeignClients
@EnablePigDoc("gen")
@EnableDiscoveryClient
@EnablePigResourceServer
@SpringBootApplication
public class PigCodeGenApplication {
public static void main(String[] args) {
SpringApplication.run(PigCodeGenApplication.class, args);
}
}
package com.pig4cloud.pig.codegen.config;
import cn.smallbun.screw.core.constant.DefaultConstants;
import lombok.Data;
import org.anyline.util.ConfigTable;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
/**
* 代码生成默认配置类
*
* @author lengleng
* @date 2025/05/31
*/
@Data
@Configuration(proxyBeanMethods = false)
@ConfigurationProperties(prefix = PigCodeGenDefaultProperties.PREFIX)
public class PigCodeGenDefaultProperties implements InitializingBean {
public static final String PREFIX = "codegen";
/**
* 是否开启在线更新
*/
private boolean autoCheckVersion = true;
/**
* 模板项目地址
*/
private String onlineUrl = DefaultConstants.CGTM_URL;
/**
* 生成代码的包名
*/
private String packageName = "com.pig4cloud.pig";
/**
* 生成代码的版本
*/
private String version = "1.0.0";
/**
* 生成代码的模块名
*/
private String moduleName = "admin";
/**
* 生成代码的后端路径
*/
private String backendPath = "pig";
/**
* 生成代码的前端路径
*/
private String frontendPath = "pig-ui";
/**
* 生成代码的作者
*/
private String author = "pig";
/**
* 生成代码的邮箱
*/
private String email = "sw@pigx.vip";
/**
* 表单布局(一列、两列)
*/
private Integer formLayout = 2;
/**
* 下载方式 (0 文件下载、1写入目录)
*/
private String generatorType = "0";
@Override
public void afterPropertiesSet() throws Exception {
ConfigTable.KEEP_ADAPTER = 0;
}
}
/*
* 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.pig.codegen.controller;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import cn.smallbun.screw.boot.config.Screw;
import cn.smallbun.screw.boot.properties.ScrewProperties;
import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pig4cloud.pig.codegen.entity.GenDatasourceConf;
import com.pig4cloud.pig.codegen.service.GenDatasourceConfService;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.core.util.SpringContextHolder;
import com.pig4cloud.pig.common.security.annotation.Inner;
import com.pig4cloud.pig.common.xss.core.XssCleanIgnore;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.*;
import javax.sql.DataSource;
/**
* 数据源管理控制器
*
* @author lengleng
* @date 2025/05/31
*/
@RestController
@RequiredArgsConstructor
@RequestMapping("/dsconf")
public class GenDsConfController {
private final GenDatasourceConfService datasourceConfService;
private final Screw screw;
/**
* 分页查询数据源配置
* @param page 分页参数对象
* @param datasourceConf 数据源配置查询条件
* @return 分页查询结果
*/
@GetMapping("/page")
public R getDsConfPage(Page page, GenDatasourceConf datasourceConf) {
return R.ok(datasourceConfService.page(page,
Wrappers.<GenDatasourceConf>lambdaQuery()
.like(StrUtil.isNotBlank(datasourceConf.getDsName()), GenDatasourceConf::getDsName,
datasourceConf.getDsName())));
}
/**
* 查询全部数据源列表
* @return 包含全部数据源列表的响应结果
*/
@GetMapping("/list")
@Inner(value = false)
public R listDsConfs() {
return R.ok(datasourceConfService.list());
}
/**
* 根据ID查询数据源表
* @param id 数据源ID
* @return 包含查询结果的响应对象
*/
@GetMapping("/{id}")
public R getDsConfById(@PathVariable("id") Long id) {
return R.ok(datasourceConfService.getById(id));
}
/**
* 新增数据源表
* @param datasourceConf 数据源配置信息
* @return 操作结果
*/
@PostMapping
@XssCleanIgnore
public R saveDsConf(@RequestBody GenDatasourceConf datasourceConf) {
return R.ok(datasourceConfService.saveDsByEnc(datasourceConf));
}
/**
* 修改数据源表
* @param conf 数据源表配置信息
* @return 操作结果
*/
@PutMapping
@XssCleanIgnore
public R updateDsConf(@RequestBody GenDatasourceConf conf) {
return R.ok(datasourceConfService.updateDsByEnc(conf));
}
/**
* 通过id数组删除数据源表
* @param ids 要删除的数据源id数组
* @return 包含操作结果的R对象
*/
@DeleteMapping
public R removeDsConfByIds(@RequestBody Long[] ids) {
return R.ok(datasourceConfService.removeByDsId(ids));
}
/**
* 生成指定数据源的数据库文档并输出到响应流
* @param dsName 数据源名称
* @param response HTTP响应对象
* @throws Exception 生成文档或IO操作过程中可能抛出的异常
*/
@SneakyThrows
@GetMapping("/doc")
public void generatorDoc(String dsName, HttpServletResponse response) {
// 设置指定的数据源
DynamicRoutingDataSource dynamicRoutingDataSource = SpringContextHolder.getBean(DynamicRoutingDataSource.class);
DynamicDataSourceContextHolder.push(dsName);
DataSource dataSource = dynamicRoutingDataSource.determineDataSource();
// 设置指定的目标表
ScrewProperties screwProperties = SpringContextHolder.getBean(ScrewProperties.class);
// 生成
byte[] data = screw.documentGeneration(dsName, dataSource, screwProperties).toByteArray();
response.reset();
response.addHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(data.length));
response.setContentType("application/octet-stream");
IoUtil.write(response.getOutputStream(), Boolean.FALSE, data);
}
}
/*
* 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.pig.codegen.controller;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pig4cloud.pig.codegen.entity.GenFieldType;
import com.pig4cloud.pig.codegen.service.GenFieldTypeService;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.log.annotation.SysLog;
import com.pig4cloud.plugin.excel.annotation.ResponseExcel;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* 列属性管理控制器
*
* @author lengleng
* @date 2025/05/31
*/
@RestController
@RequiredArgsConstructor
@RequestMapping("/fieldtype")
@Tag(description = "fieldtype", name = "列属性管理")
@SecurityRequirement(name = HttpHeaders.AUTHORIZATION)
public class GenFieldTypeController {
private final GenFieldTypeService fieldTypeService;
/**
* 分页查询字段类型
* @param page 分页对象
* @param fieldType 字段类型查询条件
* @return 分页查询结果
*/
@Operation(summary = "分页查询", description = "分页查询")
@GetMapping("/page")
public R getFieldTypePage(Page page, GenFieldType fieldType) {
return R.ok(fieldTypeService.page(page,
Wrappers.<GenFieldType>lambdaQuery()
.like(StrUtil.isNotBlank(fieldType.getColumnType()), GenFieldType::getColumnType,
fieldType.getColumnType())));
}
/**
* 查询列表
* @param fieldType 查询条件
* @return 包含查询结果的响应对象
*/
@Operation(summary = "查询列表", description = "查询列表")
@GetMapping("/list")
public R listFieldTypes(GenFieldType fieldType) {
return R.ok(fieldTypeService.list(Wrappers.query(fieldType)));
}
/**
* 通过id查询列属性
* @param id 列属性id
* @return 包含查询结果的响应对象
*/
@Operation(summary = "通过id查询", description = "通过id查询")
@GetMapping("/details/{id}")
public R getFieldTypeById(@PathVariable("id") Long id) {
return R.ok(fieldTypeService.getById(id));
}
/**
* 根据查询条件获取字段类型详情
* @param query 字段类型查询条件
* @return 包含查询结果的响应对象
*/
@GetMapping("/details")
public R getFieldTypeDetails(GenFieldType query) {
return R.ok(fieldTypeService.getOne(Wrappers.query(query), false));
}
/**
* 新增列属性
* @param fieldType 列属性对象
* @return 操作结果
*/
@Operation(summary = "新增列属性", description = "新增列属性")
@SysLog("新增列属性")
@PostMapping
public R saveFieldType(@RequestBody GenFieldType fieldType) {
return R.ok(fieldTypeService.save(fieldType));
}
/**
* 修改列属性
* @param fieldType 列属性对象
* @return 操作结果
*/
@Operation(summary = "修改列属性", description = "修改列属性")
@SysLog("修改列属性")
@PutMapping
public R updateFieldType(@RequestBody GenFieldType fieldType) {
return R.ok(fieldTypeService.updateById(fieldType));
}
/**
* 通过id批量删除列属性
* @param ids 要删除的列属性id数组
* @return 操作结果
*/
@Operation(summary = "通过id删除列属性", description = "通过id删除列属性")
@SysLog("通过id删除列属性")
@DeleteMapping
public R removeFieldTypeByIds(@RequestBody Long[] ids) {
return R.ok(fieldTypeService.removeBatchByIds(CollUtil.toList(ids)));
}
/**
* 导出excel表格
* @param fieldType 查询条件
* @return excel文件数据列表
*/
@ResponseExcel
@GetMapping("/export")
public List<GenFieldType> exportFieldTypes(GenFieldType fieldType) {
return fieldTypeService.list(Wrappers.query(fieldType));
}
}
/*
* 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.pig.codegen.controller;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pig4cloud.pig.codegen.entity.GenGroupEntity;
import com.pig4cloud.pig.codegen.service.GenGroupService;
import com.pig4cloud.pig.codegen.util.vo.GroupVO;
import com.pig4cloud.pig.codegen.util.vo.TemplateGroupDTO;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.log.annotation.SysLog;
import com.pig4cloud.pig.common.security.annotation.HasPermission;
import com.pig4cloud.plugin.excel.annotation.ResponseExcel;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* 模板分组管理控制器
*
* @author lengleng
* @date 2025/05/31
*/
@RestController
@RequiredArgsConstructor
@RequestMapping("/group")
@Tag(description = "group", name = "模板分组管理")
@SecurityRequirement(name = HttpHeaders.AUTHORIZATION)
public class GenGroupController {
private final GenGroupService genGroupService;
/**
* 分页查询模板分组
* @param page 分页对象
* @param genGroup 模板分组查询条件
* @return 分页查询结果
*/
@Operation(summary = "分页查询", description = "分页查询")
@GetMapping("/page")
@HasPermission("codegen_group_view")
public R getGroupPage(Page page, GenGroupEntity genGroup) {
LambdaQueryWrapper<GenGroupEntity> wrapper = Wrappers.<GenGroupEntity>lambdaQuery()
.like(genGroup.getId() != null, GenGroupEntity::getId, genGroup.getId())
.like(StrUtil.isNotEmpty(genGroup.getGroupName()), GenGroupEntity::getGroupName, genGroup.getGroupName());
return R.ok(genGroupService.page(page, wrapper));
}
/**
* 通过id查询模板分组
* @param id id
* @return R
*/
@Operation(summary = "通过id查询", description = "通过id查询")
@GetMapping("/{id}")
@HasPermission("codegen_group_view")
public R getGroupById(@PathVariable("id") Long id) {
return R.ok(genGroupService.getGroupVoById(id));
}
/**
* 新增模板分组
* @param genTemplateGroup 模板分组
* @return R
*/
@Operation(summary = "新增模板分组", description = "新增模板分组")
@SysLog("新增模板分组")
@PostMapping
@HasPermission("codegen_group_add")
public R saveGroup(@RequestBody TemplateGroupDTO genTemplateGroup) {
genGroupService.saveGenGroup(genTemplateGroup);
return R.ok();
}
/**
* 修改模板分组
* @param groupVo 模板分组
* @return R
*/
@Operation(summary = "修改模板分组", description = "修改模板分组")
@SysLog("修改模板分组")
@PutMapping
@HasPermission("codegen_group_edit")
public R updateGroup(@RequestBody GroupVO groupVo) {
genGroupService.updateGroupAndTemplateById(groupVo);
return R.ok();
}
/**
* 通过id删除模板分组
* @param ids id列表
* @return R
*/
@Operation(summary = "通过id删除模板分组", description = "通过id删除模板分组")
@SysLog("通过id删除模板分组")
@DeleteMapping
@HasPermission("codegen_group_del")
public R removeGroupByIds(@RequestBody Long[] ids) {
genGroupService.delGroupAndTemplate(ids);
return R.ok();
}
/**
* 导出excel 表格
* @param genGroup 查询条件
* @return excel 文件流
*/
@ResponseExcel
@GetMapping("/export")
@HasPermission("codegen_group_export")
public List<GenGroupEntity> exportGroups(GenGroupEntity genGroup) {
return genGroupService.list(Wrappers.query(genGroup));
}
/**
* 查询列表
* @return 包含列表数据的响应信息
*/
@GetMapping("/list")
@Operation(summary = "查询列表", description = "查询列表")
public R listGroups() {
List<GenGroupEntity> list = genGroupService
.list(Wrappers.<GenGroupEntity>lambdaQuery().orderByDesc(GenGroupEntity::getCreateTime));
return R.ok(list);
}
}
/*
* 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.pig.codegen.controller;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pig4cloud.pig.codegen.entity.GenTable;
import com.pig4cloud.pig.codegen.entity.GenTableColumnEntity;
import com.pig4cloud.pig.codegen.service.GenTableColumnService;
import com.pig4cloud.pig.codegen.service.GenTableService;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.log.annotation.SysLog;
import com.pig4cloud.plugin.excel.annotation.ResponseExcel;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* 代码表管理控制器
*
* @author lengleng
* @date 2025/05/31
*/
@RestController
@RequiredArgsConstructor
@RequestMapping("/table")
@Tag(description = "table", name = "代码表管理")
@SecurityRequirement(name = HttpHeaders.AUTHORIZATION)
public class GenTableController {
private final GenTableColumnService tableColumnService;
/**
* 表服务
*/
private final GenTableService tableService;
/**
* 分页查询
* @param page 分页对象
* @param table 列属性
* @return
*/
@Operation(summary = "分页查询", description = "分页查询")
@GetMapping("/page")
public R getTablePage(Page page, GenTable table) {
return R.ok(tableService.queryTablePage(page, table));
}
/**
* 通过id查询表信息(代码生成设置 + 表 + 字段设置)
* @param id id
* @return R
*/
@Operation(summary = "通过id查询", description = "通过id查询")
@GetMapping("/{id}")
public R getTableById(@PathVariable("id") Long id) {
return R.ok(tableService.getById(id));
}
/**
* 查询数据源所有表
* @param dsName 数据源名称
* @return 包含表列表的响应结果
*/
@GetMapping("/list/{dsName}")
public R listTables(@PathVariable("dsName") String dsName) {
return R.ok(tableService.queryTableList(dsName));
}
/**
* 获取表信息
* @param dsName 数据源
* @param tableName 表名称
*/
@GetMapping("/{dsName}/{tableName}")
public R<GenTable> getTable(@PathVariable("dsName") String dsName, @PathVariable String tableName) {
return R.ok(tableService.queryOrBuildTable(dsName, tableName));
}
/**
* 查询表DDL语句
* @param dsName 数据源
* @param tableName 表名称
*/
@GetMapping("/column/{dsName}/{tableName}")
public R getTableColumn(@PathVariable("dsName") String dsName, @PathVariable String tableName) throws Exception {
return R.ok(tableService.queryTableColumn(dsName, tableName));
}
/**
* 查询表DDL语句
* @param dsName 数据源
* @param tableName 表名称
*/
@GetMapping("/ddl/{dsName}/{tableName}")
public R getTableDdl(@PathVariable("dsName") String dsName, @PathVariable String tableName) throws Exception {
return R.ok(tableService.queryTableDdl(dsName, tableName));
}
/**
* 同步表信息
* @param dsName 数据源
* @param tableName 表名称
*/
@GetMapping("/sync/{dsName}/{tableName}")
public R<GenTable> syncTable(@PathVariable("dsName") String dsName, @PathVariable String tableName) {
// 表配置删除
tableService.remove(
Wrappers.<GenTable>lambdaQuery().eq(GenTable::getDsName, dsName).eq(GenTable::getTableName, tableName));
// 字段配置删除
tableColumnService.remove(Wrappers.<GenTableColumnEntity>lambdaQuery()
.eq(GenTableColumnEntity::getDsName, dsName)
.eq(GenTableColumnEntity::getTableName, tableName));
return R.ok(tableService.queryOrBuildTable(dsName, tableName));
}
/**
* 修改列属性
* @param table 列属性
* @return R
*/
@Operation(summary = "修改列属性", description = "修改列属性")
@SysLog("修改列属性")
@PutMapping
public R updateTable(@RequestBody GenTable table) {
return R.ok(tableService.updateById(table));
}
/**
* 修改表字段数据
* @param dsName 数据源
* @param tableName 表名称
* @param tableFieldList 字段列表
*/
@PutMapping("/field/{dsName}/{tableName}")
public R<String> updateTableField(@PathVariable("dsName") String dsName, @PathVariable String tableName,
@RequestBody List<GenTableColumnEntity> tableFieldList) {
tableColumnService.updateTableField(dsName, tableName, tableFieldList);
return R.ok();
}
/**
* 导出excel 表格
* @param table 查询条件
* @return excel 文件流
*/
@ResponseExcel
@GetMapping("/export")
public List<GenTable> exportTables(GenTable table) {
return tableService.list(Wrappers.query(table));
}
}
/*
* 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.pig.codegen.controller;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pig4cloud.pig.codegen.entity.GenTemplateEntity;
import com.pig4cloud.pig.codegen.service.GenTemplateService;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.log.annotation.SysLog;
import com.pig4cloud.pig.common.security.annotation.HasPermission;
import com.pig4cloud.pig.common.xss.core.XssCleanIgnore;
import com.pig4cloud.plugin.excel.annotation.ResponseExcel;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* 模板管理控制器
*
* @author lengleng
* @date 2025/05/31
*/
@RestController
@RequiredArgsConstructor
@RequestMapping("/template")
@Tag(description = "template", name = "模板管理")
@SecurityRequirement(name = HttpHeaders.AUTHORIZATION)
public class GenTemplateController {
private final GenTemplateService genTemplateService;
/**
* 分页查询模板信息
* @param page 分页参数对象
* @param genTemplate 模板查询条件
* @return 分页查询结果
*/
@Operation(summary = "分页查询", description = "分页查询")
@GetMapping("/page")
@HasPermission("codegen_template_view")
public R getTemplatePage(Page page, GenTemplateEntity genTemplate) {
LambdaQueryWrapper<GenTemplateEntity> wrapper = Wrappers.<GenTemplateEntity>lambdaQuery()
.like(genTemplate.getId() != null, GenTemplateEntity::getId, genTemplate.getId())
.like(StrUtil.isNotEmpty(genTemplate.getTemplateName()), GenTemplateEntity::getTemplateName,
genTemplate.getTemplateName());
return R.ok(genTemplateService.page(page, wrapper));
}
/**
* 查询全部模板
* @return
*/
@Operation(summary = "查询全部", description = "查询全部")
@GetMapping("/list")
@HasPermission("codegen_template_view")
public R listTemplates() {
return R.ok(genTemplateService
.list(Wrappers.<GenTemplateEntity>lambdaQuery().orderByDesc(GenTemplateEntity::getCreateTime)));
}
/**
* 通过id查询模板
* @param id id
* @return R
*/
@Operation(summary = "通过id查询", description = "通过id查询")
@GetMapping("/{id}")
@HasPermission("codegen_template_view")
public R getTemplateById(@PathVariable("id") Long id) {
return R.ok(genTemplateService.getById(id));
}
/**
* 新增模板
* @param genTemplate 模板
* @return R
*/
@XssCleanIgnore
@Operation(summary = "新增模板", description = "新增模板")
@SysLog("新增模板")
@PostMapping
@HasPermission("codegen_template_add")
public R saveTemplate(@RequestBody GenTemplateEntity genTemplate) {
return R.ok(genTemplateService.save(genTemplate));
}
/**
* 修改模板
* @param genTemplate 模板
* @return R
*/
@XssCleanIgnore
@Operation(summary = "修改模板", description = "修改模板")
@SysLog("修改模板")
@PutMapping
@HasPermission("codegen_template_edit")
public R updateTemplate(@RequestBody GenTemplateEntity genTemplate) {
return R.ok(genTemplateService.updateById(genTemplate));
}
/**
* 通过id删除模板
* @param ids id列表
* @return R
*/
@Operation(summary = "通过id删除模板", description = "通过id删除模板")
@SysLog("通过id删除模板")
@DeleteMapping
@HasPermission("codegen_template_del")
public R removeTemplateByIds(@RequestBody Long[] ids) {
return R.ok(genTemplateService.removeBatchByIds(CollUtil.toList(ids)));
}
/**
* 导出excel 表格
* @param genTemplate 查询条件
* @return excel 文件流
*/
@ResponseExcel
@GetMapping("/export")
@HasPermission("codegen_template_export")
public List<GenTemplateEntity> exportTemplates(GenTemplateEntity genTemplate) {
return genTemplateService.list(Wrappers.query(genTemplate));
}
/**
* 在线更新模板
* @return R
*/
@Operation(summary = "在线更新模板", description = "在线更新模板")
@GetMapping("/online")
@HasPermission("codegen_template_view")
public R online() {
return genTemplateService.onlineUpdate();
}
/**
* 检查版本
* @return {@link R }
*/
@Operation(summary = "在线检查模板", description = "在线检查模板")
@GetMapping("/checkVersion")
@HasPermission("codegen_template_view")
public R checkVersion() {
return genTemplateService.checkVersion();
}
}
/*
* 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.pig.codegen.controller;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pig4cloud.pig.codegen.entity.GenTemplateGroupEntity;
import com.pig4cloud.pig.codegen.service.GenTemplateGroupService;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.log.annotation.SysLog;
import com.pig4cloud.pig.common.security.annotation.HasPermission;
import com.pig4cloud.plugin.excel.annotation.ResponseExcel;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* 模板分组关联表
*
* @author PIG
* @date 2023-02-22 09:25:15
*/
@RestController
@RequiredArgsConstructor
@RequestMapping("/templateGroup")
@Tag(description = "templateGroup", name = "模板分组关联表管理")
@SecurityRequirement(name = HttpHeaders.AUTHORIZATION)
public class GenTemplateGroupController {
private final GenTemplateGroupService genTemplateGroupService;
/**
* 分页查询
* @param page 分页对象
* @param genTemplateGroup 模板分组关联表
* @return
*/
@Operation(summary = "分页查询", description = "分页查询")
@GetMapping("/page")
@HasPermission("codegen_templateGroup_view")
public R getTemplateGroupPage(Page page, GenTemplateGroupEntity genTemplateGroup) {
LambdaQueryWrapper<GenTemplateGroupEntity> wrapper = Wrappers.lambdaQuery();
return R.ok(genTemplateGroupService.page(page, wrapper));
}
/**
* 通过id查询模板分组关联表
* @param groupId id
* @return R
*/
@Operation(summary = "通过id查询", description = "通过id查询")
@GetMapping("/{groupId}")
@HasPermission("codegen_templateGroup_view")
public R getTemplateGroupById(@PathVariable("groupId") Long groupId) {
return R.ok(genTemplateGroupService.getById(groupId));
}
/**
* 新增模板分组关联表
* @param genTemplateGroup 模板分组关联表
* @return R
*/
@Operation(summary = "新增模板分组关联表", description = "新增模板分组关联表")
@SysLog("新增模板分组关联表")
@PostMapping
@HasPermission("codegen_templateGroup_add")
public R saveTemplateGroup(@RequestBody GenTemplateGroupEntity genTemplateGroup) {
return R.ok(genTemplateGroupService.save(genTemplateGroup));
}
/**
* 修改模板分组关联表
* @param genTemplateGroup 模板分组关联表
* @return R
*/
@Operation(summary = "修改模板分组关联表", description = "修改模板分组关联表")
@SysLog("修改模板分组关联表")
@PutMapping
@HasPermission("codegen_templateGroup_edit")
public R updateTemplateGroup(@RequestBody GenTemplateGroupEntity genTemplateGroup) {
return R.ok(genTemplateGroupService.updateById(genTemplateGroup));
}
/**
* 通过id删除模板分组关联表
* @param ids groupId列表
* @return R
*/
@Operation(summary = "通过id删除模板分组关联表", description = "通过id删除模板分组关联表")
@SysLog("通过id删除模板分组关联表")
@DeleteMapping
@HasPermission("codegen_templateGroup_del")
public R removeTemplateGroupByIds(@RequestBody Long[] ids) {
return R.ok(genTemplateGroupService.removeBatchByIds(CollUtil.toList(ids)));
}
/**
* 导出excel 表格
* @param genTemplateGroup 查询条件
* @return excel 文件流
*/
@ResponseExcel
@GetMapping("/export")
@HasPermission("codegen_templateGroup_export")
public List<GenTemplateGroupEntity> exportTemplateGroups(GenTemplateGroupEntity genTemplateGroup) {
return genTemplateGroupService.list(Wrappers.query(genTemplateGroup));
}
}
/*
* 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.pig.codegen.controller;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import com.pig4cloud.pig.codegen.service.GeneratorService;
import com.pig4cloud.pig.common.core.util.R;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import java.io.ByteArrayOutputStream;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipOutputStream;
/**
* 代码生成器控制器
*
* @author lengleng
* @date 2025/05/31
*/
@RestController
@RequiredArgsConstructor
@RequestMapping("/generator")
public class GeneratorController {
private final GeneratorService generatorService;
/**
* ZIP 下载生成代码
* @param tableIds 数据表ID
* @param response 流输出对象
*/
@SneakyThrows
@GetMapping("/download")
public void download(String tableIds, HttpServletResponse response) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ZipOutputStream zip = new ZipOutputStream(outputStream);
// 生成代码
for (String tableId : tableIds.split(StrUtil.COMMA)) {
generatorService.downloadCode(Long.parseLong(tableId), zip);
}
IoUtil.close(zip);
// zip压缩包数据
byte[] data = outputStream.toByteArray();
response.reset();
response.setHeader(HttpHeaders.CONTENT_DISPOSITION, String.format("attachment; filename=%s.zip", tableIds));
response.addHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(data.length));
response.setContentType("application/octet-stream; charset=UTF-8");
IoUtil.write(response.getOutputStream(), false, data);
}
/**
* 生成代码
* @param tableIds 表ID列表,多个ID用逗号分隔
* @return 操作结果
* @throws Exception 生成代码过程中可能抛出的异常
*/
@ResponseBody
@GetMapping("/code")
public R<String> code(String tableIds) throws Exception {
// 生成代码
for (String tableId : tableIds.split(StrUtil.COMMA)) {
generatorService.generatorCode(Long.valueOf(tableId));
}
return R.ok();
}
/**
* 预览代码
* @param tableId 表ID
* @return 代码预览结果列表
*/
@SneakyThrows
@GetMapping("/preview")
public List<Map<String, String>> preview(Long tableId) {
return generatorService.preview(tableId);
}
}
/*
* 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.pig.codegen.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;
/**
* JAVA 数据类型
*/
private String javaType;
/**
* 备注
*/
private String comments;
/**
* 驼峰属性
*/
private String caseAttrName;
/**
* 普通属性
*/
private String lowerAttrName;
/**
* 属性类型
*/
private String attrType;
/**
* 其他信息
*/
private String extra;
/**
* 字段类型
*/
private String columnType;
/**
* 是否可以为空
*/
private Boolean nullable;
/**
* 是否隐藏
*/
private Boolean hidden;
}
/*
* 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.pig.codegen.entity;
import lombok.Data;
/**
* @author lengleng
* @date 2018/8/2 生成配置
*/
@Data
public class GenConfig {
/**
* 数据源name
*/
private String dsName;
/**
* 包名
*/
private String packageName;
/**
* 作者
*/
private String author;
/**
* 模块名称
*/
private String moduleName;
/**
* 表前缀
*/
private String tablePrefix;
/**
* 表名称
*/
private String tableName;
/**
* 表备注
*/
private String comments;
/**
* 代码风格 0 - avue 1 - element 2 - uview
*/
private String style;
}
/*
* 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.pig.codegen.entity;
import com.baomidou.mybatisplus.annotation.*;
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(type = IdType.ASSIGN_ID)
private Long id;
/**
* 名称
*/
private String name;
/**
* 数据库类型
*/
private String dsType;
/**
* 配置类型 (0 主机形式 | 1 url形式)
*/
private Integer confType;
/**
* 主机地址
*/
private String host;
/**
* 端口
*/
private Integer port;
/**
* jdbc-url
*/
private String url;
/**
* 实例
*/
private String instance;
/**
* 数据库名称
*/
private String dsName;
/**
* 用户名
*/
private String username;
/**
* 密码
*/
private String password;
/**
* 创建时间
*/
@TableField(fill = FieldFill.INSERT)
private LocalDateTime createTime;
/**
* 修改时间
*/
@TableField(fill = FieldFill.UPDATE)
private LocalDateTime updateTime;
/**
* 0-正常,1-删除
*/
@TableLogic
@TableField(fill = FieldFill.INSERT)
private String delFlag;
}
/*
* 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.pig.codegen.entity;
import com.baomidou.mybatisplus.annotation.*;
import com.baomidou.mybatisplus.extension.activerecord.Model;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.time.LocalDateTime;
/**
* 列属性
*
* @author pigx code generator
* @date 2023-02-06 20:16:01
*/
@Data
@TableName("gen_field_type")
@EqualsAndHashCode(callSuper = true)
@Schema(description = "列属性")
public class GenFieldType extends Model<GenFieldType> {
private static final long serialVersionUID = 1L;
/**
* id
*/
@TableId(type = IdType.ASSIGN_ID)
@Schema(description = "id")
private Long id;
/**
* 字段类型
*/
@Schema(description = "字段类型")
private String columnType;
/**
* 属性类型
*/
@Schema(description = "属性类型")
private String attrType;
/**
* 属性包名
*/
@Schema(description = "属性包名")
private String packageName;
/**
* 创建人
*/
@TableField(fill = FieldFill.INSERT)
@Schema(description = "创建人")
private String createBy;
/**
* 修改人
*/
@TableField(fill = FieldFill.UPDATE)
@Schema(description = "修改人")
private String updateBy;
/**
* 创建时间
*/
@Schema(description = "创建时间")
@TableField(fill = FieldFill.INSERT)
private LocalDateTime createTime;
/**
* 修改时间
*/
@Schema(description = "修改时间")
@TableField(fill = FieldFill.UPDATE)
private LocalDateTime updateTime;
/**
* 删除标识(0-正常,1-删除)
*/
@TableLogic
@TableField(fill = FieldFill.INSERT)
@Schema(description = "删除标记,1:已删除,0:正常")
private String delFlag;
}
/*
* 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.pig.codegen.entity;
import com.baomidou.mybatisplus.annotation.*;
import com.baomidou.mybatisplus.extension.activerecord.Model;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.time.LocalDateTime;
/**
* 模板分组
*
* @author PIG
* @date 2023-02-21 20:01:53
*/
@Data
@TableName("gen_group")
@EqualsAndHashCode(callSuper = true)
@Schema(description = "模板分组")
public class GenGroupEntity extends Model<GenGroupEntity> {
private static final long serialVersionUID = 1L;
/**
* id
*/
@TableId(type = IdType.ASSIGN_ID)
@Schema(description = "id")
private Long id;
/**
* 分组名称
*/
@Schema(description = "分组名称")
private String groupName;
/**
* 分组描述
*/
@Schema(description = "分组描述")
@TableField(fill = FieldFill.INSERT)
private String groupDesc;
/**
* 创建人
*/
@TableField(fill = FieldFill.INSERT)
@Schema(description = "创建人")
private String createBy;
/**
* 修改人
*/
@TableField(fill = FieldFill.UPDATE)
@Schema(description = "修改人")
private String updateBy;
/**
* 创建时间
*/
@Schema(description = "创建时间")
@TableField(fill = FieldFill.INSERT)
private LocalDateTime createTime;
/**
* 修改时间
*/
@Schema(description = "修改时间")
@TableField(fill = FieldFill.UPDATE)
private LocalDateTime updateTime;
/**
* 删除标识(0-正常,1-删除)
*/
@TableLogic
@TableField(fill = FieldFill.INSERT)
@Schema(description = "删除标记,1:已删除,0:正常")
private String delFlag;
}
/*
* 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.pig.codegen.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.extension.activerecord.Model;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.time.LocalDateTime;
import java.util.List;
/**
* 列属性
*
* @author pigx code generator
* @date 2023-02-06 20:34:55
*/
@Data
@TableName("gen_table")
@EqualsAndHashCode(callSuper = true)
@Schema(description = "列属性")
public class GenTable extends Model<GenTable> {
private static final long serialVersionUID = 1L;
/**
* id
*/
@TableId(type = IdType.ASSIGN_ID)
@Schema(description = "id")
private Long id;
/**
* 数据源名称
*/
@Schema(description = "数据源名称")
private String dsName;
/**
* 数据源类型
*/
@Schema(description = "数据源类型")
private String dbType;
/**
* 表名
*/
@Schema(description = "表名")
private String tableName;
/**
* 类名
*/
@Schema(description = "类名")
private String className;
/**
* 说明
*/
@Schema(description = "说明")
private String tableComment;
/**
* 作者
*/
@Schema(description = "作者")
private String author;
/**
* 邮箱
*/
@Schema(description = "邮箱")
private String email;
/**
* 项目包名
*/
@Schema(description = "项目包名")
private String packageName;
/**
* 项目版本号
*/
@Schema(description = "项目版本号")
private String version;
/**
* 生成方式 0:zip压缩包 1:自定义目录
*/
@Schema(description = "生成方式 0:zip压缩包 1:自定义目录")
private String generatorType;
/**
* 后端生成路径
*/
@Schema(description = "后端生成路径")
private String backendPath;
/**
* 前端生成路径
*/
@Schema(description = "前端生成路径")
private String frontendPath;
/**
* 模块名
*/
@Schema(description = "模块名")
private String moduleName;
/**
* 功能名
*/
@Schema(description = "功能名")
private String functionName;
/**
* 表单布局 1:一列 2:两列
*/
@Schema(description = "表单布局 1:一列 2:两列")
private Integer formLayout;
/**
* 基类ID
*/
@Schema(description = "基类ID")
private Long baseclassId;
/**
* 创建时间
*/
@Schema(description = "创建时间")
private LocalDateTime createTime;
/**
* 代码生成风格
*/
private Long style;
/**
* 子表名称
*/
private String childTableName;
/**
* 主表关联键
*/
private String mainField;
/**
* 子表关联键
*/
private String childField;
/**
* 字段列表
*/
@TableField(exist = false)
private List<GenTableColumnEntity> fieldList;
/**
* 子表字段列表
*/
@TableField(exist = false)
private List<GenTableColumnEntity> childFieldList;
/**
* 代码风格(模版分组信息)
*/
@TableField(exist = false)
private List<GenGroupEntity> groupList;
}
/*
* 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.pig.codegen.entity;
import com.baomidou.mybatisplus.annotation.*;
import com.baomidou.mybatisplus.extension.activerecord.Model;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
* @author lengleng
* @date 2023-02-06
*
* 记录表字段的配置信息
*/
@Data
@TableName("gen_table_column")
@EqualsAndHashCode(callSuper = true)
public class GenTableColumnEntity extends Model<GenDatasourceConf> {
private static final long serialVersionUID = 1L;
/**
* 主键
*/
@TableId(type = IdType.ASSIGN_ID)
private Long id;
/**
* 数据源名
*/
private String dsName;
/**
* 表名称
*/
private String tableName;
/**
* 字段名称
*/
private String fieldName;
/**
* 排序
*/
private Integer sort;
/**
* 字段类型
*/
private String fieldType;
/**
* 字段说明
*/
private String fieldComment;
/**
* 属性名
*/
private String attrName;
/**
* 属性类型
*/
private String attrType;
/**
* 属性包名
*/
private String packageName;
/**
* 自动填充
*/
private String autoFill;
/**
* 主键 0:否 1:是
*/
private String primaryPk;
/**
* 基类字段 0:否 1:是
*/
private String baseField;
/**
* 表单项 0:否 1:是
*/
private String formItem;
/**
* 表单必填 0:否 1:是
*/
private String formRequired;
/**
* 表单类型
*/
private String formType;
/**
* 表单效验
*/
private String formValidator;
/**
* 列表项 0:否 1:是
*/
private String gridItem;
/**
* 列表排序 0:否 1:是
*/
private String gridSort;
/**
* 查询项 0:否 1:是
*/
private String queryItem;
/**
* 查询方式
*/
private String queryType;
/**
* 查询表单类型
*/
private String queryFormType;
/**
* 字段字典类型
*/
@TableField(updateStrategy = FieldStrategy.ALWAYS)
private String fieldDict;
}
/*
* 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.pig.codegen.entity;
import com.baomidou.mybatisplus.annotation.*;
import com.baomidou.mybatisplus.extension.activerecord.Model;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.time.LocalDateTime;
/**
* 模板
*
* @author PIG
* @date 2023-02-21 17:15:44
*/
@Data
@TableName("gen_template")
@EqualsAndHashCode(callSuper = true)
@Schema(description = "模板")
public class GenTemplateEntity extends Model<GenTemplateEntity> {
private static final long serialVersionUID = 1L;
/**
* 主键
*/
@TableId(type = IdType.ASSIGN_ID)
@Schema(description = "主键")
private Long id;
/**
* 模板名称
*/
@Schema(description = "模板名称")
private String templateName;
/**
* 模板路径
*/
@Schema(description = "模板路径")
private String generatorPath;
/**
* 模板描述
*/
@Schema(description = "模板描述")
private String templateDesc;
/**
* 模板代码
*/
@Schema(description = "模板代码")
private String templateCode;
/**
* 创建人
*/
@TableField(fill = FieldFill.INSERT)
@Schema(description = "创建人")
private String createBy;
/**
* 修改人
*/
@TableField(fill = FieldFill.UPDATE)
@Schema(description = "修改人")
private String updateBy;
/**
* 创建时间
*/
@Schema(description = "创建时间")
@TableField(fill = FieldFill.INSERT)
private LocalDateTime createTime;
/**
* 修改时间
*/
@Schema(description = "修改时间")
@TableField(fill = FieldFill.UPDATE)
private LocalDateTime updateTime;
/**
* 删除标识(0-正常,1-删除)
*/
@TableLogic
@TableField(fill = FieldFill.INSERT)
@Schema(description = "删除标记,1:已删除,0:正常")
private String delFlag;
}
/*
* 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.pig.codegen.entity;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.extension.activerecord.Model;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
/**
* 模板分组关联表
*
* @author PIG
* @date 2023-02-22 09:25:15
*/
@Data
@TableName("gen_template_group")
@Accessors(chain = true)
@EqualsAndHashCode(callSuper = true)
@Schema(description = "模板分组关联表")
public class GenTemplateGroupEntity extends Model<GenTemplateGroupEntity> {
private static final long serialVersionUID = 1L;
/**
* 分组id
*/
@Schema(description = "分组id")
private Long groupId;
/**
* 模板id
*/
@Schema(description = "模板id")
private Long templateId;
}
/*
* 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.pig.codegen.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;
/**
* 数据库类型 (用于根据数据库个性化)
*/
private String dbType;
}
/*
* 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.pig.codegen.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.pig4cloud.pig.codegen.entity.GenDatasourceConf;
import org.apache.ibatis.annotations.Mapper;
/**
* 数据源表 Mapper 接口
*
* @author lengleng
* @date 2019-03-31 16:00:20
*/
@Mapper
public interface GenDatasourceConfMapper extends BaseMapper<GenDatasourceConf> {
}
/*
* 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.pig.codegen.mapper;
import com.baomidou.mybatisplus.annotation.InterceptorIgnore;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.LinkedHashMap;
import java.util.List;
/**
* 动态查询Mapper接口
*
* @author lengleng
* @date 2025/05/31
*/
@Mapper
public interface GenDynamicMapper {
/**
* 动态SQL查询
* @param sq SQL查询语句
* @return 查询结果列表,每个结果以LinkedHashMap形式存储
*/
@InterceptorIgnore(tenantLine = "true")
List<LinkedHashMap<String, Object>> dynamicQuerySql(@Param("value") String sq);
}
/*
* 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.pig.codegen.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.pig4cloud.pig.codegen.entity.GenFieldType;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.Set;
/**
* 字段类型映射器接口:用于操作字段类型相关数据库操作
*
* @author lengleng
* @date 2025/05/31
*/
@Mapper
public interface GenFieldTypeMapper extends BaseMapper<GenFieldType> {
/**
* 根据tableId,获取包列表
* @param dsName 数据源名称
* @param tableName 表名称
* @return 返回包列表
*/
Set<String> getPackageByTableId(@Param("dsName") String dsName, @Param("tableName") String tableName);
}
/*
* 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.pig.codegen.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.pig4cloud.pig.codegen.entity.GenGroupEntity;
import com.pig4cloud.pig.codegen.util.vo.GroupVO;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
/**
* 模板分组 Mapper 接口
*
* @author lengleng
* @date 2025/05/31
*/
@Mapper
public interface GenGroupMapper extends BaseMapper<GenGroupEntity> {
/**
* 根据ID获取分组VO对象
* @param id 分组ID
* @return 分组VO对象
*/
GroupVO getGroupVoById(@Param("id") Long id);
}
/*
* 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.pig.codegen.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.pig4cloud.pig.codegen.entity.GenTableColumnEntity;
import org.apache.ibatis.annotations.Mapper;
/**
* 代码生成表列属性Mapper接口
*
* @author lengleng
* @date 2025/05/31
*/
@Mapper
public interface GenTableColumnMapper extends BaseMapper<GenTableColumnEntity> {
}
/*
* 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.pig.codegen.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.pig4cloud.pig.codegen.entity.GenTable;
import org.apache.ibatis.annotations.Mapper;
/**
* 代码生成表 Mapper 接口
*
* @author lengleng
* @date 2025/05/31
*/
@Mapper
public interface GenTableMapper extends BaseMapper<GenTable> {
}
/*
* 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.pig.codegen.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.pig4cloud.pig.codegen.entity.GenTemplateGroupEntity;
import org.apache.ibatis.annotations.Mapper;
/**
* 模板分组关联表 Mapper 接口
*
* @author lengleng
* @date 2025/05/31
*/
@Mapper
public interface GenTemplateGroupMapper extends BaseMapper<GenTemplateGroupEntity> {
}
/*
* 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.pig.codegen.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.pig4cloud.pig.codegen.entity.GenTemplateEntity;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
/**
* 代码生成模板Mapper接口
*
* @author lengleng
* @date 2025/05/31
*/
@Mapper
public interface GenTemplateMapper extends BaseMapper<GenTemplateEntity> {
/**
* 根据模板组ID查询模板列表
* @param groupId 模板组ID
* @return 模板实体列表
*/
List<GenTemplateEntity> listTemplateById(Long groupId);
}
/*
* 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.pig.codegen.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.pig4cloud.pig.codegen.entity.GenDatasourceConf;
/**
* 数据源配置服务接口 提供数据源的增删改查及校验等功能
*
* @author lengleng
* @date 2025/05/31
*/
public interface GenDatasourceConfService extends IService<GenDatasourceConf> {
/**
* 保存数据源并加密
* @param genDatasourceConf 数据源配置信息
* @return 保存是否成功
*/
Boolean saveDsByEnc(GenDatasourceConf genDatasourceConf);
/**
* 更新数据源
* @param genDatasourceConf 数据源配置信息
* @return 更新是否成功
*/
Boolean updateDsByEnc(GenDatasourceConf genDatasourceConf);
/**
* 添加动态数据源
* @param datasourceConf 数据源配置信息
*/
void addDynamicDataSource(GenDatasourceConf datasourceConf);
/**
* 校验数据源配置是否有效
* @param datasourceConf 数据源配置信息
* @return true表示有效,false表示无效
*/
Boolean checkDataSource(GenDatasourceConf datasourceConf);
/**
* 通过数据源ID删除数据源
* @param dsIds 数据源ID数组
* @return 删除是否成功
*/
Boolean removeByDsId(Long[] dsIds);
}
/*
* 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.pig.codegen.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.pig4cloud.pig.codegen.entity.GenFieldType;
import java.util.Set;
/**
* 列属性服务接口
*
* @author lengleng
* @date 2025/05/31
*/
public interface GenFieldTypeService extends IService<GenFieldType> {
/**
* 根据tableId,获取包列表
* @param dsName 数据源名称
* @param tableName 表名称
* @return 返回包列表
*/
Set<String> getPackageByTableId(String dsName, String tableName);
}
/*
* 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.pig.codegen.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.pig4cloud.pig.codegen.entity.GenGroupEntity;
import com.pig4cloud.pig.codegen.util.vo.GroupVO;
import com.pig4cloud.pig.codegen.util.vo.TemplateGroupDTO;
/**
* 模板分组服务接口
*
* @author lengleng
* @date 2025/05/31
*/
public interface GenGroupService extends IService<GenGroupEntity> {
/**
* 保存生成模板组
* @param genTemplateGroup 模板组DTO对象
*/
void saveGenGroup(TemplateGroupDTO genTemplateGroup);
/**
* 删除分组极其关系
* @param ids
*/
void delGroupAndTemplate(Long[] ids);
/**
* 查询group数据
* @param id
*/
GroupVO getGroupVoById(Long id);
/**
* 更新group数据
* @param GroupVo
*/
void updateGroupAndTemplateById(GroupVO GroupVo);
}
/*
* 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.pig.codegen.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.pig4cloud.pig.codegen.entity.GenTableColumnEntity;
import java.util.List;
/**
* 代码生成表列服务接口
*
* @author lengleng
* @date 2025/05/31
*/
public interface GenTableColumnService extends IService<GenTableColumnEntity> {
/**
* 初始化字段列表
* @param tableFieldList 表字段实体列表
*/
void initFieldList(List<GenTableColumnEntity> tableFieldList);
/**
* 更新表字段信息
* @param dsName 数据源名称
* @param tableName 表名
* @param tableFieldList 表字段列表
*/
void updateTableField(String dsName, String tableName, List<GenTableColumnEntity> tableFieldList);
}
/*
* 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.pig.codegen.service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.pig4cloud.pig.codegen.entity.GenTable;
import org.anyline.metadata.Table;
import java.util.List;
/**
* 代码生成表服务接口
*
* @author lengleng
* @date 2025/05/31
*/
public interface GenTableService extends IService<GenTable> {
/**
* 查询对应数据源的表
* @param page 分页信息
* @param table 查询条件
* @return 表
*/
IPage queryTablePage(Page<Table> page, GenTable table);
/**
* 查询表信息(列),然后插入到中间表中
* @param dsName 数据源
* @param tableName 表名
* @return GenTable
*/
GenTable queryOrBuildTable(String dsName, String tableName);
/**
* 查询表ddl 语句
* @param dsName 数据源名称
* @param tableName 表名称
* @return ddl 语句
* @throws Exception
*/
String queryTableDdl(String dsName, String tableName) throws Exception;
/**
* 查询数据源里面的全部表
* @param dsName 数据源名称
* @return table
*/
List<String> queryTableList(String dsName);
/**
* 查询表的全部字段
* @param dsName 数据源
* @param tableName 表名称
* @return column
*/
List<String> queryTableColumn(String dsName, String tableName);
}
/*
* 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.pig.codegen.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.pig4cloud.pig.codegen.entity.GenTemplateGroupEntity;
/**
* 模板分组关联服务接口
*
* @author lengleng
* @date 2025/05/31
*/
public interface GenTemplateGroupService extends IService<GenTemplateGroupEntity> {
}
/*
* 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.pig.codegen.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.pig4cloud.pig.codegen.entity.GenTemplateEntity;
import com.pig4cloud.pig.common.core.util.R;
/**
* 代码生成模板服务接口
*
* @author lengleng
* @date 2025/05/31
*/
public interface GenTemplateService extends IService<GenTemplateEntity> {
/**
* 检查版本信息
* @return 返回检查结果,包含版本信息
*/
R checkVersion();
/**
* 在线更新
* @return 更新结果
*/
R onlineUpdate();
}
/*
* 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.pig.codegen.service;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipOutputStream;
/**
* 代码生成服务接口
*
* @author lengleng
* @date 2025/05/31
*/
public interface GeneratorService {
/**
* 生成代码zip写出
* @param tableId 表
* @param zip 输出流
*/
void downloadCode(Long tableId, ZipOutputStream zip);
/**
* 预览代码
* @param tableId 表
* @return [{模板名称:渲染结果}]
*/
List<Map<String, String>> preview(Long tableId);
/**
* 目标目录写入渲染结果
* @param tableId 表
*/
void generatorCode(Long tableId);
}
/*
* 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.pig.codegen.service.impl;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.baomidou.dynamic.datasource.creator.DataSourceCreator;
import com.baomidou.dynamic.datasource.creator.DataSourceProperty;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pig4cloud.pig.codegen.entity.GenDatasourceConf;
import com.pig4cloud.pig.codegen.mapper.GenDatasourceConfMapper;
import com.pig4cloud.pig.codegen.service.GenDatasourceConfService;
import com.pig4cloud.pig.common.core.util.SpringContextHolder;
import com.pig4cloud.pig.common.datasource.enums.DsConfTypeEnum;
import com.pig4cloud.pig.common.datasource.enums.DsJdbcUrlEnum;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.jasypt.encryption.StringEncryptor;
import org.springframework.stereotype.Service;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
/**
* 数据源配置服务实现类
*
* <p>
* 提供数据源的增删改查及校验功能,支持数据源密码加密存储
* </p>
*
* @author lengleng
* @date 2025/05/31
*/
@Slf4j
@Service
@RequiredArgsConstructor
public class GenDatasourceConfServiceImpl extends ServiceImpl<GenDatasourceConfMapper, GenDatasourceConf>
implements GenDatasourceConfService {
private final StringEncryptor stringEncryptor;
private final DataSourceCreator hikariDataSourceCreator;
/**
* 保存数据源配置并进行加密处理
* @param conf 数据源配置信息
* @return 保存成功返回true,失败返回false
*/
@Override
public Boolean saveDsByEnc(GenDatasourceConf conf) {
// 校验配置合法性
if (!checkDataSource(conf)) {
return Boolean.FALSE;
}
// 添加动态数据源
addDynamicDataSource(conf);
// 更新数据库配置
conf.setPassword(stringEncryptor.encrypt(conf.getPassword()));
this.baseMapper.insert(conf);
return Boolean.TRUE;
}
/**
* 更新加密数据源
* @param conf 数据源配置信息
* @return 更新成功返回true,失败返回false
*/
@Override
public Boolean updateDsByEnc(GenDatasourceConf conf) {
if (!checkDataSource(conf)) {
return Boolean.FALSE;
}
// 先移除
DynamicRoutingDataSource dynamicRoutingDataSource = SpringContextHolder.getBean(DynamicRoutingDataSource.class);
dynamicRoutingDataSource.removeDataSource(baseMapper.selectById(conf.getId()).getName());
// 再添加
addDynamicDataSource(conf);
// 更新数据库配置
if (StrUtil.isNotBlank(conf.getPassword())) {
conf.setPassword(stringEncryptor.encrypt(conf.getPassword()));
}
this.baseMapper.updateById(conf);
return Boolean.TRUE;
}
/**
* 通过数据源ID删除数据源
* @param dsIds 数据源ID数组
* @return 删除是否成功
*/
@Override
public Boolean removeByDsId(Long[] dsIds) {
DynamicRoutingDataSource dynamicRoutingDataSource = SpringContextHolder.getBean(DynamicRoutingDataSource.class);
this.baseMapper.selectByIds(CollUtil.toList(dsIds))
.forEach(ds -> dynamicRoutingDataSource.removeDataSource(ds.getName()));
this.baseMapper.deleteByIds(CollUtil.toList(dsIds));
return Boolean.TRUE;
}
/**
* 添加动态数据源
* @param conf 数据源配置信息
*/
@Override
public void addDynamicDataSource(GenDatasourceConf conf) {
DataSourceProperty dataSourceProperty = new DataSourceProperty();
dataSourceProperty.setPoolName(conf.getName());
dataSourceProperty.setUrl(conf.getUrl());
dataSourceProperty.setUsername(conf.getUsername());
dataSourceProperty.setPassword(conf.getPassword());
DataSource dataSource = hikariDataSourceCreator.createDataSource(dataSourceProperty);
DynamicRoutingDataSource dynamicRoutingDataSource = SpringContextHolder.getBean(DynamicRoutingDataSource.class);
dynamicRoutingDataSource.addDataSource(dataSourceProperty.getPoolName(), dataSource);
}
/**
* 校验数据源配置是否有效
* @param conf 数据源配置信息
* @return 数据源配置是否有效,true表示有效
* @throws RuntimeException 数据库连接失败时抛出异常
*/
@Override
public Boolean checkDataSource(GenDatasourceConf conf) {
String url;
// JDBC 配置形式
if (DsConfTypeEnum.JDBC.getType().equals(conf.getConfType())) {
url = conf.getUrl();
}
else if (DsJdbcUrlEnum.MSSQL.getDbName().equals(conf.getDsType())) {
// 主机形式 sql server 特殊处理
DsJdbcUrlEnum urlEnum = DsJdbcUrlEnum.get(conf.getDsType());
url = String.format(urlEnum.getUrl(), conf.getHost(), conf.getPort(), conf.getDsName());
}
else {
DsJdbcUrlEnum urlEnum = DsJdbcUrlEnum.get(conf.getDsType());
url = String.format(urlEnum.getUrl(), conf.getHost(), conf.getPort(), conf.getDsName());
}
conf.setUrl(url);
try (Connection connection = DriverManager.getConnection(url, conf.getUsername(), conf.getPassword())) {
}
catch (SQLException e) {
log.error("数据源配置 {} , 获取链接失败", conf.getName(), e);
throw new RuntimeException("数据库配置错误,链接失败");
}
return Boolean.TRUE;
}
}
/*
* 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.pig.codegen.service.impl;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pig4cloud.pig.codegen.entity.GenFieldType;
import com.pig4cloud.pig.codegen.mapper.GenFieldTypeMapper;
import com.pig4cloud.pig.codegen.service.GenFieldTypeService;
import org.springframework.stereotype.Service;
import java.util.Set;
import java.util.stream.Collectors;
/**
* 列属性
*
* @author pigx code generator
* @date 2023-02-06 20:16:01
*/
@Service
public class GenFieldTypeServiceImpl extends ServiceImpl<GenFieldTypeMapper, GenFieldType>
implements GenFieldTypeService {
/**
* 根据tableId,获取包列表
* @param dsName 数据源名称
* @param tableName 表名称
* @return 返回包列表
*/
@Override
public Set<String> getPackageByTableId(String dsName, String tableName) {
Set<String> importList = baseMapper.getPackageByTableId(dsName, tableName);
return importList.stream().filter(StrUtil::isNotBlank).collect(Collectors.toSet());
}
}
/*
* 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.pig.codegen.service.impl;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pig4cloud.pig.codegen.entity.GenGroupEntity;
import com.pig4cloud.pig.codegen.entity.GenTemplateGroupEntity;
import com.pig4cloud.pig.codegen.mapper.GenGroupMapper;
import com.pig4cloud.pig.codegen.service.GenGroupService;
import com.pig4cloud.pig.codegen.service.GenTemplateGroupService;
import com.pig4cloud.pig.codegen.util.vo.GroupVO;
import com.pig4cloud.pig.codegen.util.vo.TemplateGroupDTO;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.util.LinkedList;
import java.util.List;
/**
* 模板分组服务实现类
*
* @author lengleng
* @date 2025/05/31
*/
@Slf4j
@Service
@AllArgsConstructor
public class GenGroupServiceImpl extends ServiceImpl<GenGroupMapper, GenGroupEntity> implements GenGroupService {
private final GenTemplateGroupService genTemplateGroupService;
/**
* 保存模板分组信息
* @param genTemplateGroup 模板分组DTO对象,包含分组信息及关联模板ID列表
*/
@Override
public void saveGenGroup(TemplateGroupDTO genTemplateGroup) {
// 1.保存group
GenGroupEntity groupEntity = new GenGroupEntity();
BeanUtil.copyProperties(genTemplateGroup, groupEntity);
baseMapper.insert(groupEntity);
// 2.保存关系
List<GenTemplateGroupEntity> goals = new LinkedList<>();
for (Long TemplateId : genTemplateGroup.getTemplateId()) {
GenTemplateGroupEntity templateGroup = new GenTemplateGroupEntity();
templateGroup.setTemplateId(TemplateId).setGroupId(groupEntity.getId());
goals.add(templateGroup);
}
genTemplateGroupService.saveBatch(goals);
}
/**
* 按照分组ID数组删除分组及其关联模板
* @param ids 分组ID数组
*/
@Override
public void delGroupAndTemplate(Long[] ids) {
// 删除分组
this.removeBatchByIds(CollUtil.toList(ids));
// 删除关系
genTemplateGroupService.remove(Wrappers.<GenTemplateGroupEntity>lambdaQuery()
.in(GenTemplateGroupEntity::getGroupId, CollUtil.toList(ids)));
}
/**
* 根据ID查询组信息
* @param id 组ID
* @return 组信息视图对象
*/
@Override
public GroupVO getGroupVoById(Long id) {
return baseMapper.getGroupVoById(id);
}
/**
* 根据ID更新分组及其关联模板
* @param groupVo 分组VO对象,包含分组ID和模板ID列表
*/
@Override
public void updateGroupAndTemplateById(GroupVO groupVo) {
// 1.更新自身
GenGroupEntity groupEntity = new GenGroupEntity();
BeanUtil.copyProperties(groupVo, groupEntity);
this.updateById(groupEntity);
// 2.更新模板
// 2.1根据id删除之前的模板
genTemplateGroupService.remove(
Wrappers.<GenTemplateGroupEntity>lambdaQuery().eq(GenTemplateGroupEntity::getGroupId, groupVo.getId()));
// 2.2根据ids创建新的模板分组赋值
List<GenTemplateGroupEntity> goals = new LinkedList<>();
for (Long templateId : groupVo.getTemplateId()) {
goals.add(new GenTemplateGroupEntity().setGroupId(groupVo.getId()).setTemplateId(templateId));
}
genTemplateGroupService.saveBatch(goals);
}
}
package com.pig4cloud.pig.codegen.service.impl;
import cn.hutool.core.text.NamingCase;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pig4cloud.pig.codegen.entity.GenFieldType;
import com.pig4cloud.pig.codegen.entity.GenTableColumnEntity;
import com.pig4cloud.pig.codegen.mapper.GenFieldTypeMapper;
import com.pig4cloud.pig.codegen.mapper.GenTableColumnMapper;
import com.pig4cloud.pig.codegen.service.GenTableColumnService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
/**
* 表字段信息管理服务实现类
*
* @author lengleng
* @date 2025/05/31
*/
@Service
@RequiredArgsConstructor
public class GenTableColumnServiceImpl extends ServiceImpl<GenTableColumnMapper, GenTableColumnEntity>
implements GenTableColumnService {
private final GenFieldTypeMapper fieldTypeMapper;
/**
* 初始化表单字段列表,主要是将数据库表中的字段转化为表单需要的字段数据格式,并为审计字段排序
* @param tableFieldList 表单字段列表
*/
public void initFieldList(List<GenTableColumnEntity> tableFieldList) {
// 字段类型、属性类型映射
List<GenFieldType> list = fieldTypeMapper.selectList(Wrappers.emptyWrapper());
Map<String, GenFieldType> fieldTypeMap = new LinkedHashMap<>(list.size());
list.forEach(
fieldTypeMapping -> fieldTypeMap.put(fieldTypeMapping.getColumnType().toLowerCase(), fieldTypeMapping));
// 索引计数器
AtomicInteger index = new AtomicInteger(0);
tableFieldList.forEach(field -> {
// 将字段名转化为驼峰格式
field.setAttrName(NamingCase.toCamelCase(field.getFieldName()));
// 获取字段对应的类型
GenFieldType fieldTypeMapping = fieldTypeMap.getOrDefault(field.getFieldType().toLowerCase(), null);
if (fieldTypeMapping == null) {
// 没找到对应的类型,则为Object类型
field.setAttrType("Object");
}
else {
field.setAttrType(fieldTypeMapping.getAttrType());
field.setPackageName(fieldTypeMapping.getPackageName());
}
// 设置查询类型和表单查询类型都为“=”
field.setQueryType("=");
field.setQueryFormType("text");
// 设置表单类型为文本框类型
field.setFormType("text");
// 保证审计字段最后显示
field.setSort(Objects.isNull(field.getSort()) ? index.getAndIncrement() : field.getSort());
});
}
/**
* 更新指定数据源和表名的表单字段信息
* @param dsName 数据源名称
* @param tableName 表名
* @param tableFieldList 表单字段列表
*/
@Override
public void updateTableField(String dsName, String tableName, List<GenTableColumnEntity> tableFieldList) {
AtomicInteger sort = new AtomicInteger();
this.updateBatchById(tableFieldList.stream().peek(field -> field.setSort(sort.getAndIncrement())).toList());
}
}
/*
* 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.pig.codegen.service.impl;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.text.NamingCase;
import cn.hutool.core.util.EnumUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pig4cloud.pig.codegen.config.PigCodeGenDefaultProperties;
import com.pig4cloud.pig.codegen.entity.GenGroupEntity;
import com.pig4cloud.pig.codegen.entity.GenTable;
import com.pig4cloud.pig.codegen.entity.GenTableColumnEntity;
import com.pig4cloud.pig.codegen.mapper.GenTableMapper;
import com.pig4cloud.pig.codegen.service.GenGroupService;
import com.pig4cloud.pig.codegen.service.GenTableColumnService;
import com.pig4cloud.pig.codegen.service.GenTableService;
import com.pig4cloud.pig.codegen.util.AutoFillEnum;
import com.pig4cloud.pig.codegen.util.BoolFillEnum;
import com.pig4cloud.pig.codegen.util.CommonColumnFiledEnum;
import com.pig4cloud.pig.codegen.util.GenKit;
import lombok.RequiredArgsConstructor;
import org.anyline.metadata.Column;
import org.anyline.metadata.Database;
import org.anyline.metadata.Table;
import org.anyline.proxy.CacheProxy;
import org.anyline.proxy.ServiceProxy;
import org.anyline.service.AnylineService;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Objects;
/**
* 代码生成表服务实现类
*
* @author lengleng
* @date 2025/05/31
*/
@Service
@RequiredArgsConstructor
public class GenTableServiceImpl extends ServiceImpl<GenTableMapper, GenTable> implements GenTableService {
private final PigCodeGenDefaultProperties configurationProperties;
private final GenTableColumnService columnService;
private final GenGroupService genGroupService;
/**
* 查询表ddl 语句
* @param dsName 数据源名称
* @param tableName 表名称
* @return ddl 语句
* @throws Exception
*/
@Override
public String queryTableDdl(String dsName, String tableName) throws Exception {
// 手动切换数据源
DynamicDataSourceContextHolder.push(dsName);
Table table = ServiceProxy.metadata().table(tableName); // 获取表结构
table.execute(false);// 不执行SQL
ServiceProxy.ddl().create(table);
return table.getDdl();// 返回创建表的DDL
}
/**
* 查询表的全部字段
* @param dsName 数据源
* @param tableName 表名称
* @return column
*/
@Override
public List<String> queryTableColumn(String dsName, String tableName) {
// 手动切换数据源
DynamicDataSourceContextHolder.push(dsName);
CacheProxy.clear();
return ServiceProxy.metadata().columns(tableName).values().stream().map(Column::getName).toList();
}
/**
* 查询对应数据源的表
* @param page 分页信息
* @param table 查询条件
* @return 表
*/
@Override
public IPage queryTablePage(Page<Table> page, GenTable table) {
// 手动切换数据源
DynamicDataSourceContextHolder.push(table.getDsName());
CacheProxy.clear();
List<Table> tableList = ServiceProxy.metadata().tables().values().stream().filter(t -> {
if (StrUtil.isBlank(table.getTableName())) {
return true;
}
return StrUtil.containsIgnoreCase(t.getName(false), table.getTableName());
}).toList();
// 根据 page 进行分页
List<Table> records = CollUtil.page((int) page.getCurrent() - 1, (int) page.getSize(), tableList);
page.setTotal(tableList.size());
page.setRecords(records);
return page;
}
/**
* 查询数据源里面的全部表
* @param dsName 数据源名称
* @return table
*/
@Override
public List<String> queryTableList(String dsName) {
// 手动切换数据源
DynamicDataSourceContextHolder.push(dsName);
CacheProxy.clear();
return ServiceProxy.metadata().tables().values().stream().map(Table::getName).toList();
}
/**
* 查询表信息(列),然后插入到中间表中
* @param dsName 数据源
* @param tableName 表名
* @return GenTable
*/
@Override
public GenTable queryOrBuildTable(String dsName, String tableName) {
GenTable genTable = baseMapper.selectOne(
Wrappers.<GenTable>lambdaQuery().eq(GenTable::getTableName, tableName).eq(GenTable::getDsName, dsName));
// 如果 genTable 为空, 执行导入
if (Objects.isNull(genTable)) {
genTable = this.tableImport(dsName, tableName);
}
List<GenTableColumnEntity> fieldList = columnService.list(Wrappers.<GenTableColumnEntity>lambdaQuery()
.eq(GenTableColumnEntity::getDsName, dsName)
.eq(GenTableColumnEntity::getTableName, tableName)
.orderByAsc(GenTableColumnEntity::getSort));
genTable.setFieldList(fieldList);
// 查询模板分组信息
List<GenGroupEntity> groupEntities = genGroupService.list();
genTable.setGroupList(groupEntities);
return genTable;
}
/**
* 导入表结构并生成代码配置
* @param dsName 数据源名称
* @param tableName 表名
* @return 生成的表配置信息
* @Transactional 启用事务,遇到异常时回滚
*/
@Transactional(rollbackFor = Exception.class)
protected GenTable tableImport(String dsName, String tableName) {
// 手动切换数据源
DynamicDataSourceContextHolder.push(dsName);
// 查询表是否存在
GenTable table = new GenTable();
// 从数据库获取表信息
CacheProxy.clear();
AnylineService service = ServiceProxy.service();
Table tableMetadata = service.metadata().table(tableName);
Database database = service.metadata().database();
// 获取默认表配置信息 ()
table.setPackageName(configurationProperties.getPackageName());
table.setVersion(configurationProperties.getVersion());
table.setBackendPath(configurationProperties.getBackendPath());
table.setFrontendPath(configurationProperties.getFrontendPath());
table.setAuthor(configurationProperties.getAuthor());
table.setEmail(configurationProperties.getEmail());
table.setTableName(tableName);
table.setDsName(dsName);
table.setTableComment(tableMetadata.getComment());
table.setDbType(database.getDatabase().title());
table.setFormLayout(configurationProperties.getFormLayout());
table.setGeneratorType(configurationProperties.getGeneratorType());
table.setClassName(NamingCase.toPascalCase(tableName));
// 模块名称默认为 admin
table.setModuleName(configurationProperties.getModuleName());
table.setFunctionName(GenKit.getFunctionName(tableName));
table.setCreateTime(LocalDateTime.now());
// 使用默认数据源
DynamicDataSourceContextHolder.clear();
this.save(table);
// 获取原生字段数据
List<GenTableColumnEntity> tableFieldList = getGenTableColumnEntities(dsName, tableName, tableMetadata);
// 初始化字段数据
columnService.initFieldList(tableFieldList);
// 保存列数据
columnService.saveOrUpdateBatch(tableFieldList);
table.setFieldList(tableFieldList);
return table;
}
/**
* 获取表字段信息
* @param dsName 数据源信息
* @param tableName 表名称
* @param tableMetadata 表的元数据
* @return list
*/
private static @NotNull List<GenTableColumnEntity> getGenTableColumnEntities(String dsName, String tableName,
Table tableMetadata) {
List<GenTableColumnEntity> tableFieldList = new ArrayList<>();
LinkedHashMap<String, Column> columns = tableMetadata.getColumns();
columns.forEach((columnName, column) -> {
GenTableColumnEntity genTableColumnEntity = new GenTableColumnEntity();
genTableColumnEntity.setTableName(tableName);
genTableColumnEntity.setDsName(dsName);
genTableColumnEntity.setFieldName(column.getName());
genTableColumnEntity.setFieldComment(column.getComment());
genTableColumnEntity.setFieldType(column.getTypeName());
genTableColumnEntity.setPrimaryPk(
column.isPrimaryKey() == 1 ? BoolFillEnum.TRUE.getValue() : BoolFillEnum.FALSE.getValue());
genTableColumnEntity.setAutoFill(AutoFillEnum.DEFAULT.name());
genTableColumnEntity.setFormItem(BoolFillEnum.TRUE.getValue());
genTableColumnEntity.setGridItem(BoolFillEnum.TRUE.getValue());
// 审计字段处理
if (EnumUtil.contains(CommonColumnFiledEnum.class, column.getName())) {
CommonColumnFiledEnum commonColumnFiledEnum = CommonColumnFiledEnum.valueOf(column.getName());
genTableColumnEntity.setFormItem(commonColumnFiledEnum.getFormItem());
genTableColumnEntity.setGridItem(commonColumnFiledEnum.getGridItem());
genTableColumnEntity.setAutoFill(commonColumnFiledEnum.getAutoFill());
genTableColumnEntity.setSort(commonColumnFiledEnum.getSort());
}
tableFieldList.add(genTableColumnEntity);
});
return tableFieldList;
}
}
/*
* 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.pig.codegen.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pig4cloud.pig.codegen.entity.GenTemplateGroupEntity;
import com.pig4cloud.pig.codegen.mapper.GenTemplateGroupMapper;
import com.pig4cloud.pig.codegen.service.GenTemplateGroupService;
import org.springframework.stereotype.Service;
/**
* 模板分组关联表服务实现类
*
* @author lengleng
* @date 2025/05/31
*/
@Service
public class GenTemplateGroupServiceImpl extends ServiceImpl<GenTemplateGroupMapper, GenTemplateGroupEntity>
implements GenTemplateGroupService {
}
package com.pig4cloud.pig.codegen.util;
/**
* 字段自动填充 枚举
*
* @author 阿沐 babamu@126.com
*/
public enum AutoFillEnum {
DEFAULT, INSERT, UPDATE, INSERT_UPDATE, CREATE;
}
package com.pig4cloud.pig.codegen.util;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
/**
* boolean 类型枚举
*
*/
@Getter
@RequiredArgsConstructor
public enum BoolFillEnum {
/**
* true
*/
TRUE("1"),
/**
* false
*/
FALSE("0");
private final String value;
}
package com.pig4cloud.pig.codegen.util;
import lombok.AllArgsConstructor;
import lombok.Getter;
/**
* @author lengleng
* @date 2023/3/12
* <p>
* 通用字段的填充策略和显示策略
*/
@Getter
@AllArgsConstructor
public enum CommonColumnFiledEnum {
/**
* create_by 字段
*/
create_by("0", "0", AutoFillEnum.INSERT.name(), 100),
/**
* create_time 字段
*/
create_time("0", "0", AutoFillEnum.INSERT.name(), 101),
/**
* update_by 字段
*/
update_by("0", "0", AutoFillEnum.INSERT_UPDATE.name(), 102),
/**
* update_time 字段
*/
update_time("0", "0", AutoFillEnum.INSERT_UPDATE.name(), 103),
/**
* del_flag 字段
*/
del_flag("0", "0", AutoFillEnum.DEFAULT.name(), 104),
/**
* tenant_id 字段
*/
tenant_id("0", "0", AutoFillEnum.DEFAULT.name(), 105);
/**
* 表单是否默认显示 1/0
*/
private String formItem;
/**
* 表格是否默认显示 1/0
*/
private String gridItem;
/**
* 自动填充策略
*/
private String autoFill;
/**
* 排序值
*/
private Integer sort;
}
package com.pig4cloud.pig.codegen.util;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import java.util.HashSet;
import java.util.List;
/**
* 字典工具类:提供字典相关操作的工具方法
*
* @author lengleng
* @date 2025/05/31
*/
public class DictTool {
/**
* 将字段列表转换为带有双引号的逗号分隔的字符串
* @return 带有双引号的逗号分隔的字符串
*/
public static String quotation(List<String> fields) {
return CollUtil.join(new HashSet<>(fields), StrUtil.COMMA, s -> String.format("'%s'", s));
}
/**
* 将字段列表转换为逗号分隔的字符串
* @return 逗号分隔的字符串
*/
public static String format(List<String> fields) {
return CollUtil.join(new HashSet<>(fields), StrUtil.COMMA);
}
}
<?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.pig.codegen.mapper.GenTemplateGroupMapper">
<resultMap id="genTemplateGroupMap" type="com.pig4cloud.pig.codegen.entity.GenTemplateGroupEntity">
<id property="groupId" column="group_id"/>
<id property="templateId" column="template_id"/>
</resultMap>
</mapper>
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment