MyBatis中模糊查询like的几种使用方式

1. 直接在Java代码中添加通配符的方式
String sname = "%张三%";
System.out.println(studentMapper.getStudent(sname));
<select id="getStudent" resultType="map" parameterType="String">
	SELECT sid,sname FROM student WHERE  sname like #{sname}
</select>
2. CONCAT函数的方式
String sname = "张三";
System.out.println(studentMapper.getStudent(sname));
<select id="getStudent" resultType="map" parameterType="String">
	SELECT sid,sname FROM student WHERE  sname like CONCAT('%',#{sname},'%')
</select>
3. bind标签和内置参数_parameter组合使用的方式
String sname = "张三";
System.out.println(studentMapper.getStudent(sname));
<select id="getStudent" resultType="map" parameterType="String">
	<bind name="tempStr" value="'%' + _parameter + '%'" />
	SELECT sid,sname FROM student WHERE  sname like #{tempStr}
</select>

多个参数情况:

<select id="getStudent" resultType="map">
	<bind name="tempStr" value="'%' + _parameter.get('sname') + '%'" />
	SELECT sid,sname FROM student WHERE  sname like #{tempStr}
</select>

参数是引用类型的情况:

<select id="getStudent" resultType="map" parameterType="com.buhe.co.entity.Student">
	<bind name="tempStr" value="'%' + _parameter.getSname() + '%'" />
	SELECT sid,sname FROM student WHERE  sname like #{tempStr}
</select>
4. 使用${}的方式
String sname = "张三";
System.out.println(studentMapper.getStudent(sname));
<select id="getStudent" resultType="map" parameterType="String">
	SELECT sid,sname FROM student WHERE  sname like '%${sname}%'
</select>

第四种方式会有SQL注入的风险,其他方式应该根据实际情况选择合适的方式。

posted @ 2020-12-02 11:24  布禾  阅读(571)  评论(0编辑  收藏  举报