Automatic generation of Java DMO and additions and deletions code

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 classAutogenerationdemo {2 3      Public Static voidMain (string[] args)throwsclassnotfoundexception, SQLException, IOException, templateexception {4         //Database Address5String url = "Jdbc:mysql://10.27.209.137:3306/sample";6         //User name7String name = "Root";8         //Password9String PassWord = "root";Ten         //Drive OneString Driver = "Com.mysql.jdbc.Driver"; A         //Table name -String tableName = "T_operate_log"; -         //Template Path theString Templatedir = "F:\\template"; -         //generate file path -String autogeneratedfile = "f:\\autogenerated"; -         //instantiation of +Autogenerationjavacode Autogenerationjavacode =Newautogenerationjavacode (URL, name, PassWord, driver, - tablename,autogeneratedfile,templatedir); +          A         //Calling generate Java code method at Autogenerationjavacode.autogenerationjavacode (); -     } -  -}

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:

 Packagecom.sun.autoGenerated;ImportJava.io.BufferedWriter;ImportJava.io.File;ImportJava.io.FileOutputStream;Importjava.io.IOException;ImportJava.io.OutputStreamWriter;ImportJava.io.Writer;Importjava.sql.Connection;ImportJava.sql.DriverManager;Importjava.sql.PreparedStatement;ImportJava.sql.ResultSetMetaData;Importjava.sql.SQLException;ImportJava.util.HashMap;ImportJava.util.Map;Importfreemarker.template.Configuration;Importfreemarker.template.Template;Importfreemarker.template.TemplateException; Public classAutogenerationjavacode {PrivateString URL; PrivateString name; PrivateString PassWord; PrivateString driver; PrivateString SQL; PrivateString TableName; PrivateString Templatedir; PrivateString Autogeneratedfile; Private Staticstring[][] Filenamearray =NewString[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"; }     Publicautogenerationjavacode (string url, string name, String PassWord, String driver, string tableName, string au Togeneratedfile,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 voidAutogenerationjavacode ()throwsIOException, Templateexception, ClassNotFoundException, SQLException {Configuration cfg=NewConfiguration (); Cfg.setdefaultencoding ("Utf-8"); String ClassName=Dealtablename (); String FileName=Dealclassname (className); Map<string, object> columnmap =GetColumn (); //Set template file pathCfg.setdirectoryfortemplateloading (NewFile (Templatedir)); Map<string, object> rootmap =NewHashmap<string, object>(); Rootmap.put ("ClassName", ClassName); Rootmap.put ("Columnmap", Columnmap); File dir=NewFile (autogeneratedfile + "\ \"); //checks whether the directory exists, does not exist, and creates        if(!dir.exists ())        {Dir.mkdir (); }         for(inti = 0; i < filenamearray.length; i++) {Template temp= Cfg.gettemplate (filenamearray[i][0]); File Docfile=NewFile (autogeneratedfile + "\" + FileName + filenamearray[i][1]); Writer Docout=NewBufferedWriter (NewOutputStreamWriter (NewFileOutputStream (docfile)); //Output Filetemp.process (Rootmap, docout); } System.out.println ("============== File Production success ==============="); }    //Get database table field name put in map     PublicMap<string, object> GetColumn ()throwsClassNotFoundException, 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 =NewHashmap<string, object>(); intSize =Rsmd.getcolumncount ();  for(inti = 0; i < size; i++) {String columnName=Dealcolumnname (RSMD, i);        Columnmap.put (ColumnName, columnName);        } conn.close (); returnColumnmap; }    //converts the table name to the field name of the DMO, such as operate_type after conversion to Operatetype    PrivateString Dealcolumnname (ResultSetMetaData rsmd,intIthrowsSQLException {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); returnColumnName; }     //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 converted    Privatestring 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); returnClassName; }    //convert the class name to a file name, and the Java public class name should be the same as its file name, where the first letter is converted to uppercase as Operatelog converted to Operatelog    Privatestring Dealclassname (String className) {string First= classname.substring (0, 1). toUpperCase (); String Rest= classname.substring (1, Classname.length ()); String FileName=NewStringBuffer (first). Append (rest). toString (); returnFileName; }}

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

Java DMO and additions and deletions to the automatic generation of code

Related Article

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.