1. MyBatis
模糊查询的几种写法
1.1. 在程序中拼接参数
/* 构造查询参数 */
Map<String, Object> params = new HashMap<>();
String keyword= new StringBuilder("%").append(parameter).append("%").toString();
params.put("keyword", keyword);
<select id="selectCommodity" parameterType="java.util.Map" resultMap="BaseResultMap">
SELECT c.sku_id,c.price FROM cps_commodity_info c
WHERE c.ldelete_flag = 0
<if test="keyword != null">
AND c.sku_name LIKE #{keyword}
</if>
</select>
1.2. 使用 concat()
函数
针对 MySQL
数据库的语句,采用 concat()
函数,它可以将多个字符串连接成一个字符
SELECT * FROM t1 WHERE name LIKE concat('%', #{name}, '%')
1.3. 使用 bind
标签
public UserDto selectByLike(@Param("_name") String name, @Param("_note") String note);
<select id="selectByLike">
<bind name="user_name" value="'%' + _name + '%'"/>
<bind name="user_note" value="'%' + _note + '%'"/>
SELECT * FROM t1 WHERE name LIKE #{user_name} AND note LIKE #{user_note}
</select>
如果报错如下,说明 MyBatis
版本过低,需要升级版本
Cause: org.xml.sax.SAXParseException; 必须声明元素类型 "bind"`