问题引出
今天使用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}
验证正确!