mybatis代码自动生成器,可实现entity、mapper、service层代码生成

mybatis对实体类的操作基本重复,公司的框架又已经定型,只能自己写一个代码自动生成器来减轻工作量。
这里的实体类属性来自数据库中的表的列,可以根据需要自由更改。

package oamanager.entity;

import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.extension.activerecord.Model;

/**
 * 注释表
 * @author zhanghp2017he@foxmail.com
 * @date 2022/4/29 16:32
 */
@TableName("all_col_comments")
public class TableComments extends Model<TableComments> {

    @TableField("column_name")
    private String cloumn;

    @TableField("COMMENTS")
    private String comments;

    public String getCloumn() {
        return cloumn;
    }

    public void setCloumn(String cloumn) {
        this.cloumn = cloumn;
    }

    public String getComments() {
        return comments;
    }

    public void setComments(String comments) {
        this.comments = comments;
    }
}

package oamanager.entity;

import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.extension.activerecord.Model;

/**
 * 表
 * @author zhanghp2017he@foxmail.com
 * @date 2022/4/29 15:59
 */
@TableName("cols")
public class Table extends Model<Table> {

    @TableField("column_name")
    private String cloumn;

    @TableField(exist = false)
    private String comments;

    @TableField("data_Type")
    private String type;

    @TableField("table_name")
    private String tableName;

    public String getComments() {
        return comments;
    }

    public String getTableName() {
        return tableName;
    }

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

    public void setComments(String comments) {
        this.comments = comments;
    }

    public String getCloumn() {
        return cloumn;
    }

    public void setCloumn(String cloumn) {
        this.cloumn = cloumn;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }
}

@RestController
public class CodeController {

    @Autowired
    private TableService tableService;

    @Autowired
    private TableCommentsService tableCommentsService;

    String tableName = YereeXmlContext.getXmlValue("Http", "XmlDownlaod", "tablename").toUpperCase();
    String entityName = YereeXmlContext.getXmlValue("Http", "XmlDownlaod", "entityName");

    public String transType(String type) {
        if (type.contains("VARCHAR")) {
            return "VARCHAR";
        }
        if (type.contains("NUMBER")) {
            return "BIGINT";
        }
        if (type.contains("TIME")) {
            return "TIMESTAMP";
        }
        return type;
    }

    @RequestMapping("/go")
    public String get() {
        List<Table> tableList = tableService.getByTableName(tableName);
        List<TableComments> comments = tableCommentsService.getByTableName(tableName);
        for (Table table : tableList) {
            for (TableComments tableComments : comments) {
                if (table.getCloumn().equals(tableComments.getCloumn())) {
                    table.setComments(tableComments.getComments());
                    break;
                }
            }
        }
        List<String> strings = new ArrayList<>();


        strings = getEntityClassStr(strings, tableList);

        strings.add(getTempSet(tableList).toString());

        strings.add(getEntityClass(entityName).toString());

        strings.add("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
                "<!DOCTYPE mapper PUBLIC \"-//mybatis.org//DTD Mapper 3.0//EN\" \"http://mybatis.org/dtd/mybatis-3-mapper.dtd\">\n" +
                "<mapper namespace=\"\">\n");

        strings.add("<!--ResultMap-->");
        strings = getResultMapStr(strings, tableList);

        strings.add("<!--select-->");
        strings.add(getSelect(tableList).toString());

        strings.add("<!--selectList-->");
        strings.add(getSelectList(tableList).toString());

        strings.add("<!--selectLikeList-->");
        strings.add(getSelectLikeList(tableList).toString());

        strings.add("<!--insert-->");
        strings.add(getInsert(tableList).toString());

        strings.add("<!--batchInsert-->");
        strings.add(getBatchInsert(tableList).toString());

        strings.add("<!--updateByExample-->");
        strings.add(getUpdate(tableList).toString());

        strings.add("</mapper>");
        writeTxtStrs(strings, "D:/a.txt");
        System.out.println(1);
        return "success";
    }

    public StringBuffer getTempSet(List<Table> tableList) {
        StringBuffer str = new StringBuffer();
        for (Table table : tableList) {
            // {field: 'wjh', title: '项目编号', width: 2, align: 'center'},
            String clo = table.getCloumn();
            String lowerStr = "";
            if (clo.contains("_")) {
                lowerStr = clo.substring(0, clo.indexOf("_")).toLowerCase() + clo.substring(clo.indexOf("_"));
            } else {
                lowerStr = clo.toLowerCase();
            }
            str.append(" {field: '" + lowerStr + "', title: '" + table.getComments() + "', width: 2, align: 'center'},");
        }
        return str;
    }

    public StringBuffer getBatchInsert(List<Table> tableList) {
        StringBuffer batchInsertStr = new StringBuffer();
        batchInsertStr.append("<insert id=\"saveBatch\" parameterType=\"java.util.List\" useGeneratedKeys=\"false\">\n" +
                "        insert into " + tableName + "(");
        for (int i = 0; i < tableList.size() - 1; i++) {
            batchInsertStr.append(tableList.get(i).getCloumn() + ",");
        }
        batchInsertStr.append(tableList.get(tableList.size() - 1).getCloumn() + ")\n" +
                "        <foreach item=\"item\" collection=\"list\" separator=\"union all\">\n" +
                "            (\n" +
                "            SELECT\n");
        for (int i = 0; i < tableList.size() - 1; i++) {
            batchInsertStr.append("#{item." + tableList.get(i).getCloumn() + ",jdbcType=" + transType(tableList.get(i).getType()) + "},");
        }
        batchInsertStr.append("#{item." + tableList.get(tableList.size() - 1).getCloumn() + ",jdbcType=" + transType(tableList.get(tableList.size() - 1).getType()) + "} FROM DUAL\n" +
                "            )\n" +
                "        </foreach>\n" +
                "    </insert>");
        return batchInsertStr;
    }

    public StringBuffer getInsert(List<Table> tableList) {
        StringBuffer insertStr = new StringBuffer();
        insertStr.append("  <insert id=\"save\" useGeneratedKeys=\"true\" keyProperty=\"id\">\n" +
                "        insert into " + tableName + "(");
        for (Table table : tableList) {
            insertStr.append(table.getCloumn() + ",");
        }
        insertStr = deleteLast(insertStr);
        insertStr.append(")\n values (");
        for (Table table : tableList) {
            insertStr.append("#{" + table.getCloumn() + ",jdbcType=" + transType(table.getType()) + "},");
        }
        insertStr = deleteLast(insertStr);
        insertStr.append("\n)\n" +
                "    </insert>");
        return insertStr;
    }

    public StringBuffer getSelect(List<Table> tableList) {
        StringBuffer selectSb = new StringBuffer();
        selectSb.append("<select id=\"selectById\" resultMap=\"" + tableName.toLowerCase() + "\">");
        selectSb.append("SELECT ");
        for (Table table : tableList) {
            selectSb.append(table.getCloumn() + ",");
        }
        selectSb = deleteLast(selectSb);
        selectSb.append(" \nFROM " + tableName +
                "    WHERE id =#{id}\n</select>");
        return selectSb;
    }


    public StringBuffer getSelectList(List<Table> tableList) {
        StringBuffer selectSb = new StringBuffer();
        selectSb.append("<select id=\"selectByPage\" resultMap=\"" + tableName.toLowerCase() + "\">");
        selectSb.append("SELECT ");
        for (Table table : tableList) {
            selectSb.append(table.getCloumn() + ",");
        }
        selectSb = deleteLast(selectSb);
        selectSb.append(" \nFROM " + tableName +
                "    <where>\n");
        for (Table table : tableList) {
            String column = table.getCloumn();
            if (table.getType().contains("VARCHAR")) {
                selectSb.append("<if test=\"" + column + "!= null and " + column + "!=''\"> and " + column + " = #{" + column + "}</if>\n");
            } else {
                selectSb.append("<if test=\"" + column + "!= null\"> and " + column + " = #{" + column + "}</if>\n");
            }

        }
        selectSb.append("            </where>\n" +
                "    </select>");
        return selectSb;
    }

     public StringBuffer getSelectLikeList(List<Table> tableList, String tableName) {
        StringBuffer selectSb = new StringBuffer();
        selectSb.append("<select id=\"selectLikeByPage\" resultMap=\"" + tableName.toLowerCase() + "\">");
        selectSb.append("SELECT ");
        for (Table table : tableList) {
            selectSb.append(table.getCloumn() + ",");
        }
        selectSb = deleteLast(selectSb);
        selectSb.append(" \nFROM " + tableName +
                "    <where>\n");
        for (Table table : tableList) {
            String column = table.getCloumn();
            if (table.getType().contains("VARCHAR")) {
                selectSb.append("<if test=\"" + column + " != null and " + column + " !=''\"> and \n<bind name=\"" + column + "\" value=\"'%'+"+column+"+'%'\"/>" +
                        column + " LIKE #{" + column + "}</if>\n");
            } else {
                selectSb.append("<if test=\"" + column + " != null\"> and " + column + " like #{" + column + "}</if>\n");
            }

        }
        selectSb.append("            </where>\n" +
                "    </select>");
        return selectSb;
    }


    public StringBuffer getUpdate(List<Table> tableList) {
        StringBuffer updateSb = new StringBuffer();
        updateSb.append("<update id=\"updateByExample\">\n");
        updateSb.append("update " + tableName + "\n<set>");
        for (Table table : tableList) {
            String column = table.getCloumn();
            if (table.getType().contains("VARCHAR")) {
                updateSb.append("\n             <if test=\"" + column + " !=null and" + column + " !=''\"> " + column + "=#{" + column + "}, </if>");
            } else {
                updateSb.append("\n             <if test=\"" + column + " !=null\"> " + column + "=#{" + column + "}, </if>");
            }
        }
        updateSb.append("            \n</set>\n where ID = #{ID}\n" +
                "    </update>");
        return updateSb;
    }


    public List<String> getResultMapStr(List<String> strings, List<Table> tableList) {
        strings.add("  <resultMap id=\"" + tableName.toLowerCase() + "\" type=\"\">");
        strings.add("<id column=\"ID\" jdbcType=\"VARCHAR\" property=\"ID\" />");
        for (Table table : tableList) {
            StringBuffer mapperSb = new StringBuffer();
            if (!table.getCloumn().equals("ID")) {
                mapperSb.append("<result column = \"" + table.getCloumn() + "\" jdbcType =\"" + transType(table.getType()) + "\" property=\"" + table.getCloumn() + "\" />");
            }
            strings.add(mapperSb.toString());
        }
        strings.add("  </resultMap>");
        return strings;
    }

    public List<String> getEntityClassStr(List<String> strings, List<Table> tableList) {
        for (Table table : tableList) {
            StringBuffer stringBuffer = new StringBuffer();
            stringBuffer.append("/**" + table.getComments() + "*/\n");
            stringBuffer.append("private ");
            if (table.getType().contains("VARCHAR")) {
                stringBuffer.append("String");
            }
            if (table.getType().contains("DATE") || table.getType().contains("TIMESTAMP")) {
                stringBuffer.append("Date");
            }
            if (table.getType().contains("NUMBER")) {
                stringBuffer.append("Long");
            }
            if (table.getType().contains("BLOB")) {
                stringBuffer.append("Blob");
            }
            if (table.getType().contains("CLOB")) {
                stringBuffer.append("String");
            }
            stringBuffer.append(" " + table.getCloumn() + ";");
            strings.add(stringBuffer.toString());
        }
        return strings;
    }

    public StringBuffer getEntityClass(String entityName) {
        StringBuffer stringBuffer = new StringBuffer();
        String lowerEntityName = entityName.substring(0, 1).toLowerCase() + entityName.substring(1);

        //mapper
        stringBuffer.append("@MyBatisRepository\n" +
                "public interface " + entityName + "Mapper {\n");
        stringBuffer.append(" public " + entityName + " selectById(@Param(\"id\") String id);\n");
        stringBuffer.append(" public List<" + entityName + "> selectByPage(" + entityName + " " + lowerEntityName + ");\n");
        stringBuffer.append(" public List<" + entityName + "> selectLikeByPage(" + entityName + " " + lowerEntityName + ");\n");
        stringBuffer.append(" public void save(" + entityName + " " + lowerEntityName + ");\n");
        stringBuffer.append(" public void saveBatch(@Param(\"list\") List<" + entityName + "> " + lowerEntityName + "List);\n");
        stringBuffer.append(" public void updateByExample(" + entityName + " " + lowerEntityName + ");\n}\n\n\n");

        //service
        stringBuffer.append("public interface "+entityName+"Service {\n" +
                "\n" +
                "\n" +
                "            public PageInfo<"+entityName+"> findByPage("+entityName+" "+lowerEntityName+", Integer page, Integer rows);\n" +
                "\n" +
                "            public void save("+entityName+" "+lowerEntityName+");\n" +
                "\n" +
                "            public void saveBatch(List<"+entityName+"> "+lowerEntityName+"List);\n" +
                "\n" +
                "            public "+entityName+" findById(String id);\n" +
                "\n" +
                "            public void update("+entityName+" "+lowerEntityName+");\n" +
                "        }\n\n\n");



        //serviceImpl
        stringBuffer.append("@Service\npublic class " + entityName + "ServiceImpl implements " + entityName + "Service {\n\n@Autowired\nprivate " + entityName + "Mapper " + lowerEntityName + "Mapper;");
        stringBuffer.append("\n" +
                "@Override\n" +
                "    public PageInfo<" + entityName + "> findByPage(" + entityName + " " + lowerEntityName + ", Integer page, Integer rows){\n" +
                "        PageHelper.startPage(page,rows);\n" +
                "        List<" + entityName + "> " + lowerEntityName + "List = " + lowerEntityName + "Mapper.selectByPage(" + lowerEntityName + ");\n" +
                "        return new PageInfo<>(" + lowerEntityName + "List);\n" +
                "    }" +
                "\n" +
                "    @Override\n" +
                "    public void save(" + entityName + " " + lowerEntityName + ") {\n" +
                "        " + lowerEntityName + "Mapper.save(" + lowerEntityName + ");\n" +
                "    }\n" +
                "\n" +
                "    @Override\n" +
                "    public void saveBatch(List<" + entityName + "> " + lowerEntityName + "List) {\n" +
                "        " + lowerEntityName + "Mapper.saveBatch(" + lowerEntityName + "List);\n" +
                "    }\n" +
                "\n" +
                "    @Override\n" +
                "    public " + entityName + " findById(String id) {\n" +
                "        try{\n" +
                "            return " + lowerEntityName + "Mapper.selectById(id);\n" +
                "        }catch (Exception e){\n" +
                "            return null;\n" +
                "        }\n" +
                "    }\n" +
                "\n" +
                "    @Override\n" +
                "    public void update(" + entityName + " " + lowerEntityName + "){\n" +
                "        " + lowerEntityName + "Mapper.updateByExample(" + lowerEntityName + ");\n" +
                "    }");
        stringBuffer.append("\n}");
        return stringBuffer;
    }

   /**
     * 写入txt
     *
     * @param stringList
     * @param filePath
     * @return
     * @author banxian1804@qq.com
     * @date: 2021/9/22 15:49
     */
    public void writeTxtStrs(List<String> stringList, String filePath) {
        try {
            File file = new File(filePath);
            FileOutputStream fos = new FileOutputStream(file);
            Writer w = new OutputStreamWriter(fos, "GBK");
            for (String lineStr : stringList) {
                w.write(lineStr);
                w.write("\n");
            }
            w.flush();
            w.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值