mybatis查詢字段動態變換與根據參數數組排序


@ResponseBody
    public ResponseEntity<Map<String, Object>> paramProduct(String fieldListStr, String spuCode) {
        Map<String, Object> returnMap = new HashMap<>();
        try {
            Map<String, Object> paramMap = new HashMap<>();
            if (StringUtils.isBlank(fieldListStr) || StringUtils.isBlank(spuCode)) {
                returnMap.put("status", 0);
                returnMap.put("msg", "請求參數不合法");
                return new ResponseEntity(returnMap, HttpStatus.OK);
            }
            List<String> fieldList = Arrays.asList(fieldListStr.split(","));
            paramMap.put("fieldList", fieldList);
            paramMap.put("spuCode", "'" + spuCode + "'");
            Map<String, Object> resultMap = productManageService.paramProduct(paramMap);
            returnMap.put("status", 1);
            returnMap.put("msg", "success");
            returnMap.put("data", resultMap);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            returnMap.put("status", 0);
            returnMap.put("msg", "系統異常");
        }
        return new ResponseEntity(returnMap, HttpStatus.OK);
    }

  controller中fieldListStr是需要查詢的字段,spuCode是判斷條件,需要注意的是spuCode需要用單引號括起來,否則查詢會報錯!

<select id="paramProduct" resultType="Map" parameterType="java.util.Map" statementType="STATEMENT" >
    select      
    <foreach collection="fieldList" item="field" separator=",">
         ${field}
      </foreach>
     from table where 1=1 
    <if test="spuCode != null and spuCode != ''" >
        and spu_code = ${spuCode}
      </if>
  </select>

  對應的腳本寫法,注意statementType="STATEMENT"這個需要配置,還是對應參數獲取不適用#,需要換為$

 

mybatis中,如果有需要根據某個list數組中的順序進行排序的話,可以如下:

<select id="queryProductListOrder" resultMap="BaseResultMap" parameterType="java.util.Map">
	select pro_id,name,price,cover,unit,clicks,cut_price,cut_unit,card_price, card_ship_type
	from sb_product_statistics 
	where 1=1 
	<if test="prdIdList != null and prdIdList.size > 0" >
		and pro_id in   
		<foreach collection="prdIdList" index="index" item="productId" open="(" separator="," close=")">
	         #{productId}
	     </foreach>
	     order by field(pro_id,<foreach collection="prdIdList" index="index" item="productId"  separator="," >
	         #{productId}
	     </foreach>)
     </if>
  </select>

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM