if语句
1.编写接口类
List queryBlogIf(Map map);
2.编写mapper.xml
select * from blog where
title = #{title}
and author = #{author}
3.编写test
@Test
public void queryBlogIf(){
SqlSession sqlSession = MybatisUtil.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap<String, String> map = new HashMap<>();
map.put(“title”,“Mybatis如此简单”);
map.put(“author”,“狂神说”);
List blogs = mapper.queryBlogIf(map);
for (Blog blog : blogs) {
System.out.println(blog);
}
sqlSession.close();
}
注意:单纯的使用if语句的话容易在sql语句连接的过程中,比如and出现问题
Where语句
select * from blog
and title = #{title}
and author = #{author}
注意:使用where可以避免sql拼接过程中出现多写and的问题
Set语句
1.编写接口类
int updateBlog(Map map);
2.mapper.xml文件
update blog
title=#{title}
author=#{author}
where id=#{id}
3.测试
@Test
public void updateBlog(){
SqlSession sqlSession = MybatisUtil.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap<String, String> map = new HashMap<>();
map.put(“id”,“d1dafa54696e4de7b968752cb5b314c8”);
map.put(“author”,“蔡吉”);
int i = mapper.updateBlog(map);
sqlSession.close();
}
注意:使用set标签可以避免sql语句拼接过程中出现多写,的问题
Choose语句
1.编写接口类
List queryBlogChoose(Map map);
2.编写mapper.xml
select * from blog
title=#{title}
and views=#{10000}
and views=#{views}
3.编写测试
@Test
public void queryBlogChoose(){
SqlSession sqlSession = MybatisUtil.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap<Object, Object> map = new HashMap<>();
map.put(“title”,“Java如此简单”);
List blogs = mapper.queryBlogChoose(map);
for (Blog blog : blogs) {
System.out.println(blog);
}
sqlSession.close();
}
注意:choose标签的使用,类似于switch语句,只会执行满足条件的第一条sql
SQL片段
有时候可能某个 sql 语句我们用的特别多,为了增加代码的重用性,简化代码,我们需要将这些代码抽取出来,然后使用时直接调用。
提取sql片段
title = #{title}
and author = #{author}
引用sql片段
select * from blog
注意:
● 最好根据单表来定义sql片段,提高片段的可复用性
● 在sql片段中不要包括where
Foreach
1.编写接口
List queryBlogForeach(Map map);
2.编写sql语句
select * from blog
id=#{id}
3.编写测试
@Test
public void testQueryBlogForeach(){
SqlSession session = MybatisUtils.getSession();
BlogMapper mapper = session.getMapper(BlogMapper.class);
HashMap map = new HashMap();
List<Integer> ids = new ArrayList<Integer>();
ids.add(1);
ids.add(2);
ids.add(3);
map.put("ids",ids);
List<Blog> blogs = mapper.queryBlogForeach(map);
System.out.println(blogs);
session.close();
}
小结:其实动态 sql 语句的编写往往就是一个拼接的问题,为了保证拼接准确,我们最好首先要写原生的 sql 语句出来,然后在通过 mybatis 动态sql 对照着改,防止出错。多在实践中使用才是熟练掌握它的技巧