Database tables generate Java entity classes directly

Source: Internet
Author: User
Tags stringbuffer

The code is as follows:

Package Com.nagios.info.entity;import Java.io.file;import Java.io.filewriter;import java.io.ioexception;import Java.io.printwriter;import java.sql.*;import java.util.arraylist;import Java.util.date;import java.util.HashMap; Import Java.util.list;import Java.util.map;import Com.chinaoly.utils.dateformatutil;import Org.springframework.beans.factory.annotation.autowired;import Org.springframework.beans.factory.annotation.qualifier;import org.springframework.stereotype.service;/** * @ Author Cunxp * @Description * @date 2018-01-09 pm 4:34 */public class Codeproduct {private String Packageoutpath = "com . nagios.info.entity ";//Specifies the path of the package to which the entity is generated private static string authorname =" CUNXP ";//author name private string tablename =" NA Gios_hoststatus ";//table name//database connection private static final String URL =" Jdbc:mysql://192.168.16.84:3306/nagios?useunicode=tr    Ue&characterencoding=utf8 ";    private static final String NAME = "root";    private static final String PASS = "Chinaoly"; private static FINAL String DRIVER = "Com.mysql.jdbc.Driver";        /* Constructor */public codeproduct () {//create connection Connection con;        Check the table to generate the entity class String sql = "Show full columns from" + tablename;        PreparedStatement pstemt = null;            try {try {class.forname (DRIVER);            } catch (ClassNotFoundException E1) {e1.printstacktrace ();            } con = drivermanager.getconnection (url,name,pass);            PSTEMT = con.preparestatement (sql);            ResultSet rs = Pstemt.executequery ();            List<columnentity> list=new arraylist<> ();                while (Rs.next ()) {columnentity ce=new columnentity ();                Ce.setname (rs.getstring ("Field"));                String type = rs.getstring ("type");                Ce.setdatatype (Parsetype (type));            List.add (CE);            The String content = Parse (list); try {File directory = NEW File ("");                String Path=this.getclass (). GetResource (""). GetPath (); SYSTEM.OUT.PRINTLN (path);//String OutputPath = Directory.getabsolutepath () + "/src/" +path.substring (path.la                Stindexof ("/com/", Path.length ()), Path.length ()) + INITCAP (tablename) + ". Java"; String OutputPath = Directory.getabsolutepath () + "/src/main/java/" +this.packageoutpath.replace (".", "/") + "/" +                Replaceunderlineandfirsttoupper (Tablename.tolowercase (), "_", "") + ". Java";                File File=new file (OutputPath);                System.out.println ("----------->" +outputpath);                if (!file.exists ()) {file.createnewfile ();                } FileWriter fw = new FileWriter (OutputPath);                PrintWriter pw = new PrintWriter (FW);                PW.PRINTLN (content);                Pw.flush ();            Pw.close ();            } catch (IOException e) {e.printstacktrace (); }        }catch (SQLException e) {e.printstacktrace (); } finally{//try {//Con.close ();//} catch (SQLException e) {////TODO auto- Generated catch block//e.printstacktrace ()//}} private String Parse (list<colum        Nentity> list) {StringBuffer sb = new StringBuffer ();        Sb.append ("package" + This.packageoutpath + "; \ r \ n");        Tablename=replaceunderlineandfirsttoupper (Tablename.tolowercase (), "_", ""); Importpackage (sb,this.packageoutpath+ ".")        +initcap (tablename));        Note Section infomsg (sb,tablename+ "entity class");        Entity part sb.append ("@Entity \ r \ n");        Sb.append ("@Table (name = \" "+tablename+" \ ") \ r \ n"); Sb.append ("public class" + Replaceunderlineandfirsttoupper (Tablename.tolowercase (), "_", "") + "implements S        Erializable "+" {\ r \ n ");        Sb.append ("\tprivate static final long serialversionuid = 1l;\r\n");    Sb.append ("\ r \ n");    AddElement (sb,list);        Sb.append ("}\r\n");    return sb.tostring ();  }/** * Import Package * @title * @date 2014-10-17 * @author Zhengyunfei * @param SB */public static void        Importpackage (StringBuffer sb,string tablename) {sb.append ("\ r \ n");        Sb.append ("Import javax.persistence.column;\r\n");        Sb.append ("Import javax.persistence.entity;\r\n");        Sb.append ("Import javax.persistence.id;\r\n");        Sb.append ("Import javax.persistence.table;\r\n");        Sb.append ("Import java.io.serializable;\r\n");        Sb.append ("Import java.util.date;\r\n");    Sb.append ("\ r \ n");            } public static void AddElement (StringBuffer sb,list<columnentity> List) {for (columnentity ce:list) {            Sb.append ("\[email protected" (name = \ "" "+ce.getname () +" \ ") \ r \ n");            Sb.append ("\tprivate" +ce.getdatatype () + "" +ce.getname () + "; \ r \ n");        Sb.append ("\ r \ n"); }}/** * Automatically generate comments * @title *@date 2014-10-17 * @author Zhengyunfei */public static void Infomsg (StringBuffer sb,string msg) {Sb.appe        nd ("/**\r\n");        Sb.append ("* @author" +authorname+ "\ r \ n");        Sb.append ("* @Description" +msg+ "\ r \ n");        Sb.append ("* @date" + dateformatutil.getstringbydate () + "\ r \ n");        Sb.append ("*/\r\n");    Sb.append ("\ r \ n"); }/** * Initial capital Letter * * @param srcstr * @return * */public static string Firstcharactertoupper (string s    RCSTR) {return srcstr.substring (0, 1). toUpperCase () + srcstr.substring (1); }/** * Replace the string and make its next letter uppercase * @param srcstr * @param org * @param ob * @return */public Stati        C string Replaceunderlineandfirsttoupper (string srcstr,string org,string ob) {string newstring = "";        int first=0;            while (Srcstr.indexof (org)!=-1) {first=srcstr.indexof (org); if (First!=srcstr.length ()) {newstring=newstring+srcstr.SUBSTRING (0,first) +ob;                Srcstr=srcstr.substring (First+org.length (), srcstr.length ());            Srcstr=firstcharactertoupper (SRCSTR);        }} newstring=firstcharactertoupper (NEWSTRING+SRCSTR);    return newstring;        }/** * Function: Change the initial letter of the input string to uppercase * @param str * @return */private static string Initcap (String str) {        char[] ch = str.tochararray ();        if (ch[0] >= ' A ' && ch[0] <= ' z ') {ch[0] = (char) (Ch[0]-32);    } return new String (CH); } private static String Parsetype (String type) {if (Type.tolowercase (). Contains ("int")) {return "Inte        Ger ";        } if (Type.tolowercase (). Contains ("varchar")) {return "String";        } if (Type.tolowercase (). Contains ("datetime")) {return ' Date ';        } if (Type.tolowercase (). Contains ("text")) {return "String";  } if (Type.tolowercase (). Contains ("double")) {          return "Double";    } return null;        } private class columnentity{private String name;        Private String DataType;        Public String GetName () {return name;        } public void SetName (String name) {this.name = name;        } public String Getdatatype () {return dataType;        } public void Setdatatype (String dataType) {this.datatype = DataType; }}/** * export * TODO * @param args */public static void main (string[] args) {new Codeprod    UCT (); }}

Reference link Reference Blog generated in fact is the Serviceimpl file is not an entity class, but can refer to.

Database tables generate Java entity classes directly

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.