Mybatis通用Mapper介绍与使用

前言

使用Mybatis的开发者,大多数都会遇到一个问题,就是要写大量的SQL在xml文件中,除了特殊的业务逻辑SQL之外,还有大量结构类似的增删改查SQL。而且,当数据库表结构改动时,对应的所有SQL以及实体类都需要更改。这工作量和效率的影响或许就是区别增删改查程序员和真正程序员的屏障。这时,通用Mapper便应运而生……

什么是通用Mapper

通用Mapper就是为了解决单表增删改查,基于Mybatis的插件。开发人员不需要编写SQL,不需要在DAO中增加方法,只要写好实体类,就能支持相应的增删改查方法

如何使用

以MySQL为例,假设存在这样一张表:

1
2
3
4
5
6
7
8
9
10
CREATE TABLE `test_table` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT '',
  `create_time` datetime DEFAULT NULL,
  `create_user_id` varchar(32) DEFAULT NULL,
  `update_time` datetime DEFAULT NULL,
  `update_user_id` varchar(32) DEFAULT NULL,
  `is_delete` int(8) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

主键是id,自增。下面以这张表为例介绍如何使用通用Mapper。

Maven依赖

1
2
3
4
5
6
<!-- 通用Mapper -->
<dependency>
    <groupId>tk.mybatis</groupId>
    <artifactId>mapper</artifactId>
    <version>3.3.9</version>
</dependency>

SpringMVC配置

1
2
3
4
5
6
7
8
9
<!-- 通用 Mapper -->
<bean class="tk.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="basePackage" value="cn.com.bluemoon.bd.service.spider.dao"/>
    <property name="properties">
        <value>
            mappers=tk.mybatis.mapper.common.Mapper
        </value>
    </property>
</bean>

注意这里使用tk.mybatis.spring.mapper.MapperScannerConfigure替换原来Mybatis的org.mybatis.spring.mapper.MapperScannerConfigurer。 

1
2
3
4
5
6
7
8
9
10
11
可配参数介绍:
1.UUID:设置生成UUID的方法,需要用OGNL方式配置,不限制返回值,但是必须和字段类型匹配
2.IDENTITY:取回主键的方式,可以配置的内容看下一篇如何使用中的介绍
3.ORDER:<seletKey>中的order属性,可选值为BEFORE和AFTER
4.catalog:数据库的catalog,如果设置该值,查询的时候表名会带catalog设置的前缀
5.schema:同catalog,catalog优先级高于schema
6.seqFormat:序列的获取规则,使用{num}格式化参数,默认值为{0}.nextval,针对Oracle,可选参数一共4个,对应0,1,2,3分别为SequenceName,ColumnName, PropertyName,TableName
7.notEmpty:insert和update中,是否判断字符串类型!=’’,少数方法会用到
8style:实体和表转换时的规则,默认驼峰转下划线,可选值为normal用实体名和字段名;camelhump是默认值,驼峰转下划线;uppercase转换为大写;lowercase转换为小写
9.enableMethodAnnotation:可以控制是否支持方法上的JPA注解,默认false。
大多数情况下不会用到这些参数,有特殊情况可以自行研究。

实体类的写法

记住一个原则:实体类的字段数量 >= 数据库表中需要操作的字段数量。默认情况下,实体类中的所有字段都会作为表中的字段来操作,如果有额外的字段,必须加上@Transient注解。

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
@Table(name = "test_table")
public class TestTableVO implements Serializable {
 
    private static final long serialVersionUID = 1L;
 
    @Id
    @GeneratedValue(generator = "JDBC")
    private Long id;
 
    @Transient
    private String userId;
 
    private String name;
 
    private Timestamp createTime;
 
    private String createUserId;
 
    private Timestamp updateTime;
 
    private String updateUserId;
 
    private Integer isDelete;
     
    // 省略get、set...
}

说明:

  1. 表名默认使用类名,驼峰转下划线(只对大写字母进行处理),如UserInfo默认对应的表名为user_info
  2. 表名可以使用@Table(name = "tableName")进行指定,对不符合第一条默认规则的可以通过这种方式指定表名.
  3. 字段默认和@Column一样,都会作为表字段,表字段默认为Java对象的Field名字驼峰转下划线形式.
  4. 可以使用@Column(name = "fieldName")指定不符合第3条规则的字段名
  5. 使用@Transient注解可以忽略字段,添加该注解的字段不会作为表字段使用.
  6. 建议一定是有一个@Id注解作为主键的字段,可以有多个@Id注解的字段作为联合主键.
  7. 如果是MySQL的自增字段,加上@GeneratedValue(generator = "JDBC")即可。如果是其他数据库,可以参考官网文档

DAO的写法

在传统的Mybatis写法中,DAO接口需要与Mapper文件关联,即需要编写SQL来实现DAO接口中的方法。而在通用Mapper中,DAO只需要继承一个通用接口,即可拥有丰富的方法:

1
2
public interface TestTableDao extends Mapper<TestTableVO> {
}

继承通用的Mapper,必须指定泛型

一旦继承了Mapper,继承的Mapper就拥有了Mapper所有的通用方法:

Select
方法:List<T> select(T record);
说明:根据实体中的属性值进行查询,查询条件使用等号  

方法:T selectByPrimaryKey(Object key);
说明:根据主键字段进行查询,方法参数必须包含完整的主键属性,查询条件使用等号

方法:List<T> selectAll();
说明:查询全部结果,select(null)方法能达到同样的效果

方法:T selectOne(T record);
说明:根据实体中的属性进行查询,只能有一个返回值,有多个结果是抛出异常,查询条件使用等号

方法:int selectCount(T record);
说明:根据实体中的属性查询总数,查询条件使用等号

Insert
方法:int insert(T record);
说明:保存一个实体,null的属性也会保存,不会使用数据库默认值

方法:int insertSelective(T record);
说明:保存一个实体,null的属性不会保存,会使用数据库默认值

Update
方法:int updateByPrimaryKey(T record);
说明:根据主键更新实体全部字段,null值会被更新

方法:int updateByPrimaryKeySelective(T record);
说明:根据主键更新属性不为null的值

Delete
方法:int delete(T record);
说明:根据实体属性作为条件进行删除,查询条件使用等号

方法:int deleteByPrimaryKey(Object key);
说明:根据主键字段进行删除,方法参数必须包含完整的主键属性

Example方法
方法:List<T> selectByExample(Object example);
说明:根据Example条件进行查询

重点:这个查询支持通过Example类指定查询列,通过selectProperties方法指定查询列

方法:int selectCountByExample(Object example);
说明:根据Example条件进行查询总数

方法:int updateByExample(@Param("record") T record, @Param("example") Object example);
说明:根据Example条件更新实体record包含的全部属性,null值会被更新

方法:int updateByExampleSelective(@Param("record") T record, @Param("example") Object example);
说明:根据Example条件更新实体record包含的不是null的属性值

方法:int deleteByExample(Object example);
说明:根据Example条件删除数据

代码中使用

service中注入dao,即可使用

1
2
@Autowired
private TestTableDao testTableDao;

新增

1
2
3
TestTableVO vo = new TestTableVO();
// 省略为vo设置属性...
int row = testTableDao.insertSelective(vo);

修改

1
2
3
TestTableVO vo = new TestTableVO();
// 省略为vo设置属性...
int row = testTableDao.updateByPrimaryKeySelective(vo);

查询单个

1
2
3
TestTableVO vo = new TestTableVO();
vo.setId(123L);
TestTableVO result = testTableDao.selectOne(vo);

条件查询

1
2
3
4
5
6
7
8
// 创建Example
Example example = new Example(TestTableVO.class);
// 创建Criteria
Example.Criteria criteria = example.createCriteria();
// 添加条件
criteria.andEqualTo("isDelete", 0);
criteria.andLike("name", "%abc123%");
List<TestTableVO> list = testTableDao.selectByExample(example);

总结

通用Mapper的原理是通过反射获取实体类的信息,构造出相应的SQL,因此我们只需要维护好实体类即可,对于应付复杂多变的需求提供了很大的便利。上文叙述的只是通用Mapper的简单用法,在实际项目中,还是要根据业务,在通用Mapper的基础上封装出粒度更大、更通用、更好用的方法。

附 Spring Boot 配置

1
2
3
4
5
6
7
8
9
10
11
12
<!--mybatis-->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>1.3.1</version>
</dependency>
<!--mapper-->
<dependency>
    <groupId>tk.mybatis</groupId>
    <artifactId>mapper-spring-boot-starter</artifactId>
    <version>1.1.4</version>
</dependency>
1
2
3
4
5
#mapper
#mappers 多个接口时逗号隔开
mapper.mappers=tk.mybatis.mapper.common.Mapper
mapper.not-empty=false
mapper.identity=MYSQL

Example举例:

1
2
3
4
5
6
7
8
9
10
11
public List<TestTableVO> getByExample(String name) {
        //查询器
        Example example = new Example(TestTableVO.class);
        //获得criteria
        Example.Criteria criteria=example.createCriteria();
        //参数为 属性名+值
        criteria.andEqualTo("name",name);
        //排序
        example.orderBy("age").desc();
        return testTableDao.selectByExample(example);
    }

模糊查询:

1
2
3
4
5
6
7
8
9
10
11
public List<TestTableVO> getByExampleAndKey(String key) {
       //查询器
       Example example = new Example(TestTableVO.class);
       Example.Criteria criteria=example.createCriteria();
       /**
        * 第一个参数是key:值得属性
        * 第二个是值:指匹配的值
        */
       criteria.andLike("name", "%"+ key +"%");
       return testTableDao.selectByExample(example);
   }

Mybatis通用Mapper介绍和使用的更多相关文章

  1. 详解Mybatis通用Mapper介绍与使用

    使用Mybatis的开发者,大多数都会遇到一个问题,就是要写大量的SQL在xml文件中,除了特殊的业务逻辑SQL之外,还有大量结构类似的增删改查SQL.而且,当数据库表结构改动时,对应的所有SQL以及 ...

  2. Mybatis通用Mapper介绍与使用

    前言 使用Mybatis的开发者,大多数都会遇到一个问题,就是要写大量的SQL在xml文件中,除了特殊的业务逻辑SQL之外,还有大量结构类似的增删改查SQL.而且,当数据库表结构改动时,对应的所有SQ ...

  3. 值得收藏的Mybatis通用Mapper使用大全。

    引言 由于小编的记性不太好,每次在写代码的时候总是把通用mapper的方法记错,所以今天把通用mapper的常用方法做一下总结,方便以后直接查看.好了,不废话啦. 引包 <!-- 通用Mappe ...

  4. SpringBoot 3.SpringBoot 整合 MyBatis 逆向工程以及 MyBatis 通用 Mapper

    一.添加所需依赖,当前完整的pom文件如下: <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi=&qu ...

  5. Spring boot集成 MyBatis 通用Mapper

    配置 POM文件 <parent> <groupId>org.springframework.boot</groupId> <artifactId>sp ...

  6. (一 、上)搭建简单的SpringBoot + java + maven + mysql + Mybatis+通用Mapper 《附项目源码》

    最近公司一直使用 springBoot 作为后端项目框架, 也负责搭建了几个新项目的后端框架.在使用了一段时间springBoot 后,感觉写代码 比spring 更加简洁了(是非常简洁),整合工具也 ...

  7. spring boot集成MyBatis 通用Mapper 使用总结

    spring boot集成MyBatis 通用Mapper 使用总结 2019年 参考资料: Spring boot集成 MyBatis 通用Mapper SpringBoot框架之通用mapper插 ...

  8. springboot学习笔记:8. springboot+druid+mysql+mybatis+通用mapper+pagehelper+mybatis-generator+freemarker+layui

    前言: 开发环境:IDEA+jdk1.8+windows10 目标:使用springboot整合druid数据源+mysql+mybatis+通用mapper插件+pagehelper插件+mybat ...

  9. springboot学习笔记:9.springboot+mybatis+通用mapper+多数据源

    本文承接上一篇文章:springboot学习笔记:8. springboot+druid+mysql+mybatis+通用mapper+pagehelper+mybatis-generator+fre ...

随机推荐

  1. [linux]centos7.4部署django+Uwsgi+Nginx

    前言:我已经写了几个接口用来部署在服务器上的,首先选择django+Uwsgi+Nginx因为配置简单,比较符合python的简单操作功能强大的特点 然后对于django的一些版本在之前的文章写了 参 ...

  2. 第九届网安竞赛writeup

    web easysql[已解决] uname=a') union select 1,extractvalue(1, concat(0x7e, (select database()),0x7e))#&a ...

  3. flask gevent

    flask的不同部署方式 使用gevent部署,只是在不同请求之间是异步的,同一个请求之间还是串行的. https://iximiuz.com/en/posts/flask-gevent-tutori ...

  4. Intellij Idea显示回退和前进按钮的方法

    方法1:使用快捷键: 回到上一步  ctrl + alt + <-(左方向键) 回到下一步 ctrl + alt + ->(右方向键) 方法2:在界面显示: View -> 勾选To ...

  5. 大白话讲解Mybatis的plugin(Interceptor)的使用

    mybatis提供了一个入口,可以让你在语句执行过程中的某一点进行拦截调用.官方称之为插件plugin,但是在使用的时候需要实现Interceptor接口,默认情况下,MyBatis 允许使用插件来拦 ...

  6. [luogu4548]歌唱王国

    (可以参考hdu4652,因此推导过程比较省略) 类似的定义$f_{i}$和$g_{i}$,同样去插入$len$个字符,但注意到并不是任意一个位置都可以作为结尾,$i+j$可以作为结尾当且仅当$s[0 ...

  7. 第十四章 kubernetes 核心技术-调度器

    一.概述 一个容器平台的主要功能就是为容器分配运行时所需要的计算,存储和网络资源.容器调 度系统负责选择在最合适的主机上启动容器,并且将它们关联起来.它必须能够自动的处 理容器故障并且能够在更多的主机 ...

  8. maven私服-账号管理

    关于maven私服的相关数据: 默认账号admin,密码:admin123 这个账号是不能进行上传代码 到maven仓库的. 我们光是有admin和匿名账号是不够的,我们需要创建一个专门用来部署的账号 ...

  9. java内部类的调用方式

    public class DotThis { public class Inner{ public DotThis outer(){ return DotThis.this; }; } /* 1.第一 ...

  10. Codeforces 702F - T-shirts(平衡树+势能分析)

    题面传送门 首先肯定将所有物品排个序. 考虑暴力做法,对于每个询问,枚举所有物品,能买就买.不过扫一眼就知道无法直接优化. 不妨换个角度,暴力做法是枚举询问,这次我们枚举物品.从左到右依次枚举所有物品 ...