Spring Boot, MyBatis 实现动态传递表名称, 字段名称 查询数据

摘要: 之前有个需求,需要动态查询某一个表的某些字段,看了下MyBatis的文档,它可以支持的,具体做法如下:

一:Controller层

package boss.portal.web.controller;

import boss.base.web.controller.BaseController;
import boss.base.web.support.ResponseModel;
import boss.portal.web.service.CommonService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;

/**
 * 描述:
 * 

* Author: 赵新国 * Date: 2018/1/31 17:48 */ @RestController @Api(value = "公共接口管理", description = "公共接口管理") @RequestMapping(value = "/common") public class CommonController extends BaseController { @Autowired private CommonService commonService; @ApiOperation(value = "根据ID获取指定实体,字段对应的返回值", notes = "根据ID获取指定实体,字段对应的返回值") @RequestMapping(value = "/get", method = RequestMethod.GET) public ResponseModel get(@RequestParam(required = false) String ids, @RequestParam(required = false) String tableName, @RequestParam(required = false) String fields) { List> maps = commonService.get(ids, tableName, fields); return renderSuccess(maps); } }

二:Service层

 

package boss.portal.web.service;

import boss.auth.user.provider.IUserProvider;
import com.alibaba.boot.dubbo.annotation.DubboConsumer;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

/**
 * 描述:
 * 

* Author: 赵新国 * Date: 2018/1/31 17:48 */ @Component public class CommonService { @DubboConsumer(lazy = true) private IUserProvider userProvider; public List> get(String ids, String tableName, String fields) { List> maps = userProvider.get(ids, tableName, fields); return maps; } }

三:Provider层

 

@Override
	public List> get(String ids, String tableName, String fields) {
		List> maps = userMapper.get(ids, tableName, fields);
		if (maps != null && !maps.isEmpty()) {
			return maps;
		}
        return null;
	}

四:Mapper层

 

List> get(@Param("ids") String ids, @Param("tableName") String tableName, @Param("fields") String fields);

五:Mapper.xml

 


    


附录: 最后说明一下,fields代表你要查询的字段,tableName代表你要查询的表名称,ids代表你要查询的id集合, 这样你就可以随意查询任何你想要的表和字段了,再也不用担心其他人让你加接口了!

 

你可能感兴趣的:(Java后端技术,Spring,Boot,学习笔记)