mybatis if標籤使用總結
阿新 • • 發佈:2020-01-07
在專案開發中,mybatis <if> 標籤使用廣泛,本文講解if標籤的兩種使用方式
其一、使用 <if> 標籤判斷某一欄位是否為空
其二、使用 <if> 標籤判斷傳入引數是否相等
具體程式碼如下
資料庫表結構和資料
實體類
package com.demo.bean; public class Commodity { private String name; private String date; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDate() { return date; } public void setDate(String date) { this.date = date; } @Override public String toString() { return "Com [name=" + name + ",date=" + date + "]"; } }
mapper層
package com.demo.mapper; import java.util.List; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; import com.demo.bean.Commodity; @Mapper public interface CommodityMapper { List<Commodity> getListByDate(Commodity commodity); List<Commodity> getListByStartDateAndEndDate(@Param("startDate")String startDate,@Param("endDate")String endDate); }
mapper.xml檔案
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" > <mapper namespace="com.demo.mapper.CommodityMapper"> <resultMap id="BaseResultMap" type="com.demo.bean.Commodity"> <id column="name" property="name" jdbcType="VARCHAR" /> <result column="date" property="date" jdbcType="VARCHAR" /> </resultMap> <select id="getListByDate" resultMap="BaseResultMap"> select * from commodity where 1 = 1 <if test="date != null and date != ''"> and date = #{date} </if> </select> <select id="getListByStartDateAndEndDate" resultMap="BaseResultMap"> select * from commodity where 1 = 1 <if test="#{startDate}.toString() != #{endDate}.toString()"> and date between #{startDate} and #{endDate} </if> </select> </mapper>
注意:mybatis 等值判斷的 tostring()方法 (上邊程式碼中第二個select中的toString()方法)
controller層
package com.demo.controller; import java.util.HashMap; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import com.demo.bean.Commodity; import com.demo.mapper.CommodityMapper; @RestController public class DemoController { @Autowired private CommodityMapper comMapper; @RequestMapping(value = "/commodity") public Object commodity() { Map<String,Object> map = new HashMap<String,Object>(); Commodity com =new Commodity(); com.setDate("2018-10-12"); map.put("res",comMapper.getListByDate(com)); return map; } @RequestMapping(value = "/between") public Object commodityBetween() { Map<String,Object>(); map.put("res",comMapper.getListByStartDateAndEndDate("2018-10-09","2018-10-13")); return map; } }
測試
1、訪問 http://localhost:9000/commodity
2、訪問 http://localhost:9000/between
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。