动态SQL常用标签
1 where标签
1.1若满足条件的首条sql语句前面没有‘and’或者‘or’,Mybatis会自动拼接sql语句,如果满足条件的首条sql语句前面有‘and’或者‘or’,Mybatis会自动的去掉‘and’或者‘or’
1.2 当只有title不为空时,运行结果的sql语句
Preparing: select * from blog WHERE title=?
1.3 当只有anthor不为空时,运行结果的sql语句
select * from blog WHERE author=?
这里的and被自动去掉了
1.4 当title和anthor不为空时,运行结果的sql语句
select * from blog WHERE title=? and author=?
这里的and就没有被删除,很智能化
2 choose标签(类似于Java中的swtich选择结构)
3 set标签(主要用于数据更新) set标签会自动加上set并且会去除多余的‘,’
Mapper标签
update blog
title=#{title},
author=#{author},
where views=#{views}
实现
@Test
public void updateBlog(){
SqlSession sqlSession = sqlSessionFactory.getsqlSession();
blogMapper mapper = sqlSession.getMapper(blogMapper.class);
HashMap map = new HashMap();
map.put("title","微服务11");
map.put("author","小落11");
map.put("views",1000);
mapper.updateBlog(map);
sqlSession.commit();//注意增删改要提交事务
sqlSession.close();
sql结果(可以看到author后的,没有了)
update blog SET title=?, author=? where views=?