Mybatis详解动态SQL以及单表多表查询的应用

网友投稿 313 2022-07-23


目录单表查询操作参数占位符#{}和${}SQL 注入like模糊查询多表查询操作一对一多表查询一对多多表查询动态SQL使用if标签trim标签where标签set标签foreach标签

单表查询操作

参数占位符#{}和${}

#{}:相当于JDBC里面替换占位符的操作方式(#{}->“”).相当于预编译处理(预编译处理可以防止SQL注入问题)${}:相当于直接替换(desc这种关键字),但这种不能预防SQL注入

select * from userinfo where username='${name}'

${} VS #{}

${}是直接替换,#{}是预执行;${} 会存在SQL 注入问题,#{}不存在SQL注入问题

SQL 注入

UserInfo userInfo = userMapper.login("admin","' or 1='1");

mysql> select * from userinfo where username = 'admin' and password ='' or 1='1';+----+----------+----------+-------+---------------------+---------------------+-------+| id | username | password | photo | createtime          | updatetime          | state |+----+----------+----------+-------+---------------------+---------------------+-------+|  1 | admin    | admin    |       | 2021-12-06 17:10:48 | 2021-12-06 17:10:48 |     1 |+----+----------+----------+-------+---------------------+---------------------+-------+1 row in set (0.00 sec)

like模糊查询

用concat进行字符串拼接

select * from userinfo where username like concat('%',#{name},'%')

多表查询操作

一对一多表查询

一对一的多表查询:需要设置resultMap中有个association标签,property对应实体类的属性名,resultMap是关联属性的字典映射(必须要设置),columnPrefix是设置前缀,当多表查询中有相同的字段的话,就会报错

resultMap="com.example.demo.mapper.UserMapper.BaseMap"

columnPrefix="u_">

resultMap="com.example.demo.mapper.UserMapper.BaseMap"

columnPrefix="u_">

select a.*,u.id from articleinfo as a left join userinfo as u on a.uid = u.id;

select a.*,u.id as u_id ,u.username as u_username,u.password as u_password from articleinfo as a left join userinfo as u on a.uid = u.id;

一对多多表查询

collection标签,用法同association

columnPrefix="a_">

columnPrefix="a_">

select u.*,a.id a_id,a.title a_title from userinfo u left join articleinfo a on u.id=a.uid

动态SQL使用

if标签

注册分为必填和选填,如果在添加用户的时候有不确定的字段传入,就需要使用动态标签if来判断

//p是传递过来的参数名,并不是表的字段名

insert into userinfo(username,password,

photo,

state)

values(#{username},#{password},

#{p},

#{state})

trim标签

trim标签的属性

prefix:表示整个语句块,以prefix的值作为前缀suffix:表示整个语句块,以suffix的值作为后缀prefixOverrides:去掉最前面的符合条件的字符suffixOverrides:去掉最后面的符合条件的字符

insert into userinfo

username,

password,

photo,

state,

values

#{username},

#{password},

#{p},

#{stahttp://te},

where标签

where标签首先可以帮助我们生成where,如果有查询条件,那么就生成where,如果没有查询条件,就会忽略where

其次where标签可以判断第一个查询条件前面有没有and,如果有则会删除

select * from userinfo

username=#{username}

and password=#{password}

set标签

和where的使用基本一样

可以自动帮助你处理最后一个逗号,并且自动写set

update blog

title=#{newTitle},

author=#{newAuthor},

views = #{newViews}

id=#{id}

and title=#{title}

and author=#{author}

and views = #{views}

foreach标签

foreach属性:collection:参数集合的名字item:给接下来要遍历的集合起的名字open:加的前缀是什么close:加的后缀是什么separator:每次遍历之间间隔的字符串

delete from userinfo where id in

#{item}


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:Java中PrintWriter使用方法介绍
下一篇:SpringBoot返回对象时,如何将Long类型转换为String
相关文章

 发表评论

暂时没有评论,来抢沙发吧~