基于springboot的框架搭建(2)统一配置mybatis的增删改方法
2017-08-13 16:51
1176 查看
配置目标
在使用mybatis操作数据库时,每次有变化的只是不同的查询方法,而像增删改等方法的sql与句基本不会有任何变化,于是我们可以将所有的mapper层封装一个baseMapper方法,在baseMapper里写上对于数据库的增删改方法。在每个mapper层中继承baseMapper,当我们需要对数据库进行增删改时,只需要调用父类中的方法就可以了不再需要重新写方法。实现了增删改的统一配置。baseMapper方法介绍
package com.spring.base; import java.util.Map; import org.apache.ibatis.annotations.DeleteProvider; import org.apache.ibatis.annotations.InsertProvider; import org.apache.ibatis.annotations.Options; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.SelectProvider; import org.apache.ibatis.annotations.UpdateProvider; public interface BaseMappper { /** * 保存数据. */ @InsertProvider(type =BaseMapperImpl.class, method = "insert") @Options(useGeneratedKeys=true,keyProperty="map.id") public int insert(@Param("table")String tableNmae,@Param("map") Map<String,Object> map); /** * 更改数据 */ @UpdateProvider(type =BaseMapperImpl.class, method = "update") public int update(@Param("table")String tableNmae,@Param("map") Map<String,Object> map); /** * 删除数据 多个 */ @DeleteProvider(type =BaseMapperImpl.class, method = "manyDelete") public int manyDelete(@Param("table")String tableNmae,@Param("x") String x); /** * 查询一个 */ @SelectProvider(type =BaseMapperImpl.class, method = "selectOne") public Map<String,Object> selectOne(@Param("table")String tableNmae,@Param("id") String id); /** * 删除数据 一个 */ @DeleteProvider(type =BaseMapperImpl.class, method = "delete") public int delete(@Param("table")String tableNmae,@Param("x") int x);
springboot与mybatis整合后支持直接注释写代码,如上方的
@DeleteProvider(type =BaseMapperImpl.class, method = “delete”)
此为mapper接口,sql的加载方式为注解加载。注解中的type元素为加载的类,method为加载的方法。
及sql语句为BaseMapperImpl类的method方法返回的字符传。
下面及为BaseMapperImpl类的method方法:
public String delete(final String tableName,final int x){ return new SQL() { { DELETE_FROM(tableName); WHERE("id = #{x}"); } } .toString(); }
参数tableName为表名, x为id,及删除tableName表中id为x的数据。
此处使用的是mybatis中拼接字符串的方法返回sql语句。
其他增加与修改方法不再一一列举,可以下载源码查看。
项目源码
总结
使用统一配置Mappper 层增删改方法可以有效的加快在开发过程中的开发进度。项目源码
相关文章推荐
- SSM基于注解配置Spring4.1.6、springMVC4.1.6、mybatis3.2.8的maven框架搭建
- 基于springboot搭建dubbo框架(注解和xml配置两种方式)
- SpringBoot、MyBatis配置多数据源XML方法
- java 搭建基于springboot的ssm(spring + springmvc + mybatis)的maven项目
- Spring3.2.0-mybatis3.2.0 基于全注解搭建的后台框架-基础版
- 基于springboot的框架搭建(3)取消bean对象使用hashmap代替
- spring mybatis 框架集成之applicationContext.xml配置方法
- Spring+SpringMvc+Mybatis框架集成搭建教程二(依赖配置及框架整合)
- IDEA搭建springboot+mybatis 的web框架附日志管理
- 基于Spring Boot不同的环境使用不同的配置方法
- Spring Boot 与 mybatis配置方法
- Spring3.2.0-mybatis3.2.0 基于全注解搭建的后台框架-基础版
- IntelliJ IDEA 搭建基于Maven 的SSM(一)(spring,springMvc,Mybatis)框架整合
- Spring+Spring MVC+MyBatis 框架搭建 遇到问题及解决方法
- 详解MyEclipse中搭建spring-boot+mybatis+freemarker框架
- [置顶] maven web基于spring+mybatis+springmvc框架搭建选课网站系统
- 基于maven的spring+mybatis+springMVC框架搭建
- Spring+Mybatis+Mysql搭建分布式数据库访问框架的方法
- 在IntelliJ IDEA下搭建基于Maven的spring boot框架
- spring-boot配置MySQL数据库连接、Hikari连接池、和Mybatis的简单方法