Mybatis整合通用Dao,Mybatis整合通用Mapper,MyBatis3.x整合通用 Mapper3.5.x

==============================

蕃薯耀 2018年3月15日

http://www.cnblogs.com/fanshuyao/

一、Mybatis通用Mapper项目介绍:

https://github.com/abel533/Mapper

http://www.mybatis.tk/

Maven方式下载:

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

 二、整合步骤:

1、第1步:

当然是引用相应的Jar包依赖,项目采用Maven方式,在pom.xml文件加上如下配置:

其中有Mybatis依赖Jar包,Mapper依赖Jar包,pagehelper分页依赖Jar包(可选)

  1. <!-- mybatis-->
  2. <dependency>
  3. <groupId>org.mybatis</groupId>
  4. <artifactId>mybatis</artifactId>
  5. <version>${mybatis.version}</version>
  6. </dependency>
  7. <dependency>
  8. <groupId>org.mybatis</groupId>
  9. <artifactId>mybatis-spring</artifactId>
  10. <version>${mybatis.spring.version}</version>
  11. </dependency>
  12. <dependency>
  13. <groupId>org.mybatis.generator</groupId>
  14. <artifactId>mybatis-generator-core</artifactId>
  15. <version>${mybatis.generator.version}</version>
  16. <scope>provided</scope>
  17. </dependency>
  18. <!-- mybatis分页插件 使用见:https://pagehelper.github.io/docs/howtouse/-->
  19. <dependency>
  20. <groupId>com.github.pagehelper</groupId>
  21. <artifactId>pagehelper</artifactId>
  22. <version>${pagehelper.version}</version>
  23. </dependency>
  24. <!--通用Mapper,见:http://www.mybatis.tk/-->
  25. <dependency>
  26. <groupId>tk.mybatis</groupId>
  27. <artifactId>mapper</artifactId>
  28. <version>${mybatis.mapper.version}</version>
  29. </dependency>

 2、第2步:与Spring整合

在Spring.xml配置文件加上扫描器,这个扫描器和Mybatis默认是不一样的:

使用的类是:tk.mybatis.spring.mapper.MapperScannerConfigurer,包名不一样。

  1. <!--配置扫描器,将Mybatis接口的实现加入到ioc容器 -->
  2. <!-- 使用通用Mapper,见:https://mapperhelper.github.io/docs/1.integration/ -->
  3. <bean class="tk.mybatis.spring.mapper.MapperScannerConfigurer">
  4. <property name="basePackage" value="com.lqy.ssm.dao"></property>
  5. </bean>

Spring.xml配置文件见附件

3、第3步:自动生成代码文件的mybatis-mapper-generator.xml配置

在项目根目录下建立一个mybatis-mapper-generator.xml文件,内容如下:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE generatorConfiguration
  3. PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
  4. "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
  5. <!-- 此文件为通用mapper生成代码的配置 -->
  6. <!-- 配置文件信息见:https://mapperhelper.github.io/docs/3.usembg/ -->
  7. <generatorConfiguration>
  8. <context id="Mysql" targetRuntime="MyBatis3Simple" defaultModelType="flat">
  9. <plugin type="tk.mybatis.mapper.generator.MapperPlugin">
  10. <property name="mappers" value="tk.mybatis.mapper.common.Mapper"/>
  11. <!-- caseSensitive默认false,当数据库表名区分大小写时,可以将该属性设置为true -->
  12. <!-- <property name="caseSensitive" value="true"/> -->
  13. </plugin>
  14. <jdbcConnection driverClass="com.mysql.jdbc.Driver"
  15. connectionURL="jdbc:mysql://localhost:3306/study"
  16. userId="root"
  17. password="xxx">
  18. </jdbcConnection>
  19. <!-- type="org.mybatis.generator.internal.types.JavaTypeResolverDefaultImpl" -->
  20. <javaTypeResolver>
  21. <property name="forceBigDecimals" value="false" />
  22. </javaTypeResolver>
  23. <javaModelGenerator targetPackage="com.lqy.ssm.bean" targetProject=".\src\main\java"/>
  24. <sqlMapGenerator targetPackage="mapper"  targetProject=".\src\main\resources"/>
  25. <javaClientGenerator targetPackage="com.lqy.ssm.dao" targetProject=".\src\main\java" type="XMLMAPPER" />
  26. <table tableName="%" >
  27. <generatedKey column="id" sqlStatement="Mysql" identity="true"/>
  28. </table>
  29. </context>
  30. </generatorConfiguration>

注意:需要根据自己的实际要求修改的配置项

jdbcConnection:修改为自己的数据库连接

javaModelGenerator:实体bean生成的包名及位置,其中targetProject=".\src\main\java"的.\表示当前项目的位置

sqlMapGenerator:mapper.xml文件生成的位置,其中targetPackage表示目录

javaClientGenerator:通用dao生成的位置

table:生成的表名,其中<table tableName="%" >使用通配符%表示所有表

4、第4步:自动生成代码Java类

在项目的src建立一个代码生成类,如:MybatisGenerator,代码内容为:

  1. import java.io.File;
  2. import java.util.ArrayList;
  3. import java.util.List;
  4. import org.mybatis.generator.api.MyBatisGenerator;
  5. import org.mybatis.generator.config.Configuration;
  6. import org.mybatis.generator.config.xml.ConfigurationParser;
  7. import org.mybatis.generator.internal.DefaultShellCallback;
  8. /**
  9. * 官网代码见:http://www.mybatis.org/generator/running/runningWithJava.html
  10. *
  11. */
  12. public class MybatisGenerator {
  13. public static void main(String[] args) throws Exception {
  14. List<String> warnings = new ArrayList<String>();
  15. boolean overwrite = true;
  16. File configFile = new File("mybatis-mapper-generator.xml");
  17. ConfigurationParser cp = new ConfigurationParser(warnings);
  18. Configuration config = cp.parseConfiguration(configFile);
  19. DefaultShellCallback callback = new DefaultShellCallback(overwrite);
  20. MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
  21. myBatisGenerator.generate(null);
  22. System.out.println("===============生成代码执行完毕=================");
  23. }
  24. }

主要是File configFile = new File("mybatis-mapper-generator.xml");,对应上面的配置文件

5、第5步:结果查看

Java代码运行完后,就会在项目中自动生成相应的代码

生成的mapper文件:只有resultMap,没有方法,因为提供了通用方法

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  3. <mapper namespace="com.lqy.ssm.dao.UserExtMapper">
  4. <resultMap id="BaseResultMap" type="com.lqy.ssm.bean.UserExt">
  5. <!--
  6. WARNING - @mbg.generated
  7. -->
  8. <id column="id" jdbcType="INTEGER" property="id" />
  9. <result column="user_id" jdbcType="INTEGER" property="userId" />
  10. <result column="qq" jdbcType="VARCHAR" property="qq" />
  11. <result column="address" jdbcType="VARCHAR" property="address" />
  12. </resultMap>
  13. </mapper>

生成的dao接口文件:继承了Mapper接口,里面实现了很多方法

  1. import com.lqy.ssm.bean.UserExt;
  2. import tk.mybatis.mapper.common.Mapper;
  3. public interface UserExtMapper extends Mapper<UserExt> {
  4. }

使用方式:直接注入即可使用

  1. @Autowired
  2. private UserExtMapper userExtMapper;

 6、补充:所有接口方法见:

https://mapperhelper.github.io/all/

Mapper3接口有两种形式,一种是提供了一个方法的接口。还有一种是不提供方法,但是继承了多个单方法的接口,一般是某类方法的集合。

例如SelectMapper<T>是一个单方法的接口,BaseSelectMapper<T>是一个继承了4个基础查询方法的接口。

基础接口

Select

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

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

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

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

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

Insert

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

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

Update

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

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

Delete

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

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

base 组合接口

接口:BaseSelectMapper<T>
方法:包含上面Select的4个方法

接口:BaseInsertMapper<T>
方法:包含上面Insert的2个方法

接口:BaseUpdateMapper<T>
方法:包含上面Update的2个方法

接口:BaseDeleteMapper<T>
方法:包含上面Delete的2个方法

CRUD 组合接口

接口:BaseMapper<T>
方法:继承了base组合接口中的4个组合接口,包含完整的CRUD方法

Example 方法

接口:SelectByExampleMapper<T>
方法:List<T> selectByExample(Object example);
说明:根据Example条件进行查询
重点:这个查询支持通过Example类指定查询列,通过selectProperties方法指定查询列

接口:SelectCountByExampleMapper<T>
方法:int selectCountByExample(Object example);
说明:根据Example条件进行查询总数

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

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

接口:DeleteByExampleMapper<T>
方法:int deleteByExample(Object example);
说明:根据Example条件删除数据

Example 组合接口

接口:ExampleMapper<T>
方法:包含上面Example中的5个方法

Condition 方法

Condition方法和Example方法作用完全一样,只是为了避免Example带来的歧义,提供的的Condition方法

接口:SelectByConditionMapper<T>
方法:List<T> selectByCondition(Object condition);
说明:根据Condition条件进行查询

接口:SelectCountByConditionMapper<T>
方法:int selectCountByCondition(Object condition);
说明:根据Condition条件进行查询总数

接口:UpdateByConditionMapper<T>
方法:int updateByCondition(@Param("record") T record, @Param("example") Object condition);
说明:根据Condition条件更新实体record包含的全部属性,null值会被更新

接口:UpdateByConditionSelectiveMapper<T>
方法:int updateByConditionSelective(@Param("record") T record, @Param("example") Object condition);
说明:根据Condition条件更新实体record包含的不是null的属性值

接口:DeleteByConditionMapper<T>
方法:int deleteByCondition(Object condition);
说明:根据Condition条件删除数据

Condition 组合接口

接口:ConditionMapper<T>
方法:包含上面Condition中的5个方法

RowBounds

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

接口:SelectRowBoundsMapper<T>
方法:List<T> selectByRowBounds(T record, RowBounds rowBounds);
说明:根据实体属性和RowBounds进行分页查询

接口:SelectByExampleRowBoundsMapper<T>
方法:List<T> selectByExampleAndRowBounds(Object example, RowBounds rowBounds);
说明:根据example条件和RowBounds进行分页查询

接口:SelectByConditionRowBoundsMapper<T>
方法:List<T> selectByConditionAndRowBounds(Object condition, RowBounds rowBounds);
说明:根据example条件和RowBounds进行分页查询,该方法和selectByExampleAndRowBounds完全一样,只是名字改成了Condition

RowBounds 组合接口

接口:RowBoundsMapper<T>
方法:包含上面RowBounds中的前两个方法,不包含selectByConditionAndRowBounds

special 特殊接口

这些接口针对部分数据库设计,不是所有数据库都支持

接口:InsertListMapper<T>
方法:int insertList(List<T> recordList);
说明:批量插入,支持批量插入的数据库可以使用,例如MySQL,H2等,另外该接口限制实体包含id属性并且必须为自增列

接口:InsertUseGeneratedKeysMapper<T>
方法:int insertUseGeneratedKeys(T record);
说明:插入数据,限制为实体包含id属性并且必须为自增列,实体配置的主键策略无效

MySQL 专用

接口:MySqlMapper<T>
继承方法:int insertList(List<T> recordList);
继承方法:int insertUseGeneratedKeys(T record);
说明:该接口不包含方法,继承了special中的InsertListMapper<T>InsertUseGeneratedKeysMapper<T>

SqlServer 专用

由于sqlserver中插入自增主键时,不能使用null插入,不能在insert语句中出现id

注意SqlServer的两个特有插入方法都使用了

@Options(useGeneratedKeys = true, keyProperty = "id")

这就要求表的主键为id,且为自增,如果主键不叫id可以看高级教程中的解决方法。

另外这俩方法和base中的插入方法重名,不能同时存在!

如果某种数据库和SqlServer这里类似,也可以使用这些接口(需要先测试)。

接口:InsertMapper
方法:int insert(T record);
说明:插入数据库,null值也会插入,不会使用列的默认值

接口:InsertSelectiveMapper
方法:int insertSelective(T record);
说明:插入数据库,null的属性不会保存,会使用数据库默认值

接口:SqlServerMapper
说明:这是上面两个接口的组合接口。

Ids 接口

通过操作ids字符串进行操作,ids 如 “1,2,3” 这种形式的字符串,这个方法要求实体类中有且只有一个带有@Id注解的字段,否则会抛出异常。

接口:SelectByIdsMapper
方法:List<T> selectByIds(String ids)
说明:根据主键字符串进行查询,类中只有存在一个带有@Id注解的字段

接口:DeleteByIdsMapper
方法:int deleteByIds(String ids)
说明:根据主键字符串进行删除,类中只有存在一个带有@Id注解的字段

Ids 组合接口

接口:IdsMapper<T>
方法:包含上面Ids中的前两个方法

Mapper<T> 接口

接口:Mapper<T>
该接口兼容Mapper2.x版本,继承了BaseMapper<T>ExampleMapper<T>RowBoundsMapper<T>三个组合接口。

福利,福利,福利

分享一个springMvc+spring+Mybatis+pageHelper+druid整合后的完整项目:

ssm-mapper-整合通用mapper插件.zip:见http://fanshuyao.iteye.com/blog/2413143

==============================

蕃薯耀 2018年3月15日

http://www.cnblogs.com/fanshuyao/

Mybatis整合通用Dao,Mybatis整合通用Mapper,MyBatis3.x整合通用 Mapper3.5.x的更多相关文章

  1. 【mybatis深度历险系列】深入浅出mybatis中原始dao的开发和mapper代理开发

    使用Mybatis开发Dao,通常有两个方法,即原始Dao开发方法和Mapper接口开发方法.mybatis在进行dao开发的时候,涉及到三姐妹,分别是SqlSessionFactoryBuilder ...

  2. mybatis插件 mybatis插件-------从dao快速定位到mapper的sql语句

    步骤一:打开settings,点击plugins 快捷键ctrl+alt+s打开settings 步骤二.点击ClearCase Integration,并点击下面中间的按钮(browse repos ...

  3. 使用mybatis完成通用dao和通用service

    使用mybatis完成通用dao和通用service 概述: 使用通用dao和通用service可以减少代码的开发.可以将常用的增删改查放到通用dao中.对不同的or框架,基本上都有自己的实现如Spr ...

  4. SSM实战——秒杀系统之DAO层实体定义、接口设计、mybatis映射文件编写、整合Spring与Mybatis

    一:DAO实体编码 1:首先,在src目录下,新建org.myseckill.entity包,用于存放实体类: 2:实体类设计 根据前面创建的数据库表以及映射关系,创建实体类. 表一:秒杀商品表 对应 ...

  5. Mybatis 使用PageHelper封装通用Dao分页方法

    参考: PageHelper官网:https://pagehelper.github.io/docs/howtouse/#3-%E5%A6%82%E4%BD%95%E5%9C%A8%E4%BB%A3% ...

  6. mybatis通用DAO

    扫扫关注"茶爸爸"微信公众号 坚持最初的执着,从不曾有半点懈怠,为优秀而努力,为证明自己而活. 回复:茶爸爸了解他这个人!! 花了几天的时间研究了一下mybatis的源代码,觉得这 ...

  7. 十六、springboot整合Spring-data-jpa(二)之通用DAO接口与添加自定义方法

    @NoRepositoryBean:Spring Data Jpa在启动时就不会去实例化BaseRepository这个接口 1.通用接口: import org.springframework.da ...

  8. spring+mybatis通用dao层、service层的实现

    个人理解: 1.mybatis-spring.jar 提供了SqlSessionTemplate类该类可以对数据库进行CRUD操作(底层其实还是SqlSession) 2.我们可以集成SqlSessi ...

  9. 搭建Spring + SpringMVC + Mybatis框架之二(整合Spring和Mybatis)

    整合Spring和Mybatis 首先给出完整的项目目录: (1)引入项目需要的jar包 使用http://maven.apache.org作为中央仓库即可. Spring核心包,mybatis核心包 ...

随机推荐

  1. 8大排序算法总结 JS 实现

    //bubble sort ? 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 fun ...

  2. thinkphp 控制器继承

    <?php // 本类由系统自动生成,仅供测试用途 class IndexAction extends CateAction { } ?>

  3. 关于Unity中的模型描边与Shader切换(专题二)

    模型描边 1: LOL里面的模型描边效果,点击防御塔会有描边的效果,被攻击的时候模型也要描边凸显一下2: 网上可以找到模型描边的Shader,可以直接下载使用,一组第三方的Shader, 帮我们解决了 ...

  4. 【5】JVM-垃圾收集器

    通过学习了解到现在商用的JVM中的垃圾收集采用的是分代收集算法,即针对不同年代采用不同的收集算法.在JVM中,GC主要作用于堆内存中,堆内存又被划分为新生代和老年代,由于新生代对象绝大多数是朝生夕死, ...

  5. Simsimi 小黄鸡机器人最新无限制接口api simsimi机器人接口api 微信公众号

    一.什么是Simsimi? simsimi公司是提供智能服务,其中一个服务是simsimi聊天机器人服务,每天有超过百万的用户聊天,国内最大的搜索引擎——百度的产品siri使用的就是simsimi提供 ...

  6. HttpComponents-Client学习

    HttpComponents-Client 学习 官方文档:http://hc.apache.org/httpcomponents-client-ga/tutorial/html/index.html ...

  7. nodemon是个好东西

    不说话,直接上图: 安装 使用

  8. CodeCombat地牢关卡Python代码

    最近迷上了玩CodeCombat,特将地牢关卡的Python代码整理如下,供有兴趣的人学习交流探讨 1,Kithgard地牢 hero.moveRight() hero.moveDown() hero ...

  9. e812. 强制弹出菜单为重组件

    By default, Swing popup menus used by JMenu and JPopupMenu are lightweight. If heavyweight component ...

  10. win 10中打开sql server配置管理器

    转自: https://www.cnblogs.com/He-tao-yuan/p/6744412.html