小吃店网站建设,开发公司交的农民工工资保证金可以退还吗,牡丹江住房和城乡建设厅网站,网站怎么做直播功能吗动态 SQL \if标签\trim标签\where标签\set标签\foreach标签 动态 sql 是 Mybatis 的强⼤特性之⼀#xff0c;能够完成不同条件下不同的 sql 拼接。
if标签
前端用户输入时有些选项是非必填的, 那么此时传到后端的参数是不确… 动态 SQL \if标签\trim标签\where标签\set标签\foreach标签 动态 sql 是 Mybatis 的强⼤特性之⼀能够完成不同条件下不同的 sql 拼接。
if标签
前端用户输入时有些选项是非必填的, 那么此时传到后端的参数是不确定的, 比如:
那如果在添加⽤户的时候有不确定的字段传⼊程序应该如何实现呢
这个时候就需要使⽤动态标签 来判断了⽐如添加的时候性别 country 和 city 为⾮必填字段具体实现如下 insert idinsert parameterTypecom.example.springboot3.model.Userinsert into userinfo (username, phone, email,if testcountry ! nullcountry,/ifif testcity ! nullcity,/if) values (#{username},#{phone}, #{email},if testcountry ! null#{country},/ifif testcity ! null#{city},/if)/insert这样当 test 中判断结果为 true 时才会拼接上去.
trim标签
上面的插⼊⽤户功能country 和 city 是选填项如果所有字段都是选填项就考虑使⽤ trim 标签结合 if 标签对多个字段都采取动态⽣成的⽅式。
trim标签中有如下属性
prefix表示整个语句块以prefix的值作为前缀suffix表示整个语句块以suffix的值作为后缀prefixOverrides表示整个语句块要去除掉的前缀suffixOverrides表示整个语句块要去除掉的后缀 insert idinsert parameterTypecom.example.springboot3.model.Userinsert into userinfotrim prefix( suffix) suffixOverrides,if testusername ! nullusername,/ifif testphone ! nullphone,/ifif testemail ! nullemail,/ifif testcountry ! nullcountry,/ifif testcity ! nullcity,/if/trimtrim prefixvalues ( suffix) suffixOverrides,if testusername ! null#{username},/ifif testphone ! null#{phone},/ifif testemail ! null#{email},/ifif testcountry ! null#{country},/ifif testcity ! null#{city},/if/trim/insert在以上 sql 动态解析时会对 trim 部分做如下处理
基于 prefix 配置开始部分加上 (第二个 trim 开始部分会加上 values (基于 suffix 配置结束部分加上 )多个 if 组织的语句都以 , 结尾在最后拼接好的字符串还会以 , 结尾会基于 suffixOverrides 配置去掉最后⼀个 ,
where标签
主要作用: 实现查询中的 where 替换, 可以实现无条件查询. 若存在查询条件会生成 where 的 sql 查询, 并且 where 标签可以去除最前面的 and 如果 where 中的所有参数为空, 那么 where 的 sql 就不会生成, 直接就是无条件查询
比如根据 国家(地区) 或者城市进行搜索, 根据属性做 where 条件查询国家(地区) 或者城市不为 null 的作为查询条件。
UserMapper 接口中的方法:
ListUser selectByCondition(String country, String city);UserMapper.xml 中的实现: select idselectByCondition resultTypecom.example.springboot3.model.Userselect * from userinfowhereif testcountry ! nulland country#{country}/ifif testcity ! nulland city#{city}/if/where/select以上where标签也可以使⽤ trim prefix“where” prefixOverrides“and” 替换。
set标签
主要作用: 进行修改操作时, 配合 if 处理非必须传输的参数, 特点是自动去除最后一个 ,
根据传⼊的⽤户对象属性来更新⽤户数据可以使⽤标签来指定动态内容。
UserMapper 接口中的方法:
int updateById(User user);UserMapper.xml 中的实现: update idupdateByIdupdate userinfosetif testusername ! nullusername#{username},/ifif testphone ! nullphone#{phone},/ifif testemail ! nullemail#{email},/ifif testcountry ! nullcountry#{country},/ifif testcity ! nullcity#{city},/if/setwhere id#{id}/updateset标签也可以使⽤ trim prefix“set” suffixOverrides“,” 替换。
foreach标签
对集合进⾏遍历时可以使⽤该标签。
foreach标签有如下属性
collection绑定⽅法参数中的集合如 ListSetMap或数组对象item遍历时的每⼀个对象open语句块开头的字符串close语句块结束的字符串separator每次遍历之间间隔的字符串
比如根据用户 id 删除用户:
UserMapper 接口中的方法:
int deleteByIds(ListInteger ids);UserMapper.xml 中的实现: delete iddeleteByIdsdelete from userinfo where id inforeach collectionids open( itemitem close) separator,#{item}/foreach/delete好啦 以上就是对 Mybatis 动态 SQL 的讲解希望能帮到你 评论区欢迎指正 !