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>
  • 相关阅读:
    FJNU 1151 Fat Brother And Geometry(胖哥与几何)
    FJNU 1157 Fat Brother’s ruozhi magic(胖哥的弱智术)
    FJNU 1159 Fat Brother’s new way(胖哥的新姿势)
    HDU 3549 Flow Problem(最大流)
    HDU 1005 Number Sequence(数列)
    Tickets(基础DP)
    免费馅饼(基础DP)
    Super Jumping! Jumping! Jumping!(基础DP)
    Ignatius and the Princess IV(基础DP)
    Keywords Search(AC自动机)
  • 原文地址:https://www.cnblogs.com/shadoll/p/14711188.html
Copyright © 2011-2022 走看看