I. Description of the problem
mybatis query no results, run the same sql database query results, as follows
This is a database record
image.png
This is mybatis check out the results, the number of records 0
image.png
This is exactly the same as the console directly to the sql query into Navicat execution result, a number of records
image.png
Second, the solution
The where
following conditions username = '${username}'
and and password = '${password}'
set to the same line
<select id="selectByUsernameAndPassword" resultMap="BaseResultMap" parameterType="string"> SELECT <include refid="Base_Column_List" /> FROM user where username = '${username}' and password = '${password}' </select>
<select id="selectByUsernameAndPassword" resultMap="BaseResultMap" parameterType="string"> SELECT <include refid="Base_Column_List" /> FROM user where username = '${username}' and password = '${password}' </select>
可以看到, 查询结果一致
image.png
三、异常分析
很多小伙伴都遇到过类似问题, 很懵逼, 难不成mybatis bug? 没, 原因可能千万种, 但根本原因基本上就一个, 那就是实际查询语句与我们看到的sql不一致, 即, sql写的有问题
再来分析一下上面这个问题, 看似xml sql没有问题, 控制台打印的sql也没问题, 但放到数据库执行结果就不一致了, 因为, xml sql两个条件换行了, mybatis实际执行的sql是这样的:
SELECT id, username, password FROM user where username = 'aaa' # '' and password = 'xxx'
并不是控制台打印的sql:
SELECT id, username, password FROM user where username = 'aaa' # '' and password = 'xxx'
查询结果自然不一致
四、总结
本文只是提供一种解决类似问题的思路, 出错原因可能不一样, 但问题关键就是实际执行的sql不一致, 才会导致mybatis和mysql查询结果不一致, 所以, 仔细点, 检查sql
Also, this paper is to test sql injection, so with the ${username}
actual use should be#{}