SpringBoot 是快速开发 Spring 项目的流行框架,而 MyBatis 是 Spring 中数据库操作的流行方案。本文以 MySQL 为例,总结了 SpringBoot 项目中借助 MyBatis Generator 的生成实体类和Mapper,并使用它们操作数据库的开发要点。作者: 王克锋出处: https://kefeng.wang/2018/03/15/spring-boot-mybatis/ 版权: 自由转载-非商用-非衍生-保持署名 ,转载请标明作者和出处。
1 概述 1.1 两个工具
mybatis-generator-maven-plugin: 自动生成数据表的 entity/mapper,用于 Java 代码中操作数据库;
mybatis-spring-boot-starter: 简化 MyBatis 整合,快速实现数据库操作。
1.2 准备数据库 mybatis/database.sql 1 2 3 4 5 6 7 8 9 10 11 12 13 14 DROP DATABASE IF EXISTS cloudauth;CREATE DATABASE cloudauth CHARACTER SET utf8;USE cloudauth;DROP TABLE IF EXISTS auth_users;CREATE TABLE auth_users( id INT AUTO_INCREMENT COMMENT '用户ID' , name VARCHAR (16 ) COMMENT '用户名称' , passwd VARCHAR (16 ) COMMENT '登录密码' , created TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '生成时间' , updated TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间' , PRIMARY KEY (id ), UNIQUE KEY (name ) ) ENGINE =InnoDB DEFAULT CHARSET =UTF8 COMMENT ='AUTH_用户表' ;
2 Mybatis Generator 生成 2.1 配置 config/application-local.properties
配置 MySQL 的连接参数,同时用于 Mybatis Generator/Starter;
配置生成的类所在的父 package(xxxEntity.java / xxxMapper.java 分别在其下 entity/mapper 子目录中)。
1 2 3 4 5 ## MySQL spring.datasource.username=root spring.datasource.password=root123 spring.datasource.url=jdbc:mysql://192.168.9.24:3306/cloudauth?useUnicode=true&characterEncoding=utf8&useSSL=false mybatis.generator.base-package=wang.kefeng.cloud.security
2.2 配置 mybatis/generator.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 <?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 ="config/application-local.properties" /> <context id ="MySQLTables" targetRuntime ="MyBatis3" defaultModelType ="flat" > <plugin type ="com.github.oceanc.mybatis3.generator.plugin.BatchInsertPlugin" /> <plugin type ="com.github.oceanc.mybatis3.generator.plugin.PaginationPlugin" /> <commentGenerator > <property name ="suppressAllComments" value ="true" /> <property name ="suppressDate" value ="true" /> </commentGenerator > <jdbcConnection driverClass ="com.mysql.jdbc.Driver" connectionURL ="${spring.datasource.url}" userId ="${spring.datasource.username}" password ="${spring.datasource.password}" > </jdbcConnection > <javaModelGenerator targetProject ="src/main/java" targetPackage ="${mybatis.generator.base-package}.entity" > <property name ="enableSubPackages" value ="false" /> <property name ="trimStrings" value ="true" /> </javaModelGenerator > <sqlMapGenerator targetProject ="src/main/resources" targetPackage ="mapper" > <property name ="enableSubPackages" value ="false" /> </sqlMapGenerator > <javaClientGenerator targetProject ="src/main/java" targetPackage ="${mybatis.generator.base-package}.mapper" type ="XMLMAPPER" > <property name ="enableSubPackages" value ="false" /> </javaClientGenerator > <table tableName ="auth_users" > <generatedKey column ="id" sqlStatement ="MySql" identity ="true" /> </table > </context > </generatorConfiguration >
2.3 配置 pom.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 <properties > <mysql-connector-version > 5.1.46</mysql-connector-version > <mybatis-generator-version > 1.3.6</mybatis-generator-version > </properties > <build > <plugins > <plugin > <groupId > org.mybatis.generator</groupId > <artifactId > mybatis-generator-maven-plugin</artifactId > <version > ${mybatis-generator-version}</version > <configuration > <configurationFile > src/main/resources/mybatis/generator.xml</configurationFile > <overwrite > true</overwrite > <verbose > false</verbose > </configuration > <dependencies > <dependency > <groupId > mysql</groupId > <artifactId > mysql-connector-java</artifactId > <version > ${mysql-connector-version}</version > <scope > runtime</scope > </dependency > <dependency > <groupId > com.github.oceanc</groupId > <artifactId > mybatis3-generator-plugin</artifactId > <version > 0.4.0</version > </dependency > </dependencies > </plugin > </plugins > </build >
2.4 生成 mybatis/generate.cmd 需要特别注意,pom.xml 指定的选项 overwrite=true,只对 *.java
有效; 而对 *.xml
无效,会导致 xml 文件内容重复追加而报错,所以必须另加脚本删除 xml 文件。 当然,为避免 overwrite 的警告日志,也可以增加脚本删除 java 文件。
1 2 3 4 5 6 7 8 9 10 @echo off & cls cd /d E:\projects\beyond-cloud\beyond-securitydel /q src\main\resources\mapper\*.xml del /q src\main\java\wang\kefeng\cloud\security\entity\*.java del /q src\main\java\wang\kefeng\cloud\security\mapper\*.java call mvn.cmd mybatis-generator:generate pause
2.5 生成结果
src/main/java/wang/kefeng/cloud/security/entity/AuthUsers.java
src/main/java/wang/kefeng/cloud/security/entity/AuthUsersExample.java
src/main/java/wang/kefeng/cloud/security/mapper/AuthUsersMapper.java
src/main/resources/mapper/AuthUsersMapper.xml
2.6 更多生成方式 Running MyBatis Generator Running MyBatis Generator With Command Line Running MyBatis Generator With Maven Running MyBatis Generator With Java
也可以不改动 pom.xml,用命令行方式生成:1 2 3 4 5 @echo off & cls set MYBATIS_JAR=%USERPROFILE%\.m2\repository\org\mybatis\generator\mybatis-generator-core\1.3.6\mybatis-generator-core-1.3.6.jar set MYBATIS_XML=%USERPROFILE%\Desktop\demo\mybatis.xml java -jar "%MYBATIS_JAR%" -configfile "%MYBATIS_XML%" -overwrite
3 Mybatis Starter 整合 3.1 配置 pom.xml 注意 mybatis-spring-boot-starter / mybatis-spring / mybatis 三者版本兼容性。相关资料:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 <properties > <mysql-connector-version > 5.1.46</mysql-connector-version > <mybatis-generator-version > 1.3.6</mybatis-generator-version > </properties > <dependencies > <dependency > <groupId > mysql</groupId > <artifactId > mysql-connector-java</artifactId > <version > ${mysql-connector-version}</version > </dependency > <dependency > <groupId > org.mybatis.spring.boot</groupId > <artifactId > mybatis-spring-boot-starter</artifactId > <version > 1.3.2</version > </dependency > <dependency > <groupId > org.mybatis</groupId > <artifactId > mybatis-spring</artifactId > <version > 1.3.2</version > </dependency > <dependency > <groupId > org.mybatis</groupId > <artifactId > mybatis</artifactId > <version > 3.4.6</version > </dependency > </dependencies >
3.2 配置 config/application.properties 指定文件 XxxMapper.xml 所在位置。1 mybatis.mapper-locations=classpath:mapper/*.xml
3.3 配置 BeyondSecurityApplication.java 指定 bean 包扫描路径,也就是 AuthUsersMapper.java 所在 package。1 @MapperScan ("wang.kefeng.cloud.security.mapper" )
3.4 操作数据库 1 2 3 4 5 6 7 8 9 @Resource private AuthUsersMapper authUsersMapper;@PostConstruct public void init () { AuthUsersExample example = new AuthUsersExample(); List<AuthUsers> users = authUsersMapper.selectByExample(example); users.size(); }