当前位置: 移动技术网 > IT编程>数据库>MSSQL > 动态SQL之(bind)标签使用的两种方式讲解

动态SQL之(bind)标签使用的两种方式讲解

2018年01月28日  | 移动技术网IT编程  | 我要评论

要润蓝正龙,环境卫生整治方案,武汉治酒驾新规

假设PERSON表中有id、name、age三个字段,现在要查询name中含有”x”的记录,通常做法如下

方式一(推荐);

首先定义DAO接口:

public List 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%”。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网