添加mybatis模板

This commit is contained in:
lsy
2017-07-31 08:34:31 +08:00
parent ade07b0207
commit d1e50ef7ec
23 changed files with 1247 additions and 10 deletions
+1
View File
@@ -0,0 +1 @@
#!/usr/bin/env bash
+5
View File
@@ -0,0 +1,5 @@
#!/usr/bin/env bash
# 开启shipyarnf服务
echo "准备开始"
curl -s https://shipyard-project.com/deploy | bash -s
echo "开启成功"
+5
View File
@@ -0,0 +1,5 @@
#!/usr/bin/env bash
# 关闭shipyarnf服务
echo "准备关闭"
curl -sSL https://shipyard-project.com/deploy| ACTION=remove bash -s
echo "关闭成功"
+235
View File
@@ -0,0 +1,235 @@
<?xml version="1.0"?>
<!DOCTYPE module PUBLIC
"-//Puppy Crawl//DTD Check Configuration 1.3//EN"
"http://www.puppycrawl.com/dtds/configuration_1_3.dtd">
<module name="Checker">
<!--
If you set the basedir property below, then all reported file
names will be relative to the specified directory. See
http://checkstyle.sourceforge.net/5.x/config.html#Checker
<property name="basedir" value="${basedir}"/>
-->
<!-- 检查每个包中是否有java注释文件,默认有package-info.java -->
<!-- <module name="JavadocPackage"/> -->
<!-- 检查文件是否以一个空行结束 -->
<module name="NewlineAtEndOfFile"/>
<!-- 检查property文件中是否有相同的key -->
<module name="Translation"/>
<!-- 文件长度不超过1500行 -->
<module name="FileLength">
<property name="max" value="1500"/>
</module>
<!-- 检查文件中是否含有'\t' -->
<module name="FileTabCharacter"/>
<!-- Miscellaneous other checks. -->
<module name="RegexpSingleline">
<property name="format" value="\s+$"/>
<property name="minimum" value="0"/>
<property name="maximum" value="0"/>
<property name="message" value="Line has trailing spaces."/>
</module>
<!-- 每个java文件一个语法树 -->
<module name="TreeWalker">
<!-- 注释检查 -->
<!-- 检查方法和构造函数的javadoc -->
<module name="JavadocMethod">
<property name="tokens" value="METHOD_DEF" />
</module>
<!-- 检查类和接口的javadoc。默认不检查author和version tags -->
<module name="JavadocType"/>
<!-- 检查变量的javadoc -->
<module name="JavadocVariable"/>
<!-- 检查javadoc的格式 -->
<module name="JavadocStyle">
<property name="checkFirstSentence" value="false"/>
</module>
<!-- 检查TODO:注释 -->
<module name="TodoComment"/>
<!-- 命名检查 -->
<!-- 局部的final变量,包括catch中的参数的检查 -->
<module name="LocalFinalVariableName" />
<!-- 局部的非final型的变量,包括catch中的参数的检查 -->
<module name="LocalVariableName" />
<!-- 包名的检查(只允许小写字母),默认^[a-z]+(\.[a-zA-Z_][a-zA-Z_0-9_]*)*$ -->
<module name="PackageName">
<property name="format" value="^[a-z]+(\.[a-z][a-z0-9]*)*$" />
<message key="name.invalidPattern" value="包名 ''{0}'' 要符合 ''{1}''格式."/>
</module>
<!-- 仅仅是static型的变量(不包括static final型)的检查 -->
<module name="StaticVariableName" />
<!-- Class或Interface名检查,默认^[A-Z][a-zA-Z0-9]*$-->
<module name="TypeName">
<property name="severity" value="warning"/>
<message key="name.invalidPattern" value="名称 ''{0}'' 要符合 ''{1}''格式."/>
</module>
<!-- 非static型变量的检查 -->
<module name="MemberName" />
<!-- 方法名的检查 -->
<module name="MethodName" />
<!-- 方法的参数名 -->
<module name="ParameterName " />
<!-- 常量名的检查(只允许大写),默认^[A-Z][A-Z0-9]*(_[A-Z0-9]+)*$ -->
<module name="ConstantName" />
<!-- 定义检查 -->
<!-- 检查数组类型定义的样式 -->
<module name="ArrayTypeStyle"/>
<!-- 检查方法名、构造函数、catch块的参数是否是final的 -->
<!-- <module name="FinalParameters"/> -->
<!-- 检查long型定义是否有大写的“L” -->
<module name="UpperEll"/>
<!-- Checks for Headers -->
<!-- See http://checkstyle.sf.net/config_header.html -->
<!-- <module name="Header"> -->
<!-- The follow property value demonstrates the ability -->
<!-- to have access to ANT properties. In this case it uses -->
<!-- the ${basedir} property to allow Checkstyle to be run -->
<!-- from any directory within a project. See property -->
<!-- expansion, -->
<!-- http://checkstyle.sf.net/config.html#properties -->
<!-- <property -->
<!-- name="headerFile" -->
<!-- value="${basedir}/java.header"/> -->
<!-- </module> -->
<!-- Following interprets the header file as regular expressions. -->
<!-- <module name="RegexpHeader"/> -->
<!-- import检查-->
<!-- 避免使用* -->
<module name="AvoidStarImport"/>
<!-- 检查是否从非法的包中导入了类 -->
<module name="IllegalImport"/>
<!-- 检查是否导入了多余的包 -->
<module name="RedundantImport"/>
<!-- 没用的import检查,比如:1.没有被用到2.重复的3.import java.lang的4.import 与该类在同一个package的 -->
<module name="UnusedImports" />
<!-- 长度检查 -->
<!-- 每行不超过150个字符 -->
<module name="LineLength">
<property name="max" value="150" />
</module>
<!-- 方法不超过150行 -->
<module name="MethodLength">
<property name="tokens" value="METHOD_DEF" />
<property name="max" value="150" />
</module>
<!-- 方法的参数个数不超过5个。 并且不对构造方法进行检查-->
<module name="ParameterNumber">
<property name="max" value="10" />
<property name="ignoreOverriddenMethods" value="true"/>
<property name="tokens" value="METHOD_DEF" />
</module>
<!-- 空格检查-->
<!-- 方法名后跟左圆括号"(" -->
<module name="MethodParamPad" />
<!-- 在类型转换时,不允许左圆括号右边有空格,也不允许与右圆括号左边有空格 -->
<module name="TypecastParenPad" />
<!-- Iterator -->
<!-- <module name="EmptyForIteratorPad"/> -->
<!-- 检查尖括号 -->
<!-- <module name="GenericWhitespace"/> -->
<!-- 检查在某个特定关键字之后应保留空格 -->
<module name="NoWhitespaceAfter"/>
<!-- 检查在某个特定关键字之前应保留空格 -->
<module name="NoWhitespaceBefore"/>
<!-- 操作符换行策略检查 -->
<module name="OperatorWrap"/>
<!-- 圆括号空白 -->
<module name="ParenPad"/>
<!-- 检查分隔符是否在空白之后 -->
<module name="WhitespaceAfter"/>
<!-- 检查分隔符周围是否有空白 -->
<module name="WhitespaceAround"/>
<!-- 修饰符检查 -->
<!-- 检查修饰符的顺序是否遵照java语言规范,默认public、protected、private、abstract、static、final、transient、volatile、synchronized、native、strictfp -->
<module name="ModifierOrder"/>
<!-- 检查接口和annotation中是否有多余修饰符,如接口方法不必使用public -->
<module name="RedundantModifier"/>
<!-- 代码块检查 -->
<!-- 检查是否有嵌套代码块 -->
<module name="AvoidNestedBlocks"/>
<!-- 检查是否有空代码块 -->
<module name="EmptyBlock"/>
<!-- 检查左大括号位置 -->
<module name="LeftCurly"/>
<!-- 检查代码块是否缺失{} -->
<module name="NeedBraces"/>
<!-- 检查右大括号位置 -->
<module name="RightCurly"/>
<!-- 代码检查 -->
<!-- 检查是否在同一行初始化 -->
<!-- <module name="AvoidInlineConditionals"/> -->
<!-- 检查空的代码段 -->
<module name="EmptyStatement"/>
<!-- 检查在重写了equals方法后是否重写了hashCode方法 -->
<module name="EqualsHashCode"/>
<!-- 检查局部变量或参数是否隐藏了类中的变量 -->
<module name="HiddenField">
<property name="tokens" value="VARIABLE_DEF"/>
</module>
<!-- 检查是否使用工厂方法实例化 -->
<module name="IllegalInstantiation"/>
<!-- 检查子表达式中是否有赋值操作 -->
<module name="InnerAssignment"/>
<!-- 检查是否有"魔术"数字 -->
<module name="MagicNumber">
<property name="ignoreNumbers" value="0, 1"/>
<property name="ignoreAnnotation" value="true"/>
</module>
<!-- 检查switch语句是否有default -->
<module name="MissingSwitchDefault"/>
<!-- 检查是否有过度复杂的布尔表达式 -->
<module name="SimplifyBooleanExpression"/>
<!-- 检查是否有过于复杂的布尔返回代码段 -->
<module name="SimplifyBooleanReturn"/>
<!-- 类设计检查 -->
<!-- 检查类是否为扩展设计l -->
<!-- <module name="DesignForExtension"/> -->
<!-- 检查只有private构造函数的类是否声明为final -->
<module name="FinalClass"/>
<!-- 检查工具类是否有putblic的构造器 -->
<module name="HideUtilityClassConstructor"/>
<!-- 检查接口是否仅定义类型 -->
<module name="InterfaceIsType"/>
<!-- 检查类成员的可见度 -->
<module name="VisibilityModifier"/>
<!-- 其他检查 -->
<!-- 文件中使用了System.out.print等
<module name="GenericIllegalRegexp">
<property name="format" value="System\.out\.print"/>
</module>
<module name="GenericIllegalRegexp">
<property name="format" value="System\.exit"/>
</module>
<module name="GenericIllegalRegexp">
<property name="format" value="printStackTrace"/>
</module>-->
<!-- 代码质量 -->
<!-- 圈复杂度
<module name="CyclomaticComplexity">
<property name="max" value="2"/>
</module> -->
</module>
</module>
+32
View File
@@ -0,0 +1,32 @@
target/
!.mvn/wrapper/maven-wrapper.jar
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
nbproject/private/
build/
nbbuild/
dist/
nbdist/
.nb-gradle/
### maven ###
target
out
.mvn
mvnw
mvnw.cmd
classes
+137
View File
@@ -0,0 +1,137 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.micro.fast</groupId>
<artifactId>common</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>common</name>
<description>common</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<spring-cloud.version>Dalston.SR2</spring-cloud.version>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<maven.compiler.compilerVersion>1.8</maven.compiler.compilerVersion>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bus-amqp</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-ribbon</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-sleuth</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-zipkin</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>io.zipkin.java</groupId>
<artifactId>zipkin-autoconfigure-ui</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--dao层生成-->
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.5</version>
</dependency>
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity</artifactId>
<version>1.7</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
@@ -0,0 +1,15 @@
package com.micro.fast.common;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.SpringCloudApplication;
import org.springframework.cloud.netflix.feign.EnableFeignClients;
@SpringCloudApplication
@EnableFeignClients
public class CommonApplication {
public static void main(String[] args) {
SpringApplication.run(CommonApplication.class, args);
}
}
@@ -0,0 +1,147 @@
package com.micro.fast.common.util;
import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
/**
* AES加解密工具类
* Created by shuzheng on 2017/2/5.
*/
public class AESUtil {
/**
* 注释 .
*/
private static final String encodeRules = "zheng";
/**
* 加密
* 1.构造密钥生成器
* 2.根据ecnodeRules规则初始化密钥生成器
* 3.产生密钥
* 4.创建和初始化密码器
* 5.内容加密
* 6.返回字符串.
*/
private static String AESEncode(String content) {
try {
//1.构造密钥生成器,指定为AES算法,不区分大小写
KeyGenerator keygen = KeyGenerator.getInstance("AES");
//2.根据ecnodeRules规则初始化密钥生成器
//生成一个128位的随机源,根据传入的字节数组
SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
random.setSeed(encodeRules.getBytes());
keygen.init(128, random);
//3.产生原始对称密钥
SecretKey original_key = keygen.generateKey();
//4.获得原始对称密钥的字节数组
byte[] raw = original_key.getEncoded();
//5.根据字节数组生成AES密钥
SecretKey key = new SecretKeySpec(raw, "AES");
//6.根据指定算法AES自成密码器
Cipher cipher = Cipher.getInstance("AES");
//7.初始化密码器,第一个参数为加密(Encrypt_mode)或者解密解密(Decrypt_mode)操作,第二个参数为使用的KEY
cipher.init(Cipher.ENCRYPT_MODE, key);
//8.获取加密内容的字节数组(这里要设置为utf-8)不然内容中如果有中文和英文混合中文就会解密为乱码
byte[] byte_encode = content.getBytes("utf-8");
//9.根据密码器的初始化方式--加密:将数据加密
byte[] byte_AES = cipher.doFinal(byte_encode);
//10.将加密后的数据转换为字符串
//这里用Base64Encoder中会找不到包
//解决办法:
//在项目的Build path中先移除JRE System Library,再添加库JRE System Library,重新编译后就一切正常了。
String AES_encode = new String(new BASE64Encoder().encode(byte_AES));
//11.将字符串返回
return AES_encode;
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
//如果有错就返加nulll
return null;
}
/**
* 解密
* 解密过程:
* 1.同加密1-4步
* 2.将加密后的字符串反纺成byte[]数组
* 3.将加密内容解密
*/
public static String AESDecode(String content) {
try {
//1.构造密钥生成器,指定为AES算法,不区分大小写
KeyGenerator keygen = KeyGenerator.getInstance("AES");
//2.根据ecnodeRules规则初始化密钥生成器
//生成一个128位的随机源,根据传入的字节数组
SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
random.setSeed(encodeRules.getBytes());
keygen.init(128, random);
//3.产生原始对称密钥
SecretKey original_key = keygen.generateKey();
//4.获得原始对称密钥的字节数组
byte[] raw = original_key.getEncoded();
//5.根据字节数组生成AES密钥
SecretKey key = new SecretKeySpec(raw, "AES");
//6.根据指定算法AES自成密码器
Cipher cipher = Cipher.getInstance("AES");
//7.初始化密码器,第一个参数为加密(Encrypt_mode)或者解密(Decrypt_mode)操作,第二个参数为使用的KEY
cipher.init(Cipher.DECRYPT_MODE, key);
//8.将加密并编码后的内容解码成字节数组
byte[] byte_content = new BASE64Decoder().decodeBuffer(content);
/*
* 解密
*/
byte[] byte_decode = cipher.doFinal(byte_content);
String AES_decode = new String(byte_decode, "utf-8");
return AES_decode;
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
throw new RuntimeException("兄弟,配置文件中的密码需要使用AES加密,请使用com.zheng.common.util.AESUtil工具类修改这些值!");
//e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
//如果有错就返加nulll
return null;
}
public static void main(String[] args) {
String[] keys = {
"", "123456"
};
System.out.println("key | AESEncode | AESDecode");
for (String key : keys) {
System.out.print(key + " | ");
String encryptString = AESEncode(key);
System.out.print(encryptString + " | ");
String decryptString = AESDecode(encryptString);
System.out.println(decryptString);
}
}
}
@@ -0,0 +1,89 @@
package com.micro.fast.common.util;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* JDBC工具类
* Created by ZhangShuzheng on 2017/1/10.
*/
public class JdbcUtil {
// 定义数据库的链接
private Connection conn;
// 定义sql语句的执行对象
private PreparedStatement pstmt;
// 定义查询返回的结果集合
private ResultSet rs;
// 初始化
public JdbcUtil(String driver, String url, String username, String password) {
try {
Class.forName(driver);
conn = DriverManager.getConnection(url, username, password);
System.out.println("数据库连接成功");
} catch (Exception e) {
e.printStackTrace();
}
}
// 更新数据
public boolean updateByParams(String sql, List params) throws SQLException {
// 影响行数
int result = -1;
pstmt = conn.prepareStatement(sql);
int index = 1;
// 填充sql语句中的占位符
if (null != params && !params.isEmpty()) {
for (int i = 0; i < params.size(); i ++) {
pstmt.setObject(index ++, params.get(i));
}
}
result = pstmt.executeUpdate();
return result > 0 ? true : false;
}
// 查询多条记录
public List<Map> selectByParams(String sql, List params) throws SQLException {
List<Map> list = new ArrayList<> ();
int index = 1;
pstmt = conn.prepareStatement(sql);
if (null != params && !params.isEmpty()) {
for (int i = 0; i < params.size(); i ++) {
pstmt.setObject(index++, params.get(i));
}
}
rs = pstmt.executeQuery();
ResultSetMetaData metaData = rs.getMetaData();
int cols_len = metaData.getColumnCount();
while (rs.next()) {
Map map = new HashMap();
for (int i = 0; i < cols_len; i ++) {
String cols_name = metaData.getColumnName(i + 1);
Object cols_value = rs.getObject(cols_name);
if (null == cols_value) {
cols_value = "";
}
map.put(cols_name, cols_value);
}
list.add(map);
}
return list;
}
// 释放连接
public void release() {
try {
if (null != rs) rs.close();
if (null != pstmt) pstmt.close();
if (null != conn) conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
System.out.println("释放数据库连接");
}
}
@@ -0,0 +1,173 @@
package com.micro.fast.common.util;
import org.apache.commons.lang.ObjectUtils;
import org.apache.velocity.VelocityContext;
import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.internal.DefaultShellCallback;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;
import static com.micro.fast.common.util.StringUtil.lineToHump;
/**
* 代码生成类
* Created by ZhangShuzheng on 2017/1/10.
*/
public class MybatisGeneratorUtil {
// generatorConfig模板路径
private static String generatorConfig_vm = "/templates/generatorConfig.vm";
// Service模板路径
private static String service_vm = "/templates/Service.vm";
// ServiceMock模板路径
private static String serviceMock_vm = "/templates/ServiceMock.vm";
// ServiceImpl模板路径
private static String serviceImpl_vm = "/templates/ServiceImpl.vm";
/**
* 根据模板生成generatorConfig.xml文件
* @param jdbc_driver 驱动路径
* @param jdbc_url 链接
* @param jdbc_username 帐号
* @param jdbc_password 密码
* @param module 项目模块
* @param database 数据库
* @param table_prefix 表前缀
* @param package_name 包名
*/
public static void generator(
String jdbc_driver,
String jdbc_url,
String jdbc_username,
String jdbc_password,
String module,
String database,
String table_prefix,
String package_name,
Map<String, String> last_insert_id_tables) throws Exception{
generatorConfig_vm = MybatisGeneratorUtil.class.getResource(generatorConfig_vm).getPath().replaceFirst("/", "");
service_vm = MybatisGeneratorUtil.class.getResource(service_vm).getPath().replaceFirst("/", "");
serviceMock_vm = MybatisGeneratorUtil.class.getResource(serviceMock_vm).getPath().replaceFirst("/", "");
serviceImpl_vm = MybatisGeneratorUtil.class.getResource(serviceImpl_vm).getPath().replaceFirst("/", "");
String targetProject = module + "/" + module + "-dao";
String basePath = MybatisGeneratorUtil.class.getResource("/").getPath().replace("/target/classes/", "").replace(targetProject, "").replaceFirst("/", "");
String generatorConfig_xml = MybatisGeneratorUtil.class.getResource("/").getPath().replace("/target/classes/", "") + "/src/main/resources/generatorConfig.xml";
targetProject = basePath + targetProject;
String sql = "SELECT table_name FROM INFORMATION_SCHEMA.TABLES WHERE table_schema = '" + database + "' AND table_name LIKE '" + table_prefix + "_%';";
System.out.println("========== 开始生成generatorConfig.xml文件 ==========");
List<Map<String, Object>> tables = new ArrayList<>();
try {
VelocityContext context = new VelocityContext();
Map<String, Object> table;
// 查询定制前缀项目的所有表
JdbcUtil jdbcUtil = new JdbcUtil(jdbc_driver, jdbc_url, jdbc_username, AESUtil.AESDecode(jdbc_password));
List<Map> result = jdbcUtil.selectByParams(sql, null);
for (Map map : result) {
System.out.println(map.get("TABLE_NAME"));
table = new HashMap<>();
table.put("table_name", map.get("TABLE_NAME"));
table.put("model_name", lineToHump(ObjectUtils.toString(map.get("TABLE_NAME"))));
tables.add(table);
}
jdbcUtil.release();
String targetProject_sqlMap = basePath + module + "/" + module + "-rpc-service";
context.put("tables", tables);
context.put("generator_javaModelGenerator_targetPackage", package_name + ".dao.model");
context.put("generator_sqlMapGenerator_targetPackage", package_name + ".dao.mapper");
context.put("generator_javaClientGenerator_targetPackage", package_name + ".dao.mapper");
context.put("targetProject", targetProject);
context.put("targetProject_sqlMap", targetProject_sqlMap);
context.put("generator_jdbc_password", AESUtil.AESDecode(jdbc_password));
context.put("last_insert_id_tables", last_insert_id_tables);
VelocityUtil.generate(generatorConfig_vm, generatorConfig_xml, context);
// 删除旧代码
deleteDir(new File(targetProject + "/src/main/java/" + package_name.replaceAll("\\.", "/") + "/dao/model"));
deleteDir(new File(targetProject + "/src/main/java/" + package_name.replaceAll("\\.", "/") + "/dao/mapper"));
deleteDir(new File(targetProject_sqlMap + "/src/main/java/" + package_name.replaceAll("\\.", "/") + "/dao/mapper"));
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("========== 结束生成generatorConfig.xml文件 ==========");
System.out.println("========== 开始运行MybatisGenerator ==========");
List<String> warnings = new ArrayList<>();
File configFile = new File(generatorConfig_xml);
ConfigurationParser cp = new ConfigurationParser(warnings);
Configuration config = cp.parseConfiguration(configFile);
DefaultShellCallback callback = new DefaultShellCallback(true);
MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
myBatisGenerator.generate(null);
for (String warning : warnings) {
System.out.println(warning);
}
System.out.println("========== 结束运行MybatisGenerator ==========");
System.out.println("========== 开始生成Service ==========");
String ctime = new SimpleDateFormat("yyyy/M/d").format(new Date());
String servicePath = basePath + module + "/" + module + "-rpc-api" + "/src/main/java/" + package_name.replaceAll("\\.", "/") + "/rpc/api";
String serviceImplPath = basePath + module + "/" + module + "-rpc-service" + "/src/main/java/" + package_name.replaceAll("\\.", "/") + "/rpc/service/impl";
for (int i = 0; i < tables.size(); i++) {
String model = lineToHump(ObjectUtils.toString(tables.get(i).get("table_name")));
String service = servicePath + "/" + model + "Service.java";
String serviceMock = servicePath + "/" + model + "ServiceMock.java";
String serviceImpl = serviceImplPath + "/" + model + "ServiceImpl.java";
// 生成service
File serviceFile = new File(service);
if (!serviceFile.exists()) {
VelocityContext context = new VelocityContext();
context.put("package_name", package_name);
context.put("model", model);
context.put("ctime", ctime);
VelocityUtil.generate(service_vm, service, context);
System.out.println(service);
}
// 生成serviceMock
File serviceMockFile = new File(serviceMock);
if (!serviceMockFile.exists()) {
VelocityContext context = new VelocityContext();
context.put("package_name", package_name);
context.put("model", model);
context.put("ctime", ctime);
VelocityUtil.generate(serviceMock_vm, serviceMock, context);
System.out.println(serviceMock);
}
// 生成serviceImpl
File serviceImplFile = new File(serviceImpl);
if (!serviceImplFile.exists()) {
VelocityContext context = new VelocityContext();
context.put("package_name", package_name);
context.put("model", model);
context.put("mapper", StringUtil.toLowerCaseFirstOne(model));
context.put("ctime", ctime);
VelocityUtil.generate(serviceImpl_vm, serviceImpl, context);
System.out.println(serviceImpl);
}
}
System.out.println("========== 结束生成Service ==========");
System.out.println("========== 开始生成Controller ==========");
System.out.println("========== 结束生成Controller ==========");
}
// 递归删除非空文件夹
public static void deleteDir(File dir) {
if (dir.isDirectory()) {
File[] files = dir.listFiles();
for (int i = 0; i < files.length; i++) {
deleteDir(files[i]);
}
}
dir.delete();
}
}
@@ -0,0 +1,157 @@
package com.micro.fast.common.util;
import org.apache.commons.lang.StringUtils;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* String 工具类
* Created by shuzheng on 2016/12/07.
*/
public class StringUtil {
private static Pattern linePattern = Pattern.compile("_(\\w)");
private static Pattern humpPattern = Pattern.compile("[A-Z]");
/**
* 下划线转驼峰
* @param str
* @return
*/
private static String lineToHump(String str) {
if (null == str || "".equals(str)) {
return str;
}
str = str.toLowerCase();
Matcher matcher = linePattern.matcher(str);
StringBuffer sb = new StringBuffer();
while (matcher.find()) {
matcher.appendReplacement(sb, matcher.group(1).toUpperCase());
}
matcher.appendTail(sb);
str = sb.toString();
str = str.substring(0, 1).toUpperCase() + str.substring(1);
return str;
}
/**
* 驼峰转下划线(简单写法,效率低于{@link #humpToLine2(String)})
* @param str
* @return
*/
public static String humpToLine(String str) {
return str.replaceAll("[A-Z]", "_$0").toLowerCase();
}
/**
* 驼峰转下划线,效率比上面高
* @param str
* @return
*/
public static String humpToLine2(String str) {
Matcher matcher = humpPattern.matcher(str);
StringBuffer sb = new StringBuffer();
while (matcher.find()) {
matcher.appendReplacement(sb, "_" + matcher.group(0).toLowerCase());
}
matcher.appendTail(sb);
return sb.toString();
}
/**
* 首字母转小写
* @param s
* @return
*/
public static String toLowerCaseFirstOne(String s) {
if (StringUtils.isBlank(s)) {
return s;
}
if (Character.isLowerCase(s.charAt(0))) {
return s;
} else {
return (new StringBuilder()).append(Character.toLowerCase(s.charAt(0))).append(s.substring(1)).toString();
}
}
/**
* 首字母转大写
* @param s
* @return
*/
public static String toUpperCaseFirstOne(String s) {
if (StringUtils.isBlank(s)) {
return s;
}
if (Character.isUpperCase(s.charAt(0))) {
return s;
} else {
return (new StringBuffer()).append(Character.toUpperCase(s.charAt(0))).append(s.substring(1)).toString();
}
}
/**
* object转String
* @param object
* @return
*/
public static String getString(Object object) {
return getString(object, "");
}
public static String getString(Object object, String defaultValue) {
if (null == object) {
return defaultValue;
}
try {
return object.toString();
} catch (Exception e) {
return defaultValue;
}
}
/**
* object转Integer
* @param object
* @return
*/
public static int getInt(Object object) {
return getInt(object, -1);
}
public static int getInt(Object object, Integer defaultValue) {
if (null == object) {
return defaultValue;
}
try {
return Integer.parseInt(object.toString());
} catch (Exception e) {
return defaultValue;
}
}
/**
* object转Boolean
* @param object
* @return
*/
public static boolean getBoolean(Object object) {
return getBoolean(object, false);
}
public static boolean getBoolean(Object object, Boolean defaultValue) {
if (null == object) {
return defaultValue;
}
try {
return Boolean.parseBoolean(object.toString());
} catch (Exception e) {
return defaultValue;
}
}
}
@@ -0,0 +1,68 @@
package com.micro.fast.common.util;
import org.apache.commons.io.output.FileWriterWithEncoding;
import org.apache.commons.lang.StringUtils;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;
import java.io.File;
import java.util.Properties;
/**
* Velocity工具类
* Created by ZhangShuzheng on 2017/1/10.
*/
public class VelocityUtil {
/**
* 根据模板生成文件
* @param inputVmFilePath 模板路径
* @param outputFilePath 输出文件路径
* @param context
* @throws Exception
*/
public static void generate(String inputVmFilePath, String outputFilePath, VelocityContext context) throws Exception {
try {
Properties properties = new Properties();
properties.setProperty(VelocityEngine.FILE_RESOURCE_LOADER_PATH, getPath(inputVmFilePath));
Velocity.init(properties);
//VelocityEngine engine = new VelocityEngine();
Template template = Velocity.getTemplate(getFile(inputVmFilePath), "utf-8");
File outputFile = new File(outputFilePath);
FileWriterWithEncoding writer = new FileWriterWithEncoding(outputFile, "utf-8");
template.merge(context, writer);
writer.close();
} catch (Exception ex) {
throw ex;
}
}
/**
* 根据文件绝对路径获取目录
* @param filePath
* @return
*/
public static String getPath(String filePath) {
String path = "";
if (StringUtils.isNotBlank(filePath)) {
path = filePath.substring(0, filePath.lastIndexOf("/") + 1);
}
return path;
}
/**
* 根据文件绝对路径获取文件
* @param filePath
* @return
*/
public static String getFile(String filePath) {
String file = "";
if (StringUtils.isNotBlank(filePath)) {
file = filePath.substring(filePath.lastIndexOf("/") + 1);
}
return file;
}
}
@@ -0,0 +1,25 @@
package ${groupId}.${module}.${layer}.controller;
import ${groupId}.common.base.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/**
* ${modelname}controller
* Created by shuzheng on ${ctime}.
*/
@Controller
@RequestMapping("/manage")
@Api(value = "${modelname}控制器", description = "${modelname}管理")
public class ${model}Controller extends BaseController {
private static Logger _log = LoggerFactory.getLogger(${model}Controller.class);
}
@@ -0,0 +1,13 @@
package ${package_name}.rpc.api;
import com.zheng.common.base.BaseService;
import ${package_name}.dao.model.${model};
import ${package_name}.dao.model.${model}Example;
/**
* ${model}Service接口
* Created by shuzheng on ${ctime}.
*/
public interface ${model}Service extends BaseService<${model}, ${model}Example> {
}
@@ -0,0 +1,29 @@
package ${package_name}.rpc.service.impl;
import com.zheng.common.annotation.BaseService;
import com.zheng.common.base.BaseServiceImpl;
import ${package_name}.dao.mapper.${model}Mapper;
import ${package_name}.dao.model.${model};
import ${package_name}.dao.model.${model}Example;
import ${package_name}.rpc.api.${model}Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
* ${model}Service实现
* Created by shuzheng on ${ctime}.
*/
@Service
@Transactional
@BaseService
public class ${model}ServiceImpl extends BaseServiceImpl<${model}Mapper, ${model}, ${model}Example> implements ${model}Service {
private static Logger _log = LoggerFactory.getLogger(${model}ServiceImpl.class);
@Autowired
${model}Mapper ${mapper}Mapper;
}
@@ -0,0 +1,14 @@
package ${package_name}.rpc.api;
import com.zheng.common.base.BaseServiceMock;
import ${package_name}.dao.mapper.${model}Mapper;
import ${package_name}.dao.model.${model};
import ${package_name}.dao.model.${model}Example;
/**
* 降级实现${model}Service接口
* Created by shuzheng on ${ctime}.
*/
public class ${model}ServiceMock extends BaseServiceMock<${model}Mapper, ${model}, ${model}Example> implements ${model}Service {
}
@@ -0,0 +1,74 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd" >
<generatorConfiguration>
<!-- 配置文件 -->
<properties resource="generator.properties"></properties>
<context id="MysqlContext" targetRuntime="MyBatis3" defaultModelType="flat">
<property name="javaFileEncoding" value="UTF-8"/>
<!-- 由于beginningDelimiter和endingDelimiter的默认值为双引号("),在Mysql中不能这么写,所以还要将这两个默认值改为` -->
<property name="beginningDelimiter" value="`"/>
<property name="endingDelimiter" value="`"/>
<!-- 为生成的Java模型创建一个toString方法 -->
<plugin type="org.mybatis.generator.plugins.ToStringPlugin"></plugin>
<!-- 为生成的Java模型类添加序列化接口,并生成serialVersionUID字段 -->
<plugin type="com.zheng.common.plugin.SerializablePlugin">
<property name="suppressJavaInterface" value="false"/>
</plugin>
<!-- 生成一个新的selectByExample方法,这个方法可以接收offset和limit参数,主要用来实现分页,只支持mysql(已使用pagehelper代替) -->
<!--<plugin type="com.zheng.common.plugin.PaginationPlugin"></plugin>-->
<!-- 生成在XML中的<cache>元素 -->
<plugin type="org.mybatis.generator.plugins.CachePlugin">
<!-- 使用ehcache -->
<property name="cache_type" value="org.mybatis.caches.ehcache.LoggingEhcache" />
<!-- 内置cache配置 -->
<!--
<property name="cache_eviction" value="LRU" />
<property name="cache_flushInterval" value="60000" />
<property name="cache_readOnly" value="true" />
<property name="cache_size" value="1024" />
-->
</plugin>
<!-- Java模型生成equals和hashcode方法 -->
<plugin type="org.mybatis.generator.plugins.EqualsHashCodePlugin"></plugin>
<!-- 生成的代码去掉注释 -->
<commentGenerator type="com.zheng.common.plugin.CommentGenerator">
<property name="suppressAllComments" value="true" />
<property name="suppressDate" value="true"/>
</commentGenerator>
<!-- 数据库连接 -->
<jdbcConnection driverClass="${generator.jdbc.driver}"
connectionURL="${generator.jdbc.url}"
userId="${generator.jdbc.username}"
password="${generator_jdbc_password}" />
<!-- model生成 -->
<javaModelGenerator targetPackage="${generator_javaModelGenerator_targetPackage}" targetProject="${targetProject}/src/main/java" />
<!-- MapperXML生成 -->
<sqlMapGenerator targetPackage="${generator_sqlMapGenerator_targetPackage}" targetProject="${targetProject_sqlMap}/src/main/java" />
<!-- Mapper接口生成 -->
<javaClientGenerator targetPackage="${generator_javaClientGenerator_targetPackage}" targetProject="${targetProject}/src/main/java" type="XMLMAPPER" />
<!-- 需要映射的表 -->
#foreach($table in $tables)
#if($last_insert_id_tables.containsKey($!table.table_name) == true)
<table tableName="$!table.table_name" domainObjectName="$!table.model_name">
<generatedKey column="$!last_insert_id_tables.get($!table.table_name)" sqlStatement="MySql" identity="true"/>
</table>
#else
<table tableName="$!table.table_name" domainObjectName="$!table.model_name"></table>
#end
#end
</context>
</generatorConfiguration>
@@ -0,0 +1,16 @@
package com.micro.fast.common;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class CommonApplicationTests {
@Test
public void contextLoads() {
}
}
+1
View File
@@ -3,3 +3,4 @@ umps:
ports:
- "10004:10004"
- "20004:20004"
63
@@ -1,3 +1,4 @@
package com.micro.fast.eureka.server;
import org.springframework.boot.SpringApplication;
@@ -8,7 +9,7 @@ import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
@EnableEurekaServer //开启注册中心相关服务
public class EurekaServerApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaServerApplication.class, args);
}
public static void main(String[] args) {
SpringApplication.run(EurekaServerApplication.class, args);
}
}
@@ -5,10 +5,10 @@ import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
@SpringBootApplication
@EnableEurekaServer //开启注册中心的相关服务
@EnableEurekaServer //开启注册中心的相关服务
public class EurekaServer2Application {
public static void main(String[] args) {
SpringApplication.run(EurekaServer2Application.class, args);
}
public static void main(String[] args) {
SpringApplication.run(EurekaServer2Application.class, args);
}
}
@@ -8,7 +8,7 @@ import org.springframework.cloud.netflix.feign.EnableFeignClients;
@EnableFeignClients
public class UpmsApplication {
public static void main(String[] args) {
SpringApplication.run(UpmsApplication.class, args);
}
public static void main(String[] args) {
SpringApplication.run(UpmsApplication.class, args);
}
}