org.springframework.jdbc.BadSqlGrammarException


這個錯誤在MyBatis中實際上很常見,就是SQL寫錯了。通常通過先在MySQL命令行執行一遍sql看有沒有錯誤,如果有就更改,沒有就基本上可以用了。
注意,我說的基本上可用並不代代表完全可用,比如今天我就遇到一個非常惡心的問題。

sql代碼如下(這句sql經過在mysql命令行中測試,能夠獲取數據,完全沒有問題):

<select id="categoreListInfo" resultMap="BaseResultMap">
    SELECT
    term.term_id,term.name,
    term.slug,tax.taxonomy,tax.description,tax.count FROM wp_terms AS term
    LEFT JOIN wp_term_taxonomy AS tax ON(term.term_id=tax.term_id)
    <where>
        <if test="name != null or name != ''">
            and term.name like concat('%', #{name}, '%')
        </if>
        <if test ="taxonomy != null or  taxonomy !=''">
            and tax.taxonomy = #{taxonomy}
        </if>
    </where>
    limit #{start},#{size}
</select>

但是我用如下單元測試就出現了問題,單元測試代碼如下:

@Test
public void testPageListInfo() throws Exception {
    
    Map<String,Object> paramMap = new HashMap<String,Object>();
    paramMap.put("name", "");
    paramMap.put("start","0");
    paramMap.put("size", "10");
    paramMap.put("taxonomy", "post_tag");
    
    
    List<Terms> list = termService.categoreListInfo(paramMap);
    
    int count = termService.categoryTotalCount(paramMap);
    
    System.out.println("總數:"+count);
    
    for (Terms terms : list) {
        
        System.out.println("terms:"+terms.getName());
        
        List<TermTaxonomy> taxList = terms.getTax();
        
        for (TermTaxonomy termTaxonomy : taxList) {
            
            System.out.println("tax:"+termTaxonomy.getDescription()+"||"+termTaxonomy.getTaxonomy());
        }
    }
    
}

單元測試並沒有寫錯,錯的是參數問題,關鍵點是這個:

paramMap.put("start","0");
paramMap.put("size", "10");

在mysql中limit兩個參數實際為int類型,非字符串,而我此時在此傳字符串,所以就出現org.springframework.jdbc.BadSqlGrammarException,說sql有問題。

所以大家切記在命令行執行sql以后,千萬別掉以輕心,還是要細心,否則不必要的錯誤非常讓人糟心。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM