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>
  • 相关阅读:
    C# 复制文件夹,移动文件夹
    让Base64适合在URL中使用
    修复FIREBIRD数据库
    Image.FromFile 锁文件的解决办法
    Powerbuilder 12.5 下载地址
    C# 给程序添加许可
    WIN FORM 多线程更新UI(界面控件)
    .Net WinForm 拖动控件
    SQL Server 自动增长清零
    C# 一次生成多个相同的字符
  • 原文地址:https://www.cnblogs.com/shadoll/p/14711188.html
Copyright © 2011-2022 走看看