查看原文
其他

SpringBoot使用Mybatis-Generator

大老杨。 SpringForAll社区 2020-10-17

本文介绍如何将Maven和Mybatis-Generator配合使用。

简介

Mybatis-Generator是Mybatis提供的一个便捷型插件,自动可以为项目生产对应的实体类,Mapper,dao层。

官网文档:http://www.mybatis.org/generator/index.html

入门案例

本文使用SpringBoot结合Mybatis-Generator插件使用,数据库Mysql。

新建项目

新建一个SpringBoot项目。

依赖文件

在项目pom文件中,引入Mybatis-Generator插件,并且引入Mybatis和Mysql依赖。完整pom代码如下:

  1. <?xml version="1.0" encoding="UTF-8"?>

  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

  3.         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

  4.    <modelVersion>4.0.0</modelVersion>

  5.    <groupId>com.dalaoyang</groupId>

  6.    <artifactId>springboot_generator</artifactId>

  7.    <version>0.0.1-SNAPSHOT</version>

  8.    <packaging>jar</packaging>

  9.    <name>springboot_generator</name>

  10.    <description>springboot_generator</description>

  11.    <parent>

  12.        <groupId>org.springframework.boot</groupId>

  13.        <artifactId>spring-boot-starter-parent</artifactId>

  14.        <version>1.5.15.RELEASE</version>

  15.        <relativePath/> <!-- lookup parent from repository -->

  16.    </parent>

  17.    <properties>

  18.        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

  19.        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>

  20.        <java.version>1.8</java.version>

  21.    </properties>

  22.    <dependencies>

  23.        <dependency>

  24.            <groupId>org.springframework.boot</groupId>

  25.            <artifactId>spring-boot-starter-test</artifactId>

  26.            <scope>test</scope>

  27.        </dependency>

  28.        <dependency>

  29.            <groupId>org.springframework.boot</groupId>

  30.            <artifactId>spring-boot-starter-web</artifactId>

  31.        </dependency>

  32.        <dependency>

  33.            <groupId>org.mybatis.spring.boot</groupId>

  34.            <artifactId>mybatis-spring-boot-starter</artifactId>

  35.            <version>1.3.1</version>

  36.        </dependency>

  37.        <dependency>

  38.            <groupId>org.springframework.boot</groupId>

  39.            <artifactId>spring-boot-devtools</artifactId>

  40.            <scope>runtime</scope>

  41.        </dependency>

  42.        <dependency>

  43.            <groupId>mysql</groupId>

  44.            <artifactId>mysql-connector-java</artifactId>

  45.            <scope>runtime</scope>

  46.        </dependency>

  47.    </dependencies>

  48.    <build>

  49.        <plugins>

  50.            <plugin>

  51.                <groupId>org.mybatis.generator</groupId>

  52.                <artifactId>mybatis-generator-maven-plugin</artifactId>

  53.                <version>1.3.2</version>

  54.                <executions>

  55.                    <execution>

  56.                        <id>mybatis-generator</id>

  57.                        <phase>deploy</phase>

  58.                        <goals>

  59.                            <goal>generate</goal>

  60.                        </goals>

  61.                    </execution>

  62.                </executions>

  63.                <configuration>

  64.                    <!-- Mybatis-Generator 工具配置文件的位置 -->

  65.                    <configurationFile>src/main/resources/mybatis-generator/generatorConfig.xml</configurationFile>

  66.                    <verbose>true</verbose>

  67.                    <overwrite>true</overwrite>

  68.                </configuration>

  69.                <dependencies>

  70.                    <dependency>

  71.                        <groupId>mysql</groupId>

  72.                        <artifactId>mysql-connector-java</artifactId>

  73.                        <version>5.1.46</version>

  74.                    </dependency>

  75.                    <dependency>

  76.                        <groupId>org.mybatis.generator</groupId>

  77.                        <artifactId>mybatis-generator-core</artifactId>

  78.                        <version>1.3.2</version>

  79.                    </dependency>

  80.                </dependencies>

  81.            </plugin>

  82.            <plugin>

  83.                <groupId>org.springframework.boot</groupId>

  84.                <artifactId>spring-boot-maven-plugin</artifactId>

  85.                <configuration>

  86.                    <classifier>exec</classifier>

  87.                </configuration>

  88.            </plugin>

  89.        </plugins>

  90.    </build>

  91. </project>

配置Mybatis-Generator配置

在pom文件中配置的Mybatis-Generator 工具配置文件的位置新建一个generatorConfig.xml,(本文案例配置的位置是src/main/resources/mybatis-generator/generatorConfig.xml),配置文件代码如下,具体配置需要自行修改至自己的项目:

  1. <?xml version="1.0" encoding="UTF-8"?>

  2. <!DOCTYPE generatorConfiguration

  3.        PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"

  4.        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">

  5. <!-- 配置生成器 -->

  6. <generatorConfiguration>

  7.    <!--执行generator插件生成文件的命令: call mvn mybatis-generator:generate -e -->

  8.    <!-- 引入配置文件 -->

  9.    <properties resource="application.properties"/>

  10.    <!--classPathEntry:数据库的JDBC驱动,换成你自己的驱动位置 可选 -->

  11.    <!--<classPathEntry location="D:generator_mybatismysql-connector-java-5.1.24-bin.jar" /> -->

  12.    <!-- 一个数据库一个context -->

  13.    <!--defaultModelType="flat" 大数据字段,不分表 -->

  14.    <context id="MysqlTables" targetRuntime="MyBatis3Simple" defaultModelType="flat">

  15.        <!-- 自动识别数据库关键字,默认false,如果设置为true,根据SqlReservedWords中定义的关键字列表;

  16.        一般保留默认值,遇到数据库关键字(Java关键字),使用columnOverride覆盖 -->

  17.        <property name="autoDelimitKeywords" value="true" />

  18.        <!-- 生成的Java文件的编码 -->

  19.        <property name="javaFileEncoding" value="utf-8" />

  20.        <!-- beginningDelimiter和endingDelimiter:指明数据库的用于标记数据库对象名的符号,比如ORACLE就是双引号,MYSQL默认是`反引号; -->

  21.        <property name="beginningDelimiter" value="`" />

  22.        <property name="endingDelimiter" value="`" />

  23.        <!-- 格式化java代码 -->

  24.        <property name="javaFormatter" value="org.mybatis.generator.api.dom.DefaultJavaFormatter"/>

  25.        <!-- 格式化XML代码 -->

  26.        <property name="xmlFormatter" value="org.mybatis.generator.api.dom.DefaultXmlFormatter"/>

  27.        <plugin type="org.mybatis.generator.plugins.SerializablePlugin" />

  28.        <plugin type="org.mybatis.generator.plugins.ToStringPlugin" />

  29.        <!-- 注释 -->

  30.        <commentGenerator >

  31.            <property name="suppressAllComments" value="false"/><!-- 是否取消注释 -->

  32.            <property name="suppressDate" value="true" /> <!-- 是否生成注释代时间戳-->

  33.        </commentGenerator>

  34.        <!-- jdbc连接 -->

  35.        <jdbcConnection driverClass="${spring.datasource.driver-class-name}" connectionURL="${spring.datasource.url}" userId="${spring.datasource.username}" password="${spring.datasource.password}" />

  36.        <!-- 类型转换 -->

  37.        <javaTypeResolver>

  38.            <!-- 是否使用bigDecimal, false可自动转化以下类型(Long, Integer, Short, etc.) -->

  39.            <property name="forceBigDecimals" value="false"/>

  40.        </javaTypeResolver>

  41.        <!-- 生成实体类地址 -->

  42.        <javaModelGenerator targetPackage="com.dalaoyang.entity" targetProject="${mybatis.project}" >

  43.            <property name="enableSubPackages" value="false"/>

  44.            <property name="trimStrings" value="true"/>

  45.        </javaModelGenerator>

  46.        <!-- 生成mapxml文件 -->

  47.        <sqlMapGenerator targetPackage="mapper" targetProject="${mybatis.resources}" >

  48.            <property name="enableSubPackages" value="false" />

  49.        </sqlMapGenerator>

  50.        <!-- 生成mapxml对应client,也就是接口dao -->

  51.        <javaClientGenerator targetPackage="com.dalaoyang.dao" targetProject="${mybatis.project}" type="XMLMAPPER" >

  52.            <property name="enableSubPackages" value="false" />

  53.        </javaClientGenerator>

  54.        <!-- table可以有多个,每个数据库中的表都可以写一个table,tableName表示要匹配的数据库表,也可以在tableName属性中通过使用%通配符来匹配所有数据库表,只有匹配的表才会自动生成文件 -->

  55.        <table tableName="user" enableCountByExample="true" enableUpdateByExample="true" enableDeleteByExample="true" enableSelectByExample="true" selectByExampleQueryId="true">

  56.            <property name="useActualColumnNames" value="false" />

  57.            <!-- 数据库表主键 -->

  58.            <generatedKey column="id" sqlStatement="Mysql" identity="true" />

  59.        </table>

  60.        <table tableName="book" enableCountByExample="true" enableUpdateByExample="true" enableDeleteByExample="true" enableSelectByExample="true" selectByExampleQueryId="true">

  61.            <property name="useActualColumnNames" value="false" />

  62.            <!-- 数据库表主键 -->

  63.            <generatedKey column="id" sqlStatement="Mysql" identity="true" />

  64.        </table>

  65.    </context>

  66. </generatorConfiguration>

配置application.properties

配置项目的application.properties,其中数据库信息,Mapper地址之前都有过介绍,具体SpringBoot-Mybatis配置可以参考:《SpringBoot+Mybatis+MySql学习》

本文配置如下:

  1. ## mapper xml 文件地址

  2. mybatis.mapper-locations=classpath*:mapper/*Mapper.xml

  3. ##数据库url

  4. spring.datasource.url=jdbc:mysql://localhost:3306/test?characterEncoding=utf8&useSSL=false

  5. ##数据库用户名

  6. spring.datasource.username=root

  7. ##数据库密码

  8. spring.datasource.password=123456

  9. ##数据库驱动

  10. spring.datasource.driver-class-name=com.mysql.jdbc.Driver

  11. #Mybatis Generator configuration

  12. #dao类和实体类的位置

  13. mybatis.project =src/main/java

  14. #mapper文件的位置

  15. mybatis.resources=src/main/resources

到这里其实配置就完成了,可以体验Mybatis-Generator插件的优点了,在右侧Maven处点击如图所示位置,如图:

点击完成后,可以看到Mapper,dao,实体类都已经创建好了,如图:

创建完成会给我生成几个默认的建当方法,如UserMapper代码如下:

  1. package com.dalaoyang.dao;

  2. import com.dalaoyang.entity.User;

  3. import org.apache.ibatis.annotations.Mapper;

  4. import java.util.List;

  5. public interface UserMapper {

  6.    /**

  7.     * This method was generated by MyBatis Generator.

  8.     * This method corresponds to the database table user

  9.     *

  10.     * @mbggenerated

  11.     */

  12.    int deleteByPrimaryKey(Long id);

  13.    /**

  14.     * This method was generated by MyBatis Generator.

  15.     * This method corresponds to the database table user

  16.     *

  17.     * @mbggenerated

  18.     */

  19.    int insert(User record);

  20.    /**

  21.     * This method was generated by MyBatis Generator.

  22.     * This method corresponds to the database table user

  23.     *

  24.     * @mbggenerated

  25.     */

  26.    User selectByPrimaryKey(Long id);

  27.    /**

  28.     * This method was generated by MyBatis Generator.

  29.     * This method corresponds to the database table user

  30.     *

  31.     * @mbggenerated

  32.     */

  33.    List<User> selectAll();

  34.    /**

  35.     * This method was generated by MyBatis Generator.

  36.     * This method corresponds to the database table user

  37.     *

  38.     * @mbggenerated

  39.     */

  40.    int updateByPrimaryKey(User record);

  41. }

UserMapper.xml代码如下:

  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="com.dalaoyang.dao.UserMapper" >

  4.  <resultMap id="BaseResultMap" type="com.dalaoyang.entity.User" >

  5.    <!--

  6.      WARNING - @mbggenerated

  7.      This element is automatically generated by MyBatis Generator, do not modify.

  8.    -->

  9.    <id column="id" property="id" jdbcType="BIGINT" />

  10.    <result column="user_name" property="userName" jdbcType="VARCHAR" />

  11.    <result column="user_password" property="userPassword" jdbcType="VARCHAR" />

  12.  </resultMap>

  13.  <delete id="deleteByPrimaryKey" parameterType="java.lang.Long" >

  14.    <!--

  15.      WARNING - @mbggenerated

  16.      This element is automatically generated by MyBatis Generator, do not modify.

  17.    -->

  18.    delete from user

  19.    where id = #{id,jdbcType=BIGINT}

  20.  </delete>

  21.  <insert id="insert" parameterType="com.dalaoyang.entity.User" >

  22.    <!--

  23.      WARNING - @mbggenerated

  24.      This element is automatically generated by MyBatis Generator, do not modify.

  25.    -->

  26.    <selectKey resultType="java.lang.Long" keyProperty="id" order="AFTER" >

  27.      SELECT LAST_INSERT_ID()

  28.    </selectKey>

  29.    insert into user (user_name, user_password)

  30.    values (#{userName,jdbcType=VARCHAR}, #{userPassword,jdbcType=VARCHAR})

  31.  </insert>

  32.  <update id="updateByPrimaryKey" parameterType="com.dalaoyang.entity.User" >

  33.    <!--

  34.      WARNING - @mbggenerated

  35.      This element is automatically generated by MyBatis Generator, do not modify.

  36.    -->

  37.    update user

  38.    set user_name = #{userName,jdbcType=VARCHAR},

  39.      user_password = #{userPassword,jdbcType=VARCHAR}

  40.    where id = #{id,jdbcType=BIGINT}

  41.  </update>

  42.  <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Long" >

  43.    <!--

  44.      WARNING - @mbggenerated

  45.      This element is automatically generated by MyBatis Generator, do not modify.

  46.    -->

  47.    select id, user_name, user_password

  48.    from user

  49.    where id = #{id,jdbcType=BIGINT}

  50.  </select>

  51.  <select id="selectAll" resultMap="BaseResultMap" >

  52.    <!--

  53.      WARNING - @mbggenerated

  54.      This element is automatically generated by MyBatis Generator, do not modify.

  55.    -->

  56.    select id, user_name, user_password

  57.    from user

  58.  </select>

  59. </mapper>

测试使用

新增测试方法

在UserMapper上加入注解@Mapper表明是持久化映射层,启动类上加入注解@RestController进行测试,这里简单调用一个查询所有的方法selectAll,启动类代码如下:

  1. @SpringBootApplication

  2. @RestController

  3. public class SpringbootGeneratorApplication {

  4.    @Autowired

  5.    private UserMapper userMapper;

  6.    @GetMapping("/findAll")

  7.    public List<User> findAll(){

  8.        return userMapper.selectAll();

  9.    }

  10.    public static void main(String[] args) {

  11.        SpringApplication.run(SpringbootGeneratorApplication.class, args);

  12.    }

  13. }

运行测试

运行项目,浏览器访问<8080>如图所示:

源码下载:大老杨码云


推荐: 分布式链路跟踪与【版】

上一篇:【官方翻译】:中的组件扫描

关注公众号


    您可能也对以下帖子感兴趣

    文章有问题?点此查看未经处理的缓存