代码自动生成 数据库表字段生成mybaties 映射配置文件**mapper.xml

下面试freemarker工具类

[html]  view plain  copy
  1. import java.io.BufferedWriter;  
  2. import java.io.File;  
  3. import java.io.FileOutputStream;  
  4. import java.io.IOException;  
  5. import java.io.OutputStreamWriter;  
  6. import java.io.PrintWriter;  
  7. import java.io.Writer;  
  8. import java.util.Locale;  
  9. import java.util.Map;  
  10.   
  11. import freemarker.template.Configuration;  
  12. import freemarker.template.Template;  
  13. import freemarker.template.TemplateException;  
  14.   
  15.   
  16. public class Freemarker {  
  17.   
  18.     /**  
  19.      * 打印到控制台(测试)  
  20.      *  @param ftlName  
  21.      */  
  22.     public static void print(String ftlName, Map<String,Object> root, String ftlPath) throws Exception{  
  23.         try {  
  24.             Template temp = getTemplate(ftlName, ftlPath);      //通过Template可以将模板文件输出到相应的流  
  25.             temp.process(root, new PrintWriter(System.out));  
  26.         } catch (TemplateException e) {  
  27.             e.printStackTrace();  
  28.         } catch (IOException e) {  
  29.             e.printStackTrace();  
  30.         }  
  31.     }  
  32.       
  33.     /**  
  34.      * 输出到输出到文件  
  35.      * @param ftlName   ftl文件  
  36.      * @param root      传入的map  
  37.      * @param outFile   输出后的文件全部路径  
  38.      * @param filePath  输出前的文件上部路径  
  39.      */  
  40.     public static void printFile(String ftlName, Map<String,Object> root, String outFile, String filePath, String ftlPath) throws Exception{  
  41.         try {  
  42.             File file = new File( filePath + outFile);  
  43.             if(!file.getParentFile().exists()){             //判断有没有父路径,就是判断文件整个路径是否存�?  
  44.                 file.getParentFile().mkdirs();              //不存在就全部创建  
  45.             }  
  46.             Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "utf-8"));  
  47.             Template template = getTemplate(ftlName, ftlPath);  
  48.             template.process(root, out);                    //模版输出  
  49.             out.flush();  
  50.             out.close();  
  51.         } catch (TemplateException e) {  
  52.             e.printStackTrace();  
  53.         } catch (IOException e) {  
  54.             e.printStackTrace();  
  55.         }  
  56.     }  
  57.       
  58.     /**  
  59.      * 通过文件名加载模�?  
  60.      * @param ftlName  
  61.      */  
  62.     public static Template getTemplate(String ftlName, String ftlPath) throws Exception{  
  63.         try {  
  64.             Configuration cfg = new Configuration();                                                //通过Freemaker的Configuration读取相应的ftl  
  65.             cfg.setEncoding(Locale.CHINA, "utf-8");  
  66.             cfg.setDirectoryForTemplateLoading(new File(ftlPath));      //设定去哪里读取相应的ftl模板文件  
  67.             Template temp = cfg.getTemplate(ftlName);                                               //在模板文件目录中找到名称为name的文�?  
  68.             return temp;  
  69.         } catch (IOException e) {  
  70.             e.printStackTrace();  
  71.         }  
  72.         return null;  
  73.     }  
  74. }  


java bean实体类结合上一篇生成的

[html]  view plain  copy
  1. public class Student {  
  2.  private String id;  
  3.  private String name;  
  4. public String getId() {  
  5.     return id;  
  6. }  
  7. public void setId(String id) {  
  8.     this.id = id;  
  9. }  
  10. public String getName() {  
  11.     return name;  
  12. }  
  13. public void setName(String name) {  
  14.     this.name = name;  
  15. }  
  16.    
  17. }  


这是freemarker模板文件mapperMysqlTemplate.ftl

[html]  view plain  copy
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">  
  3. <mapper namespace="${objectName}Mapper">  
  4.       
  5.       
  6.     <!-- 新增-->  
  7.     <insert id="save" parameterType="${pack}">  
  8.         insert into ${table}(  
  9.     <#list fieldList as var>  
  10.             ${var},  
  11.     </#list>  
  12.             ${id}  
  13.         ) values (  
  14.     <#list fieldList as var>  
  15.             ${r"#{"}${var}${r"}"},    
  16.     </#list>  
  17.             ${r"#{"}${id}${r"}"}  
  18.         )  
  19.     </insert>  
  20.   
  21.   
  22. <!-- 删除-->  
  23.     <delete id="delete" parameterType="${pack}">  
  24.         delete from ${table}  
  25.         where   
  26.             ${id} = ${r"#{"}${id}${r"}"}  
  27.     </delete>  
  28.       
  29.       
  30.     <!-- 修改 -->  
  31.      <update id="edit" parameterType="${pack}">  
  32.         update  ${table}  
  33.             set   
  34.     <#list fieldList as var>  
  35.         <#if var??>  
  36.                 ${var} = ${r"#{"}${var}${r"}"},  
  37.         </#if>  
  38.     </#list>    
  39.             where   
  40.                 ${id} = ${r"#{"}${id}${r"}"}  
  41.     </update>  
  42.       
  43.       
  44.     <!-- 通过ID获取数据 -->  
  45.     <select id="findById" parameterType="java.lang.String" resultType="${pack}">  
  46.         select   
  47.     <#list fieldList as var>  
  48.             ${var},   
  49.     </#list>  
  50.             ${id}  
  51.         from   
  52.             ${table}  
  53.         where   
  54.             ${id} = ${r"#{"}${id}${r"}"}  
  55.     </select>  
  56.       
  57.     <!-- 列表(全部) -->  
  58.     <select id="listAll"  resultType="${pack}">  
  59.         select  
  60.         <#list fieldList as var>  
  61.                 a.${var},     
  62.         </#list>  
  63.                 a.${id}  
  64.         from   
  65.                 ${table} a  
  66.     </select>  
  67.           
  68. </mapper>  

查找数据库表字段的工具类

[html]  view plain  copy
  1. import java.io.BufferedWriter;  
  2. import java.io.File;  
  3. import java.io.FileWriter;  
  4. import java.io.IOException;  
  5. import java.sql.Connection;  
  6. import java.sql.DriverManager;  
  7. import java.sql.PreparedStatement;  
  8. import java.sql.ResultSet;  
  9. import java.sql.ResultSetMetaData;  
  10. import java.sql.SQLException;  
  11. import java.util.ArrayList;  
  12. import java.util.List;    
  13.     
  14. public class ReflectBean {    
  15.     private Connection connection;    
  16.     /*mysql url的连接字符串*/    
  17.     private static String url = "jdbc:mysql://127.0.0.1:3306/wechat?useUnicode=true&characterEncoding=UTF-8";    
  18.     //账号    
  19.     private static String user = "root";    
  20.     //密码    
  21.     private static String password = "123456";    
  22.     
  23.     //mysql jdbc的java包驱动字符串    
  24.     private String driverClassName = "com.mysql.jdbc.Driver";    
  25.     //数据库中的表名    
  26.     private String table;    
  27.     public String getTable() {  
  28.         return table;  
  29.     }  
  30.   
  31.     public void setTable(String table) {  
  32.         this.table = table;  
  33.     }  
  34.   
  35.     //数据库的列名称    
  36.     private String[] colnames; // 列名数组    
  37.     //列名类型数组      
  38.     private String[] colTypes;   
  39.       
  40.     public String[] getColnames() {  
  41.         return colnames;  
  42.     }  
  43.   
  44.     public void setColnames(String[] colnames) {  
  45.         this.colnames = colnames;  
  46.     }  
  47.   
  48.     public String[] getColTypes() {  
  49.         return colTypes;  
  50.     }  
  51.   
  52.     public void setColTypes(String[] colTypes) {  
  53.         this.colTypes = colTypes;  
  54.     }  
  55.   
  56.     public Connection getConnection() {    
  57.             return connection;    
  58.     }    
  59.     public void setConnection(Connection connection) {    
  60.             this.connection = connection;    
  61.     }    
  62.       
  63.     public ReflectBean(){    
  64.         try {//驱动注册    
  65.             Class.forName(driverClassName);    
  66.             if (connection == null || connection.isClosed())    
  67.                 //获得链接    
  68.                 connection = DriverManager.getConnection(url, user, password);    
  69.         } catch (ClassNotFoundException ex) {    
  70.                 ex.printStackTrace();    
  71.                 System.out.println("Oh,not");    
  72.             } catch (SQLException e) {    
  73.                 e.printStackTrace();    
  74.                 System.out.println("Oh,not");    
  75.             }    
  76.     }    
  77.         
  78.      
  79.     
  80.     public List<String> doAction(){    
  81.         String sql = "select * from "+table;   
  82.         List<String> list = new ArrayList<String>();  
  83.         try {    
  84.             PreparedStatement statement = connection.prepareStatement(sql);    
  85.             //获取数据库的元数据     
  86.             ResultSetMetaData metadata = statement.getMetaData();    
  87.             ResultSet rs = connection.getMetaData().getPrimaryKeys(null, null, table);  
  88.             String id = "";  
  89.             //获取组键字段  
  90.             if(rs.next()){  
  91.                 id = rs.getString(4);  
  92.             }  
  93.             //数据库的字段个数    
  94.             int len = metadata.getColumnCount();    
  95.             //字段名称    
  96.             colnames = new String[len+1];    
  97.             //字段类型 --->已经转化为java中的类名称了    
  98.             colTypes = new String[len+1];    
  99.             for(int i1;i<=len;i++){    
  100.                 //System.out.println(metadata.getColumnName(i)+":"+metadata.getColumnTypeName(i)+":"+sqlType2JavaType(metadata.getColumnTypeName(i).toLowerCase())+":"+metadata.getColumnDisplaySize(i));    
  101.                 //metadata.getColumnDisplaySize(i);    
  102.                 colnames[i] = metadata.getColumnName(i); //获取字段名称    
  103.                 list.add( colnames[i]);  
  104.                 colTypes[i] = sqlType2JavaType(metadata.getColumnTypeName(i)); //获取字段类型     
  105.             }    
  106.             list.add(id);  
  107.         } catch (SQLException e) {    
  108.             e.printStackTrace();    
  109.         }    
  110.         return list;  
  111.     }    
  112.       
  113.     /*   
  114.      * mysql的字段类型转化为java的类型*/    
  115.     private String sqlType2JavaType(String sqlType) {      
  116.             
  117.         if(sqlType.equalsIgnoreCase("bit")){      
  118.             return "boolean";      
  119.         }else if(sqlType.equalsIgnoreCase("tinyint")){      
  120.             return "byte";      
  121.         }else if(sqlType.equalsIgnoreCase("smallint")){      
  122.             return "short";      
  123.         }else if(sqlType.equalsIgnoreCase("int")){      
  124.             return "int";      
  125.         }else if(sqlType.equalsIgnoreCase("bigint")){      
  126.             return "long";      
  127.         }else if(sqlType.equalsIgnoreCase("float")){      
  128.             return "float";      
  129.         }else if(sqlType.equalsIgnoreCase("decimal") || sqlType.equalsIgnoreCase("numeric")       
  130.                 || sqlType.equalsIgnoreCase("real") || sqlType.equalsIgnoreCase("money")       
  131.                 || sqlType.equalsIgnoreCase("smallmoney")){      
  132.             return "double";      
  133.         }else if(sqlType.equalsIgnoreCase("varchar") || sqlType.equalsIgnoreCase("char")       
  134.                 || sqlType.equalsIgnoreCase("nvarchar") || sqlType.equalsIgnoreCase("nchar")       
  135.                 || sqlType.equalsIgnoreCase("text")){      
  136.             return "String";      
  137.         }else if(sqlType.equalsIgnoreCase("datetime") ||sqlType.equalsIgnoreCase("date")){      
  138.             return "Date";      
  139.         }else if(sqlType.equalsIgnoreCase("image")){      
  140.             return "Blod";      
  141.         }else if(sqlType.equalsIgnoreCase("timestamp")){      
  142.             return "Timestamp";      
  143.         }      
  144.               
  145.         return null;      
  146.     }    
  147.     /*获取整个类的字符串并且输出为java文件   
  148.      * */    
  149.     public  StringBuffer getClassStr(){    
  150.         //输出的类字符串    
  151.         StringBuffer str = new StringBuffer("");    
  152.         //获取表类型和表名的字段名    
  153.         this.doAction();    
  154.         //校验    
  155.         if(null == colnames && null == colTypes) return null;    
  156.         //拼接    
  157.         str.append("public class "+GetTuoFeng(table)+" {\r\n");    
  158.         //拼接属性    
  159.         for(int index=1; index < colnames.length ; index++){    
  160.             str.append(getAttrbuteString(colnames[index],colTypes[index]));    
  161.         }    
  162.         //拼接get,Set方法           
  163.         for(int index=1; index < colnames.length ; index++){    
  164.             str.append(getGetMethodString(colnames[index],colTypes[index]));    
  165.             str.append(getSetMethodString(colnames[index],colTypes[index]));    
  166.         }    
  167.         str.append("}\r\n");    
  168.         //输出到文件中    
  169.         File file = new File("E:/mengwx/【源码】mysql版本_spring4.0/FHMYSQL/src/com/fh/entity/"+GetTuoFeng(table)+".java");    
  170.         BufferedWriter write = null;    
  171.     
  172.         try {    
  173.             write = new BufferedWriter(new FileWriter(file));    
  174.             write.write(str.toString());    
  175.             write.close();    
  176.         } catch (IOException e) {    
  177.     
  178.             e.printStackTrace();    
  179.             if (write != null)    
  180.                 try {    
  181.                     write.close();    
  182.                 } catch (IOException e1) {              
  183.                     e1.printStackTrace();    
  184.                 }    
  185.         }    
  186.         return str;    
  187.     }    
  188.     /*   
  189.      * 获取字段字符串*/    
  190.     public StringBuffer getAttrbuteString(String name, String type) {    
  191.         if(!check(name,type)) {    
  192.             System.out.println("类中有属性或者类型为空");    
  193.             return null;    
  194.         };    
  195.         String format = String.format("    private %s %s;\n\r", new String[]{type,name});    
  196.         return new StringBuffer(format);    
  197.     }    
  198.     /*   
  199.      * 校验name和type是否合法*/    
  200.     public boolean check(String name, String type) {    
  201.         if("".equals(name) || name == null || name.trim().length() ==0){    
  202.             return false;    
  203.         }    
  204.         if("".equals(type) || type == null || type.trim().length() ==0){    
  205.             return false;    
  206.         }    
  207.         return true;    
  208.             
  209.     }    
  210.     /*   
  211.      * 获取get方法字符串*/    
  212.     private StringBuffer getGetMethodString(String name, String type) {    
  213.         if(!check(name,type)) {    
  214.             System.out.println("类中有属性或者类型为空");    
  215.             return null;    
  216.         };    
  217.         String Methodname = "get"+GetTuoFeng(name);    
  218.         String format = String.format("    public %s %s(){\n\r", new Object[]{type,Methodname});    
  219.         format += String.format("        return this.%s;\r\n", new Object[]{name});    
  220.         format += "    }\r\n";    
  221.         return new StringBuffer(format);    
  222.     }    
  223.     //将名称首字符大写    
  224.     private String GetTuoFeng(String name) {    
  225.         name = name.trim();    
  226.         if(name.length() > 1){    
  227.             name = name.substring(0, 1).toUpperCase()+name.substring(1);    
  228.         }else    
  229.         {    
  230.             name = name.toUpperCase();    
  231.         }    
  232.         return name;    
  233.     }    
  234.     /*   
  235.      * 获取字段的get方法字符串*/    
  236.     private Object getSetMethodString(String name, String type) {    
  237.         if(!check(name,type)) {    
  238.             System.out.println("类中有属性或者类型为空");    
  239.             return null;    
  240.         };    
  241.         String Methodname = "set"+GetTuoFeng(name);    
  242.         String format = String.format("    public void %s(%s %s){\n\r", new Object[]{Methodname,type,name});    
  243.         format += String.format("        this.%s = %s;\r\n", new Object[]{name,name});    
  244.         format += "    }\r\n";    
  245.         return new StringBuffer(format);    
  246.     }    
  247.     
  248.     public static void main(String[] args) {    
  249.         ReflectBean bean = new ReflectBean();    
  250.         System.err.println(bean.getClassStr());    
  251.     }    
  252.         
  253. }    

生成mapper.xml的工具类

[html]  view plain  copy
  1. import java.util.Date;  
  2. import java.util.HashMap;  
  3. import java.util.List;  
  4. import java.util.Map;  
  5.   
  6. import com.mengwx.entiy.Student;  
  7. import com.mengwx.util.Freemarker;  
  8. import com.mengwx.util.ReflectBean;  
  9.   
  10.   
  11. public class CreateCodeController{  
  12.       
  13.     /**  
  14.      * 生成代码  
  15.      */  
  16.     public static void proCode(Object object,String table) throws Exception{  
  17.         String objectName = object.getClass().getSimpleName();  
  18.         String pack = object.getClass().getName();  
  19.         ReflectBean re = new ReflectBean();  
  20.         re.setTable(table);  
  21.         List<String> list = re.doAction();  
  22.         Map<String,Object> root = new HashMap<String,Object>();  
  23.         String id = "";  
  24.         if(list.size()>=1){//创建数据模型  
  25.          id = list.get(list.size()-1);  
  26.         }  
  27.         root.put("packageName", objectName);  
  28.         root.put("pack", pack); //包名  
  29.         root.put("objectName", objectName);                         //类名  
  30.         root.put("objectNameLower", objectName.toLowerCase());      //类名(全小写)  
  31.         root.put("objectNameUpper", objectName.toUpperCase());      //类名(全大写)                             
  32.         root.put("nowDate", new Date());                            //当前日期  
  33.         root.put("table", table);  
  34.         root.put("id", list.get(list.size()-1));  
  35.         list.remove(list.size()-1);  
  36.         list.remove(id);  
  37.         root.put("fieldList", list);  
  38.         String filePath = "C:/Users/huxf/workspace/createcode/src/com/mengwx/code/";    //存放路径  
  39.         String ftlPath = "C:/Users/huxf/workspace/createcode/src/com/mengwx/ftl";       //ftl路径  
  40.           
  41.           
  42.         /*生成mybatis xml*/  
  43.         Freemarker.printFile("mapperMysqlTemplate.ftl", root, ""+Student.class.getSimpleName()+"Mapper.xml", filePath, ftlPath);  
  44.           
  45.           
  46.     }  
  47.       
  48.     public static void main(String[] args) throws Exception {  
  49.           
  50.         proCode(new Student(),"student");  
  51.     }  
  52.       
  53. }  

生成的mapper.xml文件

[html]  view plain  copy
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">  
  3. <mapper namespace="StudentMapper">  
  4.       
  5.       
  6.     <!-- 新增-->  
  7.     <insert id="save" parameterType="com.mengwx.entiy.Student">  
  8.         insert into student(  
  9.             name,  
  10.             id  
  11.         ) values (  
  12.             #{name},      
  13.             #{id}  
  14.         )  
  15.     </insert>  
  16.   
  17.   
  18. <!-- 删除-->  
  19.     <delete id="delete" parameterType="com.mengwx.entiy.Student">  
  20.         delete from student  
  21.         where   
  22.             id = #{id}  
  23.     </delete>  
  24.       
  25.       
  26.     <!-- 修改 -->  
  27.      <update id="edit" parameterType="com.mengwx.entiy.Student">  
  28.         update  student  
  29.             set   
  30.                 name = #{name},  
  31.             where   
  32.                 id = #{id}  
  33.     </update>  
  34.       
  35.       
  36.     <!-- 通过ID获取数据 -->  
  37.     <select id="findById" parameterType="java.lang.String" resultType="com.mengwx.entiy.Student">  
  38.         select   
  39.             name,     
  40.             id  
  41.         from   
  42.             student  
  43.         where   
  44.             id = #{id}  
  45.     </select>  
  46.       
  47.       
  48.       
  49.     <!-- 列表(全部) -->  
  50.     <select id="listAll"  resultType="com.mengwx.entiy.Student">  
  51.         select  
  52.                 a.name,   
  53.                 a.id  
  54.         from   
  55.                 student a  
  56.     </select>  
  57.           
  58.       
  59.       
  60.       
  61. </mapper>  

项目目录结构  StudentMapper.xml是生成的文件


猜你喜欢

转载自blog.csdn.net/u013278314/article/details/80360703