介面引數的相容性
阿新 • • 發佈:2018-12-07
需求:根據商品id或者itemName查詢商品詳情
一個定義了若干個引數的介面,當客戶端發起請求而攜帶的引數個數不確定時,為了能夠正常響應,需要對介面做一個適配處理。
1.controller層開發
@Controller @RequestMapping("/items") public class ItemsController { @Autowired private ItemsServiceImpl itemsService; //根據商品id或者itemName查詢商品詳情 @RequestMapping(value="/getItemByItemIdAndItemName",method = RequestMethod.POST) @ResponseBody public WebResult getItemByItemIdAndItemName(@RequestBody String itemsCustom)throws Exception{ WebResult result = WebResultHelper.newResult(); ItemsCustom items = JSON.parseObject(itemsCustom, ItemsCustom.class); Items item = itemsService.getItemByItemIdAndItemName(items); if(item == null){ return WebResultHelper.newErrorResult("沒有查詢到資料!"); } result.put("data",item); return result; } }
2.service層開發
//ItemsService public interface ItemsService { Items getItemByItemIdAndItemName(ItemsCustom itemsCustom) throws Exception; } //ItemsServiceImpl @Service public class ItemsServiceImpl implements ItemsService { @Autowired private ItemsMapperCustom itemsMapperCustom; @Override public Items getItemByItemIdAndItemName(ItemsCustom itemsCustom) throws Exception { return itemsMapperCustom.getItemByItemIdAndItemName(itemsCustom); } }
3.dao層開發
//mapper介面
public interface ItemsMapperCustom {
Items getItemByItemIdAndItemName(ItemsCustom itemsCustom) throws Exception;
}
//sql對映檔案 <mapper namespace="com.steven.ssm.mapper.ItemsMapperCustom" > <select id="getItemByItemIdAndItemName" parameterType="itemsCustom" resultMap="queryItems"> select * from items <where> <if test="itemId!=null and itemId!=''"> and item_id = #{itemId} </if> <if test="itemName!=null and itemName!=''"> and item_name = #{itemName} </if> </where> </select> </mapper>
//pojo類
public class Items {
private Integer itemId;
private String itemName;
private Long itemPrice;
private String itemDetail;
private Date itemCreateDate;
//get和set方法......
}
4.測試
如截圖所示,組合選擇itemId和itemName作為請求引數都可以查詢到相應的資料。