摘要: 之前有個需求,需要動態查詢某一個表的某些字段,看了下MyBatis的文檔,它可以支持的,具體做法如下:
一:Controller層
1 package boss.portal.web.controller; 2 3 import boss.base.web.controller.BaseController; 4 import boss.base.web.support.ResponseModel; 5 import boss.portal.web.service.CommonService; 6 import io.swagger.annotations.Api; 7 import io.swagger.annotations.ApiOperation; 8 import org.springframework.beans.factory.annotation.Autowired; 9 import org.springframework.web.bind.annotation.RequestMapping; 10 import org.springframework.web.bind.annotation.RequestMethod; 11 import org.springframework.web.bind.annotation.RequestParam; 12 import org.springframework.web.bind.annotation.RestController; 13 14 import java.util.List; 15 import java.util.Map; 16 17 /** 18 * 描述: 19 * <p> 20 * Author: 趙新國 21 * Date: 2018/1/31 17:48 22 */ 23 @RestController 24 @Api(value = "公共接口管理", description = "公共接口管理") 25 @RequestMapping(value = "/common") 26 public class CommonController extends BaseController { 27 28 @Autowired 29 private CommonService commonService; 30 31 @ApiOperation(value = "根據ID獲取指定實體,字段對應的返回值", notes = "根據ID獲取指定實體,字段對應的返回值") 32 @RequestMapping(value = "/get", method = RequestMethod.GET) 33 public ResponseModel get(@RequestParam(required = false) String ids, 34 @RequestParam(required = false) String tableName, 35 @RequestParam(required = false) String fields) { 36 List<Map<String, Object>> maps = commonService.get(ids, tableName, fields); 37 return renderSuccess(maps); 38 } 39 40 }
二:Service層
1 package boss.portal.web.service; 2 3 import boss.auth.user.provider.IUserProvider; 4 import com.alibaba.boot.dubbo.annotation.DubboConsumer; 5 import org.springframework.stereotype.Component; 6 7 import java.util.List; 8 import java.util.Map; 9 10 /** 11 * 描述: 12 * <p> 13 * Author: 趙新國 14 * Date: 2018/1/31 17:48 15 */ 16 @Component 17 public class CommonService { 18 19 @DubboConsumer(lazy = true) 20 private IUserProvider userProvider; 21 22 public List<Map<String,Object>> get(String ids, String tableName, String fields) { 23 List<Map<String, Object>> maps = userProvider.get(ids, tableName, fields); 24 return maps; 25 } 26 }
三: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集合, 這樣你就可以隨意查詢任何你想要的表和字段了,再也不用擔心其他人讓你加接口了!
————————————————
版權聲明:本文為CSDN博主「迷彩的博客」的原創文章,遵循CC 4.0 BY-SA版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/sxdtzhaoxinguo/java/article/details/79235998