MyBatis的模糊查询mapper.xml的写法

2022-07-16 08:16:27

模糊查询语句不建议使用${}的方式,还是建议采用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>
  • 作者:唯爱沁源
  • 原文链接:https://blog.csdn.net/a990914093/article/details/83743562
    更新时间:2022-07-16 08:16:27