目录
动态SQL符号if标签(逻辑判断)where标签(SQL判断)choose,when,otherwise(Java中的switch)set (sql修改)trim(截断 添加)bind(模糊查询)foreach(循环)sql (复用)
动态SQL
根据不同的条件执行不同的SQL命令,称为动态SQL在Mybatis中的Mapper.xml中添加逻辑判断
符号
在Mybatis中,运算符号会被转义成字节码,所以要用代码符号
<<=>>=&'"<<=>>=&'"
if标签(逻辑判断)
成立则执行,不成立则不执行
select * from log where 1=1
and accin = #{accin}
and accout = #{accout}
where标签(SQL判断)
当编写where标签时,如果内容中第一个是and去掉第一个and如果
select * from log
and accin = #{accin}
and accout = #{accout}
choose,when,otherwise(Java中的switch)
只要有一个成立,其他都不执行如果title和content都不为null或都不为""
生成的sql中只有where title=? 如果title和content都为null或都为""
生成的sql中只有where owner = “owner1”
select * from t_blog where 1=1
and title = #{title}
and content = #{content}
and owner = "owner1"
set (sql修改)
作用:去掉最后一个逗号作用:如果
update log
id=#{id},
accIn = #{accIn},
accOut = #{accOut},
where id=#{id}
trim(截断 添加)
prefix 在前面添加内容suffix 在后面添加内容prefixOverrides 去掉前面内容suffixOverrides 去掉后面内容
update log
a=a,
where id=100
bind(模糊查询)
作用:给参数重新赋值场景:模糊查询 | 在原内容前或后添加内容
select * from log
and title like #{title}
and money = #{money}
foreach(循环)
循环参数内容,还具备在内容的前后添加内容,还具备添加分割符功能适用场景:in查询 | 批量新增(mybatis中foreach效率大幅度降低)
如果希望批量新增,SQL命令
openSession()必须指定
//底层的JBDC的PrepareStatement.addBatch()factpry.openSession(ExecuteorType.BATCH); 属性
collection:添加要遍历的集合item:迭代变量,循环内使用#{迭代变量名}来获取内容open:循环后左侧添加的内容close:循环后右侧添加的内容separator:添加每次遍历尾部追加的分割符
select * from log where id in
#{a}
sql (复用)
某些SQL片段如果需要复用,可以使用
id,accin,accout,money
在
select