“陈双凤” 12 months ago
parent a776ed1298
commit 769a3a061f

@ -0,0 +1,49 @@
######################################################################
# Build Tools
.gradle
/build/
!gradle/wrapper/gradle-wrapper.jar
target/
!.mvn/wrapper/maven-wrapper.jar
######################################################################
# IDE
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### JRebel ###
rebel.xml
### NetBeans ###
nbproject/private/
build/*
nbbuild/
dist/
nbdist/
.nb-gradle/
.node-moudles/
######################################################################
# Others
*.log
*.xml.versionsBackup
*.swp
!*/build/*.java
!*/build/*.html
!*/build/*.xml

@ -0,0 +1,27 @@
# 代码生成器
#### 前言:
自研代码生成器注意使用时需要依赖redis存储数据需要修改配置文件中的模板文件地址且在xml多表联查生成时存在小问题然后就是vue-elementui-admin这个模板的前端依赖下载可能出现问题。
#### csdn等项目下载链接
## [点击前往](http://transfer.azhou.cloud/)
## http://transfer.azhou.cloud/
#### 介绍
技术栈:
- 后端SpringBoot
- 前端Vue
存储:
- Redis

@ -0,0 +1,19 @@
# azhou-code-plugins
## Project setup
```
npm install
```
### Compiles and hot-reloads for development
```
npm run serve
```
### Compiles and minifies for production
```
npm run build
```
### Customize configuration
See [Configuration Reference](https://cli.vuejs.org/config/).

@ -0,0 +1,5 @@
module.exports = {
presets: [
'@vue/cli-plugin-babel/preset'
]
}

File diff suppressed because it is too large Load Diff

@ -0,0 +1,32 @@
{
"name": "azhou-code-plugins",
"version": "0.1.0",
"private": true,
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build"
},
"dependencies": {
"axios": "^0.24.0",
"core-js": "^3.6.5",
"element-ui": "^2.4.5",
"vue": "^2.6.11",
"vue-router": "^3.2.0",
"vuex": "^3.4.0"
},
"devDependencies": {
"@vue/cli-plugin-babel": "~4.5.0",
"@vue/cli-plugin-router": "~4.5.0",
"@vue/cli-plugin-vuex": "~4.5.0",
"@vue/cli-service": "~4.5.0",
"node-sass": "^4.9.2",
"sass-loader": "^7.0.3",
"vue-cli-plugin-element": "~1.0.1",
"vue-template-compiler": "^2.6.11"
},
"browserslist": [
"> 1%",
"last 2 versions",
"not dead"
]
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.2 KiB

@ -0,0 +1,17 @@
<!DOCTYPE html>
<html lang="">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<link rel="icon" href="<%= BASE_URL %>favicon.ico">
<title><%= htmlWebpackPlugin.options.title %></title>
</head>
<body>
<noscript>
<strong>We're sorry but <%= htmlWebpackPlugin.options.title %> doesn't work properly without JavaScript enabled. Please enable it to continue.</strong>
</noscript>
<div id="app"></div>
<!-- built files will be auto injected -->
</body>
</html>

@ -0,0 +1,19 @@
<template>
<div id="app">
<router-view></router-view>
</div>
</template>
<script>
export default {
name: 'app',
}
</script>
<style>
#app {
margin: 50px auto;
max-width: 1200px;
}
</style>

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.7 KiB

@ -0,0 +1,194 @@
<template>
<div class="">
<el-dialog
:close-on-click-modal="false"
:close-on-press-escape="false"
title="提示"
:visible.sync="myDialogVisible"
width="50%"
>
<TableFromHeader lable="选择子表" :show-name="false" @changeColData="changeColData"></TableFromHeader>
<el-form>
<el-form-item label="当前主表">{{ tableName + " " + toHump(tableName)}}</el-form-item>
<el-form-item label="关联关系(例left join sys_user_role sysUserRole.userId = sysType.id)">
<el-input v-model="correlation"></el-input>
</el-form-item>
</el-form>
<el-table
:data="tableData.tableColEntityList"
style="width: 100%;max-height: 400px;overflow: auto">
<el-table-column align="center"
prop="colName"
label="列名称"
width="150">
</el-table-column>
<el-table-column align="center"
prop="chinaName"
label="展示中文名"
width="150">
<template slot-scope="scope">
<el-input v-model="scope.row.chinaName" placeholder="请输入内容"></el-input>
</template>
</el-table-column>
<el-table-column
align="center"
prop="date"
label="属性类型"
width="150">
<template slot-scope="scope">
<el-select v-model="scope.row.paramType" placeholder="请选择">
<el-option
v-for="item in paramType"
:key="item.value"
:label="item.value"
:value="item.value">
</el-option>
</el-select>
</template>
</el-table-column>
<el-table-column
align="center"
prop="name"
label="查询配置"
width="120">
<template slot-scope="scope">
<el-select v-model="scope.row.compareType" placeholder="请选择">
<el-option
v-for="item in compareType"
:key="item.value"
:label="item.value"
:value="item.value">
</el-option>
</el-select>
</template>
</el-table-column>
<el-table-column label="搜索" width="80" align="center">
<template slot-scope="scope">
<el-checkbox v-model="scope.row.searchShow"></el-checkbox>
</template>
</el-table-column>
<el-table-column label="主表表格展示" width="80" align="center">
<template slot-scope="scope">
<el-checkbox v-model="scope.row.tableShow"></el-checkbox>
</template>
</el-table-column>
<el-table-column
align="center"
prop="name"
label="显示类型"
width="120">
<template slot-scope="scope">
<el-select v-model="scope.row.showType" placeholder="请选择">
<el-option
v-for="item in showType"
:key="item.value"
:label="item.label"
:value="item.value">
</el-option>
</el-select>
</template>
</el-table-column>
</el-table>
<span slot="footer">
<el-button @click="close"> </el-button>
<el-button type="primary" @click="sonSure"> </el-button>
</span>
</el-dialog>
</div>
</template>
<script>
import TableFromHeader from "./TableFromHeader";
import {message} from "../util/notice";
export default {
name: 'AddSonTable',
components: {TableFromHeader},
props: {
colData: {
type: Object,
default: {}
},
dialogVisible: {
type: Boolean,
default: false
},
tableName: {
type: String,
default: ""
},
},
watch: {
dialogVisible: {
handler: function (newV, oldV) {
this.myDialogVisible = newV
}
}
},
data() {
return {
tableData: {
tableComment: "",
tableName: '',
tableColEntityList: [],
},
myDialogVisible: false,
//
correlation: '',
paramType: [
{value: "String"},
{value: "Boolean"},
{value: "Long"},
{value: "Integer"}
],
showType: [
{label: "文本", value: 'text'},
{label: "开关", value: 'switch'},
{label: "枚举", value: 'enum'},
{label: "图片", value: 'image'}
],
compareType: [
{value: "="},
{value: "like"},
{value: "eq"},
{value: "nt"}
],
}
},
methods: {
close() {
this.$emit("dismissDialog", {});
},
changeColData(obj) {
console.log(obj)
if (obj.name == this.tableName) {
message("子表不能与主表一致", "error")
this.tableData = {}
return;
}
this.tableData = obj.res;
this.tableData.tableName = obj.name
this.correlation = "left join " + this.tableData.tableName + " " + this.toHump(this.tableData.tableName) + " on " + this.toHump(this.tableData.tableName) + "."
},
sonSure() {
this.myDialogVisible = false
let param = {}
param.tableData = this.tableData;
param.correlation = this.correlation
this.$emit("addSonTableList", param)
this.tableData = []
this.correlation = ""
},
toHump(name) {
return name.replace(/\_(\w)/g, function (all, letter) {
return letter.toUpperCase();
});
}
}
}
</script>
<style scoped>
</style>

@ -0,0 +1,59 @@
<template>
<div class="hello">
<h1>{{ msg }}</h1>
<p>
For a guide and recipes on how to configure / customize this project,<br>
check out the
<a href="https://cli.vuejs.org" target="_blank" rel="noopener">vue-cli documentation</a>.
</p>
<h3>Installed CLI Plugins</h3>
<ul>
<li><a href="https://github.com/vuejs/vue-cli/tree/dev/packages/%40vue/cli-plugin-babel" target="_blank" rel="noopener">babel</a></li>
<li><a href="https://github.com/vuejs/vue-cli/tree/dev/packages/%40vue/cli-plugin-router" target="_blank" rel="noopener">router</a></li>
<li><a href="https://github.com/vuejs/vue-cli/tree/dev/packages/%40vue/cli-plugin-vuex" target="_blank" rel="noopener">vuex</a></li>
</ul>
<h3>Essential Links</h3>
<ul>
<li><a href="https://vuejs.org" target="_blank" rel="noopener">Core Docs</a></li>
<li><a href="https://forum.vuejs.org" target="_blank" rel="noopener">Forum</a></li>
<li><a href="https://chat.vuejs.org" target="_blank" rel="noopener">Community Chat</a></li>
<li><a href="https://twitter.com/vuejs" target="_blank" rel="noopener">Twitter</a></li>
<li><a href="https://news.vuejs.org" target="_blank" rel="noopener">News</a></li>
</ul>
<h3>Ecosystem</h3>
<ul>
<li><a href="https://router.vuejs.org" target="_blank" rel="noopener">vue-router</a></li>
<li><a href="https://vuex.vuejs.org" target="_blank" rel="noopener">vuex</a></li>
<li><a href="https://github.com/vuejs/vue-devtools#vue-devtools" target="_blank" rel="noopener">vue-devtools</a></li>
<li><a href="https://vue-loader.vuejs.org" target="_blank" rel="noopener">vue-loader</a></li>
<li><a href="https://github.com/vuejs/awesome-vue" target="_blank" rel="noopener">awesome-vue</a></li>
</ul>
</div>
</template>
<script>
export default {
name: 'HelloWorld',
props: {
msg: String
}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h3 {
margin: 40px 0 0;
}
ul {
list-style-type: none;
padding: 0;
}
li {
display: inline-block;
margin: 0 10px;
}
a {
color: #42b983;
}
</style>

@ -0,0 +1,97 @@
<template>
<div class="">
<el-form inline>
<el-form-item :label="lable">
<el-select v-model="tableName" placeholder="请选择" @change="getTableColList" >
<el-option
v-for="item in tableNameData"
:key="item.value"
:label="item.value"
:value="item.value">
<span style="float: left">{{ item.value }}</span>
<span style="float: right; color: #8492a6; font-size: 13px">{{ item.label }}</span>
</el-option>
</el-select>
</el-form-item>
<el-form-item label="页面展示名:" v-if="showName">
<el-input v-model="tableComment" @change="changeTableName"></el-input>
</el-form-item>
</el-form>
</div>
</template>
<script>
import {get} from "../util/http";
import {message} from "../util/notice";
export default {
name: 'TableFromHeader',
props:{
lable: {
type: String,
default: "表名称"
},
showName: {
type: Boolean,
default: true
}
},
data() {
return {
random: '',
tableNameData: [],
tableName: '',
tableComment: ''
}
},
mounted() {
let random = localStorage.getItem("random");
if (!random) {
message("数据库连接信息有误,请重新配置", "error");
this.goHome();
return;
}
this.random = random;
this.getAllTable();
},
methods: {
getTableColList() {
var url = "/db/getTableColList/" + this.tableName + "/" + this.random;
get(url).then(res => {
if (res) {
var name = this.tableName;
this.$emit("changeColData", {res,name});
}
})
},
changeTableName(){
var name = this.tableComment;
this.$emit("changeTableName", {name});
},
goHome() {
this.$router.push("/");
},
getAllTable() {
var url = "/db/getAllTable/" + this.random;
get(url).then(res => {
var arr = res;
if (arr && arr.length > 0) {
var tableNameArr = [];
for (var i = 0; i < arr.length; i++) {
var param = {};
param.value = arr[i];
param.label = "未配置";
tableNameArr.push(param);
}
this.tableNameData = tableNameArr;
}
})
}
}
}
</script>
<style scoped>
</style>

@ -0,0 +1,11 @@
/*
Write your variables here. All available variables can be
found in element-ui/packages/theme-chalk/src/common/var.scss.
For example, to overwrite the theme color:
*/
$--color-primary: teal;
/* icon font path, required */
$--font-path: '~element-ui/lib/theme-chalk/fonts';
@import "~element-ui/packages/theme-chalk/src/index";

@ -0,0 +1,13 @@
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import './plugins/element.js'
Vue.config.productionTip = false
new Vue({
router,
store,
render: h => h(App)
}).$mount('#app')

@ -0,0 +1,5 @@
import Vue from 'vue'
import Element from 'element-ui'
import '../element-variables.scss'
Vue.use(Element)

@ -0,0 +1,29 @@
import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
Vue.use(VueRouter)
const routes = [
{
path: '/',
name: 'Home',
component: Home
},
{
path: '/about',
name: 'About',
component: () => import('../views/About.vue')
},
{
path: '/table',
name: 'Table',
component: () => import( '../views/Table.vue')
}
]
const router = new VueRouter({
routes
})
export default router

@ -0,0 +1,15 @@
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
},
mutations: {
},
actions: {
},
modules: {
}
})

@ -0,0 +1,72 @@
import axios from 'axios';
import router from '../router';
axios.defaults.timeout = 5000; //超市时间是5秒
axios.defaults.withCredentials = true; //允许跨域
//Content-Type 响应头
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';
//基础url
axios.defaults.baseURL = "http://localhost:8888/";
axios.interceptors.request.use(config => {
return config;
});
//响应拦截器
axios.interceptors.response.use(
response => {
console.log(response.data)
//如果reponse里面的status是200说明访问到接口了否则错误
if(response.data.code == 200){
return Promise.resolve(response.data);
}else{
return Promise.reject(response.data);
}
},
error => {
if(error.response.data.code){
switch(error.response.data.code){
case 401: //未登录
router.replace({
path:'/',
query:{
redirect: router.currentRoute.fullPath
}
});
break;
case 404: //没找到
break;
}
return Promise.reject(error.response);
}
}
);
/**
* 封装get方法
*/
export function get(url,params={}){
return new Promise((resolve,reject) => {
axios.get(url,{params:params})
.then(response =>{
resolve(response.data);
})
.catch(err =>{
reject(err);
})
});
}
/**
* 封装post方法
*/
export function post(url,data={}){
return new Promise((resolve,reject) => {
axios.post(url,data)
.then(response =>{
resolve(response.data);
})
.catch(err =>{
reject(err);
})
});
}

@ -0,0 +1,16 @@
import {Message } from 'element-ui'
import { Notification } from 'element-ui';
export function message(title, type) {
Message ({
message: title,
type: type ? type : 'success',
})
}
// export function notice(title, type) {
// Message ({
// message: title,
// type: type ? type : 'success',
// })
// }

@ -0,0 +1,5 @@
<template>
<div class="about">
<h1>This is an about page</h1>
</div>
</template>

@ -0,0 +1,206 @@
<template>
<div class="home">
<el-form
ref="sqlForm"
:model="sqlForm"
status-icon
:rules="rules"
label-width="120px">
<el-form-item label="项目端口" prop="port">
<el-input
v-model="sqlForm.port"
autocomplete="off"
></el-input>
</el-form-item>
<el-form-item label="数据库IP" prop="ip">
<el-input
v-model="sqlForm.ip"
autocomplete="off"
></el-input>
</el-form-item>
<el-form-item label="数据库端口" prop="dbPort">
<el-input
v-model="sqlForm.dbPort"
autocomplete="off"
></el-input>
</el-form-item>
<el-form-item label="用户名" prop="username">
<el-input v-model="sqlForm.username"></el-input>
</el-form-item>
<el-form-item label="密码" prop="password">
<el-input v-model="sqlForm.password"></el-input>
</el-form-item>
<el-form-item label="数据库名称" prop="dbName">
<el-input v-model="sqlForm.dbName"></el-input>
</el-form-item>
<el-form-item label="表名称" prop="tableName">
<el-input v-model="sqlForm.tableName" placeholder="表与表之间用#隔开"></el-input>
</el-form-item>
<el-form-item label="自定义登录">
<el-switch
v-model="sqlForm.hasLogin"
active-text="是"
inactive-text="否">
</el-switch>
</el-form-item>
<div v-if="sqlForm.hasLogin">
<el-form-item label="用户表">
<el-input v-model="sqlForm.loginParam.tableName" placeholder="用户表"></el-input>
</el-form-item>
<el-form-item label="账号字段">
<el-input v-model="sqlForm.loginParam.userNameCol"
placeholder="注:请填写get字段后面的值,例getUserName => UserName"></el-input>
</el-form-item>
<el-form-item label="密码字段">
<el-input v-model="sqlForm.loginParam.passWordCol" placeholder="密码字段"></el-input>
</el-form-item>
</div>
<el-form-item label="自定义用户信息">
<el-switch
v-model="sqlForm.loginParam.hasUserInfo"
active-text="是"
inactive-text="否">
</el-switch>
</el-form-item>
<div v-if="sqlForm.loginParam.hasUserInfo">
<el-form-item label="展示姓名字段">
<el-input v-model="sqlForm.loginParam.nickNameCol" placeholder="注:请填写get字段后面的值,例getUserName => UserName"></el-input>
</el-form-item>
<el-form-item label="展示头像字段">
<el-input v-model="sqlForm.loginParam.headImgCol" placeholder="注:请填写get字段后面的值,例getUserName => UserName"></el-input>
</el-form-item>
</div>
<el-form-item label="图片文件上传">
<el-switch
v-model="sqlForm.hasUploadImg"
active-text="是"
inactive-text="否">
</el-switch>
</el-form-item>
<div v-if="sqlForm.hasUploadImg">
<el-form-item label="上传地址">
<el-input v-model="sqlForm.uploadUrl" placeholder="本机图片地址服务器的webapp绝对路径"></el-input>
</el-form-item>
</div>
<el-form-item label="reids">
<el-switch
v-model="sqlForm.hasRedis"
active-text="是"
inactive-text="否">
</el-switch>
</el-form-item>
<div v-if="sqlForm.hasRedis">
<el-form-item label="redisIp">
<el-input v-model="sqlForm.redisIp"></el-input>
</el-form-item>
<el-form-item label="redis端口">
<el-input v-model="sqlForm.redisPort"></el-input>
</el-form-item>
<el-form-item label="redis密码">
<el-input v-model="sqlForm.redisPassWord"></el-input>
</el-form-item>
</div>
<el-form-item label="email发送">
<el-switch
v-model="sqlForm.hasEmail"
active-text="是"
inactive-text="否">
</el-switch>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="submitForm('sqlForm')"></el-button>
<el-button @click="resetForm('sqlForm')"></el-button>
</el-form-item>
</el-form>
</div>
</template>
<script>
import {post} from "../util/http";
import {message} from "../util/notice";
export default {
name: 'Home',
data() {
return {
sqlForm: {
port: '8001',
hasEmail: false,
hasRedis: false,
hasUploadImg: true,
ip: '81.69.235.149',
dbPort: '3306',
username: 'root',
password: 'azhou',
dbName: 'wxchat',
tableName: 'admin#article#article_urls#comments#user_likes#wx_user',
redisIp: '127.0.0.1',
redisPort: '6379',
redisPassWord: '',
uploadUrl: 'F:\\\\zt\\\\software\\\\tomcat-8.5-win64\\\\apache-tomcat-8.5.68\\\\webapps',
hasLogin: true,
loginParam: {
tableName: 'admin',
userNameCol: 'UserName',
passWordCol: 'PassWord',
hasUserInfo: true,
headImgCol: 'HeadImg',
nickNameCol: "NickName"
}
},
rules: {
ip: [{
required: true,
message: '请输入数据库IP地址',
trigger: 'blur'
}],
dbPort: [{
required: true,
message: '请输入数据库端口',
trigger: 'blur'
}],
username: [{
required: true,
message: '请输入数据库用户名',
trigger: 'blur'
}],
password: [{
required: true,
message: '请输入数据库密码',
trigger: 'blur'
}],
dbName: [{
required: true,
message: '请输入数据库名称',
trigger: 'blur'
}],
tableName: [{
required: true,
message: '请输入数据库名称',
trigger: 'blur'
}],
},
}
},
methods: {
submitForm(formName) {
this.$refs[formName].validate((valid) => {
if (valid) {
post("/db/checkDBParam", this.sqlForm).then(res => {
localStorage.setItem("random", res);
message("数据库连接成功");
this.$router.push("/table");
})
} else {
console.log('error submit!!')
return false
}
})
},
resetForm(formName) {
this.$refs[formName].resetFields()
},
},
}
</script>

@ -0,0 +1,500 @@
<template>
<div class="table">
<h2 class="title">数据库表配置</h2>
<TableFromHeader @changeColData="changeColData" @changeTableName="changeTableName"></TableFromHeader>
<el-button type="text" @click="add()"></el-button>
<el-table
:data="tableData.tableColEntityList"
style="width: 100%;max-height: 600px;overflow: auto">
<el-table-column align="center"
prop="colName"
label="列名称"
width="150">
</el-table-column>
<el-table-column align="center"
prop="chinaName"
label="展示中文名"
width="150">
<template slot-scope="scope">
<el-input v-model="scope.row.chinaName" placeholder="请输入内容"></el-input>
</template>
</el-table-column>
<el-table-column
align="center"
prop="date"
label="属性类型"
width="150">
<template slot-scope="scope">
<el-select v-model="scope.row.paramType" placeholder="请选择">
<el-option
v-for="item in paramType"
:key="item.value"
:label="item.value"
:value="item.value">
</el-option>
</el-select>
</template>
</el-table-column>
<el-table-column
align="center"
prop="name"
label="查询配置"
width="120">
<template slot-scope="scope">
<el-select v-model="scope.row.compareType" placeholder="请选择">
<el-option
v-for="item in compareType"
:key="item.value"
:label="item.value"
:value="item.value">
</el-option>
</el-select>
</template>
</el-table-column>
<el-table-column label="搜索" width="80" align="center">
<template slot-scope="scope">
<el-checkbox v-model="scope.row.searchShow"></el-checkbox>
</template>
</el-table-column>
<el-table-column label="表格展示" width="80" align="center">
<template slot-scope="scope">
<el-checkbox v-model="scope.row.tableShow"></el-checkbox>
</template>
</el-table-column>
<el-table-column
align="center"
prop="name"
label="显示类型"
width="120">
<template slot-scope="scope">
<el-select v-model="scope.row.showType" @change="tableTypeChange(scope.row)" placeholder="请选择">
<el-option
v-for="item in showType"
:key="item.value"
:label="item.label"
:value="item.value">
</el-option>
</el-select>
</template>
</el-table-column>
<el-table-column label="编辑展示" width="80" align="center">
<template slot-scope="scope">
<el-checkbox v-model="scope.row.updateShow"></el-checkbox>
</template>
</el-table-column>
<el-table-column
align="center"
prop="name"
label="编辑类型"
width="120">
<template slot-scope="scope">
<el-select v-model="scope.row.updateType" @change="updateTypeChange(scope.row)" placeholder="请选择">
<el-option
v-for="item in updateType"
:key="item.value"
:label="item.label"
:value="item.value">
</el-option>
</el-select>
</template>
</el-table-column>
<el-table-column label="图片上传" width="80" align="center">
<template slot-scope="scope">
<el-checkbox v-model="scope.row.uploadImg"></el-checkbox>
</template>
</el-table-column>
</el-table>
<div class="my-button">
<el-button @click="goHome"></el-button>
<el-button @click="submitMainFrom"></el-button>
</div>
<div>
<el-select v-model="type" @change="updateModuleType" placeholder="请选择">
<el-option
v-for="item in updateModuleTypeArr"
:key="item.value"
:label="item.label"
:value="item.value">
</el-option>
</el-select>
</div>
<div class="my-button">
<el-button @click="generateCode" type="success">生成代码</el-button>
</div>
<AddSonTable :dialogVisible=addSonTableDialog @dismissDialog="close" :col-data="currentColData"
:table-name="tableData.tableName" @addSonTableList="addSonTableList"></AddSonTable>
<el-dialog
title="数据来源"
:visible.sync="dialogVisible"
width="50%"
>
<TableFromHeader :showName="false" @changeColData="selectColName"></TableFromHeader>
<el-form>
<el-form-item label="字段">
<el-select v-model="dataSource.tableFiled" @change="updateFileChange" placeholder="请选择">
<el-option
v-for="item in colName"
:key="item.colName"
:label="item.colName"
:value="item.colName">
</el-option>
</el-select>
</el-form-item>
</el-form>
<span slot="footer" class="dialog-footer">
<el-button @click="dialogVisible = false"> </el-button>
<el-button type="primary" @click="dialogVisible = false"> </el-button>
</span>
</el-dialog>
<el-dialog
title="下拉选择配置"
:close-on-click-modal="false"
:close-on-press-escape="false"
:visible.sync="selectDialogVisible"
width="50%">
<el-form :model="selectDataParam" label-width="100px" inline>
<TableFromHeader @changeColData="changeSwitchTableName" lable="数据来源表" :showName="false"></TableFromHeader>
<el-form-item label="name列">
<el-select v-model="selectDataParam.nameCol" @change="updateFileChange" placeholder="请选择">
<el-option
v-for="item in selectDataFromTableCol"
:key="item.colName"
:label="item.chinaName"
:value="item.colName">
</el-option>
</el-select>
</el-form-item>
<el-form-item label="value列">
<el-select v-model="selectDataParam.valueCol" @change="updateFileChange" placeholder="请选择">
<el-option
v-for="item in selectDataFromTableCol"
:key="item.colName"
:label="item.chinaName"
:value="item.colName">
</el-option>
</el-select>
</el-form-item>
</el-form>
<span slot="footer" class="dialog-footer">
<el-button @click="selectDialogVisible = false"> </el-button>
<el-button type="primary" @click="submitSelectForm"> </el-button>
</span>
</el-dialog>
<el-dialog
:close-on-click-modal="false"
:close-on-press-escape="false"
title="枚举来源"
:visible.sync="dialogEnumVisible" width="50%">
<el-form :model="addEnumForm" ref="addEnumForm" label-width="100px" inline>
<div v-for="(domain, index) in addEnumForm.enums">
<el-form-item
:label="'枚举值-' + index"
:key="domain.key"
:prop="'enums.' + index + '.name'"
:rules="{
required: true, message: '枚举key不能为空', trigger: 'blur'}">
<el-input v-model="domain.name"></el-input>
</el-form-item>
<el-form-item
:label="'中文解释-' + index"
:key="domain.key1"
:prop="'enums.' + index + '.value'"
:rules="{required: true, message: '枚举value不能为空', trigger: 'blur'}">
<el-input v-model="domain.value"></el-input>
</el-form-item>
<el-button @click.prevent="removeDomain(domain)">删除</el-button>
</div>
<el-form-item>
<el-button @click="addDomain"></el-button>
<el-button @click="resetForm('addEnumForm')"></el-button>
</el-form-item>
</el-form>
<span slot="footer" class="dialog-footer">
<el-button @click="dialogEnumVisible = false"> </el-button>
<el-button type="primary" @click="submitForm('addEnumForm')"> </el-button>
</span>
</el-dialog>
</div>
</template>
<script>
import {message} from "../util/notice";
import {get, post} from "../util/http";
import AddSonTable from "../components/AddSonTable";
import TableFromHeader from "../components/TableFromHeader";
export default {
components: {AddSonTable, TableFromHeader},
data() {
return {
random: '',
paramType: [
{value: "String"},
{value: "Boolean"},
{value: "Long"},
{value: "Integer"}
],
compareType: [
{value: "="},
{value: "like"},
{value: "eq"},
{value: "nt"}
],
showType: [
{label: "文本", value: 'text'},
{label: "枚举", value: 'enum'},
{label: "图片", value: 'image'}
],
updateModuleTypeArr: [
{label: "vue-element-admin", value: '1'},
{label: "vue", value: '2'},
{label: "layui+html", value: '3'}
],
type: 1,
updateType: [
{label: "文本", value: 'text'},
{label: "开关", value: 'switch'},
{label: "枚举", value: 'enum'},//
{label: "下拉选择", value: 'select'},
{label: "数字", value: 'number'},
{label: "日期选择", value: 'date'},
{label: "文本域", value: 'textArea'},
],
tableData: {
tableComment: "",
tableName: '',
tableColEntityList: [],
sonTableEntities: [],
enumsEntities: [],
selectEntities: [],
tableEnumsEntities: []
},
correlationList: [],
sonTableEntities: [],
addSonTableDialog: false,
//
currentColData: {},
dialogVisible: false,
dialogEnumVisible: false,
selectDialogVisible: false,
colName: [],
//
dataSource: {
tableName: '',
tableFiled: ''
},
addEnumForm: {
enums: [{
name: '',
value: ''
}]
},
currentCol: '',//
//
addSwitchForm: {},
//
selectDataFromTableCol: [],
selectDataParam: {
fromTableName: '',
nameCol: '',
valueCol: ''
}
}
},
mounted() {
let random = localStorage.getItem("random");
if (!random) {
message("数据库连接信息有误,请重新配置", "error");
this.goHome();
return;
}
this.random = random;
},
methods: {
goHome() {
this.$router.push("/");
},
close(obj) {
this.addSonTableDialog = false;
},
add() {
if (this.tableData.tableColEntityList.length <= 0) {
message("请先选择主表!", "error")
return
}
this.addSonTableDialog = true
},
changeColData(obj) {
this.tableData = []
this.tableData = obj.res;
this.tableData.tableName = obj.name;
},
changeTableName(obj) {
this.tableData.tableComment = obj.name;
},
changeSwitchTableName(obj) {
this.selectDataParam.fromTableName = obj.name
this.selectDataFromTableCol = obj.res.tableColEntityList
},
updateTypeChange(obj) {
localStorage.setItem("type", 1)
this.currentCol = obj.colName
if (obj.updateType == "select") {
this.selectDialogVisible = true
}
if (obj.updateType == 'enum') {
this.dialogEnumVisible = true;
}
},
tableTypeChange(obj) {
localStorage.setItem("type", 2)
this.currentCol = obj.colName
if (obj.showType == 'enum') {
this.dialogEnumVisible = true;
}
},
selectColName(obj) {
if (this.tableData.tableName == obj.name) {
this.colName = [];
message("数据表来源不能是当前表!", "error")
return;
}
this.dataSource.tableName = obj.name;
this.colName = obj.res.tableColEntityList;
},
updateFileChange(obj) {
// console.log(this.dataSource)
},
submitSelectForm() {
if (this.selectDataParam.fromTableName && this.selectDataParam.nameCol && this.selectDataParam.valueCol) {
this.selectDataParam.colName = this.currentCol
if (this.tableData.selectEntities && this.tableData.selectEntities.length > 0) {
this.tableData.selectEntities.push(this.selectDataParam)
} else {
let arr = []
arr.push(this.selectDataParam)
this.tableData.selectEntities = arr
}
}
this.selectDataParam = {}
this.selectDialogVisible = false
},
submitForm(formName) {
let type = localStorage.getItem("type")
let that = this
this.$refs[formName].validate((valid) => {
if (valid) {
let param = {};
param.colName = that.currentCol
param.enumsDTOS = that.addEnumForm.enums
if (type == 1) {
if (that.tableData.enumsEntities && that.tableData.enumsEntities.length > 0) {
that.tableData.enumsEntities.push(param)
} else {
let arr = []
arr.push(param)
that.tableData.enumsEntities = arr
}
} else {
if (that.tableData.tableEnumsEntities && that.tableData.tableEnumsEntities.length > 0) {
that.tableData.tableEnumsEntities.push(param)
} else {
let arr = []
arr.push(param)
that.tableData.tableEnumsEntities = arr
}
}
message("枚举添加成功!", "success")
that.dialogEnumVisible = false;
that.addEnumForm.enums = []
localStorage.removeItem("type")
} else {
console.log('error submit!!');
return false;
}
});
},
resetForm(formName) {
this.$refs[formName].resetFields();
},
removeDomain(item) {
var index = this.addEnumForm.enums.indexOf(item)
if (index !== -1) {
this.addEnumForm.enums.splice(index, 1)
}
},
addDomain() {
this.addEnumForm.enums.push({
value: '',
name: "",
key: Date.now(),
key1: Date.now() + 1
});
},
submitMainFrom() {
this.tableData.correlationList = this.correlationList
this.tableData.sonTableEntities = this.sonTableEntities
let random = localStorage.getItem("random")
var that = this;
post("/table/" + random, this.tableData).then(res => {
that.correlationList = []
message("配置成功!", "success");
})
},
addSonTableList(param) {
let obj = param.tableData
this.addSonTableDialog = false
if (obj && obj.tableName) {
message("子表添加成功!")
if (this.sonTableEntities.length > 0) {
this.checkObjExist(obj);
}
if (this.correlationList.length > 0) {
this.checkCorrelationExist(param.correlation);
}
this.correlationList.push(param.correlation)
this.sonTableEntities.push(obj)
}
},
//
checkObjExist(obj) {
for (let i in this.sonTableEntities) {
let item = this.sonTableEntities[i]
if (item.tableName == obj.tableName) {
this.sonTableEntities.splice(i, 1)
}
}
},
checkCorrelationExist(obj) {
for (let i in this.correlationList) {
let item = this.correlationList[i]
if (item == obj) {
this.correlationList.splice(i, 1)
}
}
},
updateModuleType(e) {
this.type = e
},
generateCode() {
let random = localStorage.getItem("random")
let url = "/generator/" + random + "/" + this.type
get(url).then(res => {
console.log(res)
})
}
}
}
</script>
<style scoped>
.title {
height: 50px;
line-height: 50px;
}
.my-button {
margin-top: 20px;
}
</style>

@ -0,0 +1,122 @@
<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.7.RELEASE</version>
<relativePath />
</parent>
<groupId>com.example</groupId>
<artifactId>azhou-code</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>azhou-code</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.4</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<exclusions>
<exclusion>
<groupId>io.lettuce</groupId>
<artifactId>lettuce-core</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.62</version>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.7.7</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.18</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
<repository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<releases>
<enabled>false</enabled>
</releases>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</pluginRepository>
<pluginRepository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<releases>
<enabled>false</enabled>
</releases>
</pluginRepository>
</pluginRepositories>
</project>

@ -0,0 +1,14 @@
package com.azhoucode;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class AzhouCodeApplication {
public static void main(String[] args) {
SpringApplication.run(AzhouCodeApplication.class, args);
System.out.println("http://localhost:8888/index.html");
}
}

@ -0,0 +1,38 @@
package com.azhoucode.common;
import com.azhoucode.enums.BaseErrorEnum;
public class BaseError {
private Integer code;
private String message;
public BaseError(Integer code, String message) {
this.code = code;
this.message = message;
}
public BaseError(BaseErrorEnum baseErrorEnum) {
this.code = baseErrorEnum.getCode();
this.message = baseErrorEnum.getMessage();
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}

@ -0,0 +1,98 @@
package com.azhoucode.common;
import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties(prefix = "spring.redis")
public class RedisProperties {
private String host;
private Integer port;
private int timeout;
private String password;
private int database;
private int maxActive;
private int maxIdle;
private int maxWait;
private int minIdle;
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public Integer getPort() {
return port;
}
public void setPort(Integer port) {
this.port = port;
}
public int getTimeout() {
return timeout;
}
public void setTimeout(int timeout) {
this.timeout = timeout;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getDatabase() {
return database;
}
public void setDatabase(int database) {
this.database = database;
}
public int getMaxActive() {
return maxActive;
}
public void setMaxActive(int maxActive) {
this.maxActive = maxActive;
}
public int getMaxIdle() {
return maxIdle;
}
public void setMaxIdle(int maxIdle) {
this.maxIdle = maxIdle;
}
public int getMaxWait() {
return maxWait;
}
public void setMaxWait(int maxWait) {
this.maxWait = maxWait;
}
public int getMinIdle() {
return minIdle;
}
public void setMinIdle(int minIdle) {
this.minIdle = minIdle;
}
}

@ -0,0 +1,85 @@
package com.azhoucode.common;
import com.azhoucode.enums.BaseErrorEnum;
/**
* json
*
* @param <E> data
*/
public class SimpleResponse<E> {
private int code;
// 服务端是否正确响应
private boolean success;
// 错误响应时的消息提示
private String message;
// 正确响应时的数据对象
private E data;
private SimpleResponse() {
this.code = BaseErrorEnum.SUCCESS.getCode();
this.success = true;
this.message = BaseErrorEnum.SUCCESS.getMessage();
}
private SimpleResponse(int code, String message, boolean success) {
this.code = code;
this.success = success;
this.message = message;
}
private SimpleResponse(E data) {
this();
this.data = data;
}
public static <E> SimpleResponse<E> success() {
return new SimpleResponse<>();
}
public static <E> SimpleResponse<E> success(E data) {
return new SimpleResponse<>(data);
}
public static <E> SimpleResponse<E> error(int code, String message, boolean success) {
return new SimpleResponse<>(code, message, success);
}
public static <E> SimpleResponse<E> error(BaseErrorEnum baseErrorEnum) {
return error((int) baseErrorEnum.getCode(), baseErrorEnum.getMessage(), false);
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public boolean isSuccess() {
return success;
}
public void setSuccess(boolean success) {
this.success = success;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public E getData() {
return data;
}
public void setData(E data) {
this.data = data;
}
}

@ -0,0 +1,30 @@
package com.azhoucode.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
/**
* @Description:
* @Author: azhou
* @Create: 2021-05-24 23:13
*/
@Configuration
public class GlobalCorsConfig {
@Bean
public CorsFilter corsFilter() {
CorsConfiguration config = new CorsConfiguration();
config.addAllowedOrigin("*");
config.setAllowCredentials(true);
config.addAllowedMethod("*");
config.addAllowedHeader("*");
config.addExposedHeader("token");
UrlBasedCorsConfigurationSource configSource = new UrlBasedCorsConfigurationSource();
configSource.registerCorsConfiguration("/**", config);
return new CorsFilter(configSource);
}
}

@ -0,0 +1,45 @@
package com.azhoucode.config;
import com.azhoucode.common.SimpleResponse;
import com.azhoucode.enums.BaseErrorEnum;
import org.hibernate.validator.internal.engine.path.PathImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.servlet.NoHandlerFoundException;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.List;
import java.util.Set;
/**
*
*/
@ControllerAdvice
@SuppressWarnings("all")
public class GlobalExceptionHandler {
private final Logger logger = LoggerFactory.getLogger(getClass());
/**
* {@link Exception}
*
* @return json
*/
@ExceptionHandler(Exception.class)
@ResponseBody
public SimpleResponse errorProceed(Exception e) {
logger.error("请求发生错误。", e);
return SimpleResponse.error(BaseErrorEnum.SERVER_ERROR);
}
}

@ -0,0 +1,51 @@
package com.azhoucode.config;
import com.azhoucode.common.RedisProperties;
import com.azhoucode.util.RedisCacheUtils;
import freemarker.template.utility.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
@Configuration
@EnableConfigurationProperties(RedisProperties.class)
public class RedisConfiguration {
private final Logger logger = LoggerFactory.getLogger(getClass());
@Autowired
private RedisProperties redisProperties;
/**
* jedisPool bean
*
* @return {@link JedisPool}
*/
@Bean
public JedisPool jedisPool() {
JedisPoolConfig config = getRedisConfig();
JedisPool jedisPool = new JedisPool(config, redisProperties.getHost(),
redisProperties.getPort(), redisProperties.getTimeout(),
StringUtil.emptyToNull(redisProperties.getPassword()));
RedisCacheUtils.setPool(jedisPool);
logger.info("jedisPool初始化节点" + redisProperties.getHost() + ":" + redisProperties.getPort());
return jedisPool;
}
@Bean
public JedisPoolConfig getRedisConfig() {
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxTotal(redisProperties.getMaxActive());
config.setMaxIdle(redisProperties.getMaxIdle());
config.setMaxWaitMillis(redisProperties.getMaxWait());
config.setMinIdle(redisProperties.getMinIdle());
return config;
}
}

@ -0,0 +1,134 @@
package com.azhoucode.constant;
import javax.swing.*;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
public class Constant {
public static JFrame frmv;
public static final String projectName = "freeOut";
public static final String modelFiles = "C:\\codeManConfig\\modelFiles\\";
public static final String modelFilesZip = "C:\\codeManConfig\\modelFiles\\model.zip";
public static final String staticZip = "C:\\codeManConfig\\modelFiles\\static.zip";
public static final String webClientZip = "C:\\codeManConfig\\modelFiles\\webClient.zip";
public static final String mvcSettingsZip = "C:\\codeManConfig\\modelFiles\\mvcSettings.zip";
public static final String settingsZip = "C:\\codeManConfig\\modelFiles\\settings.zip";
public static final String libZip = "C:\\codeManConfig\\modelFiles\\lib.zip";
public static final String zipPwd = "beautiful123,,#@";
// 获取激活文件
public static final String lifePropertiesPath = "C:\\codeManConfig\\codeManSdk\\bin\\server\\life.properties";
// 项目根目录
public static final String freeOutPath = "\\freeOut\\";
public static final String freeOutPath_lib_MVC = "\\freeOut\\src\\main\\webapp\\WEB-INF\\lib\\";
public static final String freeOutPath_lib = "\\freeOut\\lib\\";
public static final String freeOutPath_METAINF_MVC = "\\freeOut\\src\\main\\webapp\\META-INF\\";
public static final String mainApplicationPath = "\\freeOut\\src\\main\\java\\freeOut\\";
public static final String testPath = "\\freeOut\\src\\test\\java\\freeOut\\";
public static final String freeOutPath_controller = "\\freeOut\\src\\main\\java\\freeOut\\controller\\";
public static final String freeOutPath_core = "\\freeOut\\src\\main\\java\\freeOut\\core\\";
public static final String freeOutPath_core_annotation = "\\freeOut\\src\\main\\java\\freeOut\\core\\annotation\\";
public static final String freeOutPath_core_exception = "\\freeOut\\src\\main\\java\\freeOut\\core\\exception\\";
public static final String freeOutPath_service = "\\freeOut\\src\\main\\java\\freeOut\\service\\";
public static final String freeOutPath_serviceImpl = "\\freeOut\\src\\main\\java\\freeOut\\service\\impl\\";
public static final String freeOutPath_dao = "\\freeOut\\src\\main\\java\\freeOut\\dao\\";
public static final String freeOutPath_entity = "\\freeOut\\src\\main\\java\\freeOut\\entity\\";
public static final String freeOutPath_constant = "\\freeOut\\src\\main\\java\\freeOut\\constant\\";
public static final String freeOutPath_resources = "\\freeOut\\src\\main\\resources\\";
public static final String freeOutPath_sqlMapper = "\\freeOut\\src\\main\\resources\\sqlmapper\\";
public static final String freeOutPath_sqlMapper_MVC = "\\freeOut\\src\\main\\java\\freeOut\\sqlmapper\\";
public static final String freeOutPath_static = "\\freeOut\\src\\main\\resources\\static\\mystatic\\";
public static final String freeOutPath_static_MVC = "\\freeOut\\src\\main\\webapp\\mystatic\\";
public static final String freeOutPath_templates = "\\freeOut\\src\\main\\resources\\templates\\";
public static final String freeOutPath_WEBINF_MVC = "\\freeOut\\src\\main\\webapp\\WEB-INF\\";
public static String downSettingsZipNet = "/zip/settings.zip";
public static String downMvcSettingsZipNet = "/zip/mvcSettings.zip";
public static final String freeOutPath_settings = "\\freeOut\\.settings\\";
public static String downStaticZipNet = "/zip/static.zip";
public static String downWebClientZipNet = "/zip/webClient.zip";
public static String downLibZipNet = "/zip/lib.zip";
public static final String utilPath = "\\freeOut\\src\\main\\java\\freeOut\\utils\\";
public static final String mvcConfig = "\\freeOut\\src\\main\\java\\freeOut\\config\\";
public static String everythingZip = "/zip/everything.zip";
public static final String everythingDownLoadDir = "C:\\codeManConfig\\everything\\";
public static final String everythingExeName = "C:\\codeManConfig\\everything\\Everything.exe";
public static String dubboModelZip = "/zip/dubboModel.zip";
public static String cloudModelZip = "/zip/cloudModel.zip";
public static final String gitIpAdressFilePath = "C:\\codeManConfig\\codeManIp\\ip.txt";
public static final String gitConfigFilePath = "C:\\codeManConfig\\.git";
public static final String webClientPath = "\\freeOut-webClient\\";
public static final String webClientHtmlPath = "\\freeOut-webClient\\views\\";
public static final String webClientJsConfigPath = "\\freeOut-webClient\\js\\config\\";
static {
File ipFile = new File(Constant.gitIpAdressFilePath);
try (BufferedReader reader = new BufferedReader(new FileReader(ipFile))){
String ipPath = reader.readLine();
Constant.downSettingsZipNet = ipPath + Constant.downSettingsZipNet;
Constant.downMvcSettingsZipNet = ipPath + Constant.downMvcSettingsZipNet;
Constant.downStaticZipNet = ipPath + Constant.downStaticZipNet;
Constant.downWebClientZipNet = ipPath + Constant.downWebClientZipNet;
Constant.downLibZipNet = ipPath + Constant.downLibZipNet;
Constant.everythingZip = ipPath + Constant.everythingZip;
Constant.dubboModelZip = ipPath + Constant.dubboModelZip;
Constant.cloudModelZip = ipPath + Constant.cloudModelZip;
} catch (Exception e) {
}
}
}

@ -0,0 +1,27 @@
package com.azhoucode.constant;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
/**
* @description:
* @author: azhou
* @create: 2021-12-07 17:15
**/
@Component
public class PathConstant {
@Value("${file-path.project}")
public String projectPath;
@Value("${dao}")
public String daoPath;
@Value("${dao}")
public String servicePath;
@Value("${service-impl}")
public String serviceImplPath;
@Value("${entity}")
public String entityPath;
@Value("${controller}")
public String controllerPath;
}

@ -0,0 +1,15 @@
package com.azhoucode.constant;
/**
* @description: Redis
* @author: azhou
* @create: 2021-11-01 16:38
**/
public class RedisConstant {
public static final String DB_PARAM = "db_param_%s";
public static final String TABLE_LIST = "table_list_%s";
}

@ -0,0 +1,15 @@
package com.azhoucode.constant;
/**
* @description:
* @author: azhou
* @create: 2021-12-14 15:49
**/
public class TipTemplateConstant {
public static final String REDIS_KEY_NOT_FOUND = "当前Redis中不存在【%s】key";
public static final String TEMP_TYPE_NOT_FOUND = "当前模板类型枚举中不存在【%d】";
}

@ -0,0 +1,57 @@
package com.azhoucode.controller;
import com.azhoucode.common.SimpleResponse;
import com.azhoucode.entity.ApplicationEntity;
import com.azhoucode.entity.TableEntity;
import com.azhoucode.service.DBService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* @description: db
* @author: azhou
* @create: 2021-11-01 14:50
**/
@RestController
@RequestMapping("/db")
public class DBController {
@Autowired
private DBService dbService;
/**
*
* @return
*/
@PostMapping("/checkDBParam")
public SimpleResponse<String> checkDBParam(@RequestBody ApplicationEntity applicationEntity) throws Exception {
return SimpleResponse.success(dbService.checkDBParam(applicationEntity));
}
/**
*
* @param tableName
* @return
* @throws Exception
*/
@GetMapping("/getTableColList/{tableName}/{random}")
public SimpleResponse<TableEntity> getTableColList(@PathVariable("tableName") String tableName,@PathVariable("random") String random) throws Exception {
return SimpleResponse.success(dbService.getTableColList(tableName,random));
}
/**
*
* @param random
* @return
* @throws Exception
*/
@GetMapping("/getAllTable/{random}")
public SimpleResponse<List<String>> getAllTable(@PathVariable("random") String random) throws Exception {
List<String> list = dbService.getAllTable(random);
return SimpleResponse.success(list);
}
}

@ -0,0 +1,29 @@
package com.azhoucode.controller;
import com.azhoucode.common.SimpleResponse;
import com.azhoucode.service.GenerateService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
/**
* @description:
* @author: azhou
* @create: 2021-12-14 15:32
**/
@RestController
@RequestMapping("/generator")
public class GeneratorController {
@Autowired
private GenerateService generateService;
/**
*
*/
@GetMapping("/{random}/{type}")
public SimpleResponse generator(@PathVariable("random") String random,@PathVariable("type") Integer type) throws Exception {
generateService.generateCode(random,type);
return SimpleResponse.success();
}
}

@ -0,0 +1,34 @@
package com.azhoucode.controller;
import com.azhoucode.common.SimpleResponse;
import com.azhoucode.entity.TableEntity;
import com.azhoucode.service.TableService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
/**
* @description:
* @author: azhou
* @create: 2021-12-15 10:50
**/
@RestController
@RequestMapping("/table")
public class TableController {
@Autowired
private TableService tableService;
/**
*
* info#management#message#question#test_paper#type
* @param tableEntity
* @return
*/
@PostMapping("/{random}")
public SimpleResponse<String> addTableConfiguration(@RequestBody TableEntity tableEntity,@PathVariable("random") String random) throws Exception {
tableService.addTableConfiguration(tableEntity,random);
return SimpleResponse.success();
}
}

@ -0,0 +1,67 @@
package com.azhoucode.entity;
import lombok.Data;
/**
* @description:
* @author: azhou
* @create: 2021-12-07 13:33
**/
@Data
public class ApplicationEntity extends BaseEntity {
/** 项目整体相关 start */
// 项目端口
private Integer port;
// 是否需要添加邮件发送组件
private Boolean hasEmail;
// 是否需要添加redis组件
private Boolean hasRedis;
// 是否需要添加图片文件上传组件
private Boolean hasUploadImg;
// 是否需要自定义登录
private Boolean hasLogin;
/** 项目整体相关 end */
/** 数据库相关 start */
private String ip;
private String dbPort;
private String username;
private String password;
private String dbName;
// 数据库表名称,用#隔开
private String tableName;
/** 数据库相关 end */
/** redis相关 start */
private String redisIp;
private String redisPort;
private String redisPassWord;
/** redis相关 end */
/** 图片上传相关 start */
// 本机图片地址服务器的webapp绝对路径
private String uploadUrl;
/** 图片上传相关 end */
/** 自定义登录 & 个人信息相关 start */
private LoginParam loginParam;
}

@ -0,0 +1,24 @@
package com.azhoucode.entity;
import lombok.Data;
import java.io.Serializable;
@Data
public class BaseEntity implements Serializable {
/**表名称*/
private String tableName;
/**作者名称*/
private String authorName;
/**表注释*/
private String tableComment;
/**包名*/
private String packageName;
}

@ -0,0 +1,16 @@
package com.azhoucode.entity;
import lombok.Data;
/**
* @description:
* @author: azhou
* @create: 2021-12-24 11:31
**/
@Data
public class EnumsDTO {
private String name;
private String value;
}

@ -0,0 +1,19 @@
package com.azhoucode.entity;
import lombok.Data;
import java.util.List;
/**
* @description:
* @author: azhou
* @create: 2021-12-24 11:29
**/
@Data
public class EnumsEntity {
/**当前枚举属于那一列*/
private String colName;
private List<EnumsDTO> enumsDTOS;
}

@ -0,0 +1,23 @@
package com.azhoucode.entity;
import lombok.Data;
/**
* @description: admin#beds#department#doctor#leave_hospital#rooms#sick_cost#sick_info
* @author: azhou
* @create: 2021-12-15 17:08
**/
@Data
public class LoginParam {
private String tableName;
private String className;
private String unClassName;
private String userNameCol;
private String passWordCol;
// 自定义用户信息相关
private Boolean hasUserInfo;
private String headImgCol;
private String nickNameCol;
}

@ -0,0 +1,41 @@
package com.azhoucode.entity;
import lombok.Data;
@Data
public class Parameters {
private String projectNameVal;
private String frameWorkVal;
private String clientFrameWorkVal;
private String dataBaseTypeVal;
private String dataBaseIpVal;
private String dataBasePortVal;
private String dataBasePwdVal;
private String dataBaseNameVal;
private String dataBaseUserNameVal;
private String dataBaseUrl;
private String dataBaseDriverClass;
private String outPathVal;
private String makeModelVal;
private String tableName;
private String jsFrameWork;
private String themeVal;
}

@ -0,0 +1,57 @@
package com.azhoucode.entity;
import lombok.Data;
import java.util.List;
/**
*
*/
@Data
public class ProjectParam extends BaseEntity{
/**项目名称*/
private String projectName;
/**项目访问端口*/
private Integer projectPort;
/**总包名*/
private String packageName;
/**数据库ip*/
private String dbIp;
/**数据库端口*/
private String dbPort;
/**数据库用户名*/
private String dbUserName;
/**数据库密码*/
private String dbPassWord;
/**数据库名称*/
private String dbName;
/**表名称(根据#拆分)*/
private List<String> tableNames;
/**是否需要redis*/
private Integer isRedis;
/**是否需要tomcat文件服务器*/
private Integer isTomcatFile;
/**tomcat文件保存的地址*/
private String tomcatWebAppsPath;
/**
*
* redis使redis
* 使session
*/
private Integer isLoginHandle;
}

@ -0,0 +1,17 @@
package com.azhoucode.entity;
import lombok.Data;
/**
* @description:
* @author: azhou
* @create: 2021-12-23 12:56
**/
@Data
public class RouterParam {
private String routerName;
private String chinaName;
}

@ -0,0 +1,32 @@
package com.azhoucode.entity;
import lombok.Data;
@Data
public class SearchParam {
/**列名称*/
private String colName;
/**字段名称*/
private String propertyName;
/**属性类型*/
private String propertyType;
/**字段注释*/
private String propertyChinaName;
/**比较方式*/
private String compareWay;
/**属于那张表*/
private String fromTableName;
/**比较类型*/
private String compareType;
private Boolean isUploadCol;
private String showType;
private String updateType;
}

@ -0,0 +1,34 @@
package com.azhoucode.entity;
import lombok.Data;
/**
* @description:
* @author: azhou
* @create: 2021-12-24 14:37
**/
@Data
public class SelectEntity {
/**来源那张表*/
private String fromTableName;
/**类名*/
private String className;
/**类名小写*/
private String unClassName;
/**名称列*/
private String nameCol;
/**value列*/
private String valueCol;
/**该选择框属于哪一列*/
private String colName;
/**列对应的属性名称*/
private String propertyName;
}

@ -0,0 +1,25 @@
package com.azhoucode.entity;
import lombok.Data;
/**
* @description:
* @author: azhou
* @create: 2021-11-01 16:25
**/
@Data
public class TableColEntity {
private String colName;
private String chinaName;
private Boolean tableShow;
private Boolean updateShow;
private Boolean searchShow;
private String paramType;
private String compareType;
private String showType;
private String updateType;
private Boolean uploadImg;
}

@ -0,0 +1,42 @@
package com.azhoucode.entity;
import lombok.Data;
import java.util.List;
/**
* @description:
* @author: azhou
* @create: 2021-11-01 16:29
**/
@Data
public class TableEntity {
private String tableName;
private String tableComment;
/**
*
*/
private List<TableColEntity> tableColEntityList;
/**
*
*/
private List<TableEntity> sonTableEntities;
/**
*
*/
private List<String> correlationList;
/**修改展示的枚举*/
private List<EnumsEntity> enumsEntities;
/**表格展示的枚举*/
private List<EnumsEntity> tableEnumsEntities;
private List<SelectEntity> selectEntities;
}

@ -0,0 +1,28 @@
package com.azhoucode.entity;
import lombok.Data;
import java.io.Serializable;
/**
*
* azhou
*/
@Data
public class TableNameAndType implements Serializable {
/**列明*/
private String colName;
/**对应实体名称*/
private String entityName;
/**实体中参数类型*/
private String entityParamType;
private String className;
/**注释*/
private String comment;
}

@ -0,0 +1,95 @@
package com.azhoucode.entity;
import lombok.Data;
import java.util.List;
/**
* @description:
* @author: azhou
* @create: 2021-12-15 09:28
**/
@Data
public class TableParam {
/**
*
*/
private String tableName;
/**
*
*/
private String className;
/**
*
*/
private String unClassName;
/**
*
*/
private String tableComment;
/**
*
*/
private List<SearchParam> showColList;
/**
*
*/
private Boolean hasSonTable;
/**
* dto
*/
private List<SearchParam> showSonTableColList;
/**
* xml
*/
private List<SearchParam> searchColsList;
/**
*
*/
private String correlation;
/**
*
*/
private Boolean hasUpload;
/**
*
*/
private List<SearchParam> vueShowColList;
/**
*
*/
private List<SearchParam> vueModifyColList;
/**
*
*/
private List<SearchParam> vueSearchColList;
/**
*
*/
private List<EnumsEntity> updateEnumsLists;
/**
*
*/
private List<SelectEntity> selectEntities;
private List<EnumsEntity> tableEnumsEntities;
}

@ -0,0 +1,80 @@
package com.azhoucode.enums;
public enum BaseErrorEnum {
/**
*
*/
SUCCESS(200, "成功"),
/**
*
*/
OBJECT_NOT_FOUND(10001, "请求数据不存在"),
REQUEST_PARAMETER_EXCEPTION(10002, "请求参数错误"),
PARAMETER_NOT_FOUND(10003, "必传参数缺失"),
BAD_ACCOUNTS(10004, "手机号码有误,请重新输入"),
BAD_CREDENTIALS(10005, "密码有误,请重新输入"),
ACCOUNTS_DISABLED(10006, "账号不可用"),
LOGIN_EXPIRED(10007, "登录已失效"),
REQUIRED_AUTHENTICATION(10008, "权限不足,需要登录认证"),
REQUIRED_ROLE(10019, "角色权限不足"),
VALIDATE_CODE_REQUIRED(10009, "请发送短信验证码"),
VALIDATE_CODE_EXPIRED(10010, "短信验证码已过期"),
VALIDATE_CODE_ERROR(10011, "短信验证码不匹配"),
VALIDATE_CODE_SEND_ERROR(10012, "短信验证码发送失败"),
ACCESS_TOKEN_ERROR(10013, "令牌非法"),
SUBJECT_DELETE(10014, "用户已注销"),
MOBILE_LOGIN_ERROR(10015, "一键登录失败"),
MOBILE_LOGIN_DECRYPT_EXCEPTION(10016, "一键登录解密异常"),
FILE_TOO_LARGE_EXCEPTION(10017, "上传文件太大"),
TXT_TOO_LARGE_EXCEPTION(10018, "数据太长"),
STAFF_VALIDATE_CODE_ERROR(10019, "管家认证码不存在"),
STAFF_VALIDATE_CODE_USED(10020, "管家认证码已使用"),
// 4000开头客户端异常
REQUEST_NOT_SUPPORT(40001, "请求方式不支持"),
NO_HANDLER_EXCEPTION(40002, "没有找到请求处理器"),
CITY_NOT_FIND_ERROR(40003, "不合法的城市参数"),
CONDITION_NOT_MET(40004, "条件未满足"),
NO_PERMISSION_FOR_THIS_DATA(40005, "对该数据无权限"),
// 5000开头服务端异常
SERVER_ERROR(50001, "服务内部异常"),
BUSINESS_ERROR(50002, "业务错误"),
FILE_UPLOAD_ERROR(50003, "文件上传失败"),
LOCATION_ERROR(50004,"经纬度定位失败"),
HOUSE_NULL(50005,"房源数据为空"),
HOUSE_ERROR(50006,"房源数据有误"),
RESULT_ERROR(50007,"查询的结果为空"),
;
private final int code;
private final String message;
BaseErrorEnum(int code, String message) {
this.code = code;
this.message = message;
}
public int getCode() {
return code;
}
public String getMessage() {
return message;
}
}

@ -0,0 +1,21 @@
package com.azhoucode.enums;
import lombok.AllArgsConstructor;
import lombok.Getter;
@AllArgsConstructor
@Getter
public enum DBType {
MYSQL(1, "mysql");
private Integer code;
private String value;
}

@ -0,0 +1,26 @@
package com.azhoucode.enums;
import lombok.AllArgsConstructor;
import lombok.Getter;
@AllArgsConstructor
@Getter
public enum ServerName {
SPRING_BOOT(1, "springboot"),
MYBATIS(101,"mybatis"),
MYBATIS_PLUS(102,"mybatis_plus"),
REDIS(103,"redis"),// redis
TOMCAT_FILE(301,"tomcat_file");// 文件服务器
private Integer code;
private String value;
}

@ -0,0 +1,61 @@
package com.azhoucode.enums;
import lombok.AllArgsConstructor;
import lombok.Getter;
/**
* @description:
* @author: azhou
* @create: 2021-12-14 15:58
**/
@Getter
@AllArgsConstructor
public enum TemplateTypeEnum {
APPLICATION(1, "application.ftl", "application.yml"),
ENTITY(2, "entity.ftl", "%s.java"),
CONTROLLER(3, "controller.ftl", "%sController.java"),
SERVICE(4, "service.ftl", "%sService.java"),
SERVICE_IMPL(5, "serviceImpl.ftl", "%sServiceImpl.java"),
DAO(6, "dao.ftl", "%sDao.java"),
DTO(7, "dto.ftl", "%sDTO.java"),
POM(8, "pom.ftl", "pom.xml"),
XML(9, "xml.ftl", "%sDao.xml"),
REDIS_CONFIG(10, "redisConfig.ftl", "RedisConfig.java"),
REDIS_UTIL(11, "redisUtil.ftl", "RedisUtil.java"),
MAIN_UTIL(12, "mailUtil.ftl", "MailUtil.java"),
LOGIN_CONTROLLER(13, "loginController.ftl", "LoginController.java"),
VUE_TABLE(14, "vueTable.ftl", "index.vue"),
VUE_API(15, "api.ftl", "index.js"),
VUE_ROUTER(16, "sysRouter.ftl", "index.js"),
VUE_TABLE2(17, "vueTable2.ftl", "%s.vue"),
VUE_ROUTER2(18, "sysRouter2.ftl", "index.js"),
VUE_SIDEBAR(19, "Sidebar.ftl", "Sidebar.vue"),
VUE_ROUTER3(20, "admin.ftl", "admin.json"),
;
private Integer type;
/**
*
*/
private String ftlName;
/**
* ,使
*/
private String fileName;
public static TemplateTypeEnum getByCode(Integer code) {
for (TemplateTypeEnum templateTypeEnum : TemplateTypeEnum.values()) {
if(templateTypeEnum.getType().equals(code)) {
return templateTypeEnum;
}
}
return null;
}
}

@ -0,0 +1,18 @@
package com.azhoucode.enums;
import lombok.AllArgsConstructor;
import lombok.Getter;
@Getter
@AllArgsConstructor
public enum WebName {
LAYUI(1,"layui"),
VUE(2,"vue");
private Integer code;
private String value;
}

@ -0,0 +1,22 @@
package com.azhoucode.service;
import com.azhoucode.entity.ApplicationEntity;
import com.azhoucode.entity.TableEntity;
import java.util.List;
import java.util.Map;
/**
* @description: db
* @author: azhou
* @create: 2021-11-01 14:54
**/
public interface DBService {
String checkDBParam(ApplicationEntity applicationEntity) throws Exception;
TableEntity getTableColList(String tableName,String random) throws Exception;
List<String> getAllTable(String random) throws Exception;
}

@ -0,0 +1,29 @@
package com.azhoucode.service;
import com.azhoucode.entity.TableNameAndType;
import java.util.List;
import java.util.Map;
public interface GenerateService {
/**
*
*/
void generateCode(String random,Integer type) throws Exception;
/**
*
* @param tempData
* @param type
* @param className
*/
void generateClassCode(Map<String, Object> tempData, Integer type,String className,String saveUrl) throws Exception;
/**
*
* @param tempData
* @param type
*/
void generatePublicCode(Map<String, Object> tempData, Integer type,String saveUrl) throws Exception;
}

@ -0,0 +1,14 @@
package com.azhoucode.service;
import com.azhoucode.entity.TableEntity;
/**
* @description:
* @author: azhou
* @create: 2021-12-15 10:51
**/
public interface TableService {
void addTableConfiguration(TableEntity tableEntity,String random) throws Exception;
}

@ -0,0 +1,87 @@
package com.azhoucode.service.impl;
import com.azhoucode.constant.RedisConstant;
import com.azhoucode.entity.*;
import com.azhoucode.enums.DBType;
import com.azhoucode.service.DBService;
import com.azhoucode.util.*;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import java.sql.Connection;
import java.util.*;
import java.util.stream.Collectors;
/**
* @description: db
* @author: azhou
* @create: 2021-11-01 14:54
**/
@Service
public class DBServiceImpl implements DBService {
private List<String> paramList = Arrays.asList("id", "create_time", "update_time", "create_id", "update_id");
@Override
public String checkDBParam(ApplicationEntity applicationEntity) throws Exception {
Connection connection = DBUtils.getConnection(applicationEntity);
if (connection == null) throw new Exception("连接失败");
String random = RandomUtil.getRamdom();
RedisCacheUtils.set(String.format(RedisConstant.DB_PARAM, random), applicationEntity, 60 * 60 * 24);
return random;
}
@Override
public TableEntity getTableColList(String tableName, String random) throws Exception {
ApplicationEntity applicationEntity = RedisCacheUtils.get(String.format(RedisConstant.DB_PARAM, random), ApplicationEntity.class);
if (applicationEntity == null) throw new Exception("数据库连接异常");
Connection connection = DBUtils.getConnection(applicationEntity);
List<TableNameAndType> columnNameAndTypes = DBUtils.getColumnNameAndTypes(DBType.MYSQL.getValue(), tableName, connection);
if (CollectionUtils.isEmpty(columnNameAndTypes)) return null;
TableEntity tableEntity = new TableEntity();
// 组装表的列数据
List<TableColEntity> collect = columnNameAndTypes.stream().map(item -> getTableColEntity(item)).collect(Collectors.toList());
tableEntity.setTableColEntityList(collect);
return tableEntity;
}
@Override
public List<String> getAllTable(String random) throws Exception {
ApplicationEntity applicationEntity = RedisCacheUtils.get(String.format(RedisConstant.DB_PARAM, random), ApplicationEntity.class);
if (applicationEntity == null) throw new Exception("表格基本数据异常");
String tableName = applicationEntity.getTableName();
if (tableName.startsWith("#")) tableName = tableName.substring(1);
if (tableName.endsWith("#")) tableName = tableName.substring(0, tableName.length() - 1);
List<String> list = null;
try {
list = Arrays.asList(tableName.split("#"));
} catch (Exception e) {
throw new Exception("表格基本数据异常");
}
return list;
}
public TableColEntity getTableColEntity(TableNameAndType tableNameAndType) {
TableColEntity tableColEntity = new TableColEntity();
tableColEntity.setColName(tableNameAndType.getColName());
tableColEntity.setChinaName(tableNameAndType.getComment());
// 如果是ID则默认不显示 不修改 不添加
String colName = tableColEntity.getColName();
boolean flag = checkParam(colName);
tableColEntity.setTableShow(flag ? false : true);
tableColEntity.setUpdateShow(flag ? false : true);
tableColEntity.setSearchShow(false);
tableColEntity.setCompareType("=");
tableColEntity.setShowType("text");
tableColEntity.setUpdateType("text");
tableColEntity.setUploadImg(false);
tableColEntity.setParamType(tableNameAndType.getEntityParamType());
return tableColEntity;
}
public boolean checkParam(String param) {
return paramList.contains(param);
}
}

@ -0,0 +1,204 @@
package com.azhoucode.service.impl;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.azhoucode.constant.RedisConstant;
import com.azhoucode.constant.TipTemplateConstant;
import com.azhoucode.entity.ApplicationEntity;
import com.azhoucode.entity.LoginParam;
import com.azhoucode.entity.RouterParam;
import com.azhoucode.entity.TableParam;
import com.azhoucode.enums.TemplateTypeEnum;
import com.azhoucode.service.GenerateService;
import com.azhoucode.util.FreeMarkerUtil;
import com.azhoucode.util.JsonUtils;
import com.azhoucode.util.RedisCacheUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Service;
import java.util.*;
import java.util.stream.Collectors;
@Service
public class GenerateServiceImpl implements GenerateService {
@Autowired
private FreeMarkerUtil freeMarkerUtil;
@Value("${file-path.project}")
private String pomFilePath;
@Value("${application}")
private String appFilePath;
@Value("${config}")
private String configFilePath;
@Value("${util}")
private String utilFilePath;
@Value("${controller}")
private String controllerFilePath;
@Value("${dao}")
private String daoFilePath;
@Value("${service}")
private String serviceFilePath;
@Value("${serviceImpl}")
private String serviceImplFilePath;
@Value("${entity}")
private String entityFilePath;
@Value("${dto}")
private String dtoFilePath;
@Value("${xml}")
private String xmlFilePath;
@Value("${vueTable}")
private String vueElementTablePath;
@Value("${vueTableApi}")
private String vueElementTableApiPath;
@Value("${vueRouter}")
private String vueElementRouterPath;
@Value("${vueCommonTable}")
private String vueCommonTablePath;
@Value("${vueCommonRouterPath}")
private String vueCommonRouterPath;
@Value("${vueCommonSidebarPath}")
private String vueCommonSidebarPath;
@Value("${vueTable2}")
private String vueTable2;
@Value("${vueTableApi2}")
private String vueTableApi2;
@Value("${vueRouter3}")
private String vueRouter3;
@Override
public void generateCode(String random, Integer type) throws Exception {
this.generateProjectCommonCode(random);
this.generateBusinessCode(random, type);
}
@Override
public void generateClassCode(Map<String, Object> tempData, Integer type, String className, String saveUrl) throws Exception {
TemplateTypeEnum templateTypeEnum = TemplateTypeEnum.getByCode(type);
Assert.notNull(templateTypeEnum, TipTemplateConstant.TEMP_TYPE_NOT_FOUND, type);
freeMarkerUtil.generate(tempData, templateTypeEnum.getFtlName(), saveUrl, String.format(templateTypeEnum.getFileName(), className));
}
@Override
public void generatePublicCode(Map<String, Object> tempData, Integer type, String saveUrl) throws Exception {
TemplateTypeEnum templateTypeEnum = TemplateTypeEnum.getByCode(type);
Assert.notNull(templateTypeEnum, TipTemplateConstant.TEMP_TYPE_NOT_FOUND, type);
freeMarkerUtil.generate(tempData, templateTypeEnum.getFtlName(), saveUrl, templateTypeEnum.getFileName());
}
/**
*
*
* @throws Exception
*/
public void generateProjectCommonCode(String random) throws Exception {
ApplicationEntity applicationEntity = RedisCacheUtils.get(String.format(RedisConstant.DB_PARAM, random), ApplicationEntity.class);
// 生成application代码
Map<String, Object> stringObjectMap = JsonUtils.jsonToMap(JsonUtils.objectToJson(applicationEntity));
this.generatePublicCode(stringObjectMap, TemplateTypeEnum.APPLICATION.getType(), appFilePath);
this.generatePublicCode(stringObjectMap, TemplateTypeEnum.POM.getType(), pomFilePath);
if (applicationEntity.getHasEmail())
this.generatePublicCode(stringObjectMap, TemplateTypeEnum.MAIN_UTIL.getType(), utilFilePath);
if (applicationEntity.getHasRedis()) {
this.generatePublicCode(stringObjectMap, TemplateTypeEnum.REDIS_UTIL.getType(), utilFilePath);
this.generatePublicCode(stringObjectMap, TemplateTypeEnum.REDIS_CONFIG.getType(), configFilePath);
}
// 需要自定义登录
if (applicationEntity.getHasLogin() && applicationEntity.getLoginParam() != null) {
LoginParam loginParam = applicationEntity.getLoginParam();
if (StrUtil.isNotEmpty(loginParam.getTableName()) &&
StrUtil.isNotEmpty(loginParam.getUserNameCol()) &&
StrUtil.isNotEmpty(loginParam.getPassWordCol())) {
loginParam.setClassName(freeMarkerUtil.getEntityName(loginParam.getTableName()));
loginParam.setUnClassName(freeMarkerUtil.getEntityNameLower(loginParam.getTableName()));
Map<String, Object> loginParamMap = JsonUtils.jsonToMap(JsonUtils.objectToJson(applicationEntity.getLoginParam()));
this.generatePublicCode(loginParamMap, TemplateTypeEnum.LOGIN_CONTROLLER.getType(), controllerFilePath);
}
}
}
/**
*
*
* @param type 1vue-element 2vue 3html+ layui
* @throws Exception
*/
public void generateBusinessCode(String random, @Nullable Integer type) throws Exception {
List<String> tableDataList = RedisCacheUtils.lrange(String.format(RedisConstant.TABLE_LIST, random), 0, -1);
if (CollectionUtil.isEmpty(tableDataList)) return;
List<TableParam> tableParamList = tableDataList.stream().map(item -> JSON.parseObject(item, TableParam.class)).collect(Collectors.toList());
// 倒叙生成 表重复时覆盖之前的设置
List<TableParam> reverse = CollectionUtil.reverse(tableParamList);
for (TableParam tableParam : reverse) {
Map<String, Object> stringObjectMap = JsonUtils.jsonToMap(JsonUtils.objectToJson(tableParam));
// 前端代码生成每个文件对应的文件夹名称,根据选择不同的模板来生成不同的前端
// if (type == 1) generateVueElementCode(stringObjectMap, tableParam);
// else if (type == 2) generateVueCode(stringObjectMap, tableParam);
// else if (type == 3) generateVueElementCode2(stringObjectMap, tableParam);
// 后端代码生成,不变
this.generateClassCode(stringObjectMap, TemplateTypeEnum.ENTITY.getType(), tableParam.getClassName(), entityFilePath);
this.generateClassCode(stringObjectMap, TemplateTypeEnum.DAO.getType(), tableParam.getClassName(), daoFilePath);
this.generateClassCode(stringObjectMap, TemplateTypeEnum.SERVICE.getType(), tableParam.getClassName(), serviceFilePath);
this.generateClassCode(stringObjectMap, TemplateTypeEnum.SERVICE_IMPL.getType(), tableParam.getClassName(), serviceImplFilePath);
this.generateClassCode(stringObjectMap, TemplateTypeEnum.DTO.getType(), tableParam.getClassName(), dtoFilePath);
this.generateClassCode(stringObjectMap, TemplateTypeEnum.CONTROLLER.getType(), tableParam.getClassName(), controllerFilePath);
this.generateClassCode(stringObjectMap, TemplateTypeEnum.XML.getType(), tableParam.getClassName(), xmlFilePath);
}
// Map<String, Object> map = new HashMap<>();
// List<RouterParam> routerParams = new ArrayList<>();
// reverse.stream().collect(Collectors.toMap(item -> item.getTableName(), item -> item, (o1, o2) -> o2)).entrySet().forEach(item -> {
// RouterParam routerParam = new RouterParam();
// routerParam.setRouterName(item.getValue().getUnClassName());
// routerParam.setChinaName(item.getValue().getTableComment());
// routerParams.add(routerParam);
// });
// map.put("routerParams", routerParams);
// if (type == 1) this.generatePublicCode(map, TemplateTypeEnum.VUE_ROUTER.getType(), vueElementRouterPath);
// else if(type == 2) {
// this.generatePublicCode(map, TemplateTypeEnum.VUE_ROUTER2.getType(), vueCommonRouterPath);
// this.generatePublicCode(map, TemplateTypeEnum.VUE_SIDEBAR.getType(), vueCommonSidebarPath);
// }else if(type == 3){
// this.generatePublicCode(map, TemplateTypeEnum.VUE_ROUTER3.getType(), vueRouter3);
// }
}
public void generateVueElementCode(Map<String, Object> stringObjectMap, TableParam tableParam) throws Exception {
String vueTable = String.format(vueElementTablePath, tableParam.getUnClassName());
String vueApi = String.format(vueElementTableApiPath, tableParam.getUnClassName());
this.generatePublicCode(stringObjectMap, TemplateTypeEnum.VUE_TABLE.getType(), vueTable);
this.generatePublicCode(stringObjectMap, TemplateTypeEnum.VUE_API.getType(), vueApi);
}
public void generateVueCode(Map<String, Object> stringObjectMap, TableParam tableParam) throws Exception {
String vueTable = String.format(vueCommonTablePath, tableParam.getUnClassName());
this.generateClassCode(stringObjectMap, TemplateTypeEnum.VUE_TABLE2.getType(), tableParam.getUnClassName(), vueTable);
}
public void generateVueElementCode2(Map<String, Object> stringObjectMap, TableParam tableParam) throws Exception {
String vueTable = String.format(vueTable2, tableParam.getUnClassName());
String vueApi = String.format(vueTableApi2, tableParam.getUnClassName());
this.generatePublicCode(stringObjectMap, TemplateTypeEnum.VUE_TABLE.getType(), vueTable);
this.generatePublicCode(stringObjectMap, TemplateTypeEnum.VUE_API.getType(), vueApi);
}
}

@ -0,0 +1,213 @@
package com.azhoucode.service.impl;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.azhoucode.constant.RedisConstant;
import com.azhoucode.entity.*;
import com.azhoucode.service.TableService;
import com.azhoucode.util.FreeMarkerUtil;
import com.azhoucode.util.RedisCacheUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.*;
import java.util.stream.Collectors;
import static java.util.Comparator.comparing;
import static java.util.stream.Collectors.collectingAndThen;
import static java.util.stream.Collectors.toCollection;
/**
* @description:
* @author: azhou
* @create: 2021-12-15 10:51
**/
@Service
public class TableServiceImpl implements TableService {
private static final String MODIFY = "modify";
private static final String SHOW = "show";
private static final String SEARCH = "search";
@Autowired
private FreeMarkerUtil freeMarkerUtil;
@Override
public void addTableConfiguration(TableEntity tableEntity, String random) throws Exception {
TableParam tableParam = new TableParam();
tableParam.setTableName(tableEntity.getTableName());
tableParam.setClassName(freeMarkerUtil.getEntityName(tableEntity.getTableName()));
tableParam.setUnClassName(freeMarkerUtil.getEntityNameLower(tableEntity.getTableName()));
tableParam.setTableComment(StrUtil.isEmpty(tableEntity.getTableComment()) ? tableEntity.getTableName() : tableEntity.getTableComment());
tableParam.setShowColList(buildSearchParam(tableEntity, true));
List<SearchParam> searchParamList = new ArrayList<>();
searchParamList.addAll(buildSearchParam(tableEntity, true));
Map<String, List<SearchParam>> stringListMap = buildVueTableData(tableEntity, true);
List<SearchParam> modifyList = stringListMap.get(MODIFY);
List<SearchParam> showList = stringListMap.get(SHOW);
List<SearchParam> searchList = stringListMap.get(SEARCH);
// 存在子表配置
List<TableEntity> sonTableEntities = tableEntity.getSonTableEntities();
List<String> correlationList = tableEntity.getCorrelationList();
if (CollectionUtil.isNotEmpty(sonTableEntities) && CollectionUtil.isNotEmpty(correlationList)) {
List<SearchParam> sonTableColEntities = new ArrayList<>();
tableParam.setHasSonTable(true);
for (TableEntity sonTableEntity : sonTableEntities) {
Map<String, List<SearchParam>> stringListMap1 = buildVueTableData(sonTableEntity, false);
List<SearchParam> modifyList1 = stringListMap1.get(MODIFY);
modifyList.addAll(modifyList1);
List<SearchParam> showList1 = stringListMap1.get(SHOW);
showList.addAll(showList1);
List<SearchParam> searchList1 = stringListMap1.get(SEARCH);
searchList.addAll(searchList1);
sonTableColEntities.addAll(buildSearchParam(sonTableEntity, false));
searchParamList.addAll(buildSearchParam(sonTableEntity, false));
}
tableParam.setShowSonTableColList(sonTableColEntities);
if (CollectionUtil.isNotEmpty(correlationList)) {
tableParam.setCorrelation(correlationList.stream().collect(Collectors.joining("\n\r")));
}
}
tableParam.setHasUpload(checkHasUpload(tableEntity));
tableParam.setSearchColsList(searchParamList);
tableParam.setVueModifyColList(modifyList);
tableParam.setVueShowColList(showList);
tableParam.setVueSearchColList(searchList);
if (CollectionUtil.isNotEmpty(tableEntity.getEnumsEntities())) {
List<EnumsEntity> enumsEntities = tableEntity.getEnumsEntities();
List<EnumsEntity> list = enumsEntities.stream().collect(collectingAndThen(toCollection(() ->
new TreeSet<>(comparing(n -> n.getColName()))), ArrayList::new));
tableParam.setUpdateEnumsLists(list);
}
if (CollectionUtil.isNotEmpty(tableEntity.getTableEnumsEntities())) {
List<EnumsEntity> enumsEntities = tableEntity.getTableEnumsEntities();
List<EnumsEntity> list = enumsEntities.stream().collect(collectingAndThen(toCollection(() ->
new TreeSet<>(comparing(n -> n.getColName()))), ArrayList::new));
tableParam.setTableEnumsEntities(list);
}
if(CollectionUtil.isNotEmpty(tableEntity.getSelectEntities())) {
List<SelectEntity> selectEntities = tableEntity.getSelectEntities();
List<SelectEntity> list = selectEntities.stream().collect(collectingAndThen(toCollection(() ->
new TreeSet<>(comparing(n -> n.getFromTableName()))), ArrayList::new));
List<SelectEntity> collect = list.stream().map(item -> {
item.setClassName(freeMarkerUtil.getEntityName(item.getFromTableName()));
item.setUnClassName(freeMarkerUtil.getEntityNameLower(item.getFromTableName()));
item.setPropertyName(freeMarkerUtil.getEntityNameLower(item.getColName()));
item.setNameCol(freeMarkerUtil.getEntityName(item.getNameCol()));
item.setValueCol(freeMarkerUtil.getEntityName(item.getValueCol()));
return item;
}).collect(Collectors.toList());
tableParam.setSelectEntities(collect);
}
RedisCacheUtils.lpush(String.format(RedisConstant.TABLE_LIST, random), JSON.toJSONString(tableParam));
}
/**
*
*
* @return
*/
public Boolean checkHasUpload(TableEntity tableEntity) {
List<TableColEntity> tableColEntityList = tableEntity.getTableColEntityList();
boolean flag = false;
if (CollectionUtil.isEmpty(tableColEntityList)) return flag;
for (TableColEntity tableColEntity : tableColEntityList) {
if (tableColEntity.getUploadImg()) {
flag = true;
break;
}
}
return flag;
}
/**
*
*
* @param tableEntity
* @param isMain
* @return
*/
public List<SearchParam> buildSearchParam(TableEntity tableEntity, Boolean isMain) {
List<SearchParam> searchParamList = new ArrayList<>();
List<TableColEntity> tableColEntityList = tableEntity.getTableColEntityList();
// 处理主表
for (TableColEntity tableColEntity : tableColEntityList) {
SearchParam searchParam = new SearchParam();
searchParam.setColName(tableColEntity.getColName());
searchParam.setPropertyType(tableColEntity.getParamType());
searchParam.setPropertyName(freeMarkerUtil.underlineToHump(tableColEntity.getColName()));
searchParam.setPropertyChinaName(tableColEntity.getChinaName());
searchParam.setCompareWay(tableColEntity.getCompareType());
// 下划线转驼峰
searchParam.setFromTableName(freeMarkerUtil.underlineToHump(tableEntity.getTableName()));
if (isMain) {
searchParamList.add(searchParam);
} else {
if (tableColEntity.getTableShow()) {
searchParamList.add(searchParam);
}
}
}
return searchParamList;
}
/**
* vue
*
* @param tableEntity
* @return
*/
private Map<String, List<SearchParam>> buildVueTableData(TableEntity tableEntity, Boolean isMain) {
Map<String, List<SearchParam>> map = new HashMap<>(6);
List<SearchParam> vueShowColList = new ArrayList<>();
List<SearchParam> vueModifyColList = new ArrayList<>();
List<SearchParam> vueSearchColList = new ArrayList<>();
List<TableColEntity> tableColEntityList = tableEntity.getTableColEntityList();
for (TableColEntity tableColEntity : tableColEntityList) {
// 修改属性
if (tableColEntity.getUpdateShow() && isMain) {
SearchParam searchParam = new SearchParam();
searchParam.setPropertyChinaName(searchParam.getPropertyChinaName());
searchParam.setPropertyName(freeMarkerUtil.underlineToHump(tableColEntity.getColName()));
searchParam.setColName(tableColEntity.getColName());
searchParam.setPropertyType(tableColEntity.getParamType());
searchParam.setPropertyChinaName(tableColEntity.getChinaName());
searchParam.setCompareType(tableColEntity.getCompareType());
searchParam.setShowType(tableColEntity.getShowType());
searchParam.setUpdateType(tableColEntity.getUpdateType());
vueModifyColList.add(searchParam);
}
if (tableColEntity.getTableShow()) {
SearchParam searchParam = new SearchParam();
searchParam.setPropertyChinaName(searchParam.getPropertyChinaName());
searchParam.setPropertyName(freeMarkerUtil.underlineToHump(tableColEntity.getColName()));
searchParam.setColName(tableColEntity.getColName());
searchParam.setPropertyChinaName(tableColEntity.getChinaName());
searchParam.setCompareType(tableColEntity.getCompareType());
searchParam.setIsUploadCol(tableColEntity.getUploadImg());
searchParam.setPropertyType(tableColEntity.getParamType());
searchParam.setShowType(tableColEntity.getShowType());
searchParam.setUpdateType(tableColEntity.getUpdateType());
vueShowColList.add(searchParam);
}
if (tableColEntity.getSearchShow()) {
SearchParam searchParam = new SearchParam();
searchParam.setPropertyChinaName(searchParam.getPropertyChinaName());
searchParam.setPropertyName(freeMarkerUtil.underlineToHump(tableColEntity.getColName()));
searchParam.setColName(tableColEntity.getColName());
searchParam.setPropertyChinaName(tableColEntity.getChinaName());
searchParam.setPropertyType(tableColEntity.getParamType());
searchParam.setCompareType(tableColEntity.getCompareType());
searchParam.setShowType(tableColEntity.getShowType());
searchParam.setUpdateType(tableColEntity.getUpdateType());
vueSearchColList.add(searchParam);
}
}
map.put(SHOW, vueShowColList);
map.put(MODIFY, vueModifyColList);
map.put(SEARCH, vueSearchColList);
return map;
}
}

@ -0,0 +1,425 @@
package com.azhoucode.util;
import com.azhoucode.constant.Constant;
import com.azhoucode.entity.ApplicationEntity;
import com.azhoucode.entity.Parameters;
import com.azhoucode.entity.TableNameAndType;
import javax.swing.*;
import java.sql.*;
import java.util.*;
public class DBUtils {
public static Connection getConnection(ApplicationEntity applicationEntity) {
Connection conn = null;
String url = "";
String driverClass = "";
try {
url = "jdbc:mysql://" + applicationEntity.getIp() + ":" + applicationEntity.getDbPort() + "/"
+ applicationEntity.getDbName()
+ "?connectTimeout=10000&socketTimeout=10000&serverTimezone=UTC&useUnicode=true&characterEncoding=UTF-8&useSSL=false&allowMultiQueries=true&zeroDateTimeBehavior=convertToNull";
driverClass = "com.mysql.cj.jdbc.Driver";
Class.forName(driverClass);
DriverManager.setLoginTimeout(10);
conn = DriverManager.getConnection(url, applicationEntity.getUsername(),
applicationEntity.getPassword());
} catch (Exception e) {
return null;
}
return conn;
}
/**
* id
*
* @param parameters
* @param tableName
* @return
* @throws Exception
*/
public static List<String> getPrimarykey(Parameters parameters, String tableName) throws Exception {
List<String> primaryKeyList = new ArrayList<>(3);
Connection connection = null;
if (connection == null) {
return null;
}
DatabaseMetaData metaData = connection.getMetaData();
String userName = connection.getMetaData().getUserName();
// 获取主键字段
ResultSet primaryKeys = metaData.getPrimaryKeys(null, userName, tableName);
//根据结果集元数据打印内容
ResultSetMetaData pkmd = primaryKeys.getMetaData();
while (primaryKeys.next()) {
for (int i = 1; i <= pkmd.getColumnCount(); i++) {
//获取主键的名称
if ("COLUMN_NAME".equalsIgnoreCase(pkmd.getColumnName(i))) {
primaryKeyList.add(primaryKeys.getString(i));
}
}
}
return primaryKeyList;
}
/**
* @param tableNameVal
* @param connection
* @return
*/
private static Map<String, String> getColumnComment(String databaseType, String tableNameVal, Connection connection) {
PreparedStatement columnListPst = null;
ResultSet columnListRs = null;
String sql = "";
if ("mysql".equals(databaseType)) {
sql = "show full columns from `" + tableNameVal + "`";
} else if ("postgresql".equals(databaseType)) {
String[] tableNameArr = tableNameVal.split("\\.");
if (tableNameArr.length == 1) {
tableNameVal = tableNameArr[0];
} else {
tableNameVal = tableNameArr[1];
}
sql = "SELECT" +
" A.attname AS \"Field\"," +
" col_description ( A.attrelid, A.attnum ) AS \"Comment\"" +
" FROM" +
" pg_class AS C," +
" pg_attribute AS A " +
" WHERE" +
" C.relname = '" + tableNameVal + "' " +
" AND A.attrelid = C.oid " +
" AND A.attnum > 0";
} else if ("oracle".equals(databaseType)) {
sql = "select column_name AS \"Field\",comments AS \"Comment\" from user_col_comments where lower(table_Name)='" + tableNameVal.toLowerCase() + "'";
}
// 列名集合
Map<String, String> commentMqp = new HashMap<>();
try {
columnListPst = connection.prepareStatement(sql);
columnListRs = columnListPst.executeQuery();
while (columnListRs.next()) {
commentMqp.put(columnListRs.getString("Field").toUpperCase(), columnListRs.getString("Comment"));
}
} catch (SQLException e) {
return null;
} finally {
try {
if (connection != null) {
connection.close();
}
} catch (SQLException ignored) {
}
try {
if (columnListPst != null) {
columnListPst.close();
}
} catch (SQLException ignored) {
}
try {
if (columnListRs != null) {
columnListRs.close();
}
} catch (SQLException ignored) {
}
}
return commentMqp;
}
public static List<String> getColumnNameList(String databaseType, String tableNameVal, Connection connection) {
PreparedStatement columnListPst = null;
ResultSet columnListRs = null;
String sql = "";
if ("mysql".equals(databaseType)) {
sql = "select * from `" + tableNameVal + "` where 1=0";
} else if ("oracle".equals(databaseType)) {
sql = "select * from \"" + tableNameVal + "\" where 1=0";
} else if ("postgresql".equals(databaseType)) {
sql = "select * from " + tableNameVal + " where 1=0";
}
// 列名集合
List<String> columnList = new ArrayList<>();
try {
columnListPst = connection.prepareStatement(sql);
columnListRs = columnListPst.executeQuery();
ResultSetMetaData metaData = columnListRs.getMetaData();
int columnCount = metaData.getColumnCount();
for (int i = 0; i < columnCount; i++) {
columnList.add(metaData.getColumnName(i + 1));
}
} catch (SQLException e) {
return null;
} finally {
try {
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
}
try {
if (columnListPst != null) {
columnListPst.close();
}
} catch (SQLException e) {
}
try {
if (columnListRs != null) {
columnListRs.close();
}
} catch (SQLException e) {
}
}
return columnList;
}
/**
*
*
* @return
*/
public static List<TableNameAndType> getColumnNameAndTypes(String databaseType, String tableNameVal,
Connection connection) {
PreparedStatement columnListPst = null;
ResultSet columnListRs = null;
String sql = "";
if ("mysql".equals(databaseType)) {
sql = "select * from `" + tableNameVal + "` where 1=0";
} else if ("oracle".equals(databaseType)) {
sql = "select * from \"" + tableNameVal + "\" where 1=0";
} else if ("postgresql".equals(databaseType)) {
sql = "select * from " + tableNameVal + " where 1=0";
}
// 列名集合
List<TableNameAndType> nameAndTypes = new ArrayList<>();
try {
columnListPst = connection.prepareStatement(sql);
columnListRs = columnListPst.executeQuery();
ResultSetMetaData metaData = columnListRs.getMetaData();
int columnCount = metaData.getColumnCount();
for (int i = 0; i < columnCount; i++) {
TableNameAndType nameAndType = new TableNameAndType();
nameAndType.setColName(metaData.getColumnName(i + 1));
//设置sqlParamName
nameAndType.setEntityName(DataUtils.getSqlParam(metaData.getColumnName(i + 1)));
nameAndType.setComment((metaData.getColumnName(i + 1)));
String javaTypeName = "";
String javaClassName = "";
String columnTypeName = metaData.getColumnTypeName(i + 1).toUpperCase();
switch (databaseType) {
case "postgresql":
switch (columnTypeName) {
case "VARCHAR":
javaTypeName = "String";
break;
case "bigint":
javaTypeName = "Long";
break;
case "CHAR":
javaTypeName = "String";
break;
case "INT2":
javaTypeName = "Integer";
break;
case "INT4":
javaTypeName = "Integer";
break;
case "INT8":
javaTypeName = "Long";
break;
case "SERIAL2":
javaTypeName = "Integer";
break;
case "SERIAL4":
javaTypeName = "Integer";
break;
case "SERIAL8":
javaTypeName = "Long";
break;
case "TEXT":
javaTypeName = "String";
break;
case "DATE":
javaTypeName = "Date";
javaClassName = "java.util.Date";
break;
case "TIME":
javaTypeName = "Time";
javaClassName = "java.util.Date";
break;
case "TIMETZ":
javaTypeName = "Date";
javaClassName = "java.util.Date";
break;
case "TIMESTAMP":
javaTypeName = "Date";
javaClassName = "java.util.Date";
break;
case "TIMESTAMPTZ":
javaTypeName = "Date";
javaClassName = "java.util.Date";
break;
default:
javaTypeName = "String";
break;
}
break;
case "mysql":
switch (columnTypeName) {
case "VARCHAR":
javaTypeName = "String";
break;
case "BIGINT UNSIGNED":
javaTypeName = "Long";
break;
case "INT":
javaTypeName = "Integer";
break;
case "CHAR":
javaTypeName = "String";
break;
case "BLOB":
javaTypeName = "byte[]";
break;
case "TEXT":
javaTypeName = "String";
break;
case "INTEGER":
javaTypeName = "Long";
break;
case "TINYINT":
javaTypeName = "Integer";
break;
case "SMALLINT":
javaTypeName = "Integer";
break;
case "MEDIUMINT":
javaTypeName = "Integer";
break;
case "BIT":
javaTypeName = "Long";
break;
case "BIGINT":
javaTypeName = "Long";
break;
case "FLOAT":
javaTypeName = "Float";
break;
case "DOUBLE":
javaTypeName = "Double";
break;
case "DECIMAL":
javaTypeName = "BigDecimal";
javaClassName = "java.math.BigDecimal";
break;
case "BOOLEAN":
javaTypeName = "Integer";
break;
// 主键
case "ID":
javaTypeName = "Long";
break;
case "DATE":
javaTypeName = "Date";
javaClassName = "java.util.Date";
break;
case "TIME":
javaTypeName = "Date";
javaClassName = "java.util.Date";
break;
case "DATETIME":
javaTypeName = "Date";
javaClassName = "java.util.Date";
break;
case "TIMESTAMP":
javaTypeName = "Date";
javaClassName = "java.util.Date";
break;
case "YEAR":
javaTypeName = "Date";
javaClassName = "java.util.Date";
break;
default:
javaTypeName = "String";
break;
}
break;
case "oracle":
switch (columnTypeName) {
case "NUMBER":
javaTypeName = "Integer";
break;
case "DATE":
javaTypeName = "Date";
javaClassName = "java.util.Date";
break;
case "TIMESTAMP":
javaTypeName = "Date";
javaClassName = "java.util.Date";
break;
default:
javaTypeName = "String";
break;
}
default:
break;
}
nameAndType.setEntityParamType(javaTypeName);
nameAndType.setClassName(javaClassName);
nameAndTypes.add(nameAndType);
}
// 注释map
Map<String, String> columnComment = getColumnComment(databaseType, tableNameVal, connection);
for (TableNameAndType tableNameAndType : nameAndTypes) {
String name = tableNameAndType.getColName().toUpperCase();
// 设置注释内容
assert columnComment != null;
tableNameAndType.setComment(
"".equals(columnComment.get(name)) || columnComment.get(name) == null ? tableNameAndType.getColName() : columnComment.get(name));
}
} catch (SQLException e) {
return null;
} finally {
try {
if (connection != null) {
connection.close();
}
} catch (SQLException ignored) {
}
try {
if (columnListPst != null) {
columnListPst.close();
}
} catch (SQLException ignored) {
}
try {
if (columnListRs != null) {
columnListRs.close();
}
} catch (SQLException ignored) {
}
}
return nameAndTypes;
}
}

@ -0,0 +1,60 @@
package com.azhoucode.util;
public class DataUtils {
/**
* @param columnsEng
*/
public static String getSqlParam(String columnsEng) {
String sqlParamColumEng = "";
if (columnsEng.contains(".")) {
columnsEng = columnsEng.toLowerCase();
String[] nameArr = columnsEng.split("\\.");
sqlParamColumEng = makeSqlParam(nameArr);
} else if (columnsEng.contains("_")) {
columnsEng = columnsEng.toLowerCase();
String[] nameArr = columnsEng.split("_");
sqlParamColumEng = makeSqlParam(nameArr);
} else if (columnsEng.contains("-")) {
columnsEng = columnsEng.toLowerCase();
String[] nameArr = columnsEng.split("-");
sqlParamColumEng = makeSqlParam(nameArr);
} else {
if (columnsEng.matches("^[A-Z|0-9A-Z]+$")) {
sqlParamColumEng = columnsEng.toLowerCase();
} else {
if (columnsEng.length() > 2) {
sqlParamColumEng = columnsEng.substring(0, 2).toLowerCase() + columnsEng.substring(2);
} else {
sqlParamColumEng = columnsEng.toLowerCase();
}
}
}
return sqlParamColumEng;
}
private static String makeSqlParam(String[] nameArr) {
String sqlParamColumEng = "";
for (int j = 0; j < nameArr.length; j++) {
if (j == 0) {
sqlParamColumEng += nameArr[j];
} else if (nameArr[j].length() > 1) {
sqlParamColumEng += nameArr[j].substring(0, 1).toUpperCase() + nameArr[j].substring(1);
} else {
sqlParamColumEng += nameArr[j].toUpperCase();
}
}
if (sqlParamColumEng.length() > 2) {
sqlParamColumEng = sqlParamColumEng.substring(0, 2).toLowerCase() + sqlParamColumEng.substring(2);
} else {
sqlParamColumEng = sqlParamColumEng.toLowerCase();
}
return sqlParamColumEng;
}
}

@ -0,0 +1,103 @@
package com.azhoucode.util;
import com.azhoucode.entity.BaseEntity;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Map;
/**
* 1.
* 2.
* 3.
*/
@Component
public class FreeMarkerUtil {
@Autowired
Configuration freeMarker;
/**
*
*/
private void pathJudgeExist(String path) {
File file = new File(path);
if (!file.exists()) {
file.mkdirs();
}
}
/**
*
*/
public void printFile(Map<String, Object> app, Template template, String filePath, String fileName) throws Exception {
pathJudgeExist(filePath);
File file = new File(filePath, fileName);
if (!file.exists()) {
file.createNewFile();
}
Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8));
template.process(app, out);
out.close();
}
/**
*
*/
public String capFirst(String str) {
return str.substring(0, 1).toUpperCase() + str.substring(1).toLowerCase();
}
/**
* 线
*/
public String underlineToHump(String para) {
StringBuilder result = new StringBuilder();
String a[] = para.split("_");
for (String s : a) {
if (result.length() == 0) {
result.append(s);
} else {
result.append(s.substring(0, 1).toUpperCase());
result.append(s.substring(1).toLowerCase());
}
}
return result.toString();
}
/**
*
*/
public String getEntityName(String tableName) {
return underlineToHump(capFirst(tableName.toLowerCase()));
}
/**
*
*/
public String getEntityNameLower(String tableName) {
return underlineToHump(tableName.toLowerCase());
}
/**
*
*/
public void generate(Map<String, Object> tempData, String templateName, String saveUrl, String fileName) throws Exception {
//获取模板
Template template = freeMarker.getTemplate(templateName);
//输出文件
printFile(tempData, template, saveUrl, fileName);
}
public void generate(BaseEntity baseEntity, String templateName, String saveUrl, String entityName) throws Exception {
//获取模板
Template template = freeMarker.getTemplate(templateName);
//输出文件
// printFile(root, template, saveUrl, entityName);
}
}

@ -0,0 +1,204 @@
package com.azhoucode.util;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.serializer.SimpleDateFormatSerializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
public class JsonUtils {
private final static Logger logger = LoggerFactory.getLogger(JsonUtils.class);
private static final SerializeConfig config;
private static final String EMPTY_STRING = "";
static {
config = new SerializeConfig();
config.put(Date.class, new SimpleDateFormatSerializer("yyyy-MM-dd HH:mm:ss"));
}
private static final SerializerFeature[] serializerFeatures = {
// 输出空置字段
SerializerFeature.WriteMapNullValue,
// list字段如果为null输出为[]而不是null
SerializerFeature.WriteNullListAsEmpty,
// 数值字段如果为null输出为0而不是null
// SerializerFeature.WriteNullNumberAsZero,
// Boolean字段如果为null输出为false而不是null
// SerializerFeature.WriteNullBooleanAsFalse,
// 字符类型字段如果为null输出为""而不是null
// SerializerFeature.WriteNullStringAsEmpty
};
private JsonUtils() {}
/**
* Objectjson
* @param object bean
* @return {@link String}
*/
public static String objectToJson(Object object) {
if (object == null) {
return EMPTY_STRING;
}
try {
return JSON.toJSONString(object, config, serializerFeatures);
} catch (Exception e) {
logger.error("JsonUtil | method=objectToJson() | 对象转为Json字符串 Error", e);
return EMPTY_STRING;
}
}
/**
* Object
* @param json json
* @return {@link java.util.Arrays}
*/
public static Object[] toArray(String json) {
if (StringUtils.isEmpty(json)) {
return new Object[0];
}
try {
return toArray(json, null);
} catch (Exception e) {
logger.error("JsonUtil | method=toArray() | 将json格式的数据转换为数组 Object Error", e);
return new Object[0];
}
}
/**
*
* @param json json
* @param clazz {@link Class}
* @param <T>
* @return object
*/
public static <T> Object[] toArray(String json, Class<T> clazz) {
if (StringUtils.isEmpty(json)) {
return new Object[0];
}
try {
return JSON.parseArray(json, clazz).toArray();
} catch (Exception e) {
logger.error("JsonUtil | method=toArray() | 将json格式的数据转换为数组 (可指定类型) Error" + e.getMessage(), e);
return new Object[0];
}
}
/**
* jsonjava bean
* @param json json
* @param clazz {@link Class}
* @param <T> bean
* @return T
*/
public static <T> T jsonToObject(String json, Class<T> clazz) {
if (StringUtils.isEmpty(json)) {
return null;
}
try {
return JSON.parseObject(json, clazz);
} catch (Exception e) {
logger.error("JsonUtil | method=jsonToObject() | Json 转为 Java Bean Error" + e.getMessage(), e);
return null;
}
}
public static Map<String, Object> jsonToMap(String json) {
if (StringUtils.isEmpty(json)) {
return null;
}
try {
return JSON.parseObject(json);
} catch (Exception e) {
logger.error("JsonUtil | method=jsonToMap() | Json 转为 Map {},{}" + e.getMessage(), e);
}
return null;
}
public static <T> T jsonToMap(String json, Class<T> clazz) {
if (StringUtils.isEmpty(json)) {
return null;
}
try {
return JSON.parseObject(json, clazz);
} catch (Exception e) {
logger.error("JsonUtil | method=jsonToMap() | Json 转为 Map {},{}" + e.getMessage(), e);
return null;
}
}
/**
* json List
* @param json json
* @param clazz {@link Class}
* @param <T>
* @return {@link List}
*/
public static <T> List<T> toList(String json, Class<T> clazz) {
if (StringUtils.isEmpty(json)) {
return new ArrayList<>();
}
try {
return JSON.parseArray(json, clazz);
} catch (Exception e) {
logger.error("JsonUtil | method=toList() | Json 转为List发生异常。", e);
return new ArrayList<>();
}
}
/**
* jsonkey
* @param json json
* @param key key
* @return key
*/
public static String getStringFromJson(final String json, final String key) {
if (StringUtils.isEmpty(json)) {
return EMPTY_STRING;
}
try {
if (StringUtils.isEmpty(json) || StringUtils.isEmpty(key)) {
return EMPTY_STRING;
}
return JSON.parseObject(json).getString(key);
} catch (Exception e) {
logger.error("JsonUtil | method=getStringFromJson() | 从json获取指定key的字符串 Error" + e.getMessage(), e);
return EMPTY_STRING;
}
}
/**
* jsonkey
* @param json json
* @param key key
* @param clazz key
* @param <T>
* @return T
*/
public static <T> T getValueFromJson(final String json, final String key, Class<T> clazz) {
if (StringUtils.isEmpty(json)) {
return null;
}
try {
if (StringUtils.isEmpty(json) || StringUtils.isEmpty(key)) {
return null;
}
return JSON.parseObject(json).getObject(key, clazz);
} catch (Exception e) {
logger.error("JsonUtil | method=getValueFromJson() | 从json获取指定key的字符串 Error" + e.getMessage(), e);
}
return null;
}
}

@ -0,0 +1,12 @@
package com.azhoucode.util;
public class RandomUtil {
public static String getRamdom() {
String token = String.valueOf(System.currentTimeMillis()) ;
return token;
}
}

@ -0,0 +1,645 @@
package com.azhoucode.util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class RedisCacheUtils {
private static final Logger logger = LoggerFactory.getLogger(RedisCacheUtils.class);
private static JedisPool jedisPool;
private RedisCacheUtils() {}
public static void setPool(JedisPool jedisPool) {
RedisCacheUtils.jedisPool = jedisPool;
}
/**
* redis
*
* @param key
* @param clazz
* @param <T>
* @return redisjson
*/
public static <T> T get(String key, Class<T> clazz) {
Jedis redis = null;
try {
redis = jedisPool.getResource();
String value = redis.get(key);
return stringToBean(value, clazz);
} catch (Exception e) {
logger.error("从redis读数据{get}操作发生异常", e);
return null;
} finally {
release(redis);
}
}
/**
* redis
*
* @param key
* @return redisjson
*/
public static String get(String key) {
Jedis redis = null;
try {
redis = jedisPool.getResource();
return redis.get(key);
} catch (Exception e) {
logger.error("从redis读数据{get}操作发生异常", e);
return null;
} finally {
release(redis);
}
}
/**
* keyvalue
*
* @param key
* @param <T>
* @return true
*/
public static <T> Boolean set(String key, T value) {
return set(key, value, -1);
}
/**
* keyvaluekey
*
* @param key
* @param <T>
* @return true
*/
public static <T> Boolean set(String key, T value, int expireTimeSeconds) {
Jedis redis = null;
try {
redis = jedisPool.getResource();
String str = beanToString(value);
if (str == null) {
return false;
}
if (expireTimeSeconds <= 0) {
redis.set(key, str);
} else {
redis.setex(key, expireTimeSeconds, str);
}
return true;
} catch (Exception e) {
logger.error("从redis写数据{set}操作发生异常", e);
return null;
} finally {
release(redis);
}
}
/**
* keyvalue
*
* @param key
* @return true
*/
public static Boolean delete(String key) {
Jedis redis = null;
try {
redis = jedisPool.getResource();
Long del = redis.del(key);
return del > 0L;
} catch (Exception e) {
logger.error("从redis写数据{delete}操作发生异常", e);
return null;
} finally {
release(redis);
}
}
/**
* rediskey
*
* @param key
* @return keytrue
*/
public static boolean exists(String key) {
Jedis redis = null;
try {
redis = jedisPool.getResource();
Boolean exists = redis.exists(key);
return exists != null && exists;
} catch (Exception e) {
logger.error("从redis读数据{exists}操作发生异常", e);
return false;
} finally {
release(redis);
}
}
/**
* rediskey
*
* @param key
* @return
*/
public static Long incr(String key) {
Jedis redis = null;
try {
redis = jedisPool.getResource();
return redis.incr(key);
} catch (Exception e) {
logger.error("从redis写数据{incr}操作发生异常", e);
return null;
} finally {
release(redis);
}
}
/**
* key
*
* @param key
* @param expireTimeSeconds
*/
public static void expireAfter(String key, int expireTimeSeconds) {
Jedis redis = null;
try {
redis = jedisPool.getResource();
redis.expire(key, expireTimeSeconds);
} catch (Exception e) {
logger.error("从redis写数据{expire}操作发生异常", e);
} finally {
release(redis);
}
}
/**
* hashfield
*
* @param key hash
* @param field hash
* @return hash
*/
public static String hget(String key, String field) {
Jedis redis = null;
try {
redis = jedisPool.getResource();
return redis.hget(key, field);
} catch (Exception e) {
logger.error("从redis读数据{hget}操作发生异常", e);
return null;
} finally {
release(redis);
}
}
/**
* hashfield
*
* @param key hash
* @return hash
*/
public static void hmset(String key, Map<String, String> map) {
Jedis redis = null;
try {
redis = jedisPool.getResource();
redis.hmset(key, map);
} catch (Exception e) {
logger.error("从redis读数据{hgetAll}操作发生异常", e);
} finally {
release(redis);
}
}
public static void hmset(String key, Map<String, String> map, int expireTimeSeconds) {
Jedis redis = null;
try {
redis = jedisPool.getResource();
redis.hmset(key, map);
if (expireTimeSeconds > 0) {
expireAfter(key, expireTimeSeconds);
}
} catch (Exception e) {
logger.error("从redis读数据{hgetAll}操作发生异常", e);
} finally {
release(redis);
}
}
/**
* hashfield
*
* @param key hash
* @return hash
*/
public static Map<String, String> hgetAll(String key) {
Jedis redis = null;
try {
redis = jedisPool.getResource();
return redis.hgetAll(key);
} catch (Exception e) {
logger.error("从redis读数据{hgetAll}操作发生异常", e);
return null;
} finally {
release(redis);
}
}
/**
* hashfield
*
* @param key hash
* @param field hash
* @param fieldValue hash
*/
public static void hset(String key, String field, String fieldValue) {
Jedis redis = null;
try {
redis = jedisPool.getResource();
redis.hset(key, field, fieldValue);
} catch (Exception e) {
logger.error("从redis写数据{hset}操作发生异常", e);
} finally {
release(redis);
}
}
/**
* hashfield
*
* @param key hash
* @param field hash
* @param fieldValue hash
*/
public static void hset(String key, String field, String fieldValue, int expireTimeSeconds) {
Jedis redis = null;
try {
redis = jedisPool.getResource();
hset(key, field, fieldValue);
if (expireTimeSeconds > 0) {
expireAfter(key, expireTimeSeconds);
}
} catch (Exception e) {
logger.error("从redis写数据{hset}操作发生异常", e);
} finally {
release(redis);
}
}
/**
* redis sortedSet
*
* @param key key
* @param score key
* @param member
*/
public static void zadd(String key, double score, String member) {
Jedis redis = null;
try {
redis = jedisPool.getResource();
redis.zadd(key, score, member);
} catch (Exception e) {
logger.error("从redis写数据{zadd}操作发生异常", e);
} finally {
release(redis);
}
}
/**
*
*
* @param key
* @param member
*/
public static void zremove(String key, String... member) {
Jedis redis = null;
try {
redis = jedisPool.getResource();
redis.zrem(key, member);
} catch (Exception e) {
logger.error("从redis写数据{zremove}操作发生异常", e);
} finally {
release(redis);
}
}
/**
*
*
* @param key
* @param start
* @param end
* @return
*/
public static Long zremrangeByScore(String key, long start, long end) {
Jedis redis = null;
try {
redis = jedisPool.getResource();
return redis.zremrangeByScore(key, start, end);
} catch (Exception e) {
logger.error("从redis写数据{zremrangeByScore}操作发生异常", e);
return null;
} finally {
release(redis);
}
}
/**
*
*
* @param key
* @return
*/
public static Long zcard(String key) {
Jedis redis = null;
try {
redis = jedisPool.getResource();
return redis.zcard(key);
} catch (Exception e) {
logger.error("从redis读数据{zcard}操作发生异常", e);
return null;
} finally {
release(redis);
}
}
/**
* redis
*
* @param key key
* @param start
* @param end
* @return {@link java.util.HashSet}
*/
public static Set<String> zrange(String key, long start, long end) {
Jedis redis = null;
try {
redis = jedisPool.getResource();
return redis.zrange(key, start, end);
} catch (Exception e) {
logger.error("从redis读数据{zrange}操作发生异常", e);
return null;
} finally {
release(redis);
}
}
/**
* redis
*
* @param key key
* @param start
* @param end
* @return {@link java.util.HashSet}
*/
public static Set<String> zrevrange(String key, long start, long end) {
Jedis redis = null;
try {
redis = jedisPool.getResource();
return redis.zrevrange(key, start, end);
} catch (Exception e) {
logger.error("从redis读数据{zrevrange}操作发生异常", e);
return null;
} finally {
release(redis);
}
}
/**
* push
*
* @param key key
* @param value value
* @return truefalse
*/
public static boolean lpush(String key, String value) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
jedis.lpush(key, value);
return true;
} catch (Exception e) {
logger.error("从redis写数据{lpush}操作发生异常", e);
return false;
} finally {
release(jedis);
}
}
/**
* redis
*
* @param key key
* @param clazz valueclass
* @param <T>
* @return bean
*/
public static <T> T rpop(String key, Class<T> clazz) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
String pop = jedis.rpop(key);
return stringToBean(pop, clazz);
} catch (Exception e) {
logger.error("从redis写数据{rpop}操作发生异常", e);
return null;
} finally {
release(jedis);
}
}
/**
* redis
*
* @param key key
* @param start
* @param end
* @return {@link ArrayList}
*/
public static List<String> lrange(String key, long start, long end) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
return jedis.lrange(key, start, end);
} catch (Exception e) {
logger.error("从redis读数据{lrange}操作发生异常", e);
return null;
} finally {
release(jedis);
}
}
/**
* sorted set
*
* @param key key
* @param start
* @param end
* @return {@link ArrayList}
*/
public static Set<Tuple> zrangeByScoreWithScores(String key, long start, long end) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
return jedis.zrangeByScoreWithScores(key, start, end);
} catch (Exception e) {
logger.error("从redis读数据{zrangeByScoreWithScores}操作发生异常", e);
return null;
} finally {
release(jedis);
}
}
/**
* Tuple
*
* @param key key
* @param min
* @param max
* @param offset
* @param count
* @return {@link java.util.HashSet}
*/
public static Set<Tuple> zrangeByScoreWithScores(String key, double min, double max, int offset, int count) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
return jedis.zrangeByScoreWithScores(key, min, max, offset, count);
} catch (Exception e) {
logger.error("从redis读数据{zrangeByScoreWithScores}操作发生异常", e);
return null;
} finally {
release(jedis);
}
}
/**
* Tuple
*
* @param key key
* @param max
* @param min
* @param offset
* @param count
* @return {@link java.util.HashSet}
*/
public static Set<Tuple> zrevrangeByScoreWithScores(String key, double max, double min, int offset, int count) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
return jedis.zrevrangeByScoreWithScores(key, max, min, offset, count);
} catch (Exception e) {
logger.error("从redis读数据{zrevrangeByScoreWithScores}操作发生异常", e);
return null;
} finally {
release(jedis);
}
}
/**
* Tuple
*
* @param key key
* @param max
* @param min
* @return {@link java.util.HashSet}
*/
public static Set<Tuple> zrevrangeByScoreWithScores(String key, double max, double min) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
return jedis.zrevrangeByScoreWithScores(key, max, min);
} catch (Exception e) {
logger.error("从redis读数据{zrevrangeByScoreWithScores}操作发生异常", e);
return null;
} finally {
release(jedis);
}
}
/**
* keyuser:*user:key
*
* @param keyPattern
* @return
*/
public static List<String> scan(String keyPattern) {
Jedis redis = null;
try {
redis = jedisPool.getResource();
ScanParams scanParams = new ScanParams();
scanParams.match(keyPattern);
scanParams.count(Integer.MAX_VALUE);
ScanResult<String> scanResult = redis.scan(ScanParams.SCAN_POINTER_START, scanParams);
return scanResult.getResult();
} catch (Exception e) {
logger.error("从redis读数据{scan}操作发生异常", e);
return new ArrayList<>();
} finally {
release(redis);
}
}
/**
* java bean
*
* @param value
* @param <T>
* @return json
*/
private static <T> String beanToString(T value) {
if (value == null) {
return null;
}
Class<?> clazz = value.getClass();
if ((clazz == Integer.TYPE) || (clazz == Integer.class) || (clazz == Long.TYPE) || (clazz == Long.class)) {
return String.valueOf(value);
} else if (clazz == String.class) {
return (String)value;
}
return JsonUtils.objectToJson(value);
}
/**
* java bean
*
* @param value
* @param clazz
* @param <T>
* @return json
*/
@SuppressWarnings("unchecked")
private static <T> T stringToBean(String value, Class<T> clazz) {
if (value == null || clazz == null) {
return null;
}
if ((clazz == Integer.TYPE) || (clazz == Integer.class)) {
return (T)Integer.valueOf(value);
}
if ((clazz == Long.TYPE) || (clazz == Long.class)) {
return (T)Long.valueOf(value);
}
if (clazz == String.class) {
return (T)value;
}
return JsonUtils.jsonToObject(value, clazz);
}
/**
*
*
* @param jedis {@link Jedis}
*/
private static void release(Jedis jedis) {
if (jedis != null) {
jedis.close();
}
}
}

@ -0,0 +1,7 @@
file-path:
# project: D:\\shop\\linshou\\server
# vue: D:\\shop\\linshou\\vue-element-admin
project: F:\\zt\\zt-workspace\\server
vue: F:\\zt\vue\\vue-admin\\vue-element-admin

@ -0,0 +1,4 @@
file-path:
project: F:\\zt\\zt-workspace\\server

@ -0,0 +1,38 @@
server:
port: 8888
spring:
redis:
port: 6379
host: 127.0.0.1
password:
maxActive: 300
database: 0
timeout: 2000
maxIdle: 200
maxWait: 3000
minIdle: 50
profiles:
active: dev
freemarker:
settings:
classic_compatible: true
base-path: ${file-path.project}\\src\\main\\java\\com\\server\\api
dao: ${base-path}\\dao
dto: ${base-path}\\dto
service: ${base-path}\\service
serviceImpl: ${base-path}\\service\\impl
controller: ${base-path}\\controller
entity: ${base-path}\\entity
application: ${file-path.project}\\src\\main\\resources
xml: ${file-path.project}\\src\\main\\resources\\dao
config: ${base-path}\\common\\config
util: ${base-path}\\common\\util
vueTable: ${file-path.vue}\\src\\views\\%s
vueTableApi: ${file-path.vue}\\src\\api\\%s
vueRouter: ${file-path.vue}\\src\\router
vueCommonTable: F:\\zt\\temp\\exam\\src\\views
vueCommonRouterPath: F:\\zt\\temp\\exam\\src\\router
vueCommonSidebarPath: F:\\zt\\temp\\exam\\src\\components
vueTable2: F:\\zt\\vue\\vue-admin\\vue-next-admin\src\\views\\%s
vueTableApi2: F:\\zt\\vue\\vue-admin\\vue-next-admin\\src\\api\\%s
vueRouter3: F:\\zt\\vue\\vue-admin\\vue-next-admin\\public

@ -0,0 +1,113 @@
<template>
<div class="sidebar">
<el-menu
class="sidebar-el-menu"
:default-active="onRoutes"
:collapse="collapse"
background-color="#324157"
text-color="#bfcbd9"
active-text-color="#20a0ff"
unique-opened
router
>
<template v-for="item in items">
<template v-if="item.subs">
<el-submenu :index="item.index" :key="item.index">
<template #title>
<i :class="item.icon"></i>
<span>{{ item.title }}</span>
</template>
<template v-for="subItem in item.subs">
<el-submenu
v-if="subItem.subs"
:index="subItem.index"
:key="subItem.index"
>
<template #title>{{ subItem.title }}</template>
<el-menu-item
v-for="(threeItem, i) in subItem.subs"
:key="i"
:index="threeItem.index"
>{{ threeItem.title }}
</el-menu-item
>
</el-submenu>
<el-menu-item
v-else
:index="subItem.index"
:key="subItem.index"
>{{ subItem.title }}
</el-menu-item
>
</template>
</el-submenu>
</template>
<template v-else>
<el-menu-item :index="item.index" :key="item.index">
<i :class="item.icon"></i>
<template #title>{{ item.title }}</template>
</el-menu-item>
</template>
</template>
</el-menu>
</div>
</template>
<script>
import {util} from '../utils/index';
export default {
mixins: [util],
data() {
return {
items: [{
icon: "el-icon-s-home",
index: "/main",
title: "系统首页",
},
<#if routerParams??>
<#list routerParams as col>
{
icon: "el-icon-s-home",
index: "/${col["routerName"]}",
title: "${col["chinaName"]}",
},
</#list>
</#if>
]
};
},
computed: {
onRoutes() {
return this.$route.path.replace("/", "");
},
collapse() {
return this.$store.state.collapse;
},
},
};
</script>
<style scoped>
.sidebar {
display: block;
position: absolute;
left: 0;
top: 70px;
bottom: 0;
overflow-y: scroll;
}
.sidebar::-webkit-scrollbar {
width: 0;
}
.sidebar-el-menu:not(.el-menu--collapse) {
width: 200px;
}
.sidebar > ul {
height: 100%;
}
</style>

@ -0,0 +1,45 @@
{
"code": 0,
"data": [
{
"path": "/home",
"name": "home",
"component": "home",
"meta": {
"title": "message.router.home",
"isLink": "",
"isHide": false,
"isKeepAlive": true,
"isAffix": true,
"isIframe": false,
"roles": [
"admin",
"common"
],
"icon": "iconfont icon-shouye"
}
},
<#if routerParams??>
<#list routerParams as col>
{
"path": "/${col["routerName"]}",
"name": "${col["chinaName"]}",
"component": "${col["routerName"]}",
"meta": {
"title": "${col["chinaName"]}",
"isLink": "",
"isHide": false,
"isKeepAlive": true,
"isAffix": false,
"isIframe": false,
"roles": [
"admin",
"common"
],
"icon": "iconfont icon-gongju"
}
},
</#list>
</#if>
]
}

@ -0,0 +1,43 @@
import request from '@/utils/request'
const moduleUrl = "/${unClassName}"
/** 分页 */
export function page(data) {
return request({
url: moduleUrl + '/page',
method: 'post',
data
})
}
/** 添加或修改 */
export function saveData(data) {
return request({
url: moduleUrl + "/save/update",
method: 'post',
data
})
}
/** 根据主键ID批量删除 */
export function batchDelete(data){
return request({
url: moduleUrl + "/remove",
method: 'post',
data
})
}
<#if selectEntities??>
<#list selectEntities as col>
export function get${col['className']}SelectData(){
return request({
url: moduleUrl + "/get${col['className']}Data",
method: 'get'
})
}
</#list>
</#if>

@ -0,0 +1,70 @@
server:
port: ${port?c}
spring:
<#if hasEmail>
mail:
host: smtp.qq.com #发送邮件服务器
username: 1192704429@qq.com #QQ邮箱
password: dbzczkrkwfblfjfe #客户端授权码
protocol: smtp #发送邮件协议
properties.mail.smtp.auth: true
properties.mail.smtp.port: 465 #端口号465或587
properties.mail.display.sendmail: Javen #可以任意
properties.mail.display.sendname: Spring Boot Guide Email #可以任意
properties.mail.smtp.starttls.enable: true
properties.mail.smtp.starttls.required: true
properties.mail.smtp.ssl.enable: true
default-encoding: utf-8
from: 1192704429@qq.com #与上面的username保持一致
</#if>
datasource:
username: ${username?default("root")}
password: ${password?default("root")}
url: jdbc:mysql://${ip?default("127.0.0.1")}:${dbPort?default("3306")}/${dbName?default("example")}?characterEncoding=UTF-8&useUnicode=true&useOldAliasMetadataBehavior=true&useSSL=false&serverTimezone=GMT%2B8
driver-class-name: com.mysql.cj.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
<#if hasRedis>
redis:
database: 0
password: ${redisPassWord?default("")}
port: ${redisPort?default("6379")}
host: ${redisIp?default("127.0.0.1")}
# 连接超时时间
timeout: 500000
lettuce:
pool:
# 连接池最大连接数(使用负值表示没有限制)
max-active: 8
# 连接池中的最小空闲连接
min-idle: 2
# 连接池中的最大空闲连接
max-idle: 8
# 连接池最大阻塞等待时间(使用负值表示没有限制)
max-wait: -1
#在关闭客户端连接之前等待任务处理完成的最长时间在这之后无论任务是否执行完成都会被执行器关闭默认100ms
shutdown-timeout: 100
</#if>
mybatis-plus:
#sql语句Xml扫描
mapper-locations: classpath:/dao/**/*.xml
#实体扫描多个package用逗号或者分号分隔
typeAliasesPackage: com.server.api.entity
global-config:
#数据库相关配置
db-config:
#主键类型 AUTO:"数据库ID自增",INPUT:"用户输入ID",ID_WORKER:"全局唯一ID (数字类型唯一ID)",UUID:"全局唯一ID UUID";
id-type: AUTO
banner: false
#原生配置
configuration:
map-underscore-to-camel-case: true
cache-enabled: false
call-setters-on-nulls: true
jdbc-type-for-null: 'null'
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
<#if hasUploadImg>
#图片上传文件夹地址
imgRealUrl: ${uploadUrl?if_exists}
imgHost: http://localhost:8092
</#if>

@ -0,0 +1,94 @@
package com.server.api.controller;
import com.server.api.common.BaseController;
import com.server.api.common.ReturnMsg;
import com.server.api.dto.${className}DTO;
import com.server.api.service.${className}Service;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import java.io.IOException;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.ArrayList;
import java.util.List;
<#if selectEntities??>
import com.server.api.common.BaseSelectEntity;
import cn.hutool.core.collection.CollectionUtil;
<#list selectEntities as selectCol>
import com.server.api.dto.${selectCol['className']}DTO;
import com.server.api.service.${selectCol['className']}Service;
</#list>
</#if>
/**
* @Description: ${tableComment}对外接口层
* @Author: wuming
*/
@RestController
@RequestMapping("/${unClassName}")
public class ${className}Controller extends BaseController<${className}Service, ${className}DTO> {
@Override
@Resource(name = "${unClassName}Service")
protected void setBaseService(${className}Service ${unClassName}Service) {
this.baseService = ${unClassName}Service;
}
<#if selectEntities??>
<#list selectEntities as selectCol>
@Autowired
private ${selectCol['className']}Service ${selectCol['unClassName']}Service;
</#list>
</#if>
<#if hasUpload>
/**
* 图片上传文件夹名称
*/
private final String realPath = "/${unClassName}";
/**
* 图片上传
*
* @param filename
* @param id 需要修改的数据主键id
* @return
* @throws IOException
*/
@PostMapping("/upload/{id}")
public ReturnMsg upload(@RequestParam("file") MultipartFile filename, @PathVariable("id") Long id) throws IOException {
return this.baseUpLoad(filename, id, realPath, ${className}DTO.class) ? ReturnMsg.ok() : ReturnMsg.error();
}
</#if>
/**
* 默认分页查询
* @param ${unClassName}DTO
* @return
* @throws IOException
*/
@PostMapping("/page")
public ReturnMsg page(@RequestBody ${className}DTO ${unClassName}DTO) {
return ReturnMsg.ok(baseService.basePage(${unClassName}DTO));
}
<#if selectEntities??>
<#list selectEntities as selectCol>
@GetMapping("/get${selectCol['className']}Data")
public ReturnMsg get${selectCol['className']}Data(){
List<${selectCol['className']}DTO> dataList = ${selectCol['unClassName']}Service.list();
List<BaseSelectEntity> selectEntities = new ArrayList<>();
if(CollectionUtil.isNotEmpty(dataList)){
dataList.forEach(item -> {
BaseSelectEntity baseSelectEntity = new BaseSelectEntity();
baseSelectEntity.setKey(item.get${selectCol['valueCol']}());
baseSelectEntity.setValue(item.get${selectCol['nameCol']}());
selectEntities.add(baseSelectEntity);
});
}
return ReturnMsg.ok(selectEntities);
}
</#list>
</#if>
}

@ -0,0 +1,12 @@
package com.server.api.dao;
import com.server.api.common.BaseDao;
import com.server.api.dto.${className}DTO;
/**
* @Description: ${tableComment}数据库访问持久层
* @Author: wuming
*/
public interface ${className}Dao extends BaseDao<${className}DTO> {
}

@ -0,0 +1,31 @@
package com.server.api.dto;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import com.server.api.entity.${className};
import lombok.Data;
import lombok.ToString;
/**
* @Description: ${tableComment}传输层
* @Author: wuming
*/
@Data
@ToString
@TableName("${tableName}")
public class ${className}DTO extends ${className} {
<#--循环生成变量-->
<#if showColList??>
<#list showSonTableColList as col>
<#if col["propertyName"] != "id">
/**
* ${col["propertyChinaName"]}
*/
@TableField(exist = false)
private ${col["propertyType"]} ${col["propertyName"]};
</#if>
</#list>
</#if>
}

@ -0,0 +1,37 @@
package com.server.api.entity;
import com.server.api.common.BaseEntity;
import java.util.Date;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import com.fasterxml.jackson.annotation.JsonFormat;
/**
* @Description: ${tableComment} 实体类
* @Author: wuming
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class ${className} extends BaseEntity {
<#if showColList??>
<#--循环生成变量-->
<#list showColList as col>
<#if col["propertyName"] != "id">
/**
* ${col["propertyChinaName"]}
*/
<#if col["propertyType"]=="Date">
@JsonFormat(pattern = "yyyy-MM-dd")
</#if>
private ${col["propertyType"]} ${col["propertyName"]};
</#if>
</#list>
</#if>
}

@ -0,0 +1,65 @@
package com.server.api.controller;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.server.api.common.ReturnMsg;
import com.server.api.common.constants.BaseConstant;
import com.server.api.dto.${className}DTO;
import com.server.api.service.${className}Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @description: 后台登录
* @author: wuming
**/
@RestController
@RequestMapping("/login")
public class LoginController {
@Autowired
private ${className}Service ${unClassName}Service;
@PostMapping()
public ReturnMsg login(@RequestBody ${className}DTO ${unClassName}DTO) {
Assert.isTrue(StrUtil.isNotEmpty(${unClassName}DTO.get${userNameCol}())
&& StrUtil.isNotEmpty(${unClassName}DTO.get${passWordCol}()), "账号或密码不能为空!");
LambdaQueryWrapper<${className}DTO> queryWrapper = Wrappers.lambdaQuery();
queryWrapper.eq(${className}DTO::get${userNameCol},${unClassName}DTO.get${userNameCol}()).
eq(${className}DTO::get${passWordCol},${unClassName}DTO.get${passWordCol}()).last(BaseConstant.LIMIT_ONE);
${className}DTO loginUser = ${unClassName}Service.getOne(queryWrapper);
Assert.notNull(loginUser,"账号或密码错误!");
return ReturnMsg.ok(loginUser);
}
@GetMapping("/{id}")
public ReturnMsg getUserInfo(@PathVariable("id") Long id) {
List<String> roles = new ArrayList<>();
Map<String, Object> map = new HashMap<>();
roles.add("admin");
map.put("roles", roles);
map.put("introduction", "打工人...");
<#if !hasUserInfo>
map.put("name", "admin");
map.put("avatar", "http://www.elitetest.cn/img/logo.png");
<#else>
${className}DTO userInfo = ${unClassName}Service.getById(id);
map.put("name", userInfo.get${nickNameCol}());
map.put("avatar", StrUtil.isNotEmpty(userInfo.get${headImgCol}()) ? userInfo.get${headImgCol}() : "http://www.elitetest.cn/img/logo.png");
</#if>
return ReturnMsg.ok(map);
}
@DeleteMapping()
public ReturnMsg logOut() {
return ReturnMsg.ok();
}
}

@ -0,0 +1,32 @@
<#noparse>package com.server.api.common.util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;
/**
* @Description: 简单邮件发送帮助类
* @Author: wuming
*/
@Component
public class MailUtil {
@Value("${spring.mail.from}")
private String from;
@Autowired
private JavaMailSender mailSender;
public void sendSimpleMail(String to, String subject, String content) {
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(from);
message.setTo(to);
message.setSubject(subject);
message.setText(content);
mailSender.send(message);
}
}
</#noparse>

@ -0,0 +1,116 @@
<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.6.RELEASE</version>
<relativePath/>
</parent>
<groupId>com.server</groupId>
<artifactId>server</artifactId>
<version>1.0.0</version>
<name>server</name>
<description>JAVA服务端应用</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<!-- ================================公共依赖Start====================================== -->
<!-- spring-boot启动项 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<!-- springboot web启动项 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- druid数据源 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.24</version>
</dependency>
<!-- mysql数据库驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.11</version>
</dependency>
<!-- mybatis-plus -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.3</version>
</dependency>
<!-- http请求 -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>
<!-- lombok实体层注解 -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.12</version>
</dependency>
<!-- 文件上传 -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<!-- hutool常用帮助包 -->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.7.2</version>
</dependency>
<!-- json帮助包 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.47</version>
</dependency>
<!-- springboot测试 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- ================================公共依赖End====================================== -->
<#if hasEmail>
<!-- qq邮件发送 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
</#if>
<#if hasRedis>
<!-- redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- lettuce-pool 缓存连接池 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
<version>2.7.0</version>
</dependency>
</#if>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

@ -0,0 +1,112 @@
<#noparse>package com.server.api.common.config;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisPassword;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceClientConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettucePoolingClientConfiguration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import java.time.Duration;
/**
* @Description: redis配置类
* @Author: wuming
*/
@Configuration
@EnableCaching
public class RedisConfig {
@Value("${spring.redis.database}")
private int database;
@Value("${spring.redis.host}")
private String host;
@Value("${spring.redis.password}")
private String password;
@Value("${spring.redis.port}")
private int port;
@Value("${spring.redis.timeout}")
private long timeout;
@Value("${spring.redis.lettuce.shutdown-timeout}")
private long shutDownTimeout;
@Value("${spring.redis.lettuce.pool.max-idle}")
private int maxIdle;
@Value("${spring.redis.lettuce.pool.min-idle}")
private int minIdle;
@Value("${spring.redis.lettuce.pool.max-active}")
private int maxActive;
@Value("${spring.redis.lettuce.pool.max-wait}")
private long maxWait;
Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
@Bean
public LettuceConnectionFactory lettuceConnectionFactory() {
GenericObjectPoolConfig genericObjectPoolConfig = new GenericObjectPoolConfig();
genericObjectPoolConfig.setMaxIdle(maxIdle);
genericObjectPoolConfig.setMinIdle(minIdle);
genericObjectPoolConfig.setMaxTotal(maxActive);
genericObjectPoolConfig.setMaxWaitMillis(maxWait);
genericObjectPoolConfig.setTimeBetweenEvictionRunsMillis(100);
RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration();
redisStandaloneConfiguration.setDatabase(database);
redisStandaloneConfiguration.setHostName(host);
redisStandaloneConfiguration.setPort(port);
redisStandaloneConfiguration.setPassword(RedisPassword.of(password));
LettuceClientConfiguration clientConfig = LettucePoolingClientConfiguration.builder()
.commandTimeout(Duration.ofMillis(timeout))
.shutdownTimeout(Duration.ofMillis(shutDownTimeout))
.poolConfig(genericObjectPoolConfig)
.build();
LettuceConnectionFactory factory = new LettuceConnectionFactory(redisStandaloneConfiguration, clientConfig);
factory.setShareNativeConnection(true);
factory.setValidateConnection(false);
return factory;
}
@Bean
public RedisTemplate<String, Object> redisTemplate(LettuceConnectionFactory lettuceConnectionFactory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(lettuceConnectionFactory);
//使用Jackson2JsonRedisSerializer替换默认的JdkSerializationRedisSerializer来序列化和反序列化redis的value值
ObjectMapper mapper = new ObjectMapper();
mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
mapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance,
ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);
jackson2JsonRedisSerializer.setObjectMapper(mapper);
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
//key采用String的序列化方式
template.setKeySerializer(stringRedisSerializer);
// hash的key也采用String的序列化方式
template.setHashKeySerializer(stringRedisSerializer);
// value序列化方式采用jackson
template.setValueSerializer(jackson2JsonRedisSerializer);
// hash的value序列化方式采用jackson
template.setHashValueSerializer(jackson2JsonRedisSerializer);
template.afterPropertiesSet();
return template;
}
}
</#noparse>

@ -0,0 +1,563 @@
<#noparse>package com.server.api.common.util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
/**
* @Description: redis 工具类
* @Author: wuming
*/
@Component
@SuppressWarnings(value = {"unchecked", "rawtypes"})
public class RedisUtil {
/**
* 注入redisTemplate bean
*/
@Autowired
private RedisTemplate<String,Object> redisTemplate;
/**
* 指定缓存失效时间
* @param key 键
* @param time 时间(秒)
* @return
*/
public boolean expire(String key, long time) {
try {
if (time > 0) {
redisTemplate.expire(key, time, TimeUnit.SECONDS);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 根据key获取过期时间
* @param key 键 不能为null
* @return 时间(秒) 返回0代表为永久有效
*/
public long getExpire(String key) {
return redisTemplate.getExpire(key, TimeUnit.SECONDS);
}
/**
* 判断key是否存在
* @param key 键
* @return true 存在 false不存在
*/
public boolean hasKey(String key) {
try {
return redisTemplate.hasKey(key);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 删除缓存
* @param key 可以传一个值 或多个
*/
@SuppressWarnings("unchecked")
public void del(String... key) {
if (key != null && key.length > 0) {
if (key.length == 1) {
redisTemplate.delete(key[0]);
} else {
Collection c = CollectionUtils.arrayToList(key);
redisTemplate.delete(c);
}
}
}
// ============================String(字符串)=============================
/**
* 普通缓存获取
* @param key 键
* @return 值
*/
public Object get(String key) {
return key == null ? null : redisTemplate.opsForValue().get(key);
}
/**
* 普通缓存放入
* @param key 键
* @param value 值
* @return true成功 false失败
*/
public boolean set(String key, Object value) {
try {
redisTemplate.opsForValue().set(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 普通缓存放入并设置时间
* @param key 键
* @param value 值
* @param time 时间(秒) time要大于0 如果time小于等于0 将设置无限期
* @return true成功 false 失败
*/
public boolean set(String key, Object value, long time) {
try {
if (time > 0) {
redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
} else {
set(key, value);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 递增
* @param key 键
* @param delta 要增加几(大于0)
* @return
*/
public long incr(String key, long delta) {
if (delta < 0) {
throw new RuntimeException("递增因子必须大于0");
}
return redisTemplate.opsForValue().increment(key, delta);
}
/**
* 递减
* @param key 键
* @param delta 要减少几(小于0)
* @return
*/
public long decr(String key, long delta) {
if (delta < 0) {
throw new RuntimeException("递减因子必须大于0");
}
return redisTemplate.opsForValue().increment(key, -delta);
}
// ================================Hash(哈希)=================================
/**
* HashGet
* @param key 键 不能为null
* @param item 项 不能为null
* @return 值
*/
public Object hget(String key, String item) {
return redisTemplate.opsForHash().get(key, item);
}
/**
* 获取hashKey对应的所有键值
* @param key 键
* @return 对应的多个键值
*/
public Map<Object, Object> hmget(String key) {
return redisTemplate.opsForHash().entries(key);
}
/**
* HashSet
* @param key 键
* @param map 对应多个键值
* @return true 成功 false 失败
*/
public boolean hmset(String key, Map <String, Object> map) {
try {
redisTemplate.opsForHash().putAll(key, map);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* HashSet 并设置时间
* @param key 键
* @param map 对应多个键值
* @param time 时间(秒)
* @return true成功 false失败
*/
public boolean hmset(String key, Map <String, Object> map, long time) {
try {
redisTemplate.opsForHash().putAll(key, map);
if (time > 0) {
expire(key, time);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 向一张hash表中放入数据,如果不存在将创建
* @param key 键
* @param item 项
* @param value 值
* @return true 成功 false失败
*/
public boolean hset(String key, String item, Object value) {
try {
redisTemplate.opsForHash().put(key, item, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 向一张hash表中放入数据,如果不存在将创建
* @param key 键
* @param item 项
* @param value 值
* @param time 时间(秒) 注意:如果已存在的hash表有时间,这里将会替换原有的时间
* @return true 成功 false失败
*/
public boolean hset(String key, String item, Object value, long time) {
try {
redisTemplate.opsForHash().put(key, item, value);
if (time > 0) {
expire(key, time);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 删除hash表中的值
* @param key 键 不能为null
* @param item 项 可以使多个 不能为null
*/
public void hdel(String key, Object... item) {
redisTemplate.opsForHash().delete(key, item);
}
/**
* 判断hash表中是否有该项的值
* @param key 键 不能为null
* @param item 项 不能为null
* @return true 存在 false不存在
*/
public boolean hHasKey(String key, String item) {
return redisTemplate.opsForHash().hasKey(key, item);
}
/**
* hash递增 如果不存在,就会创建一个 并把新增后的值返回
* @param key 键
* @param item 项
* @param by 要增加几(大于0)
* @return
*/
public double hincr(String key, String item, double by) {
return redisTemplate.opsForHash().increment(key, item, by);
}
/**
* hash递减
* @param key 键
* @param item 项
* @param by 要减少记(小于0)
* @return
*/
public double hdecr(String key, String item, double by) {
return redisTemplate.opsForHash().increment(key, item, -by);
}
// ============================Set(集合)=============================
/**
* 根据key获取Set中的所有值
* @param key 键
* @return
*/
public Set<Object> sGet(String key) {
try {
return redisTemplate.opsForSet().members(key);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 根据value从一个set中查询,是否存在
* @param key 键
* @param value 值
* @return true 存在 false不存在
*/
public boolean sHasKey(String key, Object value) {
try {
return redisTemplate.opsForSet().isMember(key, value);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 将数据放入set缓存
* @param key 键
* @param values 值 可以是多个
* @return 成功个数
*/
public long sSet(String key, Object... values) {
try {
return redisTemplate.opsForSet().add(key, values);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* 将set数据放入缓存
* @param key 键
* @param time 时间(秒)
* @param values 值 可以是多个
* @return 成功个数
*/
public long sSetAndTime(String key, long time, Object... values) {
try {
Long count = redisTemplate.opsForSet().add(key, values);
if (time > 0){
expire(key, time);
}
return count;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* 获取set缓存的长度
* @param key 键
* @return
*/
public long sGetSetSize(String key) {
try {
return redisTemplate.opsForSet().size(key);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* 移除值为value的
* @param key 键
* @param values 值 可以是多个
* @return 移除的个数
*/
public long setRemove(String key, Object... values) {
try {
Long count = redisTemplate.opsForSet().remove(key, values);
return count;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
// ===============================List(列表)=================================
/**
* 获取list缓存的内容
* @param key 键
* @param start 开始
* @param end 结束 0 到 -1代表所有值
* @return
*/
public <T>List<T> lGet(String key, long start, long end) {
try {
return (List<T>) redisTemplate.opsForList().range(key, start, end);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 获取list缓存的长度
*
* @param key 键
* @return
*/
public long lGetListSize(String key) {
try {
return redisTemplate.opsForList().size(key);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* 通过索引 获取list中的值
*
* @param key 键
* @param index 索引 index>=0时 0 表头1 第二个元素依次类推index<0时-1表尾-2倒数第二个元素依次类推
* @return
*/
public Object lGetIndex(String key, long index) {
try {
return redisTemplate.opsForList().index(key, index);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 将list放入缓存
*
* @param key 键
* @param value 值
* @return
*/
public boolean lSet(String key, Object value) {
try {
redisTemplate.opsForList().rightPush(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 将list放入缓存
*
* @param key 键
* @param value 值
* @param time 时间(秒)
* @return
*/
public boolean lSet(String key, Object value, long time) {
try {
redisTemplate.opsForList().rightPush(key, value);
if (time > 0){
expire(key, time);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 将list放入缓存
*
* @param key 键
* @param value 值
* @return
*/
public boolean lSet(String key, List <Object> value) {
try {
redisTemplate.opsForList().rightPushAll(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 将list放入缓存
*
* @param key 键
* @param value 值
* @param time 时间(秒)
* @return
*/
public boolean lSet(String key, List <Object> value, long time) {
try {
redisTemplate.opsForList().rightPushAll(key, value);
if (time > 0){
expire(key, time);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 根据索引修改list中的某条数据
*
* @param key 键
* @param index 索引
* @param value 值
* @return
*/
public boolean lUpdateIndex(String key, long index, Object value) {
try {
redisTemplate.opsForList().set(key, index, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 移除N个值为value
*
* @param key 键
* @param count 移除多少个
* @param value 值
* @return 移除的个数
*/
public long lRemove(String key, long count, Object value) {
try {
Long remove = redisTemplate.opsForList().remove(key, count, value);
return remove;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
public List getCacheList(final String key) {
return redisTemplate.opsForList().range(key, 0, -1);
}
/**
* 删除以模糊形态开头的key
* @param keys 键
*/
public void removeAll(String keys) {
if (keys != null) {
redisTemplate.delete(redisTemplate.keys(keys + "*"));
}
}
}
</#noparse>

@ -0,0 +1,27 @@
package com.server.api.service;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.server.api.dto.${className}DTO;
/**
* @Description: ${tableComment}业务层接口
* @Author: wuming
*/
public interface ${className}Service extends IService<${className}DTO> {
/**
* 默认分页方法
* @param ${unClassName}DTO
* @return
*/
Page<${className}DTO> basePage(${className}DTO ${unClassName}DTO);
/**
* 根据DTO对象中的条件查询单个对象
* @param ${unClassName}DTO
* @return
*/
${className}DTO find(${className}DTO ${unClassName}DTO);
}

@ -0,0 +1,34 @@
package com.server.api.service.impl;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.server.api.dao.${className}Dao;
import com.server.api.dto.${className}DTO;
import com.server.api.service.${className}Service;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* @Description: ${tableComment}业务层实现类
* @Author: wuming
*/
@Service("${unClassName}Service")
public class ${className}ServiceImpl extends ServiceImpl<${className}Dao, ${className}DTO> implements ${className}Service {
@Override
public Page<${className}DTO> basePage(${className}DTO ${unClassName}DTO) {
if (null != ${unClassName}DTO.getCurrent() && null != ${unClassName}DTO.getPageSize())
${unClassName}DTO.setCurrent((${unClassName}DTO.getCurrent() - 1) * ${unClassName}DTO.getPageSize());
List<${className}DTO> list = this.baseMapper.findList(${unClassName}DTO);
int count = this.baseMapper.findPageCount(${unClassName}DTO);
Page<${className}DTO> page = new Page<>();
page.setTotal(count);
page.setRecords(list);
return page;
}
@Override
public ${className}DTO find(${className}DTO ${unClassName}DTO) { return this.baseMapper.find(${unClassName}DTO); }
}

@ -0,0 +1,99 @@
import Vue from 'vue'
import Router from 'vue-router'
Vue.use(Router)
import Layout from '@/layout'
export const constantRoutes = [
{
path: '/redirect',
component: Layout,
hidden: true,
children: [
{
path: '/redirect/:path(.*)',
component: () => import('@/views/redirect/index')
}
]
},
{
path: '/login',
component: () => import('@/views/login/index'),
hidden: true
},
{
path: '/auth-redirect',
component: () => import('@/views/login/auth-redirect'),
hidden: true
},
{
path: '/404',
component: () => import('@/views/error-page/404'),
hidden: true
},
{
path: '/401',
component: () => import('@/views/error-page/401'),
hidden: true
},
{
path: '/',
component: Layout,
redirect: '/dashboard',
children: [
{
path: 'dashboard',
component: () => import('@/views/dashboard/index'),
name: '首页',
meta: { title: '首页', icon: 'dashboard', affix: true }
}
]
}
]
/**
* asyncRoutes
* the routes that need to be dynamically loaded based on user roles
*/
export const asyncRoutes = [
<#if routerParams??>
<#list routerParams as col>
{
path: '/sys',
component: Layout,
redirect: '/sys/${col["routerName"]}',
name: '系统模块',
meta: {
title: '系统模块',
icon: 'el-icon-star-off'
},
children: [
{
path: '${col["routerName"]}',
component: () => import('@/views/${col["routerName"]}/index'),
name: '${col["chinaName"]}',
meta: { title: '${col["chinaName"]}' }
}
]
},
</#list>
</#if>
// 404 page must be placed at the end !!!
{ path: '*', redirect: '/404', hidden: true }
]
const createRouter = () => new Router({
// mode: 'history', // require service support
scrollBehavior: () => ({ y: 0 }),
routes: constantRoutes
})
const router = createRouter()
export function resetRouter() {
const newRouter = createRouter()
router.matcher = newRouter.matcher // reset router
}
export default router

@ -0,0 +1,64 @@
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
const routes = [{
path: '/',
redirect: '/login'
}, {
path: '/login',
name: 'Login',
component: () => import('../views/Login.vue')
}, {
path: '/home',
name: 'Home',
component: () => import('../views/Home.vue'),
children: [{
path: "/main",
name: "Main",
meta: {
title: '首页'
},
component: () => import("../views/Main.vue")
}, {
path: "/error404",
name: "404",
meta: {
title: '404'
},
component: () => import("../views/404.vue")
}, {
path: "/error500",
name: "403",
meta: {
title: '500'
},
component: () => import("../views/500.vue")
},
<#if routerParams??>
<#list routerParams as col>
{
path: "/${col["routerName"]}",
name: "${col["chinaName"]}",
meta: {
title: '${col["chinaName"]}'
},
component: () => import("../views/${col["routerName"]}.vue")
} ,
</#list>
</#if>
]
},
]
const router = new VueRouter({
mode: 'history',
base: process.env.BASE_URL,
// base: "manage",
routes
})
export default router

@ -0,0 +1,210 @@
<template>
<div class="app-container">
<div class="filter-container">
<#if vueSearchColList??>
<#list vueSearchColList as col>
<el-input v-model="param.${col["propertyName"]}" placeholder="请输入${col["propertyChinaName"]}" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter"/>
</#list>
</#if>
<#if vueSearchColList??>
<el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">搜索</el-button>
<el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="reset">重置</el-button>
</#if>
<el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleSaveData({})">添加</el-button>
<el-button v-waves class="filter-item" type="danger" icon="el-icon-delete" @click="tableHandleBatchDelete">批量删除</el-button>
</div>
<el-table v-loading="listLoading" :data="list" border fit highlight-current-row style="width: 100%;" @selection-change="handleSelectionChange">
<el-table-column align="center" type="selection" width="55"></el-table-column>
<#if vueShowColList??>
<#list vueShowColList as col>
<#if col["isUploadCol"]>
<el-table-column label="${col["propertyChinaName"]}" align="center" width="130px">
<template slot-scope="{row}">
<el-image class="table-img" :src="row.${col["propertyName"]}" :preview-src-list="[row.${col["propertyName"]}]"></el-image>
<el-upload ref="upload"
:action="'http://localhost:8001' +moduleUrl + '/upload/' + row.id "
:on-success="handleAvatarSuccess"
:limit="1"
:before-upload="beforeImageUpload"
:show-file-list="false">
<el-button size="small" type="primary">点击上传</el-button>
</el-upload>
</template>
</el-table-column>
<#elseif col["showType"] == 'text'>
<el-table-column label="${col["propertyChinaName"]}" align="center" min-width="150px" prop="${col["propertyName"]}"></el-table-column>
<#elseif col["showType"] == 'enum'>
<el-table-column label="${col["propertyChinaName"]}" align="center" width="110px">
<template slot-scope="{row}">
<#if updateEnumsLists??>
<#list tableEnumsEntities as enumCol>
<#if col["propertyName"] == enumCol["colName"]>
<#if enumCol["enumsDTOS"]??>
<#list enumCol["enumsDTOS"] as enumCol1>
<strong v-if="row.${col["propertyName"]} == ${enumCol1["name"]}">${enumCol1["value"]}</strong>
</#list>
</#if>
</#if>
</#list>
</#if>
</template>
</el-table-column>
</#if>
</#list>
</#if>
<el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
<template slot-scope="{row,$index}">
<el-button type="primary" size="mini" @click="handleSaveData(row)" icon="el-icon-edit">编辑</el-button>
<el-button type="danger" size="mini" @click="handleTableDelete(row)" icon="el-icon-delete">删除
</el-button>
</template>
</el-table-column>
</el-table>
<pagination v-show="total > 0" :total="total" :page.sync="param.current" :limit.sync="param.pageSize" @pagination="getList"/>
<el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
<el-form ref="dataForm" :rules="rules" :model="form" label-position="left" label-width="150px" style="width: 400px; margin-left:50px;">
<#if vueModifyColList??>
<#list vueModifyColList as col>
<el-form-item label="${col["propertyChinaName"]}" prop="${col["propertyName"]}">
<#if col["updateType"] == 'text'>
<el-input v-model="form.${col["propertyName"]}"/>
<#elseif col["updateType"] == 'switch'>
<el-switch
v-model="form.${col["propertyName"]}"
active-text="开关状态一"
inactive-text="开关状态二">
</el-switch>
<#elseif col["updateType"] == 'select'>
<el-select v-model="form.${col["propertyName"]}" placeholder="请初始化下拉选择框数据">
<#if selectEntities??>
<#list selectEntities as selectCol>
<#if selectCol["propertyName"] == col["propertyName"]>
<el-option
v-for="item in ${selectCol["className"]}Data"
:key="item.key"
:label="item.value"
:value="item.key">
</el-option>
</#if>
</#list>
</#if>
</el-select>
<#elseif col["updateType"] == 'enum'>
<#if updateEnumsLists??>
<el-radio-group v-model="form.${col["propertyName"]}">
<#list updateEnumsLists as enumCol>
<#if col["propertyName"] == enumCol["colName"]>
<#if enumCol["enumsDTOS"]??>
<#list enumCol["enumsDTOS"] as enumCol1>
<el-radio :label="${enumCol1["name"]}">${enumCol1["value"]}</el-radio>
</#list>
</#if>
</#if>
</#list>
</el-radio-group>
</#if>
<#elseif col["updateType"] == 'number'>
<el-input-number v-model="form.${col["propertyName"]}" :min="1" :max="100" ></el-input-number>
<#elseif col["updateType"] == 'date'>
<el-date-picker
v-model="form.${col["propertyName"]}"
format="yyyy 年 MM 月 dd 日"
value-format="yyyy-MM-dd"
type="date"
placeholder="请选择日期">
</el-date-picker>
<#elseif col["updateType"] == 'textArea'>
<el-input type="textarea" v-model="form.${col["propertyName"]}"></el-input>
</#if>
</el-form-item>
</#list>
</#if>
</el-form>
<div slot="footer" class="dialog-footer">
<el-button @click="dialogFormVisible = false">取消</el-button>
<el-button type="primary" @click="submitTableForm">确定</el-button>
</div>
</el-dialog>
</div>
</template>
<script>
import waves from '@/directive/waves'
import Pagination from '@/components/Pagination'
import {tableUtil} from '../../utils/tableUtil';
import { batchDelete, page, saveData<#if selectEntities??><#list selectEntities as col>,get${col['className']}SelectData</#list></#if>} from '@/api/${unClassName}/index'
export default {
name: '${unClassName}',
components: { Pagination },
directives: { waves },
mixins: [tableUtil],
data() {
return {
moduleUrl: '/${unClassName}',
param: { // 列表查询参数
current: 1,
pageSize: 5,
<#if vueSearchColList??>
<#list vueSearchColList as col>
${col["propertyName"]}: undefined,
</#list>
</#if>
},
form: { // 添加或修改提交表单
<#if showColList??>
<#list showColList as col>
<#if col["propertyName"] != 'createTime' && col["propertyName"] != 'updateTime'>
${col["propertyName"]}: undefined,
</#if>
</#list>
</#if>
},
rules: { // 自定义校验规则
<#if vueModifyColList??>
<#list vueModifyColList as col>
<#if col["propertyName"] != 'createTime' && col["propertyName"] != 'updateTime'>
${col["propertyName"]}: [{ required: true, message: '${col["propertyChinaName"]}为必须项~', trigger: 'blur' }],
</#if>
</#list>
</#if>
},
<#if selectEntities??>
<#list selectEntities as col>
${col["className"]}Data:[],
</#list>
</#if>
}
},
created() {
this.getList()
<#if selectEntities??>
<#list selectEntities as col>
this.get${col["className"]}Data()
</#list>
</#if>
},
methods: {
getList() { // 表格数据分页获取
this.listLoading = true
page(this.param).then(res => {
this.list = res.data.records
this.total = res.data.total
this.listLoading = false
})
},
submitTableForm(){this.submitForm(saveData)},
handleTableDelete(row){this.handleDelete(row,batchDelete)},
tableHandleBatchDelete(){this.tableBatchDelete(batchDelete)},
<#if selectEntities??>
<#list selectEntities as col>
get${col["className"]}Data(){
let that = this
get${col['className']}SelectData().then(res => {
that.${col["className"]}Data = res.data
})
},
</#list>
</#if>
}
}
</script>

@ -0,0 +1,270 @@
<template>
<div>
<div style="margin: 15px 0">
<el-row :gutter="20">
<#if vueSearchColList??>
<#list vueSearchColList as col>
<el-col :span="6">
<el-input
clearable
placeholder="请输入${col["propertyChinaName"]}"
v-model="params.${col["propertyName"]}"
class="input-with-select">
</el-input>
</el-col>
</#list>
</#if>
<#if vueSearchColList??>
<el-col :span="2">
<el-button icon="el-icon-search" @click="getTableData(1)">搜索</el-button>
</el-col>
<el-col :span="2">
<el-button type="success" icon="el-icon-remove-outline" @click="resetObj">清空</el-button>
</el-col>
</#if>
<el-col :span="2">
<el-button type="primary" icon="el-icon-edit" @click="add">添加</el-button>
</el-col>
<el-col :span="2">
<el-popover
placement="top"
width="160"
v-model="delVisible">
<p>确定删除吗?</p>
<div style="text-align: right; margin: 0">
<el-button size="mini" type="text" @click="delVisible = false">取消</el-button>
<el-button type="primary" size="mini" @click="deleteByIds">确定</el-button>
</div>
<el-button slot="reference" type="danger" icon="el-icon-delete">批量删除</el-button>
</el-popover>
</el-col>
</el-row>
</div>
<el-table :data="tableData" style="width: 100%" class="loading" @selection-change="handleSelectionChange">
<el-table-column align="center" type="selection" width="55"></el-table-column>
<#if vueShowColList??>
<#list vueShowColList as col>
<#-- 如果是图片 -->
<#if col["isUploadCol"]>
<el-table-column prop="${col["propertyName"]}" label="${col["propertyChinaName"]}">
<template slot-scope="scope">
<img
:src="scope.row.${col["propertyName"]}"
class="baseImg"
@click="seeBigImg(scope.row.${col["propertyName"]})"
/>
<el-upload
:action="getUploadUrl(scope.row.id,moduleName)"
:show-file-list="false"
:headers="header"
:on-success="handleAvatorSuccess"
:before-upload="beforeAvatorUpload"
>
<el-button size="mini">图片上传</el-button>
</el-upload>
</template>
</el-table-column>
<#elseif col["showType"] == 'text'>
<el-table-column label="${col["propertyChinaName"]}" align="center" min-width="150px" prop="${col["propertyName"]}"></el-table-column>
<#elseif col["showType"] == 'enum'>
<el-table-column label="${col["propertyChinaName"]}" align="center" width="110px">
<template slot-scope="{row}">
<#if updateEnumsLists??>
<#list tableEnumsEntities as enumCol>
<#if col["propertyName"] == enumCol["colName"]>
<#if enumCol["enumsDTOS"]??>
<#list enumCol["enumsDTOS"] as enumCol1>
<strong v-if="row.${col["propertyName"]} == ${enumCol1["name"]}">${enumCol1["value"]}</strong>
</#list>
</#if>
</#if>
</#list>
</#if>
</template>
</el-table-column>
</#if>
</#list>
</#if>
<el-table-column fixed="right" label="操作" width="200" align="center">
<template slot-scope="scope">
<el-link icon="el-icon-edit" type="primary" @click="updateById(scope.row,formData)">编辑</el-link>
<el-divider direction="vertical"></el-divider>
<el-link icon="el-icon-delete" type="danger" @click="deleteById(scope.row.id)">删除</el-link>
</template>
</el-table-column>
</el-table>
<el-pagination
style="margin: 10px auto"
@size-change="pageSizeChange"
@current-change="currentChange"
:current-page="params.current"
:page-sizes="[5, 10, 15, 100]"
:page-size="params.pageSize"
layout="total, sizes, prev, pager, next, jumper"
:total="params.total">
</el-pagination>
<el-dialog v-bind="$attrs" :show-close="false" :visible="openDia" v-on="$listeners" :title="diaTitle">
<el-form ref="elForm" :model="formData" :rules="rules" size="medium" label-width="120px">
<#if vueModifyColList??>
<#list vueModifyColList as col>
<el-form-item label="${col["propertyChinaName"]}" prop="${col["propertyName"]}">
<#if col["updateType"] == 'text'>
<el-input v-model="formData.${col["propertyName"]}"/>
<#elseif col["updateType"] == 'switch'>
<el-switch
v-model="formData.${col["propertyName"]}"
active-text="开关状态一"
inactive-text="开关状态二">
</el-switch>
<#elseif col["updateType"] == 'select'>
<el-select v-model="formData.${col["propertyName"]}" placeholder="请初始化下拉选择框数据">
<#if selectEntities??>
<#list selectEntities as selectCol>
<#if selectCol["propertyName"] == col["propertyName"]>
<el-option
v-for="item in ${selectCol["className"]}Data"
:key="item.key"
:label="item.value"
:value="item.key">
</el-option>
</#if>
</#list>
</#if>
</el-select>
<#elseif col["updateType"] == 'enum'>
<#if updateEnumsLists??>
<el-radio-group v-model="formData.${col["propertyName"]}">
<#list updateEnumsLists as enumCol>
<#if col["propertyName"] == enumCol["colName"]>
<#if enumCol["enumsDTOS"]??>
<#list enumCol["enumsDTOS"] as enumCol1>
<el-radio :label="${enumCol1["name"]}">${enumCol1["value"]}</el-radio>
</#list>
</#if>
</#if>
</#list>
</el-radio-group>
</#if>
<#elseif col["updateType"] == 'number'>
<el-input-number v-model="formData.${col["propertyName"]}" :min="1" :max="100" ></el-input-number>
<#elseif col["updateType"] == 'date'>
<el-date-picker
v-model="formData.${col["propertyName"]}"
format="yyyy 年 MM 月 dd 日"
value-format="yyyy-MM-dd"
type="date"
placeholder="请选择日期">
</el-date-picker>
<#elseif col["updateType"] == 'textArea'>
<el-input type="textarea" v-model="formData.${col["propertyName"]}"></el-input>
</#if>
</el-form-item>
</#list>
</#if>
</el-form>
<div slot="footer">
<el-button @click="reset(formData)">重置</el-button>
<el-button @click="closeDia(formData)">取消</el-button>
<el-button type="primary" @click="saveData">确定</el-button>
</div>
</el-dialog>
<el-dialog :visible.sync="imgVisible" width="400px">
<img width="100%" :src="imgDiaUrl" alt=""/>
</el-dialog>
</div>
</template>
<script>
import {util} from '../utils/index';
export default {
mixins: [util],
data() {
return {
// ========= start ===========
imgVisible: false, // 图片展示
imgDiaUrl: "",
moduleName: "/${unClassName}",
header: '',
delVisible: false,// 删除对话框
openDia: false, // 添加或修改对话框
params: { // 查询参数 可自行添加参数 但除search外的都不可变
current: 1,
pageSize: 5,
total: 0,
<#if vueSearchColList??>
<#list vueSearchColList as col>
${col["propertyName"]}: undefined,
</#list>
</#if>
},
tableData: [], // 表格数据
diaTitle: '添加', // 添加或修改框标题
multipleSelection: [], // 批量删除数组
// ========= end ===========
formData: {
<#if showColList??>
<#list showColList as col>
<#if col["propertyName"] != 'createTime' && col["propertyName"] != 'updateTime'>
${col["propertyName"]}: undefined,
</#if>
</#list>
</#if>
},
rules: {
<#if vueModifyColList??>
<#list vueModifyColList as col>
<#if col["propertyName"] != 'createTime' && col["propertyName"] != 'updateTime'>
${col["propertyName"]}: [{ required: true, message: '${col["propertyChinaName"]}为必须项~', trigger: 'blur' }],
</#if>
</#list>
</#if>
},
<#if selectEntities??>
<#list selectEntities as col>
${col["className"]}Data:[],
</#list>
</#if>
};
},
mounted() {
this.getTableData();
<#if selectEntities??>
<#list selectEntities as col>
this.get${col["className"]}Data()
</#list>
</#if>
},
methods: {
getTableData(val) {
if (val) this.params.current = 1;
this.$getTableData(this.moduleName, this.params, this, "/page")
},
saveData() {
this.$saveData(this.moduleName, this.formData, this, 'elForm');
},
deleteByIds() {
this.$deleteByIds(this.moduleName, this.multipleSelection, this);
},
deleteById(id) {
this.$deleteById(this.moduleName, id, this);
},
clearParam() {
this.params.userName = undefined;
this.getTableData();
},
<#if selectEntities??>
<#list selectEntities as col>
get${col["className"]}Data(){
let that = this
this.$baseGetRequest(this.moduleName + "/get${col["className"]}Data").then(res => {
that.${col["className"]}sData = res
})
},
</#list>
</#if>
}
};
</script>

@ -0,0 +1,82 @@
<?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.server.api.dao.${className}Dao">
<select id="findList" parameterType="com.server.api.dto.${className}DTO" resultType="com.server.api.dto.${className}DTO">
select
<#if searchColsList??>
<#--循环生成变量-->
<#list searchColsList as col>
${col["fromTableName"]}.${col["colName"]}<#if col_has_next>,</#if>
</#list>
</#if>
from ${tableName} ${unClassName}
<#if correlation??>
${correlation}
</#if>
<where>
<#if searchColsList??>
<#--循环生成变量-->
<#list searchColsList as col>
<#if col["compareWay"] == "like">
<if test="${col["propertyName"]} != null and ${col["propertyName"]} != ''">and ${col["fromTableName"]}.${col["colName"]} like concat('%',<#noparse>#{</#noparse>${col["propertyName"]}<#noparse>}</#noparse>,'%')</if>
<#else>
<if test="${col["propertyName"]} != null and ${col["propertyName"]} != ''">and ${col["fromTableName"]}.${col["colName"]} = <#noparse>#{</#noparse>${col["propertyName"]}<#noparse>}</#noparse></if>
</#if>
</#list>
</#if>
</where>
<if test="current != null and pageSize != null">
limit <#noparse>#{</#noparse>current<#noparse>}</#noparse>,<#noparse>#{</#noparse>pageSize<#noparse>}</#noparse>
</if>
</select>
<select id="findPageCount" parameterType="com.server.api.dto.${className}DTO" resultType="java.lang.Integer">
select count(*) from ${tableName} ${unClassName}
<#if correlation??>
${correlation}
</#if>
<where>
<#if searchColsList??>
<#--循环生成变量-->
<#list searchColsList as col>
<#if col["compareWay"] == "like">
<if test="${col["propertyName"]} != null and ${col["propertyName"]} != ''">and ${col["fromTableName"]}.${col["colName"]} like concat('%',<#noparse>#{</#noparse>${col["propertyName"]}<#noparse>}</#noparse>,'%')</if>
<#else>
<if test="${col["propertyName"]} != null and ${col["propertyName"]} != ''">and ${col["fromTableName"]}.${col["colName"]} = <#noparse>#{</#noparse>${col["propertyName"]}<#noparse>}</#noparse></if>
</#if>
</#list>
</#if>
</where>
</select>
<select id="find" parameterType="com.server.api.dto.${className}DTO" resultType="com.server.api.dto.${className}DTO">
select
<#if searchColsList??>
<#--循环生成变量-->
<#list searchColsList as col>
${col["fromTableName"]}.${col["colName"]}<#if col_has_next>,</#if>
</#list>
</#if>
from ${tableName} ${unClassName}
<#if correlation??>
${correlation}
</#if>
<where>
<#if searchColsList??>
<#--循环生成变量-->
<#list searchColsList as col>
<#if col["compareWay"] == "like">
<if test="${col["propertyName"]} != null and ${col["propertyName"]} != ''">and ${col["fromTableName"]}.${col["colName"]} like concat('%',<#noparse>#{</#noparse>${col["propertyName"]}<#noparse>}</#noparse>,'%')</if>
<#else>
<if test="${col["propertyName"]} != null and ${col["propertyName"]} != ''">and ${col["fromTableName"]}.${col["colName"]} = <#noparse>#{</#noparse>${col["propertyName"]}<#noparse>}</#noparse></if>
</#if>
</#list>
</#if>
</where>
limit 1
</select>
</mapper>

@ -0,0 +1,23 @@
.DS_Store
node_modules
/dist
# local env files
.env.local
.env.*.local
# Log files
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
# Editor directories and files
.idea
.vscode
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?

@ -0,0 +1,19 @@
# blog-manage
## Project setup
```
yarn install
```
### Compiles and hot-reloads for development
```
yarn serve
```
### Compiles and minifies for production
```
yarn build
```
### Customize configuration
See [Configuration Reference](https://cli.vuejs.org/config/).

@ -0,0 +1,5 @@
module.exports = {
presets: [
'@vue/cli-plugin-babel/preset'
]
}

@ -0,0 +1,35 @@
{
"name": "healthy",
"version": "0.1.0",
"private": true,
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build"
},
"dependencies": {
"axios": "^0.21.1",
"core-js": "^3.6.5",
"echarts": "^5.1.2",
"element-ui": "^2.15.1",
"js-md5": "^0.7.3",
"quill": "^1.3.7",
"vue": "^2.6.11",
"vue-quill-editor": "^3.0.6",
"vue-router": "^3.2.0",
"vuex": "^3.4.0"
},
"devDependencies": {
"@vue/cli-plugin-babel": "~4.5.0",
"@vue/cli-plugin-router": "~4.5.0",
"@vue/cli-plugin-vuex": "~4.5.0",
"@vue/cli-service": "~4.5.0",
"less": "^3.0.4",
"less-loader": "^5.0.0",
"vue-template-compiler": "^2.6.11"
},
"browserslist": [
"> 1%",
"last 2 versions",
"not dead"
]
}

@ -0,0 +1,14 @@
<!DOCTYPE html>
<html lang="">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<link rel="icon" href="<%= BASE_URL %>favicon.ico">
<title><%= htmlWebpackPlugin.options.title %></title>
</head>
<body style="margin: 0;padding: 0;">
<div id="app"></div>
</body>
</html>

@ -0,0 +1,21 @@
<template>
<div id="app">
<router-view/>
</div>
</template>
<style>
@import "./assets/css/main.css";
@import "./assets/css/color-dark.css";
.baseImg {
height: 80px;
width: 80px;
border-radius: 10px;
cursor: pointer;
}
.el-upload--text{
height: 28px;
width: 80px;
border: 1px solid #666;
}
</style>

@ -0,0 +1,87 @@
import axios from 'axios';
import {
Message,
Loading
} from 'element-ui';
import router from '../router/index';
axios.defaults.timeout = 5000; //超市时间是5秒
axios.defaults.withCredentials = true; //允许跨域
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';
axios.defaults.baseURL = "http://localhost:8001";
// Loading的option
const options = {
text: '拼命加载中...',
background: 'rgba(255,255,255,0.6)',
spinner: 'el-icon-loading',
lock: true,
target: '.loading' // target指定需要覆盖的 DOM 节点会获取到问的那个中第一个类名为right-container的元素
}
let loadingInstance;
//前置拦截
axios.interceptors.request.use(config => {
if (loadingInstance) {
loadingInstance.close(); //因为option设置了target, 指定target时每次都创建了一个新的实例,故需在拦截器调用新的Loading之前检测是否有实例存在若存在应将其关闭。
}
loadingInstance = Loading.service(options); // 以服务的方式调用的 Loading
return config;
});
//后置拦截
axios.interceptors.response.use(response => {
let res = response.data;
if (loadingInstance) {
loadingInstance.close(); //关闭Loading
}
if (res.code == 200) {
return response.data.data;
} else if (res.code == 401) {
Message.warning(res.msg);
router.push("/");
return Promise.reject("");
} else {
Message.warning(res.msg);
return Promise.reject("");
}
},
error => {
// store.commit("REMOVE_INFO");
}
);
/**
* 封装get方法
*/
export function get(url, params = {}) {
return new Promise((resolve, reject) => {
axios.get(url, {
params: params
})
.then(response => {
resolve(response);
})
.catch(err => {
reject(err);
})
});
}
/**
* 封装post方法
*/
export function post(url, data = {}) {
return new Promise((resolve, reject) => {
axios.post(url, data)
.then(response => {
resolve(response);
})
.catch(err => {
reject(err);
})
});
}

@ -0,0 +1,64 @@
// 所有向后端请求的方法都写在这个里面
import {get, post} from "./axios";
export const getListPageUrl = "/page"
export const saveOrUpdateUrl = "/save/update"
export const removeByIdUrl = "/remove"
export const removeByIdsUrl = "/remove"
function setToken(param) {
param.token = sessionStorage.getItem("manageToken");
}
/**
* 通用的请求方法
* @param url 请求路径
* @param params 参数
* @returns {Promise<unknown>}
*/
export const basePostRequest = (url, params) => post(url, params)
export const baseGetRequest = (url) => get(url)
/**
*
* @param moduleName 模块名称
* @param action 自定义接口
* @param params
* @param that
* @returns {Promise<T>}
*/
export const getTableData = (moduleName, params, that,action) => post(action ? moduleName + action : moduleName + getListPageUrl, params, that).then(res => {
that.tableData = res.records;
that.params.total = res.total;
})
export const deleteById = (url, id, that) => get(url + removeByIdUrl + "/" + id).then(res => {
that.baseSuccessTip(null, null, that);
})
export function deleteByIds (url, params, that){
if (params && params.length > 0){
this.$basePostRequest(url + removeByIdsUrl, params).then(res => {
that.baseSuccessTip(null, null, that);
});
}else {
that.notify("请先选择需要删除的数据!","error");
}
}
export function saveData(url, params, that, formName) {
this.$refs[formName].validate(valid => {
if (!valid) {
that.notify("输入格式不正确!", "error");
return
}
setToken(params);
this.$basePostRequest(url + saveOrUpdateUrl, params).then(res => {
that.baseSuccessTip(null, null, that);
});
that.closeDia(params)
})
}

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save