Mybatis 通用 Mapper 和 Spring 集成

Stella981
• 阅读 521

依赖

 正常情况下,在原有依赖基础上增加的 mapper-spring。

<!-- https://mvnrepository.com/artifact/tk.mybatis/mapper-spring -->
<dependency>
    <groupId>tk.mybatis</groupId>
    <artifactId>mapper-spring</artifactId>
    <version>1.0.5</version>
</dependency>

  如果想使用其他版本的依赖文件,可以在Maven仓库上搜索“tk.mybatis”。

配置

MapperScannerConfigurer xml

<bean class="tk.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="basePackage" value="tk.mybatis.mapper.mapper"/>
    <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
    <property name="properties">
        <value>
            mappers=tk.mybatis.mapper.common.Mapper
        </value>
    </property>
</bean>

@MapperScan 注解

  Spring Boot 环境中使用 application.properties] 配置文件

  在 Spring Boot 中使用 Mapper 时,如果选择使用注解方式,可以不引入 mapper-starter 依赖。

  特别提醒:Spring Boot 中常见的是配置文件方式,使用环境变量或者运行时的参数都可以配置,这些配置都可以对通用 Mapper 生效。

  在 propertie 配置中:

mapper.mappers=tk.mybatis.mapper.common.Mapper,tk.mybatis.mapper.common.Mapper2
mapper.not-empty=true

tk.mybatis.mapper.session.Configuration 配置

  使用要求:MyBatis (3.4.0+) 和 mybatis-spring (1.3.0+)

  注意该类的包名,这个类继承了 MyBatis 的 Configuration 类,并且重写了 addMappedStatement 方法,如下:

@Override
public void addMappedStatement(MappedStatement ms) {
    try {
        super.addMappedStatement(ms);
        //在这里处理时,更能保证所有的方法都会被正确处理
        if (this.mapperHelper != null) {
            this.mapperHelper.processMappedStatement(ms);
        }
    } catch (IllegalArgumentException e) {
        //这里的异常是导致 Spring 启动死循环的关键位置,为了避免后续会吞异常,这里直接输出
        e.printStackTrace();
        throw new RuntimeException(e);
    }
}

tk.mybatis.mapper.session.Configuration 提供了 3 种配置通用 Mapper 的方式,如下所示:

/**
 * 直接注入 mapperHelper
 *
 * @param mapperHelper
 */
public void setMapperHelper(MapperHelper mapperHelper) {
    this.mapperHelper = mapperHelper;
}

/**
 * 使用属性方式配置
 *
 * @param properties
 */
public void setMapperProperties(Properties properties) {
    if (this.mapperHelper == null) {
        this.mapperHelper = new MapperHelper();
    }
    this.mapperHelper.setProperties(properties);
}

/**
 * 使用 Config 配置
 *
 * @param config
 */
public void setConfig(Config config) {
    if (mapperHelper == null) {
        mapperHelper = new MapperHelper();
    }
    mapperHelper.setConfig(config);
}

  这里直接配置一个 tk 中提供的 Configuration,然后注入到 SqlSessionFactoryBean 中。

使用 tk.mybatis.mapper.session.Configuration 和 Spring 集成

@Bean
public SqlSessionFactory sqlSessionFactory() throws Exception {
    SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
    sessionFactory.setDataSource(dataSource());
    //创建 Configuration,设置通用 Mapper 配置
    tk.mybatis.mapper.session.Configuration configuration = new tk.mybatis.mapper.session.Configuration();
    //有 3 种配置方式
    configuration.setMapperHelper(new MapperHelper());
    sessionFactory.setConfiguration(configuration);
    
    return sessionFactory.getObject();
}

代码演示

创建一个超类接口,继承通用mapper内部的所有方法,然后就可以直接调用了。

public interface BaseMapper<T> extends InsertSelectiveMapper<T>, UpdateByExampleSelectiveMapper<T>, UpdateByPrimaryKeySelectiveMapper<T>,
        SelectOneMapper<T>, SelectByPrimaryKeyMapper<T>, SelectMapper<T>, SelectByExampleMapper<T>, SelectByExampleRowBoundsMapper<T>,
        SelectCountByExampleMapper<T> {}

  下面介绍一下通用Mapper的内置方法

   countByExample --- 根据条件查询数量 

int countByExample(UserExample example);
//完整案例
UserExample example=new UserExample();
Criteria criteria = example.createCriteria();
criteria.andAgeEqualTo(23);
int count=userDAO.countByExample(example);
//相当于:select count(*) from user where age=23;

  deleteByExample  --- 根据条件删除多条

int deleteByExample(AccountExample example);
 
//完整的案例

UserExample example = new UserExample();

 Criteria criteria = example.createCriteria();

 criteria.andUsernameEqualTo("joe");

 userDAO.deleteByExample(example);

 //相当于:delete from user where username='joe'

  deleteByPrimaryKey ---根据主键删除

int deleteByPrimaryKey(Integer id);

//完整案例
userDAO.deleteByPrimaryKey(101);  

//相当于:delete from user where id=101

  insertSelective --- 插入数据

int insertSelective(Account record); 
//完整的案例
User user = new User();
user.setUsername("test"); 
user.setPassword("123456") 
user.setEmail("674531003@qq.com"); 
userDAO.insertSelective(user); 
//相当于:insert into user(username,password,email) values('test','123456','674531003@qq.com');

  selectByExample --- 根据条件查询数据

List<Account> selectByExample(AccountExample example); 
//完整的案例
UserExample example = new UserExample();
Criteria criteria = example.createCriteria();
criteria.andUsernameEqualTo("joe");
criteria.andUsernameIsNull();
example.setOrderByClause("username asc,email desc");
List<?> list = userDAO.selectByExample(example);
//相当于:select * from user where username = 'joe' and username is null order by username asc,email desc
//注:在myBatis 生成的文件UserExample.java中包含一个static 的内部类 Criteria ,在Criteria中有很多方法,主要是定义SQL 语句where后的查询条件。

  selectByPrimaryKey --- 根据主键查询数据

Account selectByPrimaryKey(Integer id);
//相当于select * from user where id = id

  updateByExampleSelective --- 按条件更新值不为null的字段

int updateByExampleSelective(@Param("record") Account record, @Param("example") AccountExample example);
 //完整的案列
UserExample example = new UserExample();
Criteria criteria = example.createCriteria(); 
criteria.andUsernameEqualTo("joe");
 User user = new User(); 
user.setPassword("123"); userDAO.updateByPrimaryKeySelective(user,example); 
//相当于:update user set password='123' where username='joe'

  updateByPrimaryKeySelective --- 根据主键更新

int updateByPrimaryKeySelective(Account record);
 //完整的案例  
User user = new User();
user.setId(101);
user.setPassword("joe");
userDAO.updateByPrimaryKeySelective(user);
//相当于:update user set password='joe' where id=101

 最后补一张从网上盗的关于Example的图

Mybatis 通用 Mapper 和 Spring 集成

点赞
收藏
评论区
推荐文章
blmius blmius
2年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
Jacquelyn38 Jacquelyn38
2年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
Wesley13 Wesley13
2年前
Java获得今日零时零分零秒的时间(Date型)
publicDatezeroTime()throwsParseException{    DatetimenewDate();    SimpleDateFormatsimpnewSimpleDateFormat("yyyyMMdd00:00:00");    SimpleDateFormatsimp2newS
Wesley13 Wesley13
2年前
mysql设置时区
mysql设置时区mysql\_query("SETtime\_zone'8:00'")ordie('时区设置失败,请联系管理员!');中国在东8区所以加8方法二:selectcount(user\_id)asdevice,CONVERT\_TZ(FROM\_UNIXTIME(reg\_time),'08:00','0
Wesley13 Wesley13
2年前
Java日期时间API系列36
  十二时辰,古代劳动人民把一昼夜划分成十二个时段,每一个时段叫一个时辰。二十四小时和十二时辰对照表:时辰时间24时制子时深夜11:00凌晨01:0023:0001:00丑时上午01:00上午03:0001:0003:00寅时上午03:00上午0
Wesley13 Wesley13
2年前
00:Java简单了解
浅谈Java之概述Java是SUN(StanfordUniversityNetwork),斯坦福大学网络公司)1995年推出的一门高级编程语言。Java是一种面向Internet的编程语言。随着Java技术在web方面的不断成熟,已经成为Web应用程序的首选开发语言。Java是简单易学,完全面向对象,安全可靠,与平台无关的编程语言。
Stella981 Stella981
2年前
Django中Admin中的一些参数配置
设置在列表中显示的字段,id为django模型默认的主键list_display('id','name','sex','profession','email','qq','phone','status','create_time')设置在列表可编辑字段list_editable
Wesley13 Wesley13
2年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
Python进阶者 Python进阶者
2个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这