1. 程式人生 > >eclipse mybatis 快速生成工具

eclipse mybatis 快速生成工具

1、首先,得先看看eclipse有沒安裝mybatis generator外掛,如果有的話,請忽略這一步

   eclipse線上安裝mybatis generator

    1、開啟eclipse,找到help->Eclispe Mapketplace

    2、在搜尋框輸入mybatis generator,然後點選go

    3、找到mybatis generator對應的版本,下載後然後重啟eclipse即可

2、

  1.配置檔案

  jdbc.driverLocation=D:/repository/mysql/mysql-connector-java/5.1.47/mysql-connector-java-5.1.47.jar
  jdbc.driverClass
=com.mysql.jdbc.Driver   jdbc.connectionURL=jdbc:mysql://xxxxxx:3306/smarthome?useUnicode=true&characterEncoding=utf-8   jdbc.userId=lsc   jdbc.password=lsc

 

   2.xml

  <?xml version="1.0" encoding="UTF-8"?>
  <!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">


  <generatorConfiguration>
  <!--匯入屬性配置 -->

  <properties resource="generator.properties"></properties>
  <!--指定特定資料庫的jdbc驅動jar包的位置 -->
  <classPathEntry location="${jdbc.driverLocation}" />
  <context id="default" targetRuntime="MyBatis3">
  <property name="javaFileEncoding" value="UTF-8" />
  <!-- 這裡的type裡寫的是你的實現類的類全類名,注:如果不配置type屬性,則會使用預設的CommentGenerator實現類DefaultCommentGenerator -->
  <commentGenerator type="com.tkgm.api.common.utils.MyCommentGenerator">
  <!-- 去除自動生成的註釋 -->
  <!-- <property name="suppressAllComments" value="true" /> -->

  <!-- 是否生成註釋代時間戳 -->
  <property name="suppressDate" value="true" />
  </commentGenerator>

  <!--jdbc的資料庫連線 -->
  <jdbcConnection driverClass="${jdbc.driverClass}"
  connectionURL
="${jdbc.connectionURL}" userId="${jdbc.userId}"   password="${jdbc.password}">   </jdbcConnection>   <!-- 型別轉換 -->   <javaTypeResolver>   <!-- 是否使用bigDecimal, false可自動轉化以下型別(Long, Integer, Short, etc.) -->   <property name="forceBigDecimals" value="false" />   </javaTypeResolver>   <!-- 生成實體類地址 -->   <javaModelGenerator targetPackage="com.tkgm.api.mapper.po"   targetProject
="smarthome-app/src/main/java">   <!-- 是否允許子包,即targetPackage.schemaName.tableName -->   <property name="enableSubPackages" value="false" />   <!-- 是否對model新增 建構函式 -->   <property name="constructorBased" value="false" />   <!-- 是否對類CHAR型別的列的資料進行trim操作 -->   <property name="trimStrings" value="user" />   <!-- 建立的Model物件是否 不可改變 即生成的Model物件不會有 setter方法,只有構造方法 -->   <property name="immutable" value="false" />   </javaModelGenerator>   <!-- 生成mapxml檔案 -->   <sqlMapGenerator targetPackage="mapper"   targetProject="smarthome-app/src/main/resources">   <property name="enableSubPackages" value="false" />   </sqlMapGenerator>   <!-- 生成mapxml對應client,也就是介面dao -->   <javaClientGenerator targetPackage="com.tkgm.api.mapper"   targetProject="smarthome-app/src/main/java" type="XMLMAPPER">   <property name="enableSubPackages" value="true" />   </javaClientGenerator>   <!-- 配置表資訊 -->   <table tableName="t_area" domainObjectName="Area"   enableCountByExample="false" enableUpdateByExample="false"   enableDeleteByExample="false" enableSelectByExample="false"   selectByExampleQueryId="false">   <!-- 忽略列,不生成bean 欄位 -->   <!-- <ignoreColumn column="FRED" /> -->   <!-- 指定列的java資料型別 -->   <!-- <columnOverride column="LONG_VARCHAR_FIELD" jdbcType="VARCHAR" /> -->   </table>   </context>   </generatorConfiguration>

 

  3.對映資料庫中文註釋

package com.tkgm.api.common.utils;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
import java.util.Set;

import org.mybatis.generator.api.CommentGenerator;
import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.dom.java.CompilationUnit;
import org.mybatis.generator.api.dom.java.Field;
import org.mybatis.generator.api.dom.java.FullyQualifiedJavaType;
import org.mybatis.generator.api.dom.java.InnerClass;
import org.mybatis.generator.api.dom.java.InnerEnum;
import org.mybatis.generator.api.dom.java.JavaElement;
import org.mybatis.generator.api.dom.java.Method;
import org.mybatis.generator.api.dom.java.Parameter;
import org.mybatis.generator.api.dom.java.TopLevelClass;
import org.mybatis.generator.api.dom.xml.XmlElement;
import org.mybatis.generator.config.MergeConstants;
import org.mybatis.generator.config.PropertyRegistry;

/**
 * 自定義實現 註釋生成器 CommentGenerator 介面
 * @author 北北
 * @date 2018年1月17日上午10:22:11
 */
public class MyCommentGenerator implements CommentGenerator {

    private Properties properties;
    private Properties systemPro;
    private boolean suppressDate;
    private boolean suppressAllComments;
    private String nowTime;

    public MyCommentGenerator() {
        super();
        properties = new Properties();
        systemPro = System.getProperties();
        suppressDate = false;
        suppressAllComments = false;
        nowTime = (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(new Date());
    }

    public void addJavaFileComment(CompilationUnit compilationUnit) {
        if (suppressAllComments) {
            return;
        }
        return;
    }

    /**
     * Adds a suitable comment to warn users that the element was generated, and
     * when it was generated.
     */
    public void addComment(XmlElement xmlElement) {
        return;
    }

    public void addRootComment(XmlElement rootElement) {
        // add no document level comments by default
        return;
    }

    public void addConfigurationProperties(Properties properties) {
        this.properties.putAll(properties);
        suppressDate = isTrue(properties.getProperty(PropertyRegistry.COMMENT_GENERATOR_SUPPRESS_DATE));
        suppressAllComments = isTrue(properties.getProperty(PropertyRegistry.COMMENT_GENERATOR_SUPPRESS_ALL_COMMENTS));
    }
    
    /**
     * 判斷傳入引數是否為true
     * @author 北北
     * @date 2018年2月2日下午3:55:06
     * @param property
     * @return
     */
    private boolean isTrue(String property) {
        if("true".equals(property)){
            return true;
        }
        return false;
    }

    /**
     * This method adds the custom javadoc tag for. You may do nothing if you do
     * not wish to include the Javadoc tag - however, if you do not include the
     * Javadoc tag then the Java merge capability of the eclipse plugin will
     * break.
     * 
     * @param javaElement
     *            the java element
     */
    protected void addJavadocTag(JavaElement javaElement, boolean markAsDoNotDelete) {
        javaElement.addJavaDocLine(" *");
        StringBuilder sb = new StringBuilder();
        sb.append(" * ");
        sb.append(MergeConstants.NEW_ELEMENT_TAG);
        if (markAsDoNotDelete) {
            sb.append(" do_not_delete_during_merge");
        }
        String s = getDateString();
        if (s != null) {
            sb.append(' ');
            sb.append(s);
        }
        javaElement.addJavaDocLine(sb.toString());
    }

    /**
     * This method returns a formated date string to include in the Javadoc tag
     * and XML comments. You may return null if you do not want the date in
     * these documentation elements.
     * 
     * @return a string representing the current timestamp, or null
     */
    protected String getDateString() {
        String result = null;
        if (!suppressDate) {
            result = nowTime;
        }
        return result;
    }

    public void addClassComment(InnerClass innerClass, IntrospectedTable introspectedTable) {
        if (suppressAllComments) {
            return;
        }
        StringBuilder sb = new StringBuilder();
        innerClass.addJavaDocLine("/**");
        sb.append(" * ");
        sb.append(introspectedTable.getFullyQualifiedTable());
        sb.append(" ");
        sb.append(getDateString());
        innerClass.addJavaDocLine(sb.toString().replace("\n", " "));
        innerClass.addJavaDocLine(" */");
    }

    public void addEnumComment(InnerEnum innerEnum, IntrospectedTable introspectedTable) {
        if (suppressAllComments) {
            return;
        }
        StringBuilder sb = new StringBuilder();
        innerEnum.addJavaDocLine("/**");
        sb.append(" * ");
        sb.append(introspectedTable.getFullyQualifiedTable());
        innerEnum.addJavaDocLine(sb.toString().replace("\n", " "));
        innerEnum.addJavaDocLine(" */");
    }
    
    /**
     * 設定欄位註釋
     */
    public void addFieldComment(Field field, IntrospectedTable introspectedTable, IntrospectedColumn introspectedColumn) {
        if (suppressAllComments) {
            return;
        }
        StringBuilder sb = new StringBuilder();
        field.addJavaDocLine("/**");
        sb.append(" * ");
        sb.append(introspectedColumn.getRemarks() + " " + introspectedColumn.getActualColumnName());
        field.addJavaDocLine(sb.toString().replace("\n", " "));
        field.addJavaDocLine(" */");
    }

    public void addFieldComment(Field field, IntrospectedTable introspectedTable) {
        if (suppressAllComments) {
            return;
        }
        StringBuilder sb = new StringBuilder();
        field.addJavaDocLine("/**");
        sb.append(" * ");
        sb.append(introspectedTable.getFullyQualifiedTable());
        field.addJavaDocLine(sb.toString().replace("\n", " "));
        field.addJavaDocLine(" */");
    }

    public void addGeneralMethodComment(Method method, IntrospectedTable introspectedTable) {
        if (suppressAllComments) {
            return;
        }
      method.addJavaDocLine("/**");
      addJavadocTag(method, false);
      method.addJavaDocLine(" */");
    }
    
    /**
     * 設定getter方法註釋
     */
    public void addGetterComment(Method method, IntrospectedTable introspectedTable,
            IntrospectedColumn introspectedColumn) {
        if (suppressAllComments) {
            return;
        }
        method.addJavaDocLine("/**");
        StringBuilder sb = new StringBuilder();
        sb.append(" * ");
        sb.append(introspectedColumn.getRemarks());
        method.addJavaDocLine(sb.toString().replace("\n", " "));
        sb.setLength(0);
        
        //加入系統使用者
        sb.append(" * @author ");
        sb.append(systemPro.getProperty("user.name"));
        method.addJavaDocLine(sb.toString().replace("\n", " "));
        sb.setLength(0);
        
        //是否加入時間戳
        if(suppressDate){
            sb.append(" * @date " + nowTime);
            method.addJavaDocLine(sb.toString().replace("\n", " "));
            sb.setLength(0);
        }
        
        sb.append(" * @return ");
        sb.append(introspectedColumn.getActualColumnName());
        sb.append(" ");
        sb.append(introspectedColumn.getRemarks());
        method.addJavaDocLine(sb.toString().replace("\n", " "));
        method.addJavaDocLine(" */");
    }
    
    /**
     * 設定setter方法註釋
     */
    public void addSetterComment(Method method, IntrospectedTable introspectedTable,
            IntrospectedColumn introspectedColumn) {
        if (suppressAllComments) {
            return;
        }
        method.addJavaDocLine("/**");
        StringBuilder sb = new StringBuilder();
        sb.append(" * ");
        sb.append(introspectedColumn.getRemarks());
        method.addJavaDocLine(sb.toString().replace("\n", " "));
        sb.setLength(0);
        
        //加入系統使用者
        sb.append(" * @author ");
        sb.append(systemPro.getProperty("user.name"));
        method.addJavaDocLine(sb.toString().replace("\n", " "));
        sb.setLength(0);
        
        //是否加入時間戳
        if(suppressDate){
            sb.append(" * @date " + nowTime);
            method.addJavaDocLine(sb.toString().replace("\n", " "));
            sb.setLength(0);
        }
        
        Parameter parm = method.getParameters().get(0);
        sb.append(" * @param ");
        sb.append(parm.getName());
        sb.append(" ");
        sb.append(introspectedColumn.getRemarks());
        method.addJavaDocLine(sb.toString().replace("\n", " "));
        method.addJavaDocLine(" */");
    }

    public void addClassComment(InnerClass innerClass, IntrospectedTable introspectedTable, boolean markAsDoNotDelete) {
        if (suppressAllComments) {
            return;
        }
        StringBuilder sb = new StringBuilder();
        innerClass.addJavaDocLine("/**");
        sb.append(" * ");
        sb.append(introspectedTable.getFullyQualifiedTable());
        innerClass.addJavaDocLine(sb.toString().replace("\n", " "));
        sb.setLength(0);
        sb.append(" * @author ");
        sb.append(systemPro.getProperty("user.name"));
        sb.append(" ");
        sb.append(nowTime);
        innerClass.addJavaDocLine(" */");
    }

    @Override
    public void addModelClassComment(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
        // TODO Auto-generated method stub
        
    }

    @Override
    public void addGeneralMethodAnnotation(Method method, IntrospectedTable introspectedTable,
            Set<FullyQualifiedJavaType> imports) {
        // TODO Auto-generated method stub
        
    }

    @Override
    public void addGeneralMethodAnnotation(Method method, IntrospectedTable introspectedTable,
            IntrospectedColumn introspectedColumn, Set<FullyQualifiedJavaType> imports) {
        // TODO Auto-generated method stub
        
    }

    @Override
    public void addFieldAnnotation(Field field, IntrospectedTable introspectedTable,
            Set<FullyQualifiedJavaType> imports) {
        // TODO Auto-generated method stub
        
    }

    @Override
    public void addFieldAnnotation(Field field, IntrospectedTable introspectedTable,
            IntrospectedColumn introspectedColumn, Set<FullyQualifiedJavaType> imports) {
        // TODO Auto-generated method stub
        
    }

    @Override
    public void addClassAnnotation(InnerClass innerClass, IntrospectedTable introspectedTable,
            Set<FullyQualifiedJavaType> imports) {
        // TODO Auto-generated method stub
        
    }
    
}