MyBatis系列 逆向工程自动生成实体类、Mapper、SQL

MyBatis 系列 逆向工程自动生成实体类,Mapper,SQL 1,项目结构 2,创建 Maven 项目 file–>new–>maven project

本文包含相关资料包-----> 点击直达获取<-------

MyBatis 系列 逆向工程自动生成实体类、Mapper、SQL

1.项目结构

2.创建 Maven 项目

file–>new–>maven project,填写自己的 Goup Id、Artifact Id

3.配置 web.xml,路径/WebRoot/WEB-INF/web.xml

```

mybatis_generator_zh

<listener>
    <listener-class>
        org.springframework.web.context.ContextLoaderListener
    </listener-class>
</listener>
<listener>
    <listener-class>
        org.springframework.web.context.request.RequestContextListener
    </listener-class>
</listener>

<filter>
    <filter-name>encodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
        <param-name>encoding</param-name>
        <param-value>utf-8</param-value>
    </init-param>
    <init-param>
        <param-name>forceEncoding</param-name>
        <param-value>true</param-value>
    </init-param>
</filter>
<filter-mapping>
    <filter-name>encodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

```

4.Maven 引入项目所需 jar 包,文件 pom.xml

``` 4.0.0 mybatis_generator_zh mybatis_generator_zh 0.0.1-SNAPSHOT UTF-8

    <!-- mysql连接 -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.34</version>
    </dependency>

    <dependency>
        <groupId>org.mybatis.generator</groupId>
        <artifactId>mybatis-generator-core</artifactId>
        <version>1.3.2</version>
    </dependency>

org.apache.maven.plugins maven-surefire-plugin true 2.18.1 ```

5.实现自定义注释,文件/src/main/java/module/MyCommentGenerator.java

``` package module; import static org.mybatis.generator.internal.util.StringUtility.isTrue; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Properties; 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.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.xml.XmlElement; import org.mybatis.generator.config.MergeConstants; import org.mybatis.generator.config.PropertyRegistry;

/ * 自定义注释 */ public class MyCommentGenerator implements CommentGenerator{

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

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

public void addJavaFileComment(CompilationUnit compilationUnit) {
    return;
}

public void addComment(XmlElement xmlElement) {
    return;
}

public void addRootComment(XmlElement rootElement) {
    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));
}

/
 * 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);
    sb.append("@ https://blog.csdn.net/caiqing116");
    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 = currentDateStr;
    }
    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());
    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(" */");
}

//get方法注释
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(" * @return ");
    sb.append(introspectedColumn.getActualColumnName());
    sb.append(" ");
    sb.append(introspectedColumn.getRemarks());
    method.addJavaDocLine(sb.toString().replace("\n", " "));
    method.addJavaDocLine(" */");
}

//set方法注释
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", " "));
    Parameter parm = method.getParameters().get(0);
    sb.setLength(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(" https://blog.csdn.net/caiqing116");
    sb.append(" ");
    sb.append(currentDateStr);
    innerClass.addJavaDocLine(" */");
}

} ```

6.配置数据源,实体类,Mapper,SQL 生成规则,文件:/generatorConfig.xml

```

<property name="javaFileEncoding" value="UTF-8"/>

<!-- 自定义注释 -->
<commentGenerator type="module.MyCommentGenerator"></commentGenerator>

<!-- 是否去除自动生成的注释 true:是 : false:否    -->
<!-- <commentGenerator>  
        <property name="suppressAllComments" value="true" />    
</commentGenerator> -->

<jdbcConnection driverClass="com.mysql.jdbc.Driver"
    connectionURL="jdbc:mysql://127.0.0.1:3306/db_ssmdemo"
    userId="root"
    password="123456">

    <property name="remarksReporting" value="true"/>
</jdbcConnection>

<javaTypeResolver >
    <property name="forceBigDecimals" value="false" />
</javaTypeResolver>

<!-- java实体类路径 -->
<javaModelGenerator targetPackage="com.ssm.entity" targetProject="D:\cqWorksapceCloud\SSM_DEMO\src\main\java" >
  <property name="enableSubPackages" value="true" />
  <property name="trimStrings" value="true" />
</javaModelGenerator>

<!-- sqlmap xml -->
<sqlMapGenerator targetPackage="sql"  targetProject="D:\cqWorksapceCloud\SSM_DEMO\src\main\resources">
  <property name="enableSubPackages" value="true" />
</sqlMapGenerator>

<!-- mapper -->
<javaClientGenerator type="XMLMAPPER" targetPackage="com.ssm.mapper"  targetProject="D:\cqWorksapceCloud\SSM_DEMO\src\main\java">
  <property name="enableSubPackages" value="true" />
</javaClientGenerator>

<!-- 要逆向生成Dao的所有表 -->
<table schema="BasicUser" tableName="tb_basic_user"  
    domainObjectName="BasicUser" enableCountByExample="false"  
    enableDeleteByExample="false" enableSelectByExample="false"  
    enableUpdateByExample="false">  
</table>

```

7.创建启动类,执行后即可自动生成实体类、Mapper、SQL,文件 src/main/java/module/StartUp.java

``` package module; import java.io.File; import java.io.IOException; import java.net.URISyntaxException; import java.sql.SQLException; import java.util.ArrayList; import java.util.List;

import org.mybatis.generator.api.MyBatisGenerator; import org.mybatis.generator.config.Configuration; import org.mybatis.generator.config.xml.ConfigurationParser; import org.mybatis.generator.exception.InvalidConfigurationException; import org.mybatis.generator.exception.XMLParserException; import org.mybatis.generator.internal.DefaultShellCallback;

public class StartUp { public static void main(String[] args) throws URISyntaxException { try {

        List<String> warnings = new ArrayList<String>();
        boolean overwrite = true;
        File configFile = new File("generatorConfig.xml");
        ConfigurationParser cp = new ConfigurationParser(warnings);
        Configuration config = cp.parseConfiguration(configFile);
        DefaultShellCallback callback = new DefaultShellCallback(overwrite);
        MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
        myBatisGenerator.generate(null);
        System.out.println("Mybatis Generator 逆向生成Dao完成");
    } catch (SQLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (InvalidConfigurationException e) {
        e.printStackTrace();
    } catch (XMLParserException e) {
        e.printStackTrace();
    }
}

} ```

参考文献

  • 基于SSM的企业网站设计与实现(黑龙江大学·张泷元)
  • 基于J2EE的远程网络教育系统研究与实现(电子科技大学·陈南荪)
  • 阿坝师院办公自动化系统设计与实现(电子科技大学·徐起超)
  • 基于SSH框架的博客用户分享平台的设计与实现(河北工业大学·刘磊)
  • B/S架构代码自动生成系统的设计与实现(河北科技大学·韩佳乐)
  • 基于改进WebML建模的网站生成系统研究(湖南大学·胡南湘)
  • 基于OAuth2.0协议的企业分布式授权系统设计与实现(华中科技大学·支猛)
  • 可选运行框架的J2EE Web应用自动生成(山东大学·段雷)
  • Java Web快速开发框架中部分关键技术初步研究(吉林大学·王循)
  • 基于OAuth2.0协议的企业分布式授权系统设计与实现(华中科技大学·支猛)
  • B/S架构代码自动生成系统的设计与实现(河北科技大学·韩佳乐)
  • 基于SSH架构的个人空间交友网站的设计与实现(北京邮电大学·隋昕航)
  • 基于J2EE的远程网络教育系统研究与实现(电子科技大学·陈南荪)
  • 基于Kettle和Weka的数据转存与挖掘平台(西南科技大学·何宇恒)
  • 人才招聘系统的设计与实现(南昌大学·周新卫)

本文内容包括但不限于文字、数据、图表及超链接等)均来源于该信息及资料的相关主题。发布者:代码港湾 ,原文地址:https://bishedaima.com/yuanma/35782.html

相关推荐

发表回复

登录后才能评论