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>

 

posted @ 2021-07-19 10:46  shine声  阅读(248)  评论(0编辑  收藏  举报