問題背景
基本上項目都離不開連接數(shù)據(jù)庫的使用桨醋,而我們連接數(shù)據(jù)庫一般有全映射框架Hibernate和半映射框架Mybatis,這篇文章主要介紹半映射框架Mybatis-generator插件的使用
- 插件可以自動生成mapper映射文件
- 可以自己靈活更改sql語句
注意事項: - 默認(rèn)已安裝mysql6或以上版本
- 默認(rèn)已安裝JDK
- 可以根據(jù)本文的項目搭建自己創(chuàng)建工程拄丰,也可以直接下載源碼進(jìn)行參考
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 創(chuàng)建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溺拱、指定特定數(shù)據(jù)庫的jdbc驅(qū)動jar包的位置千萬千萬要指定正確,不然就創(chuàng)建不了文件-->
<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逃贝、配置數(shù)據(jù)庫連接信息 -->
<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 和相應(yīng)的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句占、單個表生成策略 -->
<!--生成對應(yīng)表及類名-->
<!-- <table tableName="t_dept" domainObjectName="Dept" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false">-->
<!-- </table>-->
<!-- 6-2沪摄、整個數(shù)據(jù)庫批量生成策略 -->
<!-- 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客戶端,在數(shù)據(jù)庫中創(chuàng)建數(shù)據(jù)表
# 創(chuàng)建數(shù)據(jù)庫
CREATE DATABASE mysqlTest;
# 選擇使用數(shù)據(jù)庫
USE mysqlTest;
# 創(chuàng)建表generator_record并插入相關(guān)數(shù)據(jù)
DROP TABLE IF EXISTS generator_record;
CREATE TABLE generator_record (
id bigint(20) NOT NULL AUTO_INCREMENT COMMENT '記錄id',
create_time varchar(100) COMMENT '創(chuàng)建時間',
update_time varchar(100) COMMENT '更新時間',
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
6 一定要先有表纱烘,再使用插件進(jìn)行生成mapper文件和sql的xml文件杨拐,在maven插件中選擇mybatis-generator,點擊generate
生成結(jié)果
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凹炸,插入一條數(shù)據(jù)成功
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 最后的目錄結(jié)構(gòu)如下
測試結(jié)果
1 插入數(shù)據(jù)庫
心得
- 測試了單條的增刪改查用例戏阅,實際上為了減小mysql連接的資源開銷,都是使用的批量查詢和插入等
作為程序員第 46 篇文章啤它,每次寫一句歌詞記錄一下奕筐,看看人生有幾首歌的時間舱痘,wahahaha ...