Mybatis動態語句,if test字串不用進行null判斷
阿新 • • 發佈:2019-03-21
描述:根據creator列進行過濾獲取image表的資料。
程式碼如下:
@Select("<script>" + " select * from image " + " <where>" + " <if test='isAllCreator != 1'> " + " creator = 1 " + " </if>" + " </where>" + "</script>") List<ImageVo> testDynamicSql(@Param("isAllCreator") String isAllCreator);
想實現一個效果,針對引數isAllCreator引數,如果傳遞1則不過濾creator列,即獲取所有creator的資料,如果不傳或傳其他值,則只獲取creator=1的資料。
經過測試發現,不用對creator引數進行null判斷,直接判斷是否等於1即可,這樣做也不會報錯。
@Test public void testDynamicSql() { List<ImageVo> imageList = new ArrayList<>(); imageList = mybatisTestMapper.testDynamicSql("0"); imageList = mybatisTestMapper.testDynamicSql(null); imageList = mybatisTestMapper.testDynamicSql("1"); Assert.assertNotNull(imageList); }
列印的sql如下:
看網上的文章,都是先進行null判斷,再進行相等判斷,如果不是親自試一下,我都懷疑自己寫錯了。
Refer:Mybatis官方文件 http://www.mybatis.org/mybatis-