您的位置:首页 > 数据库

22、动态SQL之<bind>标签使用

2018-01-24 00:17 204 查看
假设PERSON表中有id、name、age三个字段,现在要查询name中含有”x”的记录,通常做法如下

方式一(推荐);

首先定义DAO接口:

public List<Person> getPersons(@Param("pattern")String pattern);


定义dao接口对应的mapper文件:

<select id="getPersons" resultType="com.lzj.mybaits.bean.Person">
select * from PERSON
<if test="pattern != null">
where name like #{pattern}
</if>
</select>


比如要查name中含有”x”的记录,通常要传入接口的字符串就要为: “%x%”,然后传入mapper文件中的pattern的值就为 “%x%”,所以sql语句就变为:

select * from PERSON where name like  "%x%"


方式二(通过
<bind>
标签实现):

还是实现上面示例的功能,DAO接口不变,对应的mapper文件变为:

<select id="getPersons" resultType="com.lzj.mybaits.bean.Person">
select * from PERSON
<!--接口传入的值在pattern变量中,然后把传入的值拼接成"'%'+pattern+'%'"形式,放入namePattern参数中-->
<bind name="namePattern" value="'%'+pattern+'%'"/>
<if test="namePattern!= null">
where name like #{namePattern}
</if>
</select>


此例中,如要查name中含有”x”的记录,只需要传入接口中字符串为“x”即可,因为在mapper文件中,通过 标签把传入的参数拼接成了“%x%”。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: