解决mybatis|解决mybatis #{}无法自动添加引号的错误

目录

  • mybatis #{}无法自动添加引号
    • 解决
  • mybatis #{}与${} 单引号
    • 解决办法
    • 验证

mybatis #{}无法自动添加引号 传入string类型时,无法自动添加引号,导致SQL将值识别为列名,导致SQL失败

解决
使用map类型代替string的传值

Map map = new HashMap<>(2); map.put("userName", userName); return userMapper.selectUserByName(map);

selectuser_id as userId,user_name as userName,user_password as userPassword,user_level as userLevel,user_gmt_create as userGmtCreate,user_gmt_modified as userGmtModifiedfrom userwhere user_name = #{userName}


mybatis #{}与${} 单引号 【解决mybatis|解决mybatis #{}无法自动添加引号的错误】今天使用mybitas查询数据库时候报了错
解决mybatis|解决mybatis #{}无法自动添加引号的错误
文章图片

提示不知道的列,查看上方的sql语句,发现sql的语法错了,where查询的条件的值少了单引号
-- 错误提示select `uid`, `username`, `password`, `time`from blogs_userwhere username = wu; -- 正确的sql语句select `uid`, `username`, `password`, `time`from blogs_userwhere username = 'wu';

这时问题就很明显了,就是字符串在sql中需要用单引号引起来,而报错的提示信息中是没有这个单引号的

解决办法
解决办法是将对应的映射文件中的${user.username} 改为 #{user.username},再次运行即可
selectfrom blogs_userwhere username = ${user.username}; selectfrom blogs_userwhere username = ${user.username};


验证
如果要验证是否正确,思路是将成的sql 语句打印出来,因此需要在mybatis-config.xml中加入
.............

重新运行程序
使用 ${user.username}
解决mybatis|解决mybatis #{}无法自动添加引号的错误
文章图片

使用 #{user.username}
解决mybatis|解决mybatis #{}无法自动添加引号的错误
文章图片

验证正确!
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

    推荐阅读