信息发布→ 登录 注册 退出

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

发布时间:2026-01-11

点击量:
目录
  • mybatis #{}无法自动添加引号
    • 解决
  • 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语句,发现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} 

验证正确!

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

在线客服
服务热线

服务热线

4008888355

微信咨询
二维码
返回顶部
×二维码

截屏,微信识别二维码

打开微信

微信号已复制,请打开微信添加咨询详情!