温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

MyBatis中如何实现模糊查询mapper.xml

发布时间:2021-09-30 13:34:31 来源:亿速云 阅读:353 作者:小新 栏目:开发技术

这篇文章主要介绍MyBatis中如何实现模糊查询mapper.xml,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!

    MyBatis模糊查询mapper.xml的写法

    模糊查询语句不建议使用${}的方式,还是建议采用MyBatis自带的#{}方式,#{}是预加载的方式运行的,比较安全,${}方式可以用但是有SQL注入的风险!!!

    1.直接传参

    在controller类中

    String id = "%"+ id +"%";
    String name = "%"+ name +"%";
    dao.selectByIdAndName(id,name);

    在mapper.xml映射文件中

    <select>
        select * from table wherer id=#{id} or name like #{name}
    </select>

    2.针对MySQL数据库的语句

    采用concat()函数,它可以将多个字符串连接成一个字符

    <select>
        select * from table where name like concat('%',#{name},'%')
    </select>

    3.适用于所有数据库的则采用MyBatis的bind元素

    public xx selectByLike(@Param("_name") String name);
    <select id="selectByLike">
        <bind name="user_name" value="'%' + _name + '%'"/>
        select * from table where name like #{user_name}
    </select>

    其中_name为传递进来的参数,bind元素的value属性将传进来的参数和 '%' 拼接到一起后赋给name属性的user_name,之后可以在select语句中使用user_name这个变量。

    bind元素也支持传递多个参数

    public xx 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 table where name like #{user_name} and note like #{user_note}
    </select>

    MyBatis在xml中模糊查询的常用的3种方式

    <!-- ******************** 模糊查询的常用的3种方式:********************* -->
        <select id="getUsersByFuzzyQuery" parameterType="User" resultType="User">
            select <include refid="columns"/> from users
            <where>
                <!--
                    方法一: 直接使用 % 拼接字符串
                    注意:此处不能写成  "%#{name}%" ,#{name}就成了字符串的一部分,
                    会发生这样一个异常: The error occurred while setting parameters,
                    应该写成: "%"#{name}"%",即#{name}是一个整体,前后加上%
                -->
                <if test="name != null">
                    name like "%"#{name}"%"
                </if>
                <!--方法二: 使用concat(str1,str2)函数将两个参数连接 -->
                <if test="phone != null">
                    and phone like concat(concat("%",#{phone}),"%")
                </if>
                <!--方法三: 使用 bind 标签,对字符串进行绑定,然后对绑定后的字符串使用 like 关键字进行模糊查询 -->
                <if test="email != null">
                    <bind name="pattern" value="'%'+email+'%'"/>
                    and email like #{pattern}
                </if>
            </where>
        </select>

    以上是“MyBatis中如何实现模糊查询mapper.xml”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注亿速云行业资讯频道!

    向AI问一下细节

    免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

    AI