有两种方法,分别是直接字符串拼接,使用mybatis的bind函数绑定再查
方法1
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.mapper.UserMapper">
<select id="findUsersByName" parameterType="String" resultType="com.example.model.User">
select * from t_user
<where>
1 = 1
<if test="username !+ null and username != ''">
and username like concat('%',#{username},'%')
</if>
</where>
</select>
</mapper>
直接使用concat拼接字符串查询。该方法无法应对多数据库适配和sql注入恶意代码
方法2
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.mapper.UserMapper">
<select id="findUsersByName" parameterType="String" resultType="com.example.model.User">
select * from t_user
<where>
1 = 1
<if test="username !+ null and username != ''">
<bind name="pattern" value="'%' + username + '%'" />
and username like #{pattern}
</if>
</where>
</select>
</mapper>
这种方法将拼接的字符串绑定到pattern上,然后在进行查询,更加安全,防止sql注入,而且bind是mybatis提供的,可以适配多个数据库
标签:username,java,适配,查询,字符串,拼接,mybatis From: https://www.cnblogs.com/rdisheng/p/18308955