您的位置:首页 > 编程语言 > Java开发

基于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 层增删改方法可以有效的加快在开发过程中的开发进度。

项目源码

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  框架 mybatis