使用MyBatis-generator 自动生成MyBatis代码

news/2024/7/24 8:08:55 标签: java, 数据库, runtime

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

参考:

http://blog.csdn.net/sunny243788557/article/details/45166397

http://blog.csdn.net/you23hai45/article/details/50792392

编译命令:mvn mybatis-generator:generate

http://blog.csdn.net/zhshulin/article/details/23912615

一、pom的build中增加plugin

<!--mybatis根据表结构自动生成配置文件及代码-->
<plugin>
    <groupId>org.mybatis.generator</groupId>
    <artifactId>mybatis-generator-maven-plugin</artifactId>
    <version>1.3.2</version>
    <configuration>
        <configurationFile>src/main/resources/generatorConfig.xml</configurationFile>
        <verbose>true</verbose>
        <overwrite>true</overwrite>
    </configuration>
    <executions>
        <execution>
            <id>generate</id>
            <goals>
                <goal>generate</goal>
            </goals>
        </execution>
    </executions>
    <dependencies>
        <dependency>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-core</artifactId>
            <version>1.3.2</version>
        </dependency>
    </dependencies>
</plugin>

 

二、新增src/main/resources/generatorConfig.xml文件,作为mybatis-generator生成代码的配置文件

文件内容如下。注意: 将一些配置写入其他配置文件,更灵活。

文件目录在src\main\resources\jdbc\jdbc4mysql.properties

数据库驱动jar包放在src\main\resources\mysql-connector-java-5.1.35.jar

<!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="jdbc/jdbc4mysql.properties"></properties>

    <!--指定特定数据库的jdbc驱动jar包的位置 -->
    <classPathEntry location="${jdbc.driverLocation}"/>

    <context id="default" targetRuntime="MyBatis3">


        <!-- optional,旨在创建class时,对注释进行控制 -->
        <commentGenerator>
            <property name="suppressDate" value="true" />
        </commentGenerator>


        <!--jdbc的数据库连接
         driverClass jar包放在src/main/resources/mysql-connector-java-5.1.35.jar
         -->
        <jdbcConnection driverClass="${driver}" connectionURL="${url}" userId="${username}" password="${password}">
        </jdbcConnection>



        <!-- 非必需,类型处理器,在数据库类型和java类型之间的转换控制-->
        <javaTypeResolver >
            <property name="forceBigDecimals" value="false" />
        </javaTypeResolver>

        <!-- Model模型生成器,用来生成含有主键key的类,记录类 以及查询Example类
            targetPackage     指定生成的model生成所在的包名
            targetProject     指定在该项目下所在的路径
        -->
        <javaModelGenerator targetPackage="${poTargetPackage}" targetProject="src/main/java">
            <!-- 是否对model添加 构造函数 -->
            <property name="constructorBased" value="true"/>

            <!-- 是否允许子包,即targetPackage.schemaName.tableName -->
            <property name="enableSubPackages" value="true"/>

            <!-- 建立的Model对象是否 不可改变  即生成的Model对象不会有 setter方法,只有构造方法 -->
            <property name="immutable" value="true"/>

            <!-- 给Model添加一个父类 -->
<!--
            <property name="rootClass" value="com.foo.louis.Hello"/>
-->

            <!-- 是否对类CHAR类型的列的数据进行trim操作 -->
            <property name="trimStrings" value="true"/>
        </javaModelGenerator>

        <!--Mapper映射文件生成所在的目录 为每一个数据库的表生成对应的SqlMap文件 -->
        <sqlMapGenerator targetPackage="${sqlMapperTargetPackage}" targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
        </sqlMapGenerator>


        <!-- 客户端代码,生成易于使用的针对Model对象和XML配置文件 的代码
                type="ANNOTATEDMAPPER",生成Java Model 和基于注解的Mapper对象
                type="MIXEDMAPPER",生成基于注解的Java Model 和相应的Mapper对象
                type="XMLMAPPER",生成SQLMap XML文件和独立的Mapper接口
        -->
        <javaClientGenerator targetPackage="${daoTargetPackage}" targetProject="src/main/java" type="MIXEDMAPPER">
            <property name="enableSubPackages" value=""/>
            <!--
                    定义Maper.java 源代码中的ByExample() 方法的可视性,可选的值有:
                    public;
                    private;
                    protected;
                    default
                    注意:如果 targetRuntime="MyBatis3",此参数被忽略
             -->
            <property name="exampleMethodVisibility" value=""/>
            <!--
                                           方法名计数器
              Important note: this property is ignored if the target runtime is MyBatis3.
             -->
            <property name="methodNameCalculator" value=""/>

            <!--
                                                为生成的接口添加父接口
             -->
            <property name="rootInterface" value=""/>

        </javaClientGenerator>

        <!-- 要生成的表 tableName是数据库中的表名或视图名 domainObjectName是实体类名-->
        <table tableName="user_t" domainObjectName="User" enableCountByExample="false"
               enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false"
               selectByExampleQueryId="false"/>


        <!--<table tableName="user_t" schema="louis">

            &lt;!&ndash; optional   , only for mybatis3 runtime
                 自动生成的键值(identity,或者序列值)
               如果指定此元素,MBG将会生成<selectKey>元素,然后将此元素插入到SQL Map的<insert> 元素之中
               sqlStatement 的语句将会返回新的值
               如果是一个自增主键的话,你可以使用预定义的语句,或者添加自定义的SQL语句. 预定义的值如下:
                  Cloudscape   This will translate to: VALUES IDENTITY_VAL_LOCAL()
                  DB2:        VALUES IDENTITY_VAL_LOCAL()
                  DB2_MF:     SELECT IDENTITY_VAL_LOCAL() FROM SYSIBM.SYSDUMMY1
                  Derby:      VALUES IDENTITY_VAL_LOCAL()
                  HSQLDB:  CALL IDENTITY()
                  Informix:    select dbinfo('sqlca.sqlerrd1') from systables where tabid=1
                  MySql:      SELECT LAST_INSERT_ID()
                  SqlServer:   SELECT SCOPE_IDENTITY()
                  SYBASE:  SELECT @@IDENTITY
                  JDBC:       This will configure MBG to generate code for MyBatis3 suport of JDBC standard generated keys. This is a database independent method of obtaining the value from identity columns.
                  identity: 自增主键  If true, then the column is flagged as an identity column and the generated <selectKey> element will be placed after the insert (for an identity column). If false, then the generated <selectKey> will be placed before the insert (typically for a sequence).

            &ndash;&gt;
            <generatedKey column="" sqlStatement="" identity="" type=""/>


            &lt;!&ndash; optional.
                    列的命名规则:
                    MBG使用 <columnRenamingRule> 元素在计算列名的对应 名称之前,先对列名进行重命名,
                    作用:一般需要对BUSI_CLIENT_NO 前的BUSI_进行过滤
                    支持正在表达式
                     searchString 表示要被换掉的字符串
                     replaceString 则是要换成的字符串,默认情况下为空字符串,可选
            &ndash;&gt;
            <columnRenamingRule searchString="" replaceString=""/>



            &lt;!&ndash; optional.告诉 MBG 忽略某一列
                    column,需要忽略的列
                    delimitedColumnName:true ,匹配column的值和数据库列的名称 大小写完全匹配,false 忽略大小写匹配
                    是否限定表的列名,即固定表列在Model中的名称
            &ndash;&gt;
            <ignoreColumn column="PLAN_ID"  delimitedColumnName="true" />


            &lt;!&ndash;optional.覆盖MBG对Model 的生成规则
                 column: 数据库的列名
                 javaType: 对应的Java数据类型的完全限定名
                 在必要的时候可以覆盖由JavaTypeResolver计算得到的java数据类型. For some databases, this is necessary to handle "odd" database types (e.g. MySql's unsigned bigint type should be mapped to java.lang.Object).
                 jdbcType:该列的JDBC数据类型(INTEGER, DECIMAL, NUMERIC, VARCHAR, etc.),该列可以覆盖由JavaTypeResolver计算得到的Jdbc类型,对某些数据库而言,对于处理特定的JDBC 驱动癖好 很有必要(e.g. DB2's LONGVARCHAR type should be mapped to VARCHAR for iBATIS).
                 typeHandler:

            &ndash;&gt;
            <columnOverride column="" javaType=""  jdbcType=""    typeHandler="" delimitedColumnName="" />

        </table>-->
    </context>
</generatorConfiguration>

 

三、新增src\main\resources\jdbc\jdbc4mysql.properties

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/springbase
username=root
password=88480288
#定义初始连接数
initialSize=0
#定义最大连接数
maxActive=20
#定义最大空闲
maxIdle=20
#定义最小空闲
minIdle=1
#定义最长等待时间
maxWait=60000
#properties below for mybatis generator
#jar location of jdbc
jdbc.driverLocation=src/main/resources/mysql-connector-java-5.1.35.jar
#pojo code generated targetPackage
poTargetPackage=com.future.dao.po
#sql mapper target package
sqlMapperTargetPackage=com.future.dao.sqlmap
#dao code target package
daoTargetPackage=com.future.dao.idao

 

四、编译工程

使用mvn mybatis-generator:generate -e编译,将自动生成相关代码及映射文件。

 

转载于:https://my.oschina.net/legend1989/blog/830798


http://www.niftyadmin.cn/n/1778597.html

相关文章

微信模板消息的发送动态封装(Java完美封装)

文章目录前提&#xff1a;官方地址模板消息文档地址测试号正式开发1、导入maven依赖实体类代码&#xff1a;&#x1f447;&#x1f447;RemarkMiniprogram //小程序相关数据&#xff0c;无小程序可以不填&#xff0c;或者填充空串Keyword&#xff0c;中间keyword部分First 首个…

Product Key Explorer(程序密钥显示工具) v3.9.1官方版

2019独角兽企业重金招聘Python工程师标准>>> 【Product Key Explorer(程序密钥显示工具)概括介绍】 Product Key Explorer是一款程序密钥显示工具。 【Product Key Explorer(程序密钥显示工具)基本介绍】 Product Key Explorer是一款程序密钥显示工具&#xff0c;可…

回文质数 USACO

时间限制: 1 s 空间限制: 128000 KB 题目等级 : 黄金 Gold题目描述 Description因为 151 既是一个质数又是一个回文数(从左到右和从右到左是看一样的),所以 151 是回文质数.写一个程序来找出范围[a,b](5<a<b<100,000,000)间的所有回文质数; 因为 151 既是一个质数又是…

java操作文件压缩ZipUtils工具类,(支持多种方式压缩)

/*** author xu* Description* createTime 2021年04月20日 08:40:00*/ public class ZipUtils {private static final int BUFFER_SIZE 2 * 1024;/*** 压缩成ZIP 方法1* param srcDir 压缩文件夹路径* param zipFilePathName 压缩文件输出地址与名字* param KeepDirStruct…

OSChina 初九乱弹 ——我住隔壁我姓王,你有困难我帮忙。

2019独角兽企业重金招聘Python工程师标准>>> 【今日歌曲】 挖红薯 &#xff1a; 分享莫文蔚的单曲《We Dont Talk Anymore (原唱&#xff1a;Charlie Puth)》 《We Dont Talk Anymore (原唱&#xff1a;Charlie Puth)》- 莫文蔚 手机党少年们想听歌&#xff0c;请使…

MD5加密工具类MD5

传入字符串可直接返回加密结果 package com.mosukj.util;import java.security.MessageDigest; import java.security.NoSuchAlgorithmException;public class MD5 {private final static String[] hexDigits {"0","1","2","3",&quo…

MongoDB 安装以及系统服务配置方法

为什么80%的码农都做不了架构师&#xff1f;>>> **一、下载 MongoDB ** 1、在官网下载mongoDB&#xff1a;https://www.mongodb.com/download-center 二、安装 MongoDB 1、将zip文件解压放到盘符的根目录&#xff08;如C&#xff1a;或D&#xff1a;&#xff09; 2…

使用zxing.jar在线生成二维码。返回base64字符串

文章目录导入Zxing依赖Gradle生成二维码工具类加强工具类&#xff0c;支持返回base64&#xff0c;生成的二维码附带图片导入Zxing依赖 Gradle // https://mvnrepository.com/artifact/com.google.zxing/core googleimplementation group: com.google.zxing, name: core, versi…