zoukankan      html  css  js  c++  java
  • mybatis中模糊查询的实现方式

    方式一.

      手动将模糊查询的参数带上%%

    //在配置文件设参数接收方式为#{}
    <select id="getUserListByName" resultMap="resultMap">
        select * from user where name like #{name}
    </select>
    
    //参数直接把%%带上
    public List<User> getUserListByName(String name){
        return userDao.getUserListByName("%张三%");
    }

      这个方式运行正常,但这样把%%带到参数上不太方便,容易出错。

    方式二.

      方式一中的%是由参数携带的,那为何不直接在配置文件中直接写匹配符%?

    <select id="getUserListByName" resultMap="resultMap">
        select * from user where name like %#{name}%
    </select>

      这样很明显的错误就是漏写双引号。那再加上试试。

    <select id="getUserListByName" resultMap="resultMap">
        select * from user where name like '%#{name}%'
    </select>

      如果加上双引号,仍然出错,因为加双引号就会把它当成字符串,在字符串中#{}是不能识别的,需要改成${}这种形式。

    <select id="getUserListByName" resultMap="resultMap">
        select * from user where name like '%${name}%'
    </select>

      这样执行就正常了。#{}和${}的区别,#{}相当于是在对应的位置添加一个占位符,编译处理时才会把参数添加到对应位置。而${}是直接将参数拼接到sql上的,这种方法可能会引起sql注入问题。

    方式三.

      可以通过mysql的concat函数来进行处理。

    <select id="getUserListByName" resultMap="resultMap">
        select * from user where name like concat('%',#{name},'%')
    </select>

    方式四.

      同样是使用concat函数,这里使用${},要注意带上双引号。

    <select id="getUserListByName" resultMap="resultMap">
        select * from user where name like concat('%','${name}','%')
    </select>
  • 相关阅读:
    Ubuntu修改root默认密码
    2012年总结
    阿朵,网上传得沸沸扬扬,我们还是听听她的歌吧!
    人力资源开发网站
    关于ant
    ObjectSpaces
    firefox plugs
    xpi插件的安装
    年关
    https的资源
  • 原文地址:https://www.cnblogs.com/shadoll/p/14711188.html
Copyright © 2011-2022 走看看