解決mybatis #{}無法自動添加引號的錯誤
mybatis #{}無法自動添加引號
傳入string類型時,無法自動添加引號,導致SQL將值識別為列名,導致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查詢數據庫時候報了錯
提示不知道的列,查看上方的sql語句,發(fā)現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中需要用單引號引起來,而報錯的提示信息中是沒有這個單引號的
解決辦法
解決辦法是將對應的映射文件中的${user.username} 改為 #{user.username},再次運行即可
<!-- ${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>
重新運行程序
使用 ${user.username}
使用 #{user.username}
驗證正確!
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
spring mvc @PathVariable綁定URI模板變量值方式
這篇文章主要介紹了spring mvc @PathVariable綁定URI模板變量值方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-11-11