Java自动生成bean、dao、service、impl、controller(JPA初版)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u011897110/article/details/89709868

关自动生成代码我是这么想的:
初步:

目录

一、拿到所有表名、列名、列类型数据。

C3P0连接数据库并获取所需数据

所需数据对象

测试拿到的数据

结果

二、用FreeMarker模板生成对应JPA架构Java文件

编写模板

bean.ftl

bean_vo.ftl

repository.ftl

service.ftl

service_impl.ftl

controller.ftl

FreeMarker生成Java代码

测试

通用工具

参数配置文件

git地址:https://github.com/boorZ/auto


目录

 

一、拿到所有表名、列名、列类型数据。

C3P0连接数据库并获取所需数据

所需数据对象

测试拿到的数据

结果

二、用FreeMarker模板生成对应JPA架构Java文件

编写模板

          bean.ftl

          bean_vo.ftl

          repository.ftl

          service.ftl

          service_impl.ftl

          controller.ftl

FreeMarker生成Java代码

通用工具

参数配置文件

git地址:https://github.com/boorZ/auto


一、拿到所有表名、列名、列类型数据。

C3P0连接数据库并获取所需数据

package auto.c3p0;

import auto.BeanConfig;
import auto.bean.utils.BeanUtils;
import auto.c3p0.pojo.ColumnPOJO;
import auto.c3p0.pojo.TablePOJO;
import com.mchange.v2.c3p0.ComboPooledDataSource;

import java.beans.PropertyVetoException;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * 描 述: 请描述功能
 * 作 者: ZhouLin
 * 日 期: 创建时间: 2019/4/28
 * 版 本: v1.0
 **/
public class C3P0Utils {

    private static  ComboPooledDataSource cpds;
    private static Connection con;
    private static Statement sta;
    private static ResultSet rs;

    /**
     * 获取Connection
     * @return
     * @throws SQLException
     * @throws PropertyVetoException
     */
    public static Connection getconnection() throws SQLException, PropertyVetoException {
        cpds = new ComboPooledDataSource();
        cpds.setDriverClass("com.mysql.cj.jdbc.Driver");
        cpds.setJdbcUrl("jdbc:mysql:///"+BeanConfig.JPA_DATABASE+"?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf-8");
        cpds.setUser(BeanConfig.JPA_USER);
        cpds.setPassword(BeanConfig.JPA_PASSWORD);
        // 得到一个Connection
        con = cpds.getConnection();
        return con;
    }
    public static ResultSet getConnection(String sql) throws SQLException, PropertyVetoException {
        con = getconnection();
        sta = con.createStatement();
        rs = sta.executeQuery(sql);
        return rs;
    }
    public static void close() throws SQLException {
        rs.close();
        sta.close();
        con.close();
        cpds.close();
    }

    /**
     * 封装表名、列名、列类型
     * @return
     * @throws PropertyVetoException
     * @throws SQLException
     */
    public static List<TablePOJO> tableColumnType() throws PropertyVetoException, SQLException {
        List<TablePOJO> tableList = new ArrayList<>();
        ResultSet rs = getConnection("show tables");
        while (rs.next()) {
            // 表名
            Object tableName = rs.getObject(1);
            tableList.add(new TablePOJO(tableName, getColumn(tableName)));
        }
        rs.close();
        close();
        return tableList;
    }

    /**
     * 根据表名来返回该表对应列名和列类型
     * @param table
     * @return
     * @throws SQLException
     * @throws PropertyVetoException
     */
    public static List<ColumnPOJO> getColumn(Object table) throws SQLException, PropertyVetoException {
        List<ColumnPOJO> columnList = new ArrayList<>();
        ResultSet tableName = C3P0Utils.getConnection("select * from "+table);
        ResultSetMetaData rsmd = tableName.getMetaData();
        // 字段总数
        int columnCount = rsmd.getColumnCount();
        for (int i = 1; i <= columnCount; i++) {
            String humpConlumName = BeanUtils.toHump(rsmd.getColumnName(i), 1);
            columnList.add(new ColumnPOJO(rsmd.getColumnName(i), humpConlumName, rsmd.getColumnTypeName(i)));
        }
        return columnList;
    }
}

所需数据对象

package auto.c3p0.pojo;

import java.util.List;

/**
 * 描 述: 请描述功能
 * 作 者: ZhouLin
 * 日 期: 创建时间: 2019/4/28
 * 版 本: v1.0
 **/
public class TablePOJO {
    // 表名
    private Object tableName;
    // 列名集
    private List<ColumnPOJO> columnCountList;

    public Object getTableName() {
        return tableName;
    }

    public void setTableName(Object tableName) {
        this.tableName = tableName;
    }

    public List<ColumnPOJO> getColumnCountList() {
        return columnCountList;
    }

    public void setColumnCountList(List<ColumnPOJO> columnCountList) {
        this.columnCountList = columnCountList;
    }

    public TablePOJO() {
    }

    public TablePOJO(Object tableName, List<ColumnPOJO> columnCountList) {
        this.tableName = tableName;
        this.columnCountList = columnCountList;
    }

    @Override
    public String toString() {
        return "TablePOJO{" +
                "tableName=" + tableName +
                ", columnCountList=" + columnCountList +
                '}';
    }
}

package auto.c3p0.pojo;

/**
 * 描 述: 请描述功能
 * 作 者: ZhouLin
 * 日 期: 创建时间: 2019/4/28
 * 版 本: v1.0
 **/
public class ColumnPOJO {
    // 列名
    private Object conlumName;
    // 驼峰列名
    private Object humpConlumName;
    // 列类型
    private Object conlumTypeName;

    public Object getConlumName() {
        return conlumName;
    }

    public Object getHumpConlumName() {
        return humpConlumName;
    }

    public void setHumpConlumName(Object humpConlumName) {
        this.humpConlumName = humpConlumName;
    }

    public void setConlumName(Object conlumName) {
        this.conlumName = conlumName;
    }

    public Object getConlumTypeNameOriginal() {
        return conlumTypeName;
    }
    public Object getConlumTypeName() {
        switch (conlumTypeName.toString()) {
            case "INT":
                return "int";
            case "VARCHAR":
                return "String";
            default:
                return "";
        }
    }

    public void setConlumTypeName(Object conlumTypeName) {
        this.conlumTypeName = conlumTypeName;
    }

    public ColumnPOJO() {
    }

    public ColumnPOJO(Object conlumName, Object humpConlumName, Object conlumTypeName) {
        this.conlumName = conlumName;
        this.humpConlumName = humpConlumName;
        this.conlumTypeName = conlumTypeName;
    }

    public ColumnPOJO(Object conlumName, Object conlumTypeName) {
        this.conlumName = conlumName;
        this.conlumTypeName = conlumTypeName;
    }

    @Override
    public String toString() {
        return "ColumnPOJO{" +
                "conlumName=" + conlumName +
                ", humpConlumName=" + humpConlumName +
                ", conlumTypeName=" + conlumTypeName +
                '}';
    }
}

测试拿到的数据

@Test
    public void test01() throws PropertyVetoException, SQLException {
        List<TablePOJO> tablePOJOS = C3P0Utils.tableColumnType();
        tablePOJOS.forEach(table -> {
            System.out.println("=======================================");
            System.out.println("表名:"+table.getTableName());
            table.getColumnCountList().forEach(column -> {
                System.out.println("列名:"+column.getConlumName());
                System.out.println("列类型:"+column.getConlumTypeNameOriginal());
                System.out.println("转换列类型:"+column.getConlumTypeName());
                System.out.println("列驼峰:"+column.getHumpConlumName());
                System.out.println("-----------------------");
            });
        });
    }

结果


二、用FreeMarker模板生成对应JPA架构Java文件

编写模板

bean.ftl

<#if classPath??>
package ${classPath};
</#if>
${imports}

@Entity
@Table(name = "${className}")
public class ${fileName} extends BaseEntity{
<#--public class ${fileName} {-->

<#list newMember as m>
    @Column(name = "${m.conlumName}")
    private ${m.conlumTypeName} ${m.humpConlumName ? uncap_first};

</#list>
<#list newMember as m>
    public ${m.conlumTypeName} get${m.humpConlumName}() {
        return ${m.humpConlumName ? uncap_first};
    }

    public void set${m.humpConlumName}(${m.conlumTypeName} ${m.humpConlumName ? uncap_first}) {
        this.${m.humpConlumName ? uncap_first} = ${m.humpConlumName ? uncap_first};
    }

</#list>
    public ${fileName}() {
    }

    public ${fileName}(<#list newMember as m>${m.conlumTypeName} ${m.humpConlumName ? uncap_first}<#if m_has_next>,</#if></#list> ) {
        <#list newMember as m>
            this.${m.humpConlumName ? uncap_first} = ${m.humpConlumName ? uncap_first};
        </#list>
    }
}

bean_vo.ftl

<#if classPath??>
package ${classPath};
</#if>

${imports}

public class ${fileName} extends BaseEntity{
<#--public class ${fileName} {-->

<#list newMember as m>
    private ${m.conlumTypeName} ${m.humpConlumName ? uncap_first};
</#list>

<#list newMember as m>
    public ${m.conlumTypeName} get${m.humpConlumName}() {
        return ${m.humpConlumName ? uncap_first};
    }

    public void set${m.humpConlumName}(${m.conlumTypeName} ${m.humpConlumName ? uncap_first}) {
        this.${m.humpConlumName ? uncap_first} = ${m.humpConlumName ? uncap_first};
    }

</#list>
    public ${fileName}() {
    }

    public ${fileName}(<#list newMember as m>${m.conlumTypeName} ${m.humpConlumName ? uncap_first}<#if m_has_next>,</#if></#list> ) {
        <#list newMember as m>
            this.${m.humpConlumName ? uncap_first} = ${m.humpConlumName ? uncap_first};
        </#list>
    }
}

repository.ftl

<#if classPath??>
package ${classPath};
</#if>

${imports}

public interface ${fileName} extends CommonRepository<${T}, Integer>{

}

service.ftl

<#if classPath??>
package ${classPath};
</#if>
${imports}

public interface ${fileName} extends SimpCommonService<${T}, Integer>{

}

service_impl.ftl

<#if classPath??>
package ${classPath};
</#if>

${imports}

@Service
public class ${fileName} implements ${Service} {
    @Autowired
    private ${Repository} ${Repository ? uncap_first};

    @Override
    public CommonRepository<${T}, Integer> getCommonRepository() {
        return this.${Repository ? uncap_first};
    }

}

controller.ftl

<#if classPath??>
package ${classPath};
</#if>

${imports}

@RestController
@RequestMapping(value = "/")
public class ${fileName} {
    @Autowired
    private ${Service} ${Service ? lower_case};

}

FreeMarker生成Java代码

package auto.freemarker.templates.ftlutils;

import auto.BeanConfig;
import freemarker.template.Configuration;
import freemarker.template.Template;

import java.io.*;
import java.util.Map;

/**
 * 描 述: 请描述功能
 * 作 者: ZhouLin
 * 日 期: 创建时间: 2019/4/28
 * 版 本: v1.0
 **/
public class FreemarkerUtils {

    public static void base(Map<String, Object> dataMap, String ftlName, String dir, String newFileName) {
        // step1 创建freeMarker配置实例
        Configuration configuration = new Configuration(Configuration.VERSION_2_3_23);
        Writer out = null;
        try {
            // step2 获取模版路径
            configuration.setDirectoryForTemplateLoading(new File(BeanConfig.JPA_TEMPLATE_PATH));
            // step3 创建数据模型
            // step4 加载模版文件
            Template template = configuration.getTemplate(ftlName);
            // step5 生成数据
            File newDir=new File(BeanConfig.JPA_CLASS_PATH + dir);
            File newFile = new File(newDir,newFileName);
            if (!newDir.exists()) {
                newDir.mkdirs();
                newFile.createNewFile();
            }
            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(newFile)));
            // step6 输出文件
            template.process(dataMap, out);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != out) {
                    out.flush();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
    }
}
package auto.freemarker;

import auto.BeanConfig;
import auto.bean.utils.BeanUtils;
import auto.c3p0.C3P0Utils;
import auto.c3p0.pojo.ColumnPOJO;
import auto.c3p0.pojo.TablePOJO;
import auto.freemarker.templates.ftlutils.FreemarkerUtils;

import java.beans.PropertyVetoException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 描 述: 请描述功能
 * 作 者: ZhouLin
 * 日 期: 创建时间: 2019/4/29
 * 版 本: v1.0
 **/
public class JpaUtils {
    /**
     *
     * @param ftlName
     * @param beanConfig
     * @param javaPostfix
     * @param fileName
     * @throws PropertyVetoException
     * @throws SQLException
     */
    public static void jpaBase(String ftlName, String beanConfig, String javaPostfix, String fileName) throws PropertyVetoException, SQLException {

        List<TablePOJO> tableList = C3P0Utils.tableColumnType();
        for (TablePOJO table : tableList) {
            String hump = BeanUtils.toHump((String) table.getTableName(), 1);
            String java = hump + javaPostfix;

            Map<String, Object> map = new HashMap<>();

            String classPath = BeanConfig.JPA_CLASS_PATH;
            if (classPath.contains("src/main/java")) {
                classPath = classPath.split("src/main/java/")[1].replace("/", ".");
                classPath += fileName;
            } else {
                classPath = null;
            }
            map.put("classPath", classPath);
            map.put("imports", beanConfig);
            map.put("className", table.getTableName());
            map.put("fileName", java);
            map.put("newMember", filtration(table.getColumnCountList()));
            map.put("T", hump + "Entity");
            map.put("Service", hump + "Service");
            map.put("Repository", hump + "Repository");
            map.put("mapping", javaPostfix);
            FreemarkerUtils.base(map, ftlName, fileName, java+".java");
        }
    }

    /** 过滤 **/
    private static List<ColumnPOJO> filtration(List<ColumnPOJO> columnPOJOList) {
        List<ColumnPOJO> columnCountList = new ArrayList<>();
        for (ColumnPOJO columnPOJO : columnPOJOList) {
            if (!BeanConfig.JPA_NEGLECT_FIELDS.contains((CharSequence) columnPOJO.getConlumName())) {
                columnCountList.add(columnPOJO);
            }
        }
        return columnCountList;
    }
}

测试

public class AutoMain {
    public static void main(String[] args) throws PropertyVetoException, SQLException, IOException {
        JpaUtils.jpaBase("bean.ftl", BeanConfig.JPA_IMPORTS_BEAN, "Entity", "bean");
        JpaUtils.jpaBase("bean_vo.ftl", BeanConfig.JPA_IMPORTS_BEAN_VO, "VO", "vo");
        JpaUtils.jpaBase("repository.ftl", BeanConfig.JPA_IMPORTS_REPOSITORY, "Repository", "repository");
        JpaUtils.jpaBase("service.ftl", BeanConfig.JPA_IMPORTS_SERVICE, "Service", "service");
        JpaUtils.jpaBase("service_impl.ftl", BeanConfig.JPA_IMPORTS_SERVICE_IMPL, "ServiceImpl", "service//impl");
        JpaUtils.jpaBase("controller.ftl", BeanConfig.JPA_IMPORTS_CONTROLLER, "Controller", "controller");
    }
}

通用工具

import java.io.IOException;

/**
 * 描 述: 请描述功能
 * 作 者: ZhouLin
 * 日 期: 创建时间: 2019/4/29
 * 版 本: v1.0
 **/
public class BeanUtils {
    /**
     * 转成驼峰命名规则
     * yOrn: 1(首字母大写)
     * yOrn: 0(首字母不大写)
     */
    public static String toHump(String s, Integer yOrn){
        s = s.toLowerCase();
        String[] split = s.split("_");
        String ss = "";
        for (int i = 0; i < split.length; i++) {
            String s0 = "";
            if (i == 0) {
                if (yOrn == 0) {
                    s0 = split[i].substring(0, 1);
                } else if (yOrn == 1) {
                    s0 = split[i].substring(0, 1).toUpperCase();
                }
            } else {
                s0 = split[i].substring(0, 1).toUpperCase();
            }
            ss += s0 + split[i].substring(1);
        }
        return ss;
    }

    public static void openFileDirectory(String url) throws IOException {
        if (url != null && !"".equals(url)) {
            String[] cmd = new String[5];
            cmd[0] = "cmd";
            cmd[1] = "/c";
            cmd[2] = "start";
            cmd[3] = " ";
            cmd[4] = url;
            Runtime.getRuntime().exec(cmd);
        }
    }
}

参数配置文件

/**
 * 描 述: 请描述功能
 * 作 者: ZhouLin
 * 日 期: 创建时间: 2019/4/29
 * 版 本: v1.0
 **/
public class BeanConfig {
    /** 数据库用户 **/
    public static String JPA_USER = "root";
    /** 数据库密码 **/
    public static String JPA_PASSWORD = "123456";
    /** 数据库 **/
    public static String JPA_DATABASE = "zl";
    /** 忽略字段 **/
    public static String JPA_NEGLECT_FIELDS = "id";
    /** ftl模板所在目录 **/
    public static String JPA_TEMPLATE_PATH = "src/main/java/auto/freemarker/templates/jpa/";
    /** 生成文件路径 **/
    public static String JPA_CLASS_PATH = "C:\\Users\\Administrator\\Desktop\\autoCode\\";

    /** 不同文件导入的包 **/
    public static String JPA_IMPORTS_BEAN = "import common.model.BaseEntity;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Table;";
    public static String JPA_IMPORTS_BEAN_VO = "import common.model.BaseEntity;";
    public static String JPA_IMPORTS_REPOSITORY = "import common.repository.CommonRepository;\nimport org.springframework.data.repository.NoRepositoryBean;";
    public static String JPA_IMPORTS_SERVICE = "import common.service.SimpCommonService;";
    public static String JPA_IMPORTS_SERVICE_IMPL = "import common.repository.CommonRepository;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Service;";
    public static String JPA_IMPORTS_CONTROLLER = "import org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.bind.annotation.RestController;";
}

git地址:https://github.com/boorZ/auto

展开阅读全文

没有更多推荐了,返回首页