SpringBoot2.x整合Freemark、MySQL、hibernate、nutz项目搭建详细过程

个人兴趣搭建了一个自动生成java文件的项目,下面是具体步骤;

1、创建SpringBoot项目

SpringBoot2.x整合Freemark、MySQL、hibernate、nutz项目搭建详细过程_第1张图片

2、自己命名项目。选择gradle或者maven

SpringBoot2.x整合Freemark、MySQL、hibernate、nutz项目搭建详细过程_第2张图片 

3、选择freemark服务和基础web的服务

SpringBoot2.x整合Freemark、MySQL、hibernate、nutz项目搭建详细过程_第3张图片

SpringBoot2.x整合Freemark、MySQL、hibernate、nutz项目搭建详细过程_第4张图片

4、点击下一步确认就行

5、配置服务build.gradle

plugins {
   id 'org.springframework.boot' version '2.1.5.RELEASE'
   id 'java'
}

apply plugin: 'io.spring.dependency-management'

group = 'com.godsnet'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'

repositories {
   maven { url'http://maven.aliyun.com/nexus/content/groups/public' }
   mavenCentral()
}

dependencies {

   // SpringBoot base modules
   compile 'org.springframework.boot:spring-boot-starter'
   compile 'org.springframework.boot:spring-boot-starter-web'
   compile 'org.springframework.boot:spring-boot-starter-test'

   //freemarker
   compile 'org.springframework.boot:spring-boot-starter-freemarker'
   //log4j2
   compile "org.springframework.boot:spring-boot-starter-log4j2"

   //mysql JDBC
   compile 'mysql:mysql-connector-java:8.0.13'

   //Hibernate validation
   compile "org.hibernate:hibernate-validator:5.3.1.Final"

   //nutz
   compile "org.nutz:nutz-plugins-spring-boot-starter:1.r.65"
   //poi
   compile group: 'org.apache.poi', name: 'poi', version: '3.17'
   compile "org.apache.poi:poi-ooxml:3.17"
   // lombok
   compile group: 'org.projectlombok', name: 'lombok', version: '1.16.20'
   //freemarker
   compile "org.freemarker:freemarker:2.3.23"
   //druid
   compile "com.alibaba:druid-spring-boot-starter:1.1.10"

}
configurations {
   all*.exclude module: 'spring-boot-starter-logging'
   all*.exclude module: 'logback-classic'
   all*.exclude module: 'log4j-over-slf4j'
}
6、配置properties文件
#server port
server.port= 8080
server.servlet.context-path=/godsnet
###mysql
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test?characterEncoding=utf8&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=

##druid连接池的设置
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
#初始化时建立物理连接的个数
spring.datasource.druid.initial-size=5
#最小连接池数量
spring.datasource.druid.min-idle=5
#最大连接池数量 maxIdle已经不再使用
spring.datasource.druid.max-active=20
#获取连接时最大等待时间,单位毫秒
spring.datasource.druid.max-wait=60000
#申请连接的时候检测,如果空闲时间大于timeBetweenEvictionRunsMillis,执行validationQuery检测连接是否有效。
spring.datasource.druid.test-while-idle=true
#既作为检测的间隔时间又作为testWhileIdel执行的依据
spring.datasource.druid.time-between-eviction-runs-millis=60000
#销毁线程时检测当前连接的最后活动时间和当前时间差大于该值时,关闭当前连接
spring.datasource.druid.min-evictable-idle-time-millis=30000
#用来检测连接是否有效的sql 必须是一个查询语句
#mysql中为 select 'x'
spring.datasource.druid.validation-query=select 'x'
#申请连接时会执行validationQuery检测连接是否有效,开启会降低性能,默认为true
spring.datasource.druid.test-on-borrow=false
#归还连接时会执行validationQuery检测连接是否有效,开启会降低性能,默认为true
spring.datasource.druid.test-on-return=false
#是否缓存preparedStatement,mysql5.5+建议开启
#spring.datasource.druid.pool-prepared-statements=true
#当值大于0时poolPreparedStatements会自动修改为true
spring.datasource.druid.max-pool-prepared-statement-per-connection-size=20
#配置扩展插件
spring.datasource.druid.filters=stat,wall
#通过connectProperties属性来打开mergeSql功能;慢SQL记录
spring.datasource.druid.connection-properties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
#合并多个DruidDataSource的监控数据
spring.datasource.druid.use-global-data-source-stat=true
7、创建连接类链接数据库,获取字段名和字段类型
package com.godsnet.godsnet.freemark;

import com.godsnet.godsnet.enums.GodsErrorCode;
import com.godsnet.godsnet.exception.GodsException;
import org.springframework.util.StringUtils;
import java.io.IOException;
import java.sql.*;
import java.util.HashMap;
import java.util.Map;

public class GetEntityOnMysql {

    public Map getTableStructureByName(String databaseName) throws IOException {
        String driver = "com.mysql.cj.jdbc.Driver";
        String url = "jdbc:mysql://localhost:3306/test?characterEncoding=utf8&serverTimezone=UTC";
        String username = "root";
        String password = "";
        Map columnNameMap = new HashMap<>();
        //加载驱动
        try {
            Class.forName(driver);
            //获得数据库连接
            Connection connection = DriverManager.getConnection(url, username, password);
            //获得元数据
            DatabaseMetaData metaData = connection.getMetaData();
            //获得表信息
            ResultSet tables = metaData.getTables(null, null, null, new String[]{"TABLE"});
            while (tables.next()) {
                columnNameMap = new HashMap<>(); //保存字段名
                //获得表名
                String table_name = tables.getString("TABLE_NAME");
                if(table_name.equals(databaseName)){
                    //通过表名获得所有字段名
                    ResultSet columns = metaData.getColumns(null, null, table_name, "%");
                    //获得所有字段名
                    while (columns.next()) {
                        //获得字段名
                        String column_name = columns.getString("COLUMN_NAME");
                        column_name = getColumnName(column_name);
                        //获得字段类型
                        String type_name = columns.getString("TYPE_NAME");
                        columnNameMap.put(column_name,ColumnsType.valueOf(type_name).getValue());
                    }
                    break;
                }
            }
            return columnNameMap;
        }catch (ClassNotFoundException e){
            throw new GodsException(GodsErrorCode.SYSTEM_ERROR,e.getMessage());
        }catch (SQLException e){
            throw new GodsException(GodsErrorCode.SYSTEM_ERROR,e.getMessage());
        }
    }


    public String getColumnName(String column_name) throws GodsException{
        if(StringUtils.isEmpty(column_name)){
            throw new GodsException(GodsErrorCode.PARAM_MISSING,"存在表的字段名为空");
        }
        String[] strArr = column_name.split("_");
        StringBuffer columnName = new StringBuffer();
        for(int i = 0 ; i < strArr.length ; i++){
            if(i == 0){
                columnName.append(strArr[i].toLowerCase());
            }else{
                char[] cc = strArr[i].toLowerCase().toCharArray();
                cc[0] -= 32;
                columnName.append(String.valueOf(cc));
            }
        }
        return String.valueOf(columnName);
    }
}

8、执行 模板类

package com.godsnet.godsnet.freemark;

import com.godsnet.godsnet.enums.GodsErrorCode;
import com.godsnet.godsnet.exception.GodsException;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.util.HashMap;
import java.util.Map;

public class FreemarkerCreator {
    private static final String TEMPLATE_PATH = "C:\\Program Files\\JetBrains\\godsnet\\src\\main\\java\\com\\godsnet\\godsnet\\freemark";
    private static final String CLASS_PATH = "C:\\Program Files\\JetBrains\\godsnet\\src\\main\\java\\com\\godsnet\\godsnet\\freemark";
    private static Logger logger = LoggerFactory.getLogger(FreemarkerCreator.class);

    /**
     * 创建Entity类
     * @param tableName
     */
    public static Map createEntity(String  tableName) throws GodsException {

        //  创建freeMarker配置实例
        Configuration configuration = new Configuration();
        Writer out = null;
        try {
            Map tableMap = new HashMap<>();
            try{
                GetEntityOnMysql getEntityOnMysql = new GetEntityOnMysql();
                tableMap = getEntityOnMysql.getTableStructureByName(tableName);
            }catch (Exception e){
                throw new GodsException(GodsErrorCode.SYSTEM_ERROR,e.getMessage());
            }

            //  获取模版路径
            configuration.setDirectoryForTemplateLoading(new File(TEMPLATE_PATH));
            //  创建数据模型
            Map dataMap = new HashMap<>();
            dataMap.put("classPath", "com.godsnet.godsnet.freemark");
            dataMap.put("tableName",tableName);
            dataMap.put("className", getClassName(tableName));
            dataMap.put("vmap", tableMap);
            //  加载模版文件
            Template template = configuration.getTemplate("entityClass.ftl");
            //  生成数据
            File docFile = new File(CLASS_PATH + "\\" + getClassName(tableName) +".java");
            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(docFile)));
            //  输出文件
            template.process(dataMap, out);
            logger.info("********************Entity文件创建成功 !********************");
            return tableMap;
        } catch (Exception e) {
            throw new GodsException(GodsErrorCode.SYSTEM_ERROR,e.getMessage());
        } finally {
            try {
                if (null != out) {
                    out.flush();
                }
            } catch (Exception e) {
                throw new GodsException(GodsErrorCode.SYSTEM_ERROR,e.getMessage());
            }
        }
    }

    /**
     * 创建Controller
     * @param tableName
     * @throws GodsException
     */
    public static void createController(String tableName) throws GodsException {

        //  创建freeMarker配置实例
        Configuration configuration = new Configuration();
        Writer out = null;
        try {
            //  获取模版路径
            configuration.setDirectoryForTemplateLoading(new File(TEMPLATE_PATH));
            //  创建数据模型
            Map dataMap = new HashMap<>();
            dataMap.put("classPath", "com.godsnet.godsnet.freemark");
            dataMap.put("className", getClassName(tableName));
            //  加载模版文件
            Template template = configuration.getTemplate("controllerClass.ftl");
            //  生成数据
            File docFile = new File(CLASS_PATH + "\\" + getClassName(tableName) +".java");
            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(docFile)));
            //  输出文件
            template.process(dataMap, out);
            logger.info("********************Controller文件创建成功 !********************");
        } catch (Exception e) {
            throw new GodsException(GodsErrorCode.SYSTEM_ERROR,e.getMessage());
        } finally {
            try {
                if (null != out) {
                    out.flush();
                }
            } catch (Exception e) {
                throw new GodsException(GodsErrorCode.SYSTEM_ERROR,e.getMessage());
            }
        }
    }

    /**
     * 规范化类名称
     * @param tableName
     * @return
     */
    public static String getClassName(String tableName){
        String[] arrStr = tableName.split("_");
        StringBuffer sb = new StringBuffer();
        for(int i = 1 ; i < arrStr.length ; i++){
            char[] cc = arrStr[i].toCharArray();
            cc[0] -= 32;
            sb.append(String.valueOf(cc));
        }
        return String.valueOf(sb);
    }

}

9、这些搞完就行了

这些我的代码,已经上传到GitHub了,需要的朋友可以点击下载,也希望你能给我的GITHUB项目点个星

https://github.com/liangguojieCN/godsnet

SpringBoot2.x整合Freemark、MySQL、hibernate、nutz项目搭建详细过程_第5张图片

你可能感兴趣的:(java,web项目)