一、前言

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

二、什么是通用Mapper

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

三、如何使用

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

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。

3.1 Maven依赖

<!-- 通用Mapper -->
<dependency>
    <groupId>tk.mybatis</groupId>
    <artifactId>mapper</artifactId>
    <version>3.3.9</version>
</dependency>

3.2 SpringMVC配置

<!-- 通用 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。

可配参数介绍:

  • UUID:设置生成UUID的方法,需要用OGNL方式配置,不限制返回值,但是必须和字段类型匹配

  • IDENTITY:取回主键的方式,可以配置的内容看下一篇如何使用中的介绍

  • ORDER:中的order属性,可选值为BEFORE和AFTER

  • catalog:数据库的catalog,如果设置该值,查询的时候表名会带catalog设置的前缀

  • schema:同catalog,catalog优先级高于schema

  • seqFormat:序列的获取规则,使用{num}格式化参数,默认值为{0}.nextval,针对Oracle,可选参数一共4个,对应0,1,2,3分别为SequenceName,ColumnName, PropertyName,TableName

  • notEmpty:insert和update中,是否判断字符串类型!=’’,少数方法会用到

  • style:实体和表转换时的规则,默认驼峰转下划线,可选值为normal用实体名和字段名;camelhump是默认值,驼峰转下划线;uppercase转换为大写;lowercase转换为小写

  • enableMethodAnnotation:可以控制是否支持方法上的JPA注解,默认false。

大多数情况下不会用到这些参数,有特殊情况可以自行研究。

3.3 实体类的写法

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

@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”)即可。如果是其他数据库,可以参考官网文档。

3.4 DAO的写法

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

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

public interface TestTableDao extends Mapper<TestTableVO> {
}

一旦继承了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条件删除数据

3.5 代码中使用

在service中注入dao,即可使用。

@Autowired
private TestTableDao testTableDao;

3.6 演示

下面演示大概的写法:

新增

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

修改

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

查询单个

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

条件查询

// 创建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 配置

5.1 Maven

<!--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>

5.2 application.properties 配置

#mapper
#mappers 多个接口时逗号隔开
mapper.mappers=tk.mybatis.mapper.common.Mapper
mapper.not-empty=false
mapper.identity=MYSQL

一、mapper接口中的方法解析

mapper接口中的函数及方法

方法 功能说明
int countByExample(UserExample example) thorws SQLException 按条件计数
int deleteByPrimaryKey(Integer id) thorws SQLException 按主键删除
int deleteByExample(UserExample example) thorws SQLException 按条件查询
String/Integer insert(User record) thorws SQLException 插入数据(返回值为ID)
User selectByPrimaryKey(Integer id) thorws SQLException 按主键查询
ListselectByExample(UserExample example) thorws SQLException 按条件查询
ListselectByExampleWithBLOGs(UserExample example) thorws SQLException 按条件查询(包括BLOB字段)。只有当数据表中的字段类型有为二进制的才会产生。
int updateByPrimaryKey(User record) thorws SQLException 按主键更新
int updateByPrimaryKeySelective(User record) thorws SQLException 按主键更新值不为null的字段
int updateByExample(User record, UserExample example) thorws SQLException 按条件更新
int updateByExampleSelective(User record, UserExample example) thorws SQLException 按条件更新值不为null的字段

二、example实例

mybatis的逆向工程中会生成实例及实例对应的example,example用于添加条件,相当where后面的部分.
Example为我们创建的实例 Example.createCriteria()为我们创建了条件容器,然后将我们的筛选条件一一添加到里面,最后用这个实例去查询.
Example example = new xxxExample(entity.class);
Criteria criteria = new Example().createCriteria();

方法 说明
example.setOrderByClause(“字段名 ASC”) 添加升序排列条件,DESC为降序
example.setDistinct(false) 去除重复,boolean型,true为选择不重复的记录。
criteria.andXxxIsNotNull 添加字段xxx不为null的条件
criteria.andXxxEqualTo(value) 添加xxx字段等于value条件
criteria.andXxxNotEqualTo(value) 添加xxx字段不等于value条件
criteria.andXxxGreaterThan(value) 添加xxx字段大于value条件
criteria.andXxxGreaterThanOrEqualTo(value) 添加xxx字段大于等于value条件
criteria.andXxxLessThan(value) 添加xxx字段小于value条件
criteria.andXxxLessThanOrEqualTo(value) 添加xxx字段小于等于value条件
criteria.andXxxIn(List<?>) 添加xxx字段值在List<?>条件
criteria.andXxxNotIn(List<?>) 添加xxx字段值不在List<?>条件
criteria.andXxxLike(“%”+value+”%”) 添加xxx字段值为value的模糊查询条件
criteria.andXxxNotLike(“%”+value+”%”) 添加xxx字段值不为value的模糊查询条件

三、应用举例

1.查询

① selectByPrimaryKey()

User user = XxxMapper.selectByPrimaryKey(100); //相当于select * from user where id = 100

② selectByExample() 和 selectByExampleWithBLOGs()

Example example = new Example(entity.class);
Criteria criteria = example.createCriteria();
criteria.andUsernameEqualTo("wyw");
criteria.andUsernameIsNull();
example.setOrderByClause("username asc,email desc");
List<?>list = XxxMapper.selectByExample(example);
//相当于:select * from user where username = 'wyw' and  username is null order by username asc,email desc

注:在iBator逆向工程生成的文件XxxExample.java中包含一个static的内部类Criteria,Criteria中的方法是定义SQL 语句where后的查询条件。

2.插入数据

①insert()

User user = new User();
user.setId("dsfgsdfgdsfgds");
user.setUsername("admin");
user.setPassword("admin")
user.setEmail("wyw@163.com");
XxxMapper.insert(user);
//相当于:insert into user(ID,username,password,email) values ('dsfgsdfgdsfgds','admin','admin','wyw@126.com');

3.更新数据

①updateByPrimaryKey()

User user =new User();
user.setId("dsfgsdfgdsfgds");
user.setUsername("wyw");
user.setPassword("wyw");
user.setEmail("wyw@163.com");
XxxMapper.updateByPrimaryKey(user);
//相当于:update user set username='wyw', password='wyw', email='wyw@163.com' where id='dsfgsdfgdsfgds'

②updateByPrimaryKeySelective()

User user = new User();
user.setId("dsfgsdfgdsfgds");
user.setPassword("wyw");
XxxMapper.updateByPrimaryKey(user);
//相当于:update user set password='wyw' where id='dsfgsdfgdsfgds'

③ updateByExample() 和 updateByExampleSelective()

Example example = new Example(entity.class);
Criteria criteria = example.createCriteria();
criteria.andUsernameEqualTo("admin");
User user = new User();
user.setPassword("wyw");
XxxMapper.updateByPrimaryKeySelective(user,example);
//相当于:update user set password='wyw' where username='admin'

updateByExample()更新所有的字段,包括字段为null的也更新,建议使用 updateByExampleSelective()更新想更新的字段

4.删除数据

①deleteByPrimaryKey()

XxxMapper.deleteByPrimaryKey(1);  //相当于:delete from user where id=1

②deleteByExample()

Example example = new Example(entity.class);
Criteria criteria = example.createCriteria();
criteria.andUsernameEqualTo("admin");
XxxMapper.deleteByExample(example);
//相当于:delete from user where username='admin'

5.查询数据数量

①countByExample()

Example example = new Example(entity.class);
Criteria criteria = example.createCriteria();
criteria.andUsernameEqualTo("wyw");
int count = XxxMapper.countByExample(example);
//相当于:select count(*) from user where username='wyw'

四、实操实例

1.多条件排序

根据多条件排序直接就在后续添加排序字段(Entity是我的DO实体类)

Example example = new Example(Affiche.class);
Example.Criteria criteria = example.createCriteria();
example.orderBy(DataConstants.SHOW_TIME).desc();
example.orderBy(DataConstants.ID).desc();

2.or条件

or条件的查询,必须建立两个criteria对象,然后出了or条件字段,其他查询条件字段必须相同,这里是我的实例就不改了,DataConstants类存放的是我的常用常量字段,DbConstants和NumConstans是存放用的String类型和Integer类型的常用值。

Example example = new Example(Affiche.class);
    Example.Criteria criteria = example.createCriteria();
    criteria.andEqualTo(DataConstants.AFFICHE_TYPE,type)
            .andEqualTo(DataConstants.INSTITUTION_ID,institutionId)
            .andEqualTo(DataConstants.DELETE_TIME,DbConstants.NO_DEL_VAL)
            .andEqualTo(DataConstants.IF_DISPLAY,NumConstants.IS_DISPLAY)
            .andEqualTo(DataConstants.SHOW_STATUS,NumConstants.IS_PUBLISHED)
            .andLessThanOrEqualTo(DataConstants.SHOW_TIME,new Date());
    if(StringUtils.isNotBlank(keyWord)){
        criteria.andLike(DataConstants.AFFICHE_TITLE,keyWord);
    }

    Example.Criteria criteria1 = example.createCriteria();
    criteria1.andEqualTo(DataConstants.AFFICHE_TYPE,type)
            .andEqualTo(DataConstants.INSTITUTION_ID,institutionId)
            .andEqualTo(DataConstants.DELETE_TIME,DbConstants.NO_DEL_VAL)
            .andEqualTo(DataConstants.IF_DISPLAY,NumConstants.IS_DISPLAY)
            .andEqualTo(DataConstants.SHOW_STATUS,NumConstants.IS_PUBLISHED)
            .andLessThanOrEqualTo(DataConstants.SHOW_TIME,new Date());
    if(StringUtils.isNotBlank(keyWord)){
        criteria1.andLike(DataConstants.AFFICHE_CONTENT,keyWord);
    }
    example.or(criteria1);
    List<Affiche> afficheList = afficheMapper.selectByExample(example);

3.IN条件

in条件入参可以是集合形式,如下的List ids具体的实现方法,目前只会用分析不了原理

Example example = new Example(Affiche.class);
    example.createCriteria().andEqualTo(DbConstants.DELETE_TIME, DbConstants.NO_DEL_VAL)
            .andEqualTo(DataConstants.INSTITUTION_ID, institutionId)
            .andIn(DataConstants.ID, ids);

五、拓展

Criteria类

Criteria 内部类的每个属性都包含 andXXX 方法,以及如下的标准的SQL查询方法:

IS NULL - 指相关的列必须为NULL
IS NOT NULL - 指相关的列必须不为NULL
= (equal) - 指相关的列必须等于方法参数中的值

<> (not equal) - 指相关的列必须不等于方法参数中的值

(greater than) - 指相关的列必须大于方法参数中的值
= (greater than or equal) - 指相关的列必须大于等于方法参数中的值
< (less than) - 指相关的列必须小于于方法参数中的值
<= (less than or equal) - 指相关的列必须小于等于方法参数中的值
LIKE - 指相关的列必须 “like” 方法参数中的值. 这个方法不用必须加入 ‘%’, 您必须设置方法参数中的值.
NOT LIKE - 指相关的列必须 “not like” 方法参数中的值. 这个方法不用必须加入 ‘%’, 您必须设置方法参数中的值.
BETWEEN - 指相关的列必须在 “between” 方法参数中的两个值之间.
NOT BETWEEN - 指相关的列必须不在 “not between” 方法参数中的两个值之间.
IN - 指相关的列必须在传入的方法参数的list中.
NOT IN - 指相关的列必须不在传入的方法参数的list中

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐