zoukankan      html  css  js  c++  java
  • mybatis 单一参数时的动态语句


     

    多参数时,可以传对象或封装成map
    1. public void getBookList(String publisher,String author){  
    2.          Map<String,Object> maps = new HashMap<String, Object>();  
    3.          maps.put("publisher", publisher);  
    4.          maps.put("author", author);  
    5.            
    6.          this.getListByEntity("getBookList",maps);  
    7. }  

     
     在CODE上查看代码片派生到我的代码片
    1. <select id="getBookList"  resultType="Book">  
    2.          SELECT * FROM bookinfo  
    3.          <where>  
    4.                    <if test="publisher != null">  
    5.                             publisher = #{publisher}  
    6.                    </if>  
    7.                    <if test="author != null">  
    8.                             AND author = #{author}  
    9.                    </if>  
    10.          </where>  
    11. </select>  

    如上写法,是没有问题的,但是当情况变得简单的时候,比如只根据作者查询图书列表的时候,当然我们可以采用和上面相同的处理方法,在方法中将参数封装到map中去。但是当我们直接使用String作为参数来查询时,就需要注意一个问题:
     
    1. public void getBookList(String author){  
    2.   
    3.          this.getListByEntity("getBookListByAuthor",author);  
    4. }  


     单一参数时,这么写会报错
    1. <select id="getBookListByAuthor" parameterType="java.lang.String" resultType="Book">  
    2.          SELECT * FROM bookinfo  
    3.          <where>  
    4.                    <if test="author != null">  
    5.                             author = #{author}  
    6.                    </if>  
    7.          </where>  
    8. </select>  

    看似没有问题,当我们运行的时候,报异常了,原因是当我们的参数为String时,在sql语句中#{author} 会去我们传进来的参数调getAuthor()方法获取参数,很明显,String没有对应的方法,所以报错了,那我们这里要如何引用author对象呢,需要采用下面的写法:

    如下写法正解

     
    1. <select id="getBookListByAuthor" parameterType="java.lang.String" resultType="Book">  
    2.          SELECT * FROM bookinfo  
    3.          <where>  
    4.                    <if test="_parameter != null">  
    5.                             AND author = #{author}  
    6.                    </if>  
    7.          </where>  
    8. </select>  

    结论:当mybatis传参为单个参数时,在sql语句中需要使用_parameter 来引用这个参数
  • 相关阅读:
    洛谷 P1525 关押罪犯(并查集|二分图判定&二分答案)
    洛谷 P1948 [USACO08JAN]Telephone Lines S(贪心+最短路)
    洛谷 P1315 观光公交(贪心+模拟)
    洛谷 P3258 [JLOI2014]松鼠的新家(树上差分)
    【NOIP2001】统计单词个数
    【洛谷习题】皇后游戏
    【洛谷习题】木棍加工
    【SDOI2008】仪仗队
    【洛谷习题】末日的传说
    【洛谷习题】又是毕业季I
  • 原文地址:https://www.cnblogs.com/siashan/p/5648847.html
Copyright © 2011-2022 走看看