Mybatis generator和tk.Mapper
Kang Lv3

Mybatis generator是什么呢,在使用Mybatis的时候,不仅要自己写entity实体类和dao层,对应的xml文件也要自己去写,不仅工作量很大而且还很枯燥,而Mybatis-generator就是自动生成这些代码的。当然后面发现了更好用的Mapper层接口。

一、Mybatis generator的使用

1.引入 Maven

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
<?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>
<build>
<plugins>
<plugin>
<!--Mybatis-generator插件-->
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.5</version>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.27</version>
</dependency>
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.7</version>
</dependency>
</dependencies>
<configuration>
<!--generatorConfig.xml位置-->
<configurationFile>src/main/resources/mybatis-generator/generatorConfig.xml</configurationFile>
<verbose>true</verbose>
<overwrite>true</overwrite>
</configuration>
<executions>
<execution>
<id>Generate MyBatis Artifacts</id>
<goals>
<goal>generate</goal>
</goals>
<phase>generate-sources</phase>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

2.数据库建立

自己随表建一个就行

1
2
3
4
5
6
7
8
create table article
(
article_id int auto_increment
primary key,
title varchar(45) not null,
create_time datetime not null,
tags varchar(500) null
);

3.generatorConfig.xml文件

这个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
<?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>
<!--指定特定数据库的jdbc驱动jar包的位置-->
<classPathEntry location="C:\Users\Administrator\.m2\repository\mysql\mysql-connector-java\8.0.27\mysql-connector-java-8.0.27.jar"/>
<context id="MySqlTables" targetRuntime="MyBatis3">
<!--插件,可以生成通过RowBounds取记录-->
<plugin type="org.mybatis.generator.plugins.RowBoundsPlugin"/>
<commentGenerator>
<!--是否去除自动生成的注释 true:是; false:否-->
<property name="suppressAllComments" value="true" />
</commentGenerator>
<!--数据库连接信息:驱动类、链接地址、用户名、密码 -->
<jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
connectionURL="jdbc:mysql://localhost/face_ic?useUnicode=true&amp;characterEncoding=utf-8&amp;zeroDateTimeBehavior=convertToNull&amp;serverTimezone=GMT%2B8&amp;useAffectedRows=true"
userId="root" password="root">
</jdbcConnection>
<javaTypeResolver>
<!--类型解析器-->
<!--默认false,把jdbc decimal 和 numeric 类型解析为integer -->
<!--true,把jdbc decimal 和 numeric 类型解析为java.math.bigdecimal-->
<property name="forceBigDecimals" value="false" />
</javaTypeResolver>

<!--生成实体类及Example类的包名和位置-->
<javaModelGenerator targetPackage="net.faceIC.faceicms.entity"
targetProject="src/main/java">
<!--是否让schema作为包后缀-->
<property name="enableSubPackages" value="true" />
<!--从数据库返回的值被清理前后的空格-->
<property name="trimStrings" value="true" />
</javaModelGenerator>
<!--生成映射文件xml的包名和位置-->
<sqlMapGenerator targetPackage="net/faceIC/faceicms/dao/mysql"
targetProject="src/main/resources">
<!--是否让schema作为包后缀-->
<property name="enableSubPackages" value="true" />
</sqlMapGenerator>
<!--生成Dao接口的包名和位置-->
<javaClientGenerator type="XMLMAPPER"
targetPackage="net.faceIC.faceicms.dao.mysql"
targetProject="src/main/java">
<property name="enableSubPackages" value="true"/>
</javaClientGenerator>

<!--自动生成代码的数据库表;生成哪些表就写哪几个表-->
<table tableName="article" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false"
enableSelectByExample="false" selectByExampleQueryId="false">
<generatedKey column="article_id" sqlStatement="postgresql" identity="true"/>
</table>
</context>
</generatorConfiguration>

需要修改的几个地方

  • mysql8版本之后需要加com.mysql.cj.jdbc.Driver。
  • entity和mapper的包名改成自己的,路径就是src/main/resources或者src/main/java
  • table里面写自己需要生成的表名,后面几个enable都是是否生成对应的example类,column为主键

4.运行

直接点击IDEA右侧的Maven/Plugins/mybatis-generator下面的generator即可,待运行结束,就可以看到自动生成的entity、mapper和xml文件。

二、tk.mybatis.mapper.common.Mapper(通用mapper的使用)

使用

1.引入 Maven

1
2
3
4
5
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper-spring-boot-starter</artifactId>
<version>2.1.5</version>
</dependency>

2.Mapper使用

继承Tk.Mapper,如果不符合业务逻辑的话,可以自己重写

1
2
3
4
5
6
import tk.mybatis.mapper.common.Mapper;

public interface ArticleMapper extends Mapper<Article>{
@Override
int insert(Article article);
}

然后再对应的xml文件里面写增删改查操作

1
2
3
4
5
6
7
8
9
10
11
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="net.faceIC.dao.mysql.ArticleMapper">
<insert id="insert" parameterType="net.faceIC.entity.media.Article" useGeneratedKeys="true" keyProperty="articleId">
insert into article (article_id, title, file_url,
create_time, total_pv, author_id, content, cover_url, tags)
values (#{articleId,jdbcType=INTEGER}, #{title,jdbcType=VARCHAR}, #{fileUrl,jdbcType=VARCHAR},
#{createTime,jdbcType=TIMESTAMP}, #{totalPv,jdbcType=INTEGER}, #{authorId,jdbcType=INTEGER},
#{content,jdbcType=VARCHAR}, #{coverUrl,jdbcType=VARCHAR}, #{tags,jdbcType=VARCHAR})
</insert>
</mapper>

tk.mapper的一些常用方法

本身已经封装了一些基本的单表操作

Mapper的基本继承方法

Base 方法

Select
接口 方法 说明
SelectMapper List select(T record); 根据实体中的属性值进行查询,查询条件使用等号
SelectByPrimaryKeyMapper T selectByPrimaryKey(Object key); 根据主键字段进行查询,方法参数必须包含完整的主键属性,查询条件使用等号
SelectAllMapper List selectAll(); 查询全部结果,select(null)方法能达到同样的效果
SelectOneMapper T selectOne(T record); 根据实体中的属性进行查询,只能有一个返回值,有多个结果是抛出异常,查询条件使用等号
SelectCountMapper int selectCount(T record); 根据实体中的属性查询总数,查询条件使用等号
1
2
3
4
5
6
7
public Article findArticle(Integer articleId) {
return articleMapper.selectByPrimaryKey(articleId)
}

public Integer CountArticle(Article article) {
return articleMapper.selectCount(article);
}
Insert
接口 方法 说明
InsertMapper int insert(T record); 保存一个实体,null的属性也会保存,不会使用数据库默认值
InsertSelectiveMapper int insertSelective(T record); 保存一个实体,null的属性不会保存,会使用数据库默认值
Update
接口 方法 说明
UpdateByPrimaryKeyMapper int updateByPrimaryKey(T record); 根据主键更新实体全部字段,null值会被更新
UpdateByPrimaryKeySelectiveMapper int updateByPrimaryKeySelective(T record); 根据主键更新属性不为null的值
Delete
接口 方法 说明
DeleteMapper int delete(T record); 根据实体属性作为条件进行删除,查询条件使用等号
DeleteByPrimaryKeyMapper int deleteByPrimaryKey(Object key); 根据主键字段进行删除,方法参数必须包含完整的主键属性

Example 方法

接口 方法 说明
SelectByExampleMapper List selectByExample(Object example); 根据Example条件进行查询,重点:这个查询支持通过Example类指定查询列,通过selectProperties方法指定查询列
SelectCountByExampleMapper int selectCountByExample(Object example); 根据Example条件进行查询总数
UpdateByExampleMapper int updateByExample(@Param(“record”) T record, @Param(“example”) Object example); 根据Example条件更新实体record包含的全部属性,null值会被更新
UpdateByExampleSelectiveMapper int updateByExampleSelective(@Param(“record”) T record, @Param(“example”) Object example); 根据Example条件更新实体record包含的不是null的属性值
DeleteByExampleMapper int deleteByExample(Object example); 根据Example条件删除数据
1
2
3
4
5
6
7
public List<Article> findArticleList(Date startCreatTime, Date endCreatTime) {
Example example = new Example(Article.class);
Example.Criteria criteria = example.createCriteria();
criteria.andBetween("createTime", startCreatTime, endCreatTime);
example.setOrderByClause("create_time desc");
return articleMapper.selectByExample(example);
}

RowBounds

默认为内存分页,可以配合PageHelper实现物理分页

接口 方法 说明
SelectRowBoundsMapper List selectByRowBounds(T record, RowBounds rowBounds); 根据实体属性和RowBounds进行分页查询
SelectByExampleRowBoundsMapper List selectByExampleAndRowBounds(Object example, RowBounds rowBounds); 根据example条件和RowBounds进行分页查询
1
2
3
4
5
6
public List<Article> findArticleList(Integer pageNo, Integer pageSize, String title) {
Example example = new Example(Article.class);
Example.Criteria criteria = example.createCriteria();
if (title != null) criteria.andEqualTo("title",title);
return articleMapper.selectByExampleAndRowBounds(example, new RowBounds(pageSize * (pageNo- 1), pageSize));
}
  • 本文标题:Mybatis generator和tk.Mapper
  • 本文作者:Kang
  • 创建时间:2022-01-13 16:46:23
  • 本文链接:ykhou.github.io2022/01/13/Mybatis-generator的使用/
  • 版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!