问题背景
基本上项目都离不开连接数据库的使用,而我们连接数据库一般有全映射框架Hibernate和半映射框架Mybatis,这篇文章主要介绍半映射框架Mybatis-generator插件的使用
- 插件可以自动生成mapper映射文件
- 可以自己灵活更改sql语句
注意事项: - 默认已安装mysql6或以上版本
- 默认已安装JDK
- 可以根据本文的项目搭建自己创建工程,也可以直接下载源码进行参考
DAO层使用Mybatis-generator生成映射文件连接Mysql入门测试用例(无限速源码下载),单条增删改查CRUD(一)
DAO层使用Mybatis-generator生成映射文件连接Mysql入门测试用例(无限速源码下载),selectByExample,insertSelective,countByExample,selectOneByExample的使用(二)
DAO层使用Mybatis-generator生成映射文件连接Mysql入门测试用例(无限速源码下载),deleteByExample,batchInsert,updateByExampleSelective,updateByExample的使用(三)
DAO层使用Mybatis-generator生成映射文件连接Mysql入门测试用例(无限速源码下载),page分页和limit的使用(四)
DAO层使用Mybatis-generator生成映射文件连接Mysql入门测试用例(无限速源码下载),insert和update插入返回带自增主键的两种方式(五)
项目搭建
1 创建springboot工程,添加pom依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.6.3</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.yg</groupId>
<artifactId>mybatisGenerator</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>mybatisGenerator</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<!-- <scope>test</scope>-->
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>2.6.0</version>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
<!--mybatis-generator插件-->
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.5</version>
<dependencies>
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.5</version>
</dependency>
</dependencies>
<configuration>
<!--允许移动生成的文件 -->
<verbose>true</verbose>
<!-- 是否覆盖 -->
<overwrite>true</overwrite>
<!-- 自动生成的配置 -->
<configurationFile>
src/main/resources/generatorConfig.xml
</configurationFile>
</configuration>
</plugin>
</plugins>
</build>
</project>
其中,这个是mybatis配置文件所在的位置
<configurationFile>
src/main/resources/generatorConfig.xml
</configurationFile>
2 添加application.yml配置
spring:
datasource:
url: jdbc:mysql://localhost:3306/mysqlTest?serverTimezone=UTC&characterEncoding=UTF-8
username: root
password: 123456
driver-class-name: com.mysql.cj.jdbc.Driver
sql:
init:
encoding: utf-8
mybatis:
mapper-locations: mapper/mysql/*Mapper.xml
3 在resources中添加mybatis插件配置文件generatorConfig.xml,在里面配置mapper生成的路径
<?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>
<!--1、指定特定数据库的jdbc驱动jar包的位置千万千万要指定正确,不然就创建不了文件-->
<classPathEntry location="D:\software\javaFamily\repository\mysql\mysql-connector-java\8.0.27\mysql-connector-java-8.0.27.jar"/>
<context id="DB2Tables" targetRuntime="MyBatis3">
<commentGenerator>
<property name="suppressDate" value="true"/>
<!-- 是否去除自动生成的注释 true:是 : false:否 -->
<property name="suppressAllComments" value="true"/>
</commentGenerator>
<!--2、配置数据库连接信息 -->
<jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/mysqlTest?serverTimezone=UTC"
userId="root"
password="123456">
</jdbcConnection>
<javaTypeResolver>
<property name="forceBigDecimals" value="false"/>
</javaTypeResolver>
<!--3、指定Model生成的位置 -->
<javaModelGenerator
targetPackage="com.yg.mybatisgenerator.entity.mysql"
targetProject=".\src\main\java">
<property name="enableSubPackages" value="true"/>
<property name="trimStrings" value="true"/>
</javaModelGenerator>
<!--4、指定sql映射文件生成的位置 -->
<sqlMapGenerator
targetPackage="mapper\mysql"
targetProject=".\src\main\resources">
<property name="enableSubPackages" value="true"/>
</sqlMapGenerator>
<!--4.1、如果放程序包中-->
<!-- <sqlMapGenerator -->
<!-- targetPackage="com.anson.mapper"-->
<!-- targetProject=".\src\main\java">-->
<!-- <property name="enableSubPackages" value="true"/>-->
<!-- </sqlMapGenerator>-->
<!--5、指定dao接口生成的位置 .mapper接口 -->
<!-- type生成类型含义,项目中基本都是用:XMLMAPPER
type="ANNOTATEDMAPPER",生成Java Model 和基于注解的Mapper对象
type="MIXEDMAPPER",生成基于注解的Java Model 和相应的Mapper对象
type="XMLMAPPER",生成SQLMap XML文件和独立的Mapper接口
-->
<javaClientGenerator type="XMLMAPPER"
targetPackage="com.yg.mybatisgenerator.dao.mysql"
targetProject=".\src\main\java">
<property name="enableSubPackages" value="true"/>
</javaClientGenerator>
<!-- 6-1、单个表生成策略 -->
<!--生成对应表及类名-->
<!-- <table tableName="t_dept" domainObjectName="Dept" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false">-->
<!-- </table>-->
<!-- 6-2、整个数据库批量生成策略 -->
<!-- table tableName="idmapping_record"
enableCountByExample="false"
enableUpdateByExample="false"
enableDeleteByExample="false"
enableSelectByExample="false"
selectByExampleQueryId="false">
<property name="useActualColumnNames" value="false"/>
</table> -->
<table tableName="generator_record">
<property name="useActualColumnNames" value="false"/>
</table>
</context>
</generatorConfiguration>
4 在启动类上添加mapper扫描注解
package com.yg.mybatisgenerator;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@MapperScan("com/yg/mybatisgenerator/dao/mysql")
@SpringBootApplication
public class MybatisGeneratorApplication {
public static void main(String[] args) {
SpringApplication.run(MybatisGeneratorApplication.class, args);
}
}
5 使用navicat或者sqlyog客户端,在数据库中创建数据表
# 创建数据库
CREATE DATABASE mysqlTest;
# 选择使用数据库
USE mysqlTest;
# 创建表generator_record并插入相关数据
DROP TABLE IF EXISTS generator_record;
CREATE TABLE generator_record (
id bigint(20) NOT NULL AUTO_INCREMENT COMMENT '记录id',
create_time varchar(100) COMMENT '创建时间',
update_time varchar(100) COMMENT '更新时间',
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
6 一定要先有表,再使用插件进行生成mapper文件和sql的xml文件,在maven插件中选择mybatis-generator,点击generate
生成结果
7 编写增删改查CRUD测试程序
package com.yg.mybatisgenerator.springbootTest;
import com.yg.mybatisgenerator.dao.mysql.GeneratorRecordMapper;
import com.yg.mybatisgenerator.entity.mysql.GeneratorRecord;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
@Slf4j
public class GeneratorTest {
@Autowired
GeneratorRecordMapper generatorRecordMapper;
// 插入测试
@Test
public void insertTest() {
GeneratorRecord generatorRecord = GeneratorRecord.builder()
.createTime("123456")
.updateTime("789987")
.build();
int insert = generatorRecordMapper.insert(generatorRecord); // 成功返回1,插入一条数据成功
log.info("insert: {}", insert);
GeneratorRecord record = generatorRecordMapper.selectByPrimaryKey(1L);
log.info("generatorRecord: {}", record);
}
// 查询测试
@Test
public void selectTest() {
GeneratorRecord record = generatorRecordMapper.selectByPrimaryKey(1L);
log.info("generatorRecord: {}", record);
}
// 更新测试
@Test
public void updateTest(){
GeneratorRecord generatorRecord = GeneratorRecord.builder()
.id(2L)
.createTime("111111")
.updateTime("222222")
.build();
int i = generatorRecordMapper.updateByPrimaryKey(generatorRecord);
log.info("i: {}", i);
}
// 删除测试
@Test
public void deleteTest() {
int i = generatorRecordMapper.deleteByPrimaryKey(1L);
log.info("i: {}", i);
}
}
8 最后的目录结构如下
测试结果
1 插入数据库
心得
- 测试了单条的增删改查用例,实际上为了减小mysql连接的资源开销,都是使用的批量查询和插入等
作为程序员第 46 篇文章,每次写一句歌词记录一下,看看人生有几首歌的时间,wahahaha ...