摘要: 之前有个需求,需要动态查询某一个表的某些字段,看了下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;
/**
* 描述:
* <p>
* 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<Map<String, Object>> 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;
/**
* 描述:
* <p>
* Author: 赵新国
* Date: 2018/1/31 17:48
*/
@Component
public class CommonService {
@DubboConsumer(lazy = true)
private IUserProvider userProvider;
public List<Map<String,Object>> get(String ids, String tableName, String fields) {
List<Map<String, Object>> maps = userProvider.get(ids, tableName, fields);
return maps;
}
}
三:Provider层
@Override
public List<Map<String, Object>> get(String ids, String tableName, String fields) {
List<Map<String, Object>> maps = userMapper.get(ids, tableName, fields);
if (maps != null && !maps.isEmpty()) {
return maps;
}
return null;
}
四:Mapper层
List<Map<String,Object>> get(@Param("ids") String ids, @Param("tableName") String tableName, @Param("fields") String fields);
五:Mapper.xml
<!-- 根据指定ID获取指定数据表的指定字段的数据集 -->
<select id="get" resultType="java.util.Map" statementType="STATEMENT" >
select ${fields} from ${tableName} where id in ( ${ids} )
</select>
附录: 最后说明一下,fields代表你要查询的字段,tableName代表你要查询的表名称,ids代表你要查询的id集合, 这样你就可以随意查询任何你想要的表和字段了,再也不用担心其他人让你加接口了!