软件编程
位置:首页>> 软件编程>> java编程>> 解决mybatis #{}无法自动添加引号的错误

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

作者:Kevinten10  发布时间:2023-09-21 11:45:02 

标签: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查询数据库时候报了错

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

提示不知道的列,查看上方的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}

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

使用 #{user.username} 

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

验证正确!

来源:https://blog.csdn.net/wsh596823919/article/details/81113119

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com