Commit bcf3d4ad authored by 孙长纪's avatar 孙长纪

初始化项目

parents
Pipeline #115067 failed with stages
in 0 seconds
# maven ignore
target/
*.jar
*.war
*.zip
*.tar
*.tar.gz
# eclipse ignore
.settings/
.project
.classpath
# idea ignore
.idea
*.ipr
*.iml
*.iws
# gradle ignore
.gradle/
# temp ignore
*.log
*.cache
*.diff
*.patch
*.tmp
# system ignore
.DS_Store
Thumbs.db
bin
build
.class
classes/
out/
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="GradleSettings">
<option name="linkedExternalProjectsSettings">
<GradleProjectSettings>
<option name="distributionType" value="LOCAL" />
<option name="externalProjectPath" value="$PROJECT_DIR$" />
<option name="gradleHome" value="$PROJECT_DIR$/../../software/gradle-4.6" />
<option name="gradleJvm" value="1.8" />
<option name="modules">
<set>
<option value="$PROJECT_DIR$" />
</set>
</option>
<option name="useAutoImport" value="true" />
</GradleProjectSettings>
</option>
</component>
</project>
\ No newline at end of file
<component name="InspectionProjectProfileManager">
<profile version="1.0">
<option name="myName" value="Project Default" />
<inspection_tool class="ComparatorNotSerializable" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="ExternalizableWithSerializationMethods" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="NonSerializableFieldInSerializableClass" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="NonSerializableObjectBoundToHttpSession" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="NonSerializableObjectPassedToObjectStream" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="NonSerializableWithSerialVersionUIDField" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="NonSerializableWithSerializationMethods" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="ReadObjectAndWriteObjectPrivate" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="ReadObjectInitialization" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="ReadResolveAndWriteReplaceProtected" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="SerialPersistentFieldsWithWrongSignature" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="SerialVersionUIDNotStaticFinal" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="SerializableHasSerialVersionUIDField" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="SerializableHasSerializationMethods" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="SerializableInnerClassHasSerialVersionUIDField" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="SerializableInnerClassWithNonSerializableOuterClass" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="SerializableStoresNonSerializable" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="SerializableWithUnconstructableAncestor" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="TransientFieldInNonSerializableClass" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="TransientFieldNotInitialized" enabled="true" level="WARNING" enabled_by_default="true" />
</profile>
</component>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectInspectionProfilesVisibleTreeState">
<entry key="Project Default">
<profile-state>
<expanded-state>
<State>
<id />
</State>
<State>
<id>AOP</id>
</State>
<State>
<id>Abstraction issuesJava</id>
</State>
<State>
<id>ActionScript specificJavaScript</id>
</State>
<State>
<id>Ali-Check</id>
</State>
<State>
<id>Android &gt; Lint &gt; Correctness</id>
</State>
<State>
<id>Android &gt; Lint &gt; Correctness &gt; Messages</id>
</State>
<State>
<id>Android &gt; Lint &gt; Performance</id>
</State>
<State>
<id>Android &gt; Lint &gt; Security</id>
</State>
<State>
<id>Android &gt; Lint &gt; Usability</id>
</State>
<State>
<id>Android Lint for Kotlin</id>
</State>
<State>
<id>Application Server Specific Inspections</id>
</State>
<State>
<id>ArquillianJava</id>
</State>
<State>
<id>Assignment issuesJava</id>
</State>
<State>
<id>Assignment issuesJavaScript</id>
</State>
<State>
<id>Bitwise operation issuesJava</id>
</State>
<State>
<id>Bitwise operation issuesJavaScript</id>
</State>
<State>
<id>CDI(Contexts and Dependency Injection) issues</id>
</State>
<State>
<id>Class metricsJava</id>
</State>
<State>
<id>Class structureJava</id>
</State>
<State>
<id>Cloning issuesJava</id>
</State>
<State>
<id>Code maturity issuesJava</id>
</State>
<State>
<id>Code quality toolsJavaScript</id>
</State>
<State>
<id>Code style issuesJava</id>
</State>
<State>
<id>Code style issuesJavaScript</id>
</State>
<State>
<id>CodeSpring CoreSpring</id>
</State>
<State>
<id>Compiler issuesJava</id>
</State>
<State>
<id>Concurrency annotation issuesJava</id>
</State>
<State>
<id>Control flow issuesJava</id>
</State>
<State>
<id>Control flow issuesJavaScript</id>
</State>
<State>
<id>Cucumber Java</id>
</State>
<State>
<id>DOM issuesJavaScript</id>
</State>
<State>
<id>Data flow issuesJava</id>
</State>
<State>
<id>Data flow issuesJavaScript</id>
</State>
<State>
<id>Declaration redundancyJava</id>
</State>
<State>
<id>Dependency issuesJava</id>
</State>
<State>
<id>ECMAScript 6 migration aidsJavaScript</id>
</State>
<State>
<id>Encapsulation issuesJava</id>
</State>
<State>
<id>Error handlingJava</id>
</State>
<State>
<id>Error handlingJavaScript</id>
</State>
<State>
<id>Faces Model</id>
</State>
<State>
<id>Finalization issuesJava</id>
</State>
<State>
<id>Flow type checkerJavaScript</id>
</State>
<State>
<id>GPath inspectionsGroovy</id>
</State>
<State>
<id>General</id>
</State>
<State>
<id>GeneralJava</id>
</State>
<State>
<id>GeneralJavaScript</id>
</State>
<State>
<id>Google Web Toolkit issues</id>
</State>
<State>
<id>Groovy</id>
</State>
<State>
<id>Hibernate Issues</id>
</State>
<State>
<id>ImportsJava</id>
</State>
<State>
<id>Inheritance issuesJava</id>
</State>
<State>
<id>Initialization issuesJava</id>
</State>
<State>
<id>Internationalization issuesJava</id>
</State>
<State>
<id>J2ME SupportJava</id>
</State>
<State>
<id>J2ME issuesJava</id>
</State>
<State>
<id>JBoss Seam issues</id>
</State>
<State>
<id>JPA issues</id>
</State>
<State>
<id>JSP Inspections</id>
</State>
<State>
<id>JUnit issuesJava</id>
</State>
<State>
<id>Java</id>
</State>
<State>
<id>Java 5Java language level migration aidsJava</id>
</State>
<State>
<id>Java 7Java language level migration aidsJava</id>
</State>
<State>
<id>Java 8Java language level migration aidsJava</id>
</State>
<State>
<id>Java EE issues</id>
</State>
<State>
<id>Java language level issuesJava</id>
</State>
<State>
<id>Java language level migration aidsJava</id>
</State>
<State>
<id>JavaBeans issuesJava</id>
</State>
<State>
<id>JavaFX</id>
</State>
<State>
<id>JavaScript</id>
</State>
<State>
<id>JavaScript function metricsJavaScript</id>
</State>
<State>
<id>JavaScript validity issuesJavaScript</id>
</State>
<State>
<id>Javadoc issuesJava</id>
</State>
<State>
<id>Kotlin</id>
</State>
<State>
<id>Language Injection</id>
</State>
<State>
<id>Logging issuesJava</id>
</State>
<State>
<id>Manifest</id>
</State>
<State>
<id>Memory issuesJava</id>
</State>
<State>
<id>Method metricsJava</id>
</State>
<State>
<id>Modularization issuesJava</id>
</State>
<State>
<id>Naming ConventionsGroovy</id>
</State>
<State>
<id>Naming conventionsJava</id>
</State>
<State>
<id>Naming conventionsJavaScript</id>
</State>
<State>
<id>Numeric issuesJava</id>
</State>
<State>
<id>OSGi</id>
</State>
<State>
<id>Packaging issuesJava</id>
</State>
<State>
<id>Performance issuesJava</id>
</State>
<State>
<id>Plugin DevKit</id>
</State>
<State>
<id>Portability issuesJava</id>
</State>
<State>
<id>Potentially confusing code constructsGroovy</id>
</State>
<State>
<id>Potentially confusing code constructsJavaScript</id>
</State>
<State>
<id>Probable bugsGroovy</id>
</State>
<State>
<id>Probable bugsJava</id>
</State>
<State>
<id>Probable bugsJavaScript</id>
</State>
<State>
<id>Properties Files</id>
</State>
<State>
<id>Properties FilesJava</id>
</State>
<State>
<id>RESTful Web Service</id>
</State>
<State>
<id>Resource management issuesJava</id>
</State>
<State>
<id>Security issuesJava</id>
</State>
<State>
<id>Serialization issuesJava</id>
</State>
<State>
<id>Spring</id>
</State>
<State>
<id>Spring CoreSpring</id>
</State>
<State>
<id>Spring DataSpring</id>
</State>
<State>
<id>Struts</id>
</State>
<State>
<id>Struts 1Struts</id>
</State>
<State>
<id>StyleGroovy</id>
</State>
<State>
<id>TestNGJava</id>
</State>
<State>
<id>Threading issuesGroovy</id>
</State>
<State>
<id>Threading issuesJava</id>
</State>
<State>
<id>TypeScript</id>
</State>
<State>
<id>Verbose or redundant code constructsJava</id>
</State>
<State>
<id>Visibility issuesJava</id>
</State>
<State>
<id>Web Services</id>
</State>
<State>
<id>WebSocket issues</id>
</State>
<State>
<id>toString() issuesJava</id>
</State>
</expanded-state>
</profile-state>
</entry>
</component>
<component name="ProjectRootManager" version="2" project-jdk-name="1.8" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/out" />
</component>
<component name="masterDetails">
<states>
<state key="ArquillianSettingsConfigurable.UI">
<settings>
<splitter-proportions>
<option name="proportions">
<list>
<option value="0.2" />
</list>
</option>
</splitter-proportions>
</settings>
</state>
<state key="GlobalLibrariesConfigurable.UI">
<settings>
<splitter-proportions>
<option name="proportions">
<list>
<option value="0.2" />
</list>
</option>
</splitter-proportions>
</settings>
</state>
<state key="JdkListConfigurable.UI">
<settings>
<last-edited>1.8</last-edited>
<splitter-proportions>
<option name="proportions">
<list>
<option value="0.2" />
</list>
</option>
</splitter-proportions>
</settings>
</state>
<state key="ProjectJDKs.UI">
<settings>
<last-edited>1.8</last-edited>
<splitter-proportions>
<option name="proportions">
<list>
<option value="0.2" />
</list>
</option>
</splitter-proportions>
</settings>
</state>
<state key="ProjectLibrariesConfigurable.UI">
<settings>
<splitter-proportions>
<option name="proportions">
<list>
<option value="0.2" />
</list>
</option>
</splitter-proportions>
</settings>
</state>
</states>
</component>
</project>
\ No newline at end of file
# readme
description = "mysql-generator"
buildscript {
repositories {
mavenLocal()
maven { url "http://nexus.dui88.com:8081/nexus/content/groups/public/" }
maven { url "https://plugins.gradle.org/m2/" }
mavenCentral()
}
dependencies {
}
}
apply plugin: "maven"
apply plugin: "java"
apply plugin: "idea"
apply plugin: "eclipse"
group = "cn.com.duiba"
version = "0.0.1"
sourceCompatibility = 1.8
targetCompatibility = 1.8
jar {
baseName = "mysql-generator"
version = ""
}
repositories {
mavenLocal()
maven { url "http://nexus.dui88.com:8081/nexus/content/groups/public/" }
maven { url "https://plugins.gradle.org/m2/" }
mavenCentral()
}
dependencies {
compile("mysql:mysql-connector-java:5.1.21")
compile("commons-io:commons-io:2.4")
compile("commons-lang:commons-lang:2.6")
compile("org.freemarker:freemarker:2.3.19")
compile("commons-dbutils:commons-dbutils:1.7")
}
uploadArchives {
repositories {
mavenDeployer {
snapshotRepository(url: "http://nexus.dui88.com:8081/nexus/content/repositories/snapshots/") {
authentication(userName: "admin", password: "admin123")
}
repository(url: "http://nexus.dui88.com:8081/nexus/content/repositories/releases/") {
authentication(userName: "admin", password: "admin123")
}
pom.project {
name project.name
packaging "jar"
description project.name
url "www.duiba.com.cn"
scm {
url ""
connection ""
developerConnection ""
}
licenses {
license {
name "No License"
url "http://www.duiba.com.cn"
distribution "repo"
}
}
developers {
developer {
id "xuhengfei"
name "Hengfei Xu"
}
}
}
}
}
}
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<module external.linked.project.id="mysql-generator" external.linked.project.path="$MODULE_DIR$" external.root.project.path="$MODULE_DIR$" external.system.id="GRADLE" external.system.module.group="cn.com.duiba" external.system.module.version="0.0.1" type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$">
<excludeFolder url="file://$MODULE_DIR$/.gradle" />
<excludeFolder url="file://$MODULE_DIR$/build" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>
\ No newline at end of file
rootProject.name = 'mysql-generator'
package cn.com.duiba.mysql.generator;
import cn.com.duiba.mysql.generator.entity.GeneratorConfig;
import cn.com.duiba.mysql.generator.entity.TableEntity;
import cn.com.duiba.mysql.generator.exceptions.DuibaGeneratorException;
import cn.com.duiba.mysql.generator.gencode.JavaDaoGenerator;
import cn.com.duiba.mysql.generator.gencode.JavaDaoImplGenerator;
import cn.com.duiba.mysql.generator.gencode.JavaEntityGenerator;
import cn.com.duiba.mysql.generator.gencode.SQLXmlGenerator;
import cn.com.duiba.mysql.generator.service.DuibaFreemarkerService;
import cn.com.duiba.mysql.generator.utils.DBUtils;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
/**
* 代码生成器
* @author sunchangji
*/
public class MybatisGenerator {
/**
* 代码生成器主类
*
* @return
*/
public static void genCode(GeneratorConfig config) {
check(config);
DuibaFreemarkerService freemarkerService = new DuibaFreemarkerService();
TableEntity tableEntity = null;
try {
tableEntity = DBUtils.getTableInfo(config);
} catch (SQLException e) {
throw new DuibaGeneratorException(e);
}
//生成entity文件
JavaEntityGenerator doGenerator = new JavaEntityGenerator(freemarkerService, tableEntity, config);
doGenerator.gen();
//生成dao文件
JavaDaoGenerator daoGenerator = new JavaDaoGenerator(freemarkerService, tableEntity, config);
daoGenerator.gen();
//生成daoImpl文件
JavaDaoImplGenerator daoImplGenerator = new JavaDaoImplGenerator(freemarkerService, tableEntity, config);
daoImplGenerator.gen();
//生成xml文件
SQLXmlGenerator sqlXmlGenerator = new SQLXmlGenerator(freemarkerService, tableEntity, config);
sqlXmlGenerator.gen();
}
private static void check(GeneratorConfig config) {
if (config == null){
throw new DuibaGeneratorException("生成代码前请设置");
}
config.check();
}
public static Connection getConnection(String url, String user, String pwd){
Connection connection = null;
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection(url, user,pwd);
} catch (ClassNotFoundException | SQLException e) {
throw new DuibaGeneratorException(e);
}
return connection;
}
}
package cn.com.duiba.mysql.generator.entity;
/**
* 列的属性
*/
public class ColumnEntity {
/**
* 列名
*/
private String columnName;
/**
* 列名类型
*/
private String dataType;
/**
* 列名备注
*/
private String comments;
/**
* 属性名称(第一个字母大写),如:user_name => UserName
*/
private String attrName;
/**
* 属性名称(第一个字母小写),如:user_name => userName
*/
private String attrname;
/**
* 属性类型
*/
private String attrType;
/**
* auto_increment
*/
private String extra;
public String getColumnName() {
return columnName;
}
public void setColumnName(String columnName) {
this.columnName = columnName;
}
public String getDataType() {
return dataType;
}
public void setDataType(String dataType) {
this.dataType = dataType;
}
public String getComments() {
return comments;
}
public void setComments(String comments) {
this.comments = comments;
}
public String getAttrName() {
return attrName;
}
public void setAttrName(String attrName) {
this.attrName = attrName;
}
public String getAttrname() {
return attrname;
}
public void setAttrname(String attrname) {
this.attrname = attrname;
}
public String getAttrType() {
return attrType;
}
public void setAttrType(String attrType) {
this.attrType = attrType;
}
public String getExtra() {
return extra;
}
public void setExtra(String extra) {
this.extra = extra;
}
@Override
public String toString() {
return "ColumnEntity{" +
"columnName='" + columnName + '\'' +
", dataType='" + dataType + '\'' +
", comments='" + comments + '\'' +
", attrName='" + attrName + '\'' +
", attrname='" + attrname + '\'' +
", attrType='" + attrType + '\'' +
", extra='" + extra + '\'' +
'}';
}
}
package cn.com.duiba.mysql.generator.entity;
import cn.com.duiba.mysql.generator.MybatisGenerator;
import cn.com.duiba.mysql.generator.exceptions.DuibaGeneratorException;
import org.apache.commons.lang.StringUtils;
import java.sql.Connection;
/**
* 代码生成器配置类
*/
public class GeneratorConfig {
/**
* 表名称 前缀,例如tb_activity, tb为前缀
*/
private String tablePrefix;
/**
* 数据库连接
*/
private Connection connection;
/**
* 要生成代码的表名称
*/
private String tableName;
/**
* table_schema,表所在的库名称
*/
private String tableSchema;
/**
* dao的包名
*/
private String daoPackage;
/**
* Mybatis的xml的相对路径,相对于src/main/resources
*/
private String xmlLocation;
/**
* entity包名,要生成的数据库对应实体包名
*/
private String entityPackage;
/**
* 模块名称
*/
private String moduleName;
public GeneratorConfig(String dbUrl, String dbUserName, String dbPasswd) {
this.connection = MybatisGenerator.getConnection(dbUrl, dbUserName, dbPasswd);
}
public void check() {
if (connection == null) {
throw new DuibaGeneratorException("connect to mysql failed");
}
if (StringUtils.isEmpty(tableName)) {
throw new DuibaGeneratorException("tableName is null");
}
if (StringUtils.isEmpty(daoPackage)) {
throw new DuibaGeneratorException("daoPackage is null");
}
if (StringUtils.isEmpty(entityPackage)) {
throw new DuibaGeneratorException("DOpackage is null");
}
if (StringUtils.isEmpty(xmlLocation)) {
throw new DuibaGeneratorException("xmlLocation is null");
}
}
public String getTablePrefix() {
return tablePrefix;
}
public void setTablePrefix(String tablePrefix) {
this.tablePrefix = tablePrefix;
}
public Connection getConnection() {
return connection;
}
public void setConnection(Connection connection) {
this.connection = connection;
}
public String getTableName() {
return tableName;
}
public void setTableName(String tableName) {
this.tableName = tableName;
}
public String getDaoPackage() {
return daoPackage;
}
public void setDaoPackage(String daoPackage) {
this.daoPackage = daoPackage;
}
public String getXmlLocation() {
return xmlLocation;
}
public void setXmlLocation(String xmlLocation) {
this.xmlLocation = xmlLocation;
}
public String getEntityPackage() {
return entityPackage;
}
public void setEntityPackage(String entityPackage) {
this.entityPackage = entityPackage;
}
public String getTableSchema() {
return tableSchema;
}
public void setTableSchema(String tableSchema) {
this.tableSchema = tableSchema;
}
public String getModuleName() {
return moduleName;
}
public void setModuleName(String moduleName) {
this.moduleName = moduleName;
}
}
package cn.com.duiba.mysql.generator.entity;
import java.util.List;
import java.util.Map;
/**
* 表数据
* @author sunchangji
*/
public class TableEntity {
/**
* 库名
*/
private String tableSchema;
/**
* 表的名称
*/
private String tableName;
/**
* 表的备注
*/
private String comments;
/**
* 表的列名(所有列名)
*/
private List<ColumnEntity> columns;
/**
* 表的所有列,不包含 anto_increment 和 on update CURRENT_TIMESTAMP 和 gmt_create
*/
private List<ColumnEntity> mainColumns;
/**
* 类名(第一个字母大写),如:duiba_user => DuibaUser
*/
private String className;
/**
* 类名(第一个字母小写),如:duiba_user => duibaUser
*/
private String classname;
/**
* 表的主键
*/
private ColumnEntity pk;
/**
* 表的唯一键列表, key是唯一索引名称,value是唯一索引包含的列
*/
private Map<String, List<ColumnEntity>> uniqueKeyMap;
public String getTableName() {
return tableName;
}
public void setTableName(String tableName) {
this.tableName = tableName;
}
public String getComments() {
return comments;
}
public void setComments(String comments) {
this.comments = comments;
}
public ColumnEntity getPk() {
return pk;
}
public void setPk(ColumnEntity pk) {
this.pk = pk;
}
public List<ColumnEntity> getColumns() {
return columns;
}
public void setColumns(List<ColumnEntity> columns) {
this.columns = columns;
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
public String getClassname() {
return classname;
}
public void setClassname(String classname) {
this.classname = classname;
}
public Map<String, List<ColumnEntity>> getUniqueKeyMap() {
return uniqueKeyMap;
}
public void setUniqueKeyMap(Map<String, List<ColumnEntity>> uniqueKeyMap) {
this.uniqueKeyMap = uniqueKeyMap;
}
public String getTableSchema() {
return tableSchema;
}
public void setTableSchema(String tableSchema) {
this.tableSchema = tableSchema;
}
public List<ColumnEntity> getMainColumns() {
return mainColumns;
}
public void setMainColumns(List<ColumnEntity> mainColumns) {
this.mainColumns = mainColumns;
}
@Override
public String toString() {
return "TableEntity{" +
"tableName='" + tableName + '\'' +
", comments='" + comments + '\'' +
", columns=" + columns +
", className='" + className + '\'' +
", classname='" + classname + '\'' +
", pk=" + pk +
", uniqueKeyMap=" + uniqueKeyMap +
'}';
}
}
package cn.com.duiba.mysql.generator.exceptions;
public class DuibaGeneratorException extends RuntimeException {
private static final long serialVersionUID = -1832371381972592054L;
public DuibaGeneratorException(String message) {
super(message);
}
public DuibaGeneratorException(Throwable cause) {
super(cause);
}
}
package cn.com.duiba.mysql.generator.gencode;
import cn.com.duiba.mysql.generator.entity.GeneratorConfig;
import cn.com.duiba.mysql.generator.entity.TableEntity;
import cn.com.duiba.mysql.generator.exceptions.DuibaGeneratorException;
import cn.com.duiba.mysql.generator.service.DuibaFreemarkerService;
import org.apache.commons.io.IOUtils;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
/**
* @author sunchangji
*/
public abstract class AbstractGenerator {
private DuibaFreemarkerService freemarkerService;
protected TableEntity tableEntity;
protected GeneratorConfig config;
private Map<String, Object> params = new HashMap<>();
public AbstractGenerator(DuibaFreemarkerService freemarkerService, TableEntity tableEntity, GeneratorConfig config) {
this.freemarkerService = freemarkerService;
this.tableEntity = tableEntity;
this.config = config;
params.put("table", tableEntity);
params.put("pk", tableEntity.getPk());
params.put("pathName", tableEntity.getClassname().toLowerCase());
params.put("columns", tableEntity.getColumns());
params.put("entityPackage", config.getEntityPackage());
params.put("daoPackage", config.getDaoPackage());
params.put("uks", tableEntity.getUniqueKeyMap());
params.put("pre", "#{");
params.put("end", "}");
}
public final void gen() {
//利用Freemarker生成代码字符串
String genStr = freemarkerService.merge(getFTL(), params);
//生成文件名
String fileName = genFileName();
String filePath = genFilePath();
//写文件
this.writeFile(genStr, filePath, fileName);
}
/**
* 文件不存在的情况下生成文件
*
* @param content
* @param dirPath 文件目录
* @param fileName 文件名称
*/
private void writeFile(String content, String dirPath, String fileName) {
File fp = new File(dirPath);
if (!fp.exists()) {
boolean dirs = fp.mkdirs();
if (!dirs) {
throw new DuibaGeneratorException(dirPath + " 文件目录创建失败");
}
}
String file = dirPath + File.separator + fileName;
File ff = new File(file);
if (!ff.exists()) {
try {
boolean success = ff.createNewFile();
if (!success) {
throw new DuibaGeneratorException(file + "创建失败");
}
FileOutputStream fos = new FileOutputStream(file);
IOUtils.write(content, fos);
fos.close();
} catch (IOException e) {
throw new DuibaGeneratorException(file + " error " + e);
}
}
}
protected abstract String getFTL();
protected abstract String genFileName();
protected abstract String genFilePath();
}
package cn.com.duiba.mysql.generator.gencode;
import cn.com.duiba.mysql.generator.entity.GeneratorConfig;
import cn.com.duiba.mysql.generator.entity.TableEntity;
import cn.com.duiba.mysql.generator.service.DuibaFreemarkerService;
import cn.com.duiba.mysql.generator.utils.PathUtils;
public class JavaDaoGenerator extends AbstractGenerator{
public JavaDaoGenerator(DuibaFreemarkerService freemarkerService, TableEntity tableEntity, GeneratorConfig config) {
super(freemarkerService, tableEntity, config);
}
@Override
public String getFTL() {
return "java_dao";
}
@Override
public String genFileName() {
return tableEntity.getClassName() + "Dao.java";
}
@Override
protected String genFilePath() {
return PathUtils.getPathByPackage(config.getDaoPackage(), config);
}
}
package cn.com.duiba.mysql.generator.gencode;
import cn.com.duiba.mysql.generator.entity.GeneratorConfig;
import cn.com.duiba.mysql.generator.entity.TableEntity;
import cn.com.duiba.mysql.generator.service.DuibaFreemarkerService;
import cn.com.duiba.mysql.generator.utils.PathUtils;
/**
* Created by sunchangji on 2019/3/29.
*/
public class JavaDaoImplGenerator extends AbstractGenerator{
public JavaDaoImplGenerator(DuibaFreemarkerService freemarkerService, TableEntity tableEntity, GeneratorConfig config) {
super(freemarkerService, tableEntity, config);
}
@Override
protected String getFTL() {
return "java_dao_impl";
}
@Override
public String genFileName() {
return tableEntity.getClassName() + "DaoImpl.java";
}
@Override
protected String genFilePath() {
return PathUtils.getPathByPackage(config.getDaoPackage()+".impl", config);
}
}
package cn.com.duiba.mysql.generator.gencode;
import cn.com.duiba.mysql.generator.entity.GeneratorConfig;
import cn.com.duiba.mysql.generator.entity.TableEntity;
import cn.com.duiba.mysql.generator.service.DuibaFreemarkerService;
import cn.com.duiba.mysql.generator.utils.PathUtils;
/**
* @author sunchangji
*/
public class JavaEntityGenerator extends AbstractGenerator{
public JavaEntityGenerator(DuibaFreemarkerService freemarkerService, TableEntity tableEntity, GeneratorConfig config){
super(freemarkerService,tableEntity, config);
}
@Override
public String getFTL() {
return "java_entity";
}
@Override
public String genFileName() {
return tableEntity.getClassName() + "Entity.java";
}
@Override
protected String genFilePath() {
return PathUtils.getPathByPackage(config.getEntityPackage(), config);
}
}
package cn.com.duiba.mysql.generator.gencode;
import cn.com.duiba.mysql.generator.entity.GeneratorConfig;
import cn.com.duiba.mysql.generator.entity.TableEntity;
import cn.com.duiba.mysql.generator.service.DuibaFreemarkerService;
public class SQLXmlGenerator extends AbstractGenerator{
public SQLXmlGenerator(DuibaFreemarkerService freemarkerService, TableEntity tableEntity, GeneratorConfig config) {
super(freemarkerService, tableEntity, config);
}
@Override
public String getFTL() {
return "sql_xml";
}
@Override
public String genFileName() {
return tableEntity.getClassName() + "Mapper.xml";
}
@Override
protected String genFilePath() {
return config.getXmlLocation();
}
}
package cn.com.duiba.mysql.generator.service;
import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Map;
/**
* FreeMarker模板
*
* @author sunchangji
*/
public class DuibaFreemarkerService {
private String location;
private String suffix;
private Configuration cfg = new Configuration();
private String encoding = "utf-8";
public DuibaFreemarkerService() {
cfg.setDefaultEncoding(encoding);
cfg.setClassForTemplateLoading(DuibaFreemarkerService.class, "/tpls");
cfg.setObjectWrapper(new DefaultObjectWrapper());
cfg.setNumberFormat("#");
this.location = "";
this.suffix = "ftl";
}
public String merge(String template, Map<String, Object> model) {
try {
Template tpl = cfg.getTemplate(template + "." + suffix);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
OutputStreamWriter writer = new OutputStreamWriter(bos);
tpl.process(model, writer);
writer.flush();
writer.close();
byte[] byteArray = bos.toByteArray();
return new String(byteArray, encoding);
} catch (IOException | TemplateException e) {
throw new RuntimeException(e);
}
}
}
package cn.com.duiba.mysql.generator.utils;
import cn.com.duiba.mysql.generator.entity.ColumnEntity;
import cn.com.duiba.mysql.generator.entity.GeneratorConfig;
import cn.com.duiba.mysql.generator.entity.TableEntity;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.WordUtils;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class DBUtils {
private static Map<String, String> typeMap= new HashMap<>();
static {
typeMap.put("tinyint","Integer");
typeMap.put("smallint","Integer");
typeMap.put("mediumint","Integer");
typeMap.put("int","Integer");
typeMap.put("integer","Integer");
typeMap.put("bigint","Long");
typeMap.put("bigint unsigned","Long");
typeMap.put("float","Float");
typeMap.put("double","Double");
typeMap.put("decimal","BigDecimal");
typeMap.put("char","String");
typeMap.put("varchar","String");
typeMap.put("tinytext","String");
typeMap.put("text","String");
typeMap.put("mediumtext","String");
typeMap.put("longtext","String");
typeMap.put("date","Date");
typeMap.put("datetime","Date");
typeMap.put("timestamp","Date");
}
public static TableEntity getTableInfo(GeneratorConfig config) throws SQLException {
String tableName = config.getTableName();
String tableCatalog = config.getTableSchema();
Connection conn = config.getConnection();
//select * from information_schema.TABLES where TABLE_NAME = 'daily' and TABLE_SCHEMA = 'shark';
String getTableSql = "select table_name as tableName, table_comment as comments from information_schema.tables where table_schema = '" + tableCatalog + "' and table_name = '" + tableName + "'";
QueryRunner qRunner = new QueryRunner();
TableEntity entity = qRunner.query(conn, getTableSql, new BeanHandler<>(TableEntity.class));
entity.setTableSchema(config.getTableSchema());
String className = tableToJava(entity.getTableName(), config.getTablePrefix());
entity.setClassName(className);
entity.setClassname(StringUtils.uncapitalize(className));
List<ColumnEntity> columnList = getTableColumns(conn, tableCatalog, tableName);
entity.setColumns(columnList);
entity.setMainColumns(getMainColumns(columnList));
entity.setPk(getPk(columnList ,conn, tableCatalog, tableName));
Map<String, List<ColumnEntity>> maps = getUniqueKeyMap(conn, tableCatalog, tableName, columnList);
entity.setUniqueKeyMap(maps);
return entity;
}
/**
* 排除 c.extra != 'auto_increment' && c.extra != "on update CURRENT_TIMESTAMP" && c.columnName != "gmt_create">
* @param columnList
* @return
*/
private static List<ColumnEntity> getMainColumns(List<ColumnEntity> columnList) {
List<ColumnEntity> list = new ArrayList<>();
for (ColumnEntity columnEntity : columnList){
if ( !"auto_increment".equalsIgnoreCase(columnEntity.getExtra())
&& !"on update CURRENT_TIMESTAMP".equalsIgnoreCase(columnEntity.getExtra())
&& !"gmt_create".equalsIgnoreCase(columnEntity.getColumnName())){
list.add(columnEntity);
}
}
return list;
}
private static Map<String,List<ColumnEntity>> handleUniqueName(Map<String, List<ColumnEntity>> uniqueKeyMap) {
Map<String, List<ColumnEntity>> map = new HashMap<>();
for (Map.Entry<String, List<ColumnEntity>> entry : uniqueKeyMap.entrySet()) {
StringBuilder builder = new StringBuilder();
for (ColumnEntity columnEntity : entry.getValue()) {
builder.append(columnEntity.getAttrName()).append("And");
}
String key = builder.substring(0, builder.lastIndexOf("And"));
map.put(key, entry.getValue());
}
return map;
}
private static Map<String,List<ColumnEntity>> getUniqueKeyMap(Connection conn, String schemaName, String tableName, List<ColumnEntity> columns) throws SQLException {
String sql = "select * from information_schema.KEY_COLUMN_USAGE " +
"where TABLE_NAME = '" + tableName + "' and TABLE_SCHEMA = '" + schemaName + "' and CONSTRAINT_NAME != 'PRIMARY'";
QueryRunner queryRunner = new QueryRunner();
return queryRunner.query(conn, sql, resultSet -> {
Map<String, List<ColumnEntity>> map = new HashMap<>();
while (resultSet.next()) {
String keyName = getUkName(resultSet.getString("CONSTRAINT_NAME"));
ColumnEntity columnEntity = getByColumnName(resultSet.getString("COLUMN_NAME"), columns);
if (columnEntity!=null) {
if (map.containsKey(keyName)) {
map.get(keyName).add(columnEntity);
} else {
List<ColumnEntity> columnEntities = new ArrayList<>();
columnEntities.add(columnEntity);
map.put(keyName, columnEntities);
}
}
}
return map;
});
}
/**
* 获取主键
*/
private static ColumnEntity getPk(List<ColumnEntity> list, Connection conn, String schemaName, String tableName) throws SQLException {
String sql = "select COLUMN_NAME as columnName from information_schema.KEY_COLUMN_USAGE where " +
"TABLE_NAME = '" + tableName + "' and TABLE_SCHEMA = '" + schemaName + "' and CONSTRAINT_NAME = 'PRIMARY'";
QueryRunner queryRunner = new QueryRunner();
ColumnEntity columnEntity = queryRunner.query(conn, sql, new BeanHandler<>(ColumnEntity.class));
for (ColumnEntity pkColumn : list) {
if (pkColumn.getColumnName().equalsIgnoreCase(columnEntity.getColumnName())) {
return pkColumn;
}
}
return null;
}
private static List<ColumnEntity> getTableColumns(Connection conn, String schemaName, String tableName) throws SQLException {
String getColumnSql = "SELECT COLUMN_NAME as columnName, DATA_TYPE as dataType, COLUMN_COMMENT as comments, " +
"extra as extra from information_schema.COLUMNS where TABLE_SCHEMA = '" + schemaName + "' and TABLE_NAME = '" + tableName + "'";
QueryRunner queryRunner = new QueryRunner();
List<ColumnEntity> columnEntities = queryRunner.query(conn, getColumnSql, resultSet -> {
List<ColumnEntity> list = new ArrayList<>();
while (resultSet.next()){
ColumnEntity columnEntity = new ColumnEntity();
columnEntity.setColumnName(resultSet.getString("columnName"));
columnEntity.setDataType(resultSet.getString("dataType"));
columnEntity.setComments(resultSet.getString("comments"));
columnEntity.setExtra(resultSet.getString("extra"));
//列名转换成Java属性名
String attrName = columnToJava(columnEntity.getColumnName()).replace("uk","");
columnEntity.setAttrName(attrName);
columnEntity.setAttrname(StringUtils.uncapitalize(attrName));
//columnEntity.setExtra(rs.getString("EXTRA"));
//列的数据类型,转换成Java类型
String attrType = typeMap.get(StringUtils.lowerCase(columnEntity.getDataType()));
columnEntity.setAttrType(attrType);
list.add(columnEntity);
}
return list;
});
return columnEntities;
}
/**
* 列名转换成Java属性名
*/
private static String columnToJava(String columnName) {
return WordUtils.capitalizeFully(columnName, new char[]{'_'}).replace("_", "" );
}
/**
* 表名转换成Java类名
*/
private static String tableToJava(String tableName, String tablePrefix) {
if (StringUtils.isNotBlank(tablePrefix)) {
tableName = tableName.replace(tablePrefix, "" );
}
return columnToJava(tableName);
}
private static ColumnEntity getByColumnName(String columnName, List<ColumnEntity> columns) {
for (ColumnEntity columnEntity : columns) {
if (columnEntity.getColumnName().equalsIgnoreCase(columnName)) {
return columnEntity;
}
}
return null;
}
private static String getUkName(String name){
return columnToJava(name.replace("uk","_"));
}
}
package cn.com.duiba.mysql.generator.utils;
import cn.com.duiba.mysql.generator.entity.GeneratorConfig;
import cn.com.duiba.mysql.generator.exceptions.DuibaGeneratorException;
import org.apache.commons.lang.StringUtils;
import java.io.File;
import java.net.URL;
public class PathUtils {
private PathUtils(){
//X Y
}
private static String getProjectHome(){
ClassLoader loader = PathUtils.class.getClassLoader();
URL url = loader.getResource("");
String file = url.getFile();
File testPath = new File(file);
return testPath.getParentFile().getParent();
}
/**
* 根据包名找到包的实际路径
* @param packageName 包名,例如:cn.com.duiba.shark.gitlab.dao
* @return 包的文件路径
*/
public static String getPathByPackage(String packageName, GeneratorConfig config){
if (StringUtils.isEmpty(packageName)){
throw new DuibaGeneratorException("包名不能为空");
}
if (StringUtils.isEmpty(config.getModuleName())) {
return "src/main/java/" + StringUtils.replace(packageName,"." ,"/");
} else {
return config.getModuleName() + File.separator + "src/main/java/" + StringUtils.replace(packageName,"." ,"/");
}
}
}
package ${daoPackage};
import ${entityPackage}.${table.className}Entity;
import java.util.List;
public interface ${table.className}Dao {
int save(${table.className}Entity ${table.classname}Entity);
<#if pk??>
int deleteBy${pk.attrName}(${pk.attrType} ${pk.attrname});
int deleteBatchBy${pk.attrName}s(List<${pk.attrType}> ${pk.attrname}s);
int updateBy${pk.attrName}(${table.className}Entity ${table.classname}Entity);
${table.className}Entity getBy${pk.attrName}(${pk.attrType} ${pk.attrname});
List<${table.className}Entity> listBy${pk.attrName}s(List<${pk.attrType}> ${pk.attrname}s);
</#if>
<#list uks?keys as key>
${table.className}Entity getBy${key}(<#assign idx=0><#list uks[key] as uk>${uk.attrType} ${uk.attrname}<#assign idx=idx+1><#if (idx<uks[key]?size)>,</#if></#list>);
List<${table.className}Entity> listBy${key}s(<#assign idx=0><#list uks[key] as uk>List<${uk.attrType}> ${uk.attrname}s<#assign idx=idx+1><#if (idx<uks[key]?size)>,</#if></#list>);
</#list>
}
package ${daoPackage}.impl;
import ${daoPackage}.${table.className}Dao;
import ${entityPackage}.${table.className}Entity;
import java.util.List;
import org.springframework.stereotype.Repository;
@Repository
public class ${table.className}DaoImpl implements ${table.className}Dao{
@Override
public int save(${table.className}Entity ${table.classname}Entity){
return 0;
}
<#if pk??>
@Override
public int deleteBy${pk.attrName}(${pk.attrType} ${pk.attrname}){
return 0;
}
@Override
public int deleteBatchBy${pk.attrName}s(List<${pk.attrType}> ${pk.attrname}s){
return 0;
}
@Override
public int updateBy${pk.attrName}(${table.className}Entity ${table.classname}Entity){
return 0;
}
@Override
public ${table.className}Entity getBy${pk.attrName}(${pk.attrType} ${pk.attrname}){
return null;
}
@Override
public List<${table.className}Entity> listBy${pk.attrName}s(List<${pk.attrType}> ${pk.attrname}s){
return null;
}
</#if>
<#list uks?keys as key>
@Override
public ${table.className}Entity getBy${key}(<#assign idx=0><#list uks[key] as uk>${uk.attrType} ${uk.attrname}<#assign idx=idx+1><#if (idx<uks[key]?size)>,</#if></#list>){
return null;
}
@Override
public List<${table.className}Entity> listBy${key}s(<#assign idx=0><#list uks[key] as uk>List<${uk.attrType}> ${uk.attrname}s<#assign idx=idx+1><#if (idx<uks[key]?size)>,</#if></#list>){
return null;
}
</#list>
}
package ${entityPackage};
<#assign hasBigDecimal=0, hasDate=0 >
<#list columns as c>
<#if c.attrType == 'BigDecimal' >
<#assign hasBigDecimal=hasBigDecimal+1>
<#elseif c.attrType == 'Date' >
<#assign hasDate = hasDate + 1>
</#if>
</#list>
<#if (hasBigDecimal>0) >
import java.math.BigDecimal;
</#if>
<#if (hasDate>0)>
import java.util.Date;
</#if>
<#if table.comments?? >
/**
* ${table.comments}
*/
</#if>
public class ${table.className}Entity {
<#list columns as column>
<#if column.comments?? >
/**
* ${column.comments}
*/
</#if>
private ${column.attrType} ${column.attrname};
</#list>
<#list columns as column>
public void set${column.attrName}(${column.attrType} ${column.attrname}) {
this.${column.attrname} = ${column.attrname};
}
public ${column.attrType} get${column.attrName}() {
return ${column.attrname};
}
</#list>
}
<?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="${daoPackage}.impl.${table.className}DaoImpl">
<resultMap type="${entityPackage}.${table.className}Entity" id="${table.classname}Map">
<#list columns as column>
<result property="${column.attrname}" column="${column.columnName}"/>
</#list>
</resultMap>
<sql id="columns">
<#assign idx=1><#list columns as c>
${c.columnName}<#if (idx<columns?size)>,</#if>
<#assign idx=idx+1></#list>
</sql>
<insert id="save" <#if pk.extra == 'auto_increment'>useGeneratedKeys="true" keyProperty="${pk.attrname}"</#if>
parameterType="${entityPackage}.${table.className}Entity">
INSERT INTO ${table.tableSchema}.${table.tableName}(<#assign idx=1><#list table.mainColumns as c>${c.columnName}<#if (idx<table.mainColumns?size)>,</#if><#assign idx=idx+1></#list>)
VALUES(<#assign idx=1><#list table.mainColumns as c>${pre}${c.attrname}${end}<#if (idx<table.mainColumns?size)>,</#if><#assign idx=idx+1></#list>)
</insert>
<delete id="deleteBy${pk.attrName}">
DELETE FROM ${table.tableSchema}.${table.tableName} WHERE ${pk.columnName}=${pre}${pk.attrname}${end}
</delete>
<delete id="deleteBatchBy${pk.attrName}s">
DELETE FROM ${table.tableSchema}.${table.tableName} WHERE ${pk.columnName} IN
<foreach item="item" index="index" collection="${pk.attrname}s" open="(" separator="," close=")">
${pre}item${end}
</foreach>
</delete>
<update id="updateBy${pk.attrName}" parameterType="${entityPackage}.${table.className}Entity">
UPDATE ${table.tableSchema}.${table.tableName}
<set>
<#list columns as c>
<#if c.extra != 'auto_increment' && c.extra != "on update CURRENT_TIMESTAMP" && c.columnName != "gmt_create">
<if test="${c.attrname} != null">
${c.columnName} = ${pre}${c.attrname}${end},
</if>
</#if>
</#list>
</set>
WHERE ${pk.columnName}=${pre}${pk.attrname}${end}
</update>
<select id="getBy${pk.attrName}" resultMap="${table.classname}Map">
SELECT <include refid="columns"/>
FROM ${table.tableSchema}.${table.tableName}
WHERE ${pk.columnName} = ${pre}${pk.attrname}${end}
</select>
<select id="listBy${pk.attrName}s" resultMap="${table.classname}Map">
SELECT <include refid="columns"/>
FROM ${table.tableSchema}.${table.tableName}
WHERE ${pk.columnName} IN
<foreach item="item" index="index" collection="${pk.attrname}s" open="(" separator="," close=")">
${pre}item${end}
</foreach>
</select>
<#list uks?keys as key>
<select id="getBy${key}" resultMap="${table.classname}Map">
SELECT <include refid="columns"/>
FROM ${table.tableSchema}.${table.tableName}
WHERE <#assign idx=0><#list uks[key] as uk>${uk.columnName}=${pre}${uk.attrname}${end}<#assign idx=idx+1><#if (idx<uks[key]?size)> and </#if></#list>
</select>
<select id="listBy${key}s" resultMap="${table.classname}Map">
SELECT <include refid="columns"/>
FROM ${table.tableSchema}.${table.tableName}
WHERE
<#assign idx=0><#list uks[key] as uk>
${uk.columnName} IN
<foreach item="item" index="index" collection="${uk.attrname}s" open="(" separator="," close=")">
${pre}item${end}
</foreach>
<#assign idx=idx+1>
<#if (idx<uks[key]?size)> and </#if>
</#list>
</select>
</#list>
</mapper>
\ No newline at end of file
package cn.com.duiba.mysql.generator;
import cn.com.duiba.mysql.generator.entity.GeneratorConfig;
public class CodeGeneratorTest {
public static void main(String[] args) {
String DB_URL = "jdbc:mysql://dev.config.duibar.com:3306/act_com_conf?createDatabaseIfNotExist=true&useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true&connectTimeout=5000&socketTimeout=60000";
String user = "dev";
String pwd = "dev_fas015";
GeneratorConfig config = new GeneratorConfig(DB_URL, user, pwd);
config.setDaoPackage("cn.com.duiba.mysql.generator.test.dao");
config.setEntityPackage("cn.com.duiba.mysql.generator.test.entity");
config.setXmlLocation("src/main/resources/mappers");
config.setTableSchema("act_com_conf");
config.setTableName("tb_duiba_brick_config");
config.setTablePrefix("tb");
config.setModuleName("");
MybatisGenerator.genCode(config);
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment