Mybatis在註解上如何實現動態SQL
在註解上實現動態SQL
使用Mybatis註解實現sql語句,但是有些時候有些字段是空的,這時候這個空的字段就要從條件查詢語句中刪除,這個時候就需要用到動態Sql。
註解的動態語句支持以下
trim
where
set
foreach
if
choose
when
otherwise
bind
@Select({"<script> " + "select * from t_user " + "where 1=1 " + "<if test='userId!=null'> and id = #{userId}</if> " + "</script>"})
要加上標簽就可以實現條件判斷
但是在無法使用大於號 、小於號,那如何解決這問題呢,其實隻要把大於號、小於號轉義即可
註解方式動態sql寫法和註意事項
@Select({"<script>" + "select * from tb_examine" + "<where> 1 = 1" + "<if test = \" employeeId != null and employeeId != '' \"> AND employee_id = #{employeeId} </if>" + "<if test = \" gradeId != null and gradeId != '' \"> AND grade_id = #{gradeId} </if>" + "<if test = \" year != null and year != '' \"> AND year like #{year} </if>" + "<if test = \" (statrMonth != null and statrMonth != '') and (endMonth == null or endMonth == '') \"> AND month >= #{statrMonth} </if>" + "<if test = \" (statrMonth == null or statrMonth == '') and (endMonth != null and endMonth != '') \"> AND month <= #{endMonth} </if>" + "<if test = \" (statrMonth != null and statrMonth != '') and (endMonth != null and endMonth != '') \">AND month >= #{statrMonth} AND month <= #{endMonth} </if>" + "</where>" + "</script>"}) public List<Examine> getName(Examine examine);
判斷字符串為空串 用單引號
大於等於用
小於等於用
以上為個人經驗,希望能給大傢一個參考,也希望大傢多多支持WalkonNet。
推薦閱讀:
- 關於Mybatis動態sql中test的坑點總結
- MyBatis中關於SQL的寫法總結
- Mybatis結果集映射與生命周期詳細介紹
- MyBatis在註解上使用動態SQL方式(@select使用if)
- MySQL優化之如何寫出高質量sql語句