[mybatis]动态sql_if_where_trim判断OGNL
生活随笔
收集整理的這篇文章主要介紹了
[mybatis]动态sql_if_where_trim判断OGNL
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
OGNL
if
要求:查詢員工,要求,攜帶了哪個字段查詢條件就帶上這個字段的值
//攜帶了哪個字段查詢條件就帶上這個字段的值public List<Employee> getEmpsByConditionIf(Employee employee); <!-- public List<Employee> getEmpsByConditionIf(Employee employee);--> <select id="getEmpsByConditionIf" resultType="com.atguigu.mybatis.bean.Employee">select * from tb1_employeewhere<!--test,判斷表達式(OGNL)OGNL參照PPT或者官方文檔c:if test從參數中取值進行判斷遇見特殊符號應該去寫轉義字符;--><if test = "id!=null">id = #{id}</if><if test = "lastName!=null && lastName!=""">and last_name like #{lastName}</if> <if test="email!=null and email.trim()!=""">and email = #{email} </if><!--ognl會進行字符串與數字的轉換判斷 "0"==0 --> <if test="gender==0 or gender==1">and gender = #{gender}</if></select> @Testpublic void test04() throws IOException {SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();SqlSession sqlSession = sqlSessionFactory.openSession();try{EmployeeMapperDynamicSQL mapper = sqlSession.getMapper(EmployeeMapperDynamicSQL.class);Employee employee = new Employee(3,"%e%","jerry@qq.com",null);List<Employee> emps = mapper.getEmpsByConditionIf(employee);for (Employee emp:emps){System.out.println(emp);}}finally {sqlSession.close();}}- 查詢的時候,如果某些條件沒帶,sql的拼裝可能出現問題
解決方法,使用where
where
- 第一種方法
給where后面加上1=1,以后的條件都and xxx
- 第二種方法
mybatis使用where標簽來將所有的查詢條件包括在內。mybatis就會將where標簽中拼接的sql,多出來的and或者or去掉,where只會去掉第一個多出來的and或者or。
<!-- public List<Employee> getEmpsByConditionIf(Employee employee);--> <select id="getEmpsByConditionIf" resultType="com.atguigu.mybatis.bean.Employee">select * from tb1_employee<where><if test = "id!=null">id = #{id}</if><if test = "lastName!=null && lastName!=""">and last_name like #{lastName}</if><if test="email!=null and email.trim()!=""">and email = #{email}</if><!--ognl會進行字符串與數字的轉換判斷 "0"==0 --><if test="gender==0 or gender==1">and gender = #{gender}</if></where></select>trim
后面多出的and或者or where標簽不能解決
- prefix = “”:前綴;trim標簽體中整個字符串拼串后的結果。
- prefix給拼串后的整個字符串加一個前綴
- prefixOverrides = “”:前綴覆蓋;去掉整個字符串多余的字符
- suffix = “”:給拼串后的整個字符串加一個后綴
- suffixOverrides = “”:后綴覆蓋;去掉整個字符串后面多余的字符
總結
以上是生活随笔為你收集整理的[mybatis]动态sql_if_where_trim判断OGNL的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: [mybatis]映射文件_select
- 下一篇: 酒泡蒜的功效与作用、禁忌和食用方法