解決mybatis #{}無法自動添加引號的錯誤
mybatis #{}無法自動添加引號
傳入string類型時,無法自動添加引號,導(dǎo)致SQL將值識別為列名,導(dǎo)致SQL失敗
解決
使用map類型代替string的傳值
如
Map<String, String> map = new HashMap<>(2); map.put("userName", userName); return userMapper.selectUserByName(map);
<select id="selectUserByName" parameterType="map" resultType="userDO"> ? ? select ? ? ? ? user_id as userId, ? ? ? ? user_name as userName, ? ? ? ? user_password as userPassword, ? ? ? ? user_level as userLevel, ? ? ? ? user_gmt_create as userGmtCreate, ? ? ? ? user_gmt_modified as userGmtModified ? ? from user ? ? where user_name = #{userName} </select>
mybatis #{}與${} 單引號
今天使用mybitas查詢數(shù)據(jù)庫時候報了錯
提示不知道的列,查看上方的sql語句,發(fā)現(xiàn)sql的語法錯了,where查詢的條件的值少了單引號
-- 錯誤提示 select `uid`, `username`, `password`, `time` from blogs_user where username = wu; -- 正確的sql語句 select `uid`, `username`, `password`, `time` from blogs_user where username = 'wu';
這時問題就很明顯了,就是字符串在sql中需要用單引號引起來,而報錯的提示信息中是沒有這個單引號的
解決辦法
解決辦法是將對應(yīng)的映射文件中的${user.username} 改為 #{user.username},再次運(yùn)行即可
<!-- ${user.username} --> <select id="xxx" parameterType="wu.bean.User" resultMap="BaseResultMap"> select <include refid="base_column_list"/> from blogs_user where username = ${user.username}; </select> <!-- #{user.username} --> <select id="xxx" parameterType="wu.bean.User" resultMap="BaseResultMap"> select <include refid="base_column_list"/> from blogs_user where username = ${user.username}; </select>
驗證
如果要驗證是否正確,思路是將成的sql 語句打印出來,因此需要在mybatis-config.xml中加入<setting name="logImpl" value="STDOUT_LOGGING"/>
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <settings> <!-- 打印查詢語句 --> <setting name="logImpl" value="STDOUT_LOGGING"/> .... </settings> <typeAliases> .... </typeAliases> <mappers> ..... </mappers> </configuration>
重新運(yùn)行程序
使用 ${user.username}
使用 #{user.username}
驗證正確!
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
spring mvc @PathVariable綁定URI模板變量值方式
這篇文章主要介紹了spring mvc @PathVariable綁定URI模板變量值方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-11-11Java實現(xiàn)經(jīng)典角色扮演偵探游戲游戲的示例代碼
這篇文章主要介紹了如何利用Java語言自制一個偵探文字游戲—《角色扮演偵探》,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編學(xué)習(xí)一下2022-02-02SpringCloud整合分布式服務(wù)跟蹤zipkin的實現(xiàn)
這篇文章主要介紹了SpringCloud整合分布式服務(wù)跟蹤zipkin的實現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-09-09