依赖

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

  1. <!-- https://mvnrepository.com/artifact/tk.mybatis/mapper-spring -->
  2. <dependency>
  3. <groupId>tk.mybatis</groupId>
  4. <artifactId>mapper-spring</artifactId>
  5. <version>1.0.5</version>
  6. </dependency>

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

配置 

  MapperScannerConfigurer xml

  1. <bean class="tk.mybatis.spring.mapper.MapperScannerConfigurer">
  2. <property name="basePackage" value="tk.mybatis.mapper.mapper"/>
  3. <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
  4. <property name="properties">
  5. <value>
  6. mappers=tk.mybatis.mapper.common.Mapper
  7. </value>
  8. </property>
  9. </bean>

  @MapperScan 注解

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

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

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

  在 propertie 配置中:

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

  tk.mybatis.mapper.session.Configuration 配置

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

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

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

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

  1. /**
  2. * 直接注入 mapperHelper
  3. *
  4. * @param mapperHelper
  5. */
  6. public void setMapperHelper(MapperHelper mapperHelper) {
  7. this.mapperHelper = mapperHelper;
  8. }
  9.  
  10. /**
  11. * 使用属性方式配置
  12. *
  13. * @param properties
  14. */
  15. public void setMapperProperties(Properties properties) {
  16. if (this.mapperHelper == null) {
  17. this.mapperHelper = new MapperHelper();
  18. }
  19. this.mapperHelper.setProperties(properties);
  20. }
  21.  
  22. /**
  23. * 使用 Config 配置
  24. *
  25. * @param config
  26. */
  27. public void setConfig(Config config) {
  28. if (mapperHelper == null) {
  29. mapperHelper = new MapperHelper();
  30. }
  31. mapperHelper.setConfig(config);
  32. }

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

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

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

代码演示  

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

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

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

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

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

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

  1. int deleteByExample(AccountExample example);
  2.  
  3. //完整的案例
  4.  
  5. UserExample example = new UserExample();
  6.  
  7. Criteria criteria = example.createCriteria();
  8.  
  9. criteria.andUsernameEqualTo("joe");
  10.  
  11. userDAO.deleteByExample(example);
  12.  
  13. //相当于:delete from user where username='joe'

  deleteByPrimaryKey ---根据主键删除

  1. int deleteByPrimaryKey(Integer id);
  2.  
  3. //完整案例
  4. userDAO.deleteByPrimaryKey(101);
  5.  
  6. //相当于:delete from user where id=101

  insertSelective --- 插入数据

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

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

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

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

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

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

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

  updateByPrimaryKeySelective --- 根据主键更新

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

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

 

Mybatis 通用 Mapper 和 Spring 集成的更多相关文章

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

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

  2. Spring boot集成 MyBatis 通用Mapper

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

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

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

  4. springboot学习笔记:11.springboot+shiro+mysql+mybatis(通用mapper)+freemarker+ztree+layui实现通用的java后台管理系统(权限管理+用户管理+菜单管理)

    一.前言 经过前10篇文章,我们已经可以快速搭建一个springboot的web项目: 今天,我们在上一节基础上继续集成shiro框架,实现一个可以通用的后台管理系统:包括用户管理,角色管理,菜单管理 ...

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

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

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

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

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

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

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

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

  9. Mybatis通用Mapper介绍和使用

    Mybatis通用Mapper介绍与使用 前言 使用Mybatis的开发者,大多数都会遇到一个问题,就是要写大量的SQL在xml文件中,除了特殊的业务逻辑SQL之外,还有大量结构类似的增删改查SQL. ...

随机推荐

  1. Math & Number Theory

    数学 数论: 莫比乌斯反演 矩阵游戏 小学数学,欧拉定理 组合: 线性代数: 高斯消元 其他: 一些题目

  2. '{}/{}_frames_{:02d}.npy'.format(dataset, train_or_test, i+1)函数

    在阅读有关代码的时候,发现一段代码写为: data_frames = np.load(os.path.join(video_root_path, '{}/{}_frames_{:02d}.npy'.f ...

  3. Mysql双主热备+LVS+Keepalived高可用部署实施手册

    MySQL复制能够保证数据的冗余的同时可以做读写分离来分担系统压力,如果是主主复制还可以很好的避免主节点的单点故障.然而MySQL主主复制存在一些问题无法满足我们的实际需要:未提供统一访问入口来实现负 ...

  4. pkuseg:一个多领域中文分词工具包

    pkuseg简单易用,支持细分领域分词,有效提升了分词准确度. 目录 主要亮点 编译和安装 各类分词工具包的性能对比 使用方式 相关论文 作者 常见问题及解答 主要亮点 pkuseg具有如下几个特点: ...

  5. 《JavaScript.DOM》读书笔记

  6. 常见RPC开源框架

    什么是rpc框架先回答第一个问题:什么是RPC框架? 如果用一句话概括RPC就是:远程调用框架(Remote Procedure Call) 那什么是远程调用?通常我们调用一个php中的方法,比如这样 ...

  7. Hibernate 4.3.11 下问题的解决

    2017.01.09 问题:hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hib ...

  8. android Button上面的英文字符串自动大写的问题解决

    xml文件中加入: android:textAllCaps="false"

  9. tnsping 不通

    好久没装oracle 了,竟然被一个简单问题一下子蒙住了,防火墙没关,或者说没有放开oracle端口,这都能忘,还是记录一下吧.

  10. javascript中事件对象注册与删除

    事件对象 注册事件 直接给dom对象设置属性,只能给对象设置一个属性,如果设置多个事件处理函数,则最后的生效: 给html标签设置属性,(若法1和法2同时使用,则法1生效): 事件注册 绑定事件监听函 ...