Java reverse engineering (java class generate database table)

Speaking it very simply, it is to listen to the name on the big feeling pricey. There are a lot of reverse engineering the way, such as mybatis provides one such tool mybatis-genderator, this is not used anyway, I just heard that before the tools companies are written with the company's recent is idle, bored own hands to write one.

My engineer this spring and mybatis based on written, interested plus spring-mvc, add a page is good.

Actually using mybatis do reverse engineering was simply two select queries like, database foundation should remember what good children's shoes are two of the query (do not remember it does not matter, you can learn thing):

  1. Query database all the tables: select * from information_schema.TABLES where TABLE_SCHEMA = (select database ())

  2. All the information fields of the table query: select * from information_schema.COLUMNS where TABLE_SCHEMA = (select database ()) and TABLE_NAME = # {tableName}

For the first sql query the database for which it is connected on the line, do not need to pass parameters. But the second sql need to pass in the name of the table (which is understandable)

We are the essential parameters that need to connect 4 large databases, and database linking all should need these stuff (this statement here is what I use MySQL ) . Other things on the profiles I will not say more. Today, the focus is not here

Next simply be posted out dao, service layer, and a web structure as usually very simple.

service layer

service implementation class

Then there is the focus of today. In fact, very simple, many people may have thought, we have to get a table field information, and then we only need a file stream can not it? (Ah, yes, big brother, anyway, so I just wrote)

In fact, I have this very simple, mainly around a stringbuffer were first spliced ​​into a string, and then written to a file stream. I stick my bottom of the code.

package com.ml.code.one.codegenerator.util;

import com.ml.code.one.codegenerator.myservice.MyCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

@Component
public class CodeGenerator {
    @Autowired
    private  MyCodeService service;

    public void codeGenerator(String tableName,String path){
        List <the Map> = service.listColumn the Columns (tableName); // query all the information table fields 
        String className = getClassName (tableName);
        StringBuffer sb = new StringBuffer();
        sb.append("package "+getPackageName(path)+";\n");
        sb.append("import java.io.Serializable;"+"\n");
        sb.append("import java.util.*;\n");
        sb.append("import java.lang.*;\n");
        sb.append("import lombok.Data;\n");
        sb.append("import lombok.ToString;\n\n");
        sb.append("@Data\n@ToString\n");
        sb.append("public class "+className+" implements Serializable {\n");
        sb.append("\tprivate static final long serialVersionUID = 1L;\n\n");
        //获取字段信息
        Iterator<Map> iterator = columns.iterator();
        while (iterator.hasNext()){
            Map next = iterator.next();
            DataType Object = next.get ( "DATA_TYPE"); // Gets the data type 
            String = classCast of the type (dataType); // data type 
            Object Property = next.get ( "COLUMN_NAME"); // get the field name 
            String propertity = getPropertity (property); // property name 
            Object annotation = next.get ( "COLUMN_COMMENT"); // comment 
            sb.append ( "\ tprivate" + type + "" + propertity + ";" + "//" + (String) annotation + "\ the n-" );
        }
        sb.append ( "}" );
         // spliced end

        // makefile 
        the try {
             // generate java files 
            the getFile (className, sb.toString (), path);
             // generate mapper.xml
 //             getMapperFile (className, path); 
        } the catch (IOException E) {
            e.printStackTrace ();
        }
    }

    /**
     * Generate class name
     * @Param tableName table
     * @return
     */
    private String getClassName(String tableName){
        String newClassName="";
        int i = tableName.indexOf("_");
        if (i<0){//没有下划线
            newClassName = tableName.substring(0, 1).toUpperCase() + tableName.substring(1)+"Po";
        } The else { // underlined 
            String [] = tableName.split STRs ( "_" );
            StringBuffer sb = new StringBuffer();
            for (int m = 0; m<strs.length; m++){
                sb.append(strs[m].substring(0, 1).toUpperCase() + strs[m].substring(1));
            }
            newClassName=sb.toString()+"Po";
        }
        return newClassName;
    }
    // generates java attribute type 
    Private String classCast (Object obj) {
        String type="";
        String str=(String)obj;
        if (str.equals("varchar")||str.equals("char")||str.equals("text")){
            type="String";
        }else if (str.equals("int")){
            type="Integer";
        }else if (str.equals("bigint")){
            type="Long";
        }else if (str.equals("double")||str.equals("float")){
            type="Double";
        }else if (str.equals("date")||str.equals("datetime")||str.equals("timestamp")){
            type="Date";
        }else {
            type="String";
        }
        return type;
    }
    // database field name attribute name transfer java 
    Private   String getPropertity (Object obj) {
        String pro="";
        Colum String = (String) obj;
         int index = colum.indexOf ( "_"); // determines whether there is underlined 
        IF (index <0) { // not underlined 
            pro = colum.substring (0,1) .toLowerCase ( ) colum.substring + (. 1); // first letter lowercase 
        } the else { // underlined 
            the StringBuilder SB = new new the StringBuilder ();
            String[] colums = colum.split("_");
            for (int i = 0; i<colums.length; i++){
                if (i==0){
                    sb.append (colums [I] .substring ( 0,1) .toLowerCase () + colums [I] .substring (. 1)); // first splicing, and the first letter lowercase 
                } the else {
                    sb.append (colums [I] .substring ( 0,1) .toUpperCase () + colums [I] .substring (. 1)); // except the first will capitalize the first letter 
                }
            }
            pro=sb.toString();
        }

        return pro;
    }

    /**
     * Generate package name
     */
    private  String getPackageName(String path){
        int index = path.indexOf("java\\");
        String newPackage="";
        if (index>0){
            String substring = path.substring(index+5);
            newPackage = substring.replace("\\", ".");
        }
        return newPackage;
    }

    /**
     * Generate file
     * @Param fileName file name
     * @Param contents of info to be written
     * @throws IOException
     */
    private  void getFile(String fileName,String info,String path) throws IOException {
        //生成文件
        File file = new File(path+"\\"+fileName+".java");
        if (!file.exists()){
            file.createNewFile();
        }
        FileWriter writer = new FileWriter(file);
        writer.write(info);
        writer.flush();
        writer.close();
    }

    /**
     * Generate Mapper.xml
     * @Param POName
      * / 
    Private  void getMapperFile (POName String, String path) throws IOException {
         // get the file name of 
        the StringBuilder fileName = new new the StringBuilder ();
         int index = poName.indexOf ( "Po" );
         IF (index <0) { // no suffix Po 
            fileName.append (POName + "Mapper" );
        } The else { // the presence Po suffix 
            String poName.substring Sub = (0, index); // taken to the desired portion 
            fileName.append (Sub + "Mapper" );
        }
        //获取路径
        StringBuilder newPath = new StringBuilder();
        int main = path.indexOf("main\\");
        if (main>0){
            String substring = path.substring(0, main+5);
            newPath.append(substring).append("\\resources\\mapper\\");
        }

        File file = new File(newPath+fileName.toString()+".xml");
        StringBuilder xmlInfo = new StringBuilder();
        xmlInfo.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
        xmlInfo.append("<!DOCTYPE mapper PUBLIC \"-//mybatis.org//DTD Mapper 3.0//EN\"  \n" +
                "     \"http://mybatis.org/dtd/mybatis-3-mapper.dtd\">\n");
        xmlInfo.append("<mapper namespace=\"\">\n");
        xmlInfo.append("\n\n");
        xmlInfo.append("</mapper>");
        FileWriter fw = new FileWriter(file);
        fw.write(xmlInfo.toString());
        fw.flush();
        fw.close();
    }
}

Here I use the boot project to write, when I chose to run the boot with built-in test tools running on ok ( do not forget to pack plus scanning dao layer on startup class Yo )

Here to do this simple reverse engineering is over, this can be generated directly to the file you specify, incidentally, is also generated even Mapper.xml. Gangster do not spray.

There needs to be the source of the network disk acquisition, (the only part of the network disk, but the reverse engineering part, other needs you compensate by itself, should not be difficult) 

Link: https: //pan.baidu.com/s/1KW7h9vro2U199hsL85Q38w
extraction code: obpf

 

Guess you like

Origin www.cnblogs.com/Tiandaochouqin1/p/11075363.html