Freemakeer first entry

Source: Internet
Author: User

In the Web development process, especially in the background management system development, without adding and deleting the basic operation, the original my own practice is a copy of the paste, and then modify the differences, but this is both dull and wasted a lot of time, So according to the characteristics of their own project structure to write a tool jar automatically generated structure code, you can directly generate the corresponding Database model object (DMO) according to the database table, as well as the additions and deletions of the table to change the code.

Before I considered a variety of automatic generation of code, such as the way the Web, by entering various parameters in the page text box, such as template file address, generate file address, database name, database user name and password, click the Generate button can generate source code files. But this requires deployment to start the Web program. Using the Java graphical user interface, but I do not know about Java graphics related APIs, and finally decided to use a jar package in a way that is convenient and concise.

Since the template file uses Freemarker, the database uses MySQL, so the other two jar files are introduced.

For example, Autogenerationjavacode.jar is the original project in the Autogenerationjavacode.java file packaging generated, but also the final form. By setting parameters in the Autogenerationdemo class main function, the code is automatically generated by calling directly.

After you have configured the parameters, you can generate the right-hand code file by running the Java program on the left-hand side of the diagram:

The call is as follows:

1 public class Autogenerationdemo {2  3 public     static void Main (string[] args) throws ClassNotFoundException, SQLE Xception, IOException, templateexception {4         //Database address 5         String url = "Jdbc:mysql://10.27.209.137:3306/sample"; 6         //user name 7         String name = "Root"; 8         //Password 9         string passWord = "root";         //Driver one         string driver = "com.mysql.jdbc.Driver";//         table name 13         string tableName = "T_operate_log";//         template path,         string templatedir = "F:\\template";         Generate file path         , String autogeneratedfile = "f:\\autogenerated";         //instantiation of         Autogenerationjavacode Autogenerationjavacode = new Autogenerationjavacode (URL, name, PassWord, driver,20                 tablename,autogeneratedfile, Templatedir         //Call Generate Java code method         Autogenerationjavacode.autogenerationjavacode ();     }25 26}

In the main method to configure the required parameters, because the code contains comments, do not repeat, call the jar package in the Autogenerationjavacode Autogenerationjavacode method can be generated, the console will print the file production completed

The structure of my Web project is a three-tier structure, the controller layer calls the service layer, from the service layer calls the DAO layer (data manipulation layer), so decided to generate the service layer, DAO layer code. The essence of this is to replace the variables in the template file. The template files and corresponding generated Java code are as follows:

The source code for the jar package is as follows:

Package Com.sun.autogenerated;import Java.io.bufferedwriter;import Java.io.file;import java.io.FileOutputStream; Import Java.io.ioexception;import java.io.outputstreamwriter;import java.io.writer;import java.sql.Connection; Import Java.sql.drivermanager;import Java.sql.preparedstatement;import Java.sql.resultsetmetadata;import Java.sql.sqlexception;import Java.util.hashmap;import Java.util.map;import freemarker.template.Configuration; Import Freemarker.template.template;import Freemarker.template.templateexception;public class    Autogenerationjavacode {private String URL;    private String name;    Private String PassWord;    Private String driver;    private String SQL;    Private String TableName;    Private String Templatedir;    Private String Autogeneratedfile;    private static string[][] Filenamearray = new string[5][2];        static {Filenamearray[0][0] = "DMOTEMPLATE.FTL";        FILENAMEARRAY[0][1] = "Dmo.java";        Filenamearray[1][0] = "SERVICETEMPLATE.FTL";FILENAMEARRAY[1][1] = "Service.java";        Filenamearray[2][0] = "SERVICEIMPLTEMPLATE.FTL";        FILENAMEARRAY[2][1] = "Serviceimpl.java";        Filenamearray[3][0] = "DAOTEMPLATE.FTL";        FILENAMEARRAY[3][1] = "Dao.java";        Filenamearray[4][0] = "DAOIMPLTEMPLATE.FTL";    FILENAMEARRAY[4][1] = "Daoimpl.java"; Public autogenerationjavacode (string url, string name, String PassWord, String driver, string tableName, St        Ring autogeneratedfile,string templatedir) {this.url = URL;        THIS.name = name;        This.password = PassWord;        This.driver = driver;        This.sql = "SELECT * from" + tableName;        This.tablename = TableName;        This.templatedir = Templatedir;    This.autogeneratedfile = Autogeneratedfile; } public void Autogenerationjavacode () throws IOException, Templateexception, ClassNotFoundException, SQLE        xception {Configuration cfg = new configuration (); Cfg.setdefaultencoding ("UTF-8 ");            String className = Dealtablename ();        String fileName = Dealclassname (className);        map<string, object> columnmap = GetColumn ();             Set template file path cfg.setdirectoryfortemplateloading (new file (Templatedir));        map<string, object> rootmap = new hashmap<string, object> ();        Rootmap.put ("ClassName", className);        Rootmap.put ("Columnmap", Columnmap);        File dir = new file (autogeneratedfile + "\ \");        Checks if the directory exists and does not exist create if (!dir.exists ()) {Dir.mkdir (); } for (int i = 0; i < filenamearray.length; i++) {Template temp = cfg.gettemplate (filenamear                               Ray[i][0]);            File Docfile = new file (autogeneratedfile + "\ \" + FileName + filenamearray[i][1]);            Writer docout = new BufferedWriter (new OutputStreamWriter (New FileOutputStream (docfile)));        Output file Temp.process (Rootmap, docout); } System.out.println ("============== File production success ===============");        }//Get database table field name put in Map public map<string, Object> GetColumn () throws ClassNotFoundException, SQLException {        Connection Conn;        PreparedStatement pstemt = null;        Class.forName (driver);        conn = drivermanager.getconnection (URL, name, PassWord);        PSTEMT = conn.preparestatement (sql);        ResultSetMetaData RSMD = Pstemt.getmetadata ();        map<string, object> columnmap = new hashmap<string, object> ();         int size = Rsmd.getcolumncount ();            for (int i = 0; i < size; i++) {String columnName = dealcolumnname (RSMD, i);        Columnmap.put (ColumnName, columnName);        } conn.close ();    return columnmap; }//Convert the table name to the field name of the DMO, for example Operate_type converted to Operatetype private String dealcolumnname (resultsetmetadata rsmd, int i) thro        WS SQLException {String columnName = rsmd.getcolumnname (i + 1). toLowerCase (); String charafterline = String.ValueOf (Columnname.charat ((Columnname.indexof ("_") + 1));        String Convertedchar = Charafterline.touppercase ();        ColumnName = Columnname.replace ("_" + Charafterline, Convertedchar);    return columnName;        }//Convert table name to type class name such as T_operate_log converted to Operatelog, the first letter of the class name should be uppercase, here in Freemarker template directly convert private String dealtablename () {        String className = tablename.tolowercase (). substring (Tablename.indexof ("_") + 1);        String charafterline = string.valueof (Classname.charat ((Classname.indexof ("_") + 1));        String Convertedchar = Charafterline.touppercase ();        ClassName = Classname.replace ("_" + Charafterline, Convertedchar);    return className; }//Convert the class name to a file name, and the Java public class name should be the same as its file name, where the initial letter is converted to uppercase as Operatelog converted to Operatelog private string Dealclassname (String Classnam        e) {String first = classname.substring (0, 1). toUpperCase ();        String rest = classname.substring (1, Classname.length ()); String fileName = new StringBuffer (first). Append (REST). toString ();    return fileName; }}

SOURCE Download: Http://files.cnblogs.com/files/jarman/sourceCode.zip

(Turn) Freemakeer beginner

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.