zoukankan      html  css  js  c++  java
  • Mybatis-Generator自动生成Dao、Model、Mapping等相关映射文件(懒人版)

    今天在学习mybatis生成相关的映射文件的时候,发现了往期的生成Dao、Model、Mapping等文章多数都是一样的,我也在学着重复造轮子,不过是懒人造的。本文旨在解决开发过程,简化配置文件的“手写”。

    废话不多说,show me the code!

      步骤一:新建普通maven工程,pom.xml文件配置如下:

     1 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     2     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
     3     <modelVersion>4.0.0</modelVersion>
     4     <groupId>com.generator</groupId>
     5     <artifactId>mybatis-gererator</artifactId>
     6     <version>0.0.1-SNAPSHOT</version>
     7 
     8     <properties>
     9         <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    10     </properties>
    11     <dependencies>
    12         <!-- Mysql -->
    13         <dependency>
    14             <groupId>org.mybatis</groupId>
    15             <artifactId>mybatis</artifactId>
    16             <version>3.2.7</version>
    17         </dependency>
    18         <!-- Mysql 依赖 -->
    19         <dependency>
    20             <groupId>mysql</groupId>
    21             <artifactId>mysql-connector-java</artifactId>
    22             <version>5.1.6</version>
    23         </dependency>
    24         <!--生成代码插件 -->
    25         <dependency>
    26             <groupId>org.mybatis.generator</groupId>
    27             <artifactId>mybatis-generator-core</artifactId>
    28             <version>1.3.2</version>
    29             <type>jar</type>
    30         </dependency>
    31     </dependencies>
    32     <build>
    33         <plugins>
    34             <plugin>
    35                 <artifactId>maven-war-plugin</artifactId>
    36             </plugin>
    37             <plugin>
    38                 <artifactId>maven-compiler-plugin</artifactId>
    39                 <configuration>
    40                     <source>1.6</source>
    41                     <target>1.6</target>
    42                 </configuration>
    43             </plugin>
    44         </plugins>
    45     </build>
    46 </project>

      步骤二:添加generatorConfig.xml(27行--31行可以不用急着写,请看步骤三

     1 <?xml version="1.0" encoding="UTF-8" ?> 
     2 <!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" 
     3 "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd" >
     4 <generatorConfiguration>
     5  <context id="prod">
     6   <!-- RowBounds pagination -->
     7   <plugin type="org.mybatis.generator.plugins.RowBoundsPlugin" />
     8   <plugin type="org.mybatis.generator.plugins.CaseInsensitiveLikePlugin" />
     9   <plugin type="org.mybatis.generator.plugins.SerializablePlugin" />
    10 
    11   <commentGenerator>
    12    <property name="suppressDate" value="true" />
    13    <property name="suppressAllComments" value="true" />
    14   </commentGenerator>
    15 
    16   <!-- jdbc连接 -->
    17   <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://127.0.0.1:3306/shopping"
    18    userId="root" password="1234" />
    19 
    20   <javaModelGenerator targetPackage="com.shopping.entity" targetProject="src/main/java">
    21    <!-- 是否针对string类型的字段在set的时候进行trim调用 -->
    22    <property name="trimStrings" value="true" />
    23   </javaModelGenerator>
    24   <sqlMapGenerator targetPackage="mappers" targetProject="src/main/java" />
    25   <javaClientGenerator targetPackage="com.shopping.mapper" targetProject="src/main/java" type="XMLMAPPER" />
    26 
    27   <table tableName="tb_address" domainObjectName="tbAddress"></table>
    28   <table tableName="tb_areas" domainObjectName="tbAreas"></table>
    29   <table tableName="tb_brand" domainObjectName="tbBrand"></table>
    30   <table tableName="tb_cities" domainObjectName="tbCities"></table>
    31   <table tableName="tb_user" domainObjectName="tbUser"></table>
    32 
    33  </context>
    34 </generatorConfiguration>

       步骤三:生成表的名字与别名的映射字符串

    修改jdbc的相关配置参数,运行main方法,可以在控制台输出所有的表名与驼峰命名的表名映射关系xml对,然后从控制台中复制了贴回步骤二中的generatorConfig.xml,替换原有的27~31行。添加此步骤的目的在于表名过多的时候,优势就出来了。需要修改的地方也给大家标记出来了,怎么样,全程都在偷懒~

     1 package com.mybatis;
     2 
     3 import java.sql.Connection;
     4 import java.sql.DriverManager;
     5 import java.sql.ResultSet;
     6 import java.sql.SQLException;
     7 import java.sql.Statement;
     8 
     9 import org.mybatis.generator.api.ShellRunner;
    10 
    11 public class SqlMaperCreater {
    12 
    13     public static void main(String[] args) throws ClassNotFoundException, SQLException {
    14 
    15         // 生成表的名与别名对应xml
    16         createTableMapping();
    17 
    18         //生成dao mapper entity对应文件
    19         //args = new String[] { "-configfile", "src\main\resources\gereratorConfig.xml", "-overwrite" };
    20         //ShellRunner.main(args);
    21     }
    22 
    23     public static void createTableMapping() throws ClassNotFoundException, SQLException {
    24         String URL = "jdbc:mysql://127.0.0.1:3306/shopping?useUnicode=true&amp;characterEncoding=utf-8";
    25         String USER = "root";
    26         String PASSWORD = "1234";
    27         // 1.加载驱动程序
    28         Class.forName("com.mysql.jdbc.Driver");
    29         // 2.获得数据库链接
    30         Connection conn = DriverManager.getConnection(URL, USER, PASSWORD);
    31         // 3.通过数据库的连接操作数据库,实现增删改查(使用Statement类)
    32         Statement st = conn.createStatement();
    33         ResultSet rs = st.executeQuery("select table_name from information_schema.tables where table_schema='shopping';");
    34         // 4.处理数据库的返回结果(使用ResultSet类)
    35         while (rs.next()) {
    36             String tableName = rs.getString("table_name");
    37             String xml = fotmatTableName2Xml(tableName);
    38             System.out.println(xml);
    39         }
    40 
    41         // 关闭资源
    42         rs.close();
    43         st.close();
    44         conn.close();
    45     }
    46 
    47     /**
    48      * 格式化生成table名与别名的映射xml
    49      * @param tableName
    50      * @return
    51      */
    52     private static String fotmatTableName2Xml(String tableName) {
    53         StringBuilder tableNamefmt = formatCamelName(tableName);
    54         StringBuilder sb = new StringBuilder("<table tableName="");
    55         sb.append(tableName).append("" domainObjectName="").append(tableNamefmt).append(""></table>");
    56         return sb.toString();
    57     }
    58 
    59     /**
    60      * 将下划线大写方式命名的字符串转换为驼峰式。 例如:HELLO_WORLD->HelloWorld
    61      * @param name 转换前的下划线大写方式命名的字符串
    62      * @return 转换后的驼峰式命名的字符串StringBuilder
    63      */
    64     public static StringBuilder formatCamelName(String name) {
    65 
    66         StringBuilder result = new StringBuilder();
    67         // 非法字符串过滤
    68         if (name == null || name.isEmpty()) {
    69             return result;
    70         }
    71 
    72         // 不含下划线,仅将首字母小写
    73         if (!name.contains("_")) {
    74             return result.append(name.substring(0, 1).toLowerCase()).append(name.substring(1));
    75         }
    76 
    77         // 用下划线将原始字符串分割
    78         String camels[] = name.split("_");
    79         for (String camel : camels) {
    80             if (camel.isEmpty()) {
    81                 continue;
    82             }
    83 
    84             if (result.length() == 0) {
    85                 result.append(camel.toLowerCase());
    86                 continue;
    87             }
    88 
    89             result.append(camel.substring(0, 1).toUpperCase());
    90             result.append(camel.substring(1).toLowerCase());
    91         }
    92         return result;
    93     }
    94 
    95 }

      步骤四:生成dao,mapper和entity(或者是model)

    将步骤二中的16行注释,放开19,20行的注释,再次运行main方法,然后在项目上右键refresh,最终生成的文件结构如下图

     

    欢迎转载学习和“偷懒”、拍砖。

  • 相关阅读:
    iOS开发之--打印一堆奇怪东西的解决方案
    iOS开发之--从URL加载图片
    iOS开发之--搭建本地的SVN服务器
    HTML5
    swift
    swift
    HTML 换行
    HTML 注释
    HTML 水平线
    /etc/rc.d/rc.local
  • 原文地址:https://www.cnblogs.com/qinglangsunny/p/9276913.html
Copyright © 2011-2022 走看看