天津市市建设与管理局网站,wordpress自带gallery,名字logo设计在线生成免费,山西省建设主管部门网站目录 if标签trim标签where标签set标签foreach标签 动态SQL就是根据不同的条件或需求动态地生成查询语句#xff0c;比如动态搜索条件、动态表或列名、动态排序等。
if标签
在我们填写一些信息时#xff0c;有些信息是必填字段#xff0c;有的则是非必填的#xff0c;这些… 目录 if标签trim标签where标签set标签foreach标签 动态SQL就是根据不同的条件或需求动态地生成查询语句比如动态搜索条件、动态表或列名、动态排序等。
if标签
在我们填写一些信息时有些信息是必填字段有的则是非必填的这些信息的传入就需要使⽤动态标签 if来判断了
创建这样想学生表就可以进行测试了
drop table if exists stu;
create table stu(id int primary key auto_increment,name varchar(100) ,sex varchar(10) ) default charset utf8mb4;
下面是xml语句 insert idinsert useGeneratedKeystrue keyPropertyid parameterTypecom.example.mybatisdemo.model.UserINSERT INTO stu(nameif testsex ! null, sex/if) VALUES (#{name}if testsex ! null, #{sex}/if)/insert通过结果我们发现数据已经被插入进入数据库了并且sex为空。
trim标签
如果所有字段都是⾮必填项可以考虑使⽤trim标签结合if标签对多个字段都采取动态⽣成的⽅式。 trim标签中有如下属性
prefix表示整个语句块以prefix的值作为前缀suffix表示整个语句块以suffix的值作为后缀prefixOverrides表示整个语句块要去除掉的前缀suffixOverrides表示整个语句块要去除掉的后缀
通过对前面的xml代码进行修改结果如下
insert idinsert useGeneratedKeystrue keyPropertyid parameterTypecom.example.mybatisdemo.model.UserINSERT INTO stutrim prefix( suffix) suffixOverrides,if testname ! null name,/ifif testsex ! nullsex/if/trimtrim prefixvalues ( suffix) suffixOverrides,if testname ! null#{name},/ifif testsex ! null#{sex}/if/trim/insert数据添加成功依旧只添加了姓名。
where标签
根据属性做 where 条件查询⽤户对象中属性不为 null 的都为查询条件。 写一个查询方法 RequestMapping(selectByCondition)public ListUser selectByCondition(User user){return userService.selectByCondition(user);}xml代码如下 /insertselect idselectByCondition parameterTypecom.example.mybatisdemo.model.User select id,name,sex from stuwhereif testname ! null and name#{name} /ifif test sex ! null and sex #{sex} /if/where/select根据name进行查询
where标签也可以使⽤ trim prefixwhere prefixOverridesand 替换。set标签
根据传⼊的⽤户对象属性来更新⽤户数据可以使⽤set标签来指定动态内容。 UserMapper 接⼝中修改⽤户⽅法根据传⼊的⽤户 id 属性修改其他不为 null 的属性
int updateById(User user);在xml中添加更新⽤户 sql update idupdateById parameterTypecom.example.mybatisdemo.model.User update stusetif testname ! nullname#{name},/ifif testsex ! nullsex#{sex},/if/setwhere id#{id}/update查看数据库发现修改成功
set标签也可以使⽤ trim prefixset suffixOverrides, 替换foreach标签
对集合进⾏遍历时可以使⽤该标签。foreach标签有如下属性
collection绑定⽅法参数中的集合如 ListSetMap或数组对象item遍历时的每⼀个对象open语句块开头的字符串close语句块结束的字符串separator用于指定循环迭代时元素之间的分隔符
例如一次性删除多个id对应的用户
ArticleMapper 中新增接⼝⽅法
int deleteByIds(ListInteger ids);UserMapper.xml 中新增删除 sql delete iddeleteByIdsdelete from stuwhere id inforeach collectionlist itemitem open( close) separator,#{item}/foreach/delete我们删除id为1,23的用户信息 通过查看数据库我们知道删除已经成功。
以上就是我记录的一些动态SQL如果想了解更多可前往mybatis官网查看 。