(1)搭建数据库
create table blog1(
id varchar(50) not null ,
title varchar(100) not null ,
author varchar(30) not null ,
create_time datetime not null ,
views int(30) not null
)
insert into mybatis.blog1 values ('1','我的第四次学习','鸭鸭','2022-04-23 10:12:58',11234);
insert into mybatis.blog1 values ('2','我的第四次学习','鸭鸭','2022-04-23 10:12:58',11234);
insert into mybatis.blog1 values ('3','我的第四次学习','鸭鸭','2022-04-23 10:12:58',11234);
insert into mybatis.blog1 values ('4','我的第四次学习','鸭鸭','2022-04-23 10:12:58',11234);
(2)创建对应实体类
(3)创建对应方法接口
(4)测试类
二、if 语句select * from mybatis.blog1 --> and title = #{title} and author = #{author}
测试类;
@Test
public void test01(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap map = new HashMap();
// map.put("title","我的第1次学习");
map.put("author","狗狗");
List blogList = mapper.blogIF(map);
for (Blog blog : blogList){
System.out.println(blog);
}
sqlSession.close();
}
当 title 和 author 都为空时则 查询全表,如果填入则在Sql语句 select * from mybatis.blog1 where 后面加上title 和 author 的条件;
二、choose 语句当我们不想用到全部的查询条件,只想选择其中一个,选择choose标签可以解决此类问题;类似于Java中的Switch 语句。
select * from mybatis.blog1 title = #{title}; author = #{author}; and views = #{views};
测试类;
@Test
public void test02(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap map = new HashMap();
// map.put("title","我的第2次学习");
map.put("views","99999");
List blogList = mapper.blogChoose(map);
for (Blog blog : blogList){
System.out.println(blog);
}
sqlSession.close();
}
当有一个满足条件后面的将不再执行;
三、set 语句update mybatis.blog1 where id = #{id} title = #{title}, author = #{author}
注意;set 是用 “,” 隔开的
测试类;
@Test
public void test03(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap map = new HashMap();
map.put("title","第二次学习");
map.put("author","老虎");
map.put("id","1");
int num = mapper.updateBlog(map);
sqlSession.close();
}
四、Foreach 语句
遍历集合;
select * from mybatis.blog1
id = #{id}
测试类;
@Test
public void test04(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap map = new HashMap();
ArrayList ids = new ArrayList<>();
ids.add(1);
ids.add(2);
ids.add(3);
map.put("ids",ids);
List blogList= mapper.blogForeach(map);
for (Blog blog:blogList){
System.out.println(blog);
}
sqlSession.close();
}
五、Sql 片段
有时部分代码段频繁出现,为了提高代码的复用性,简化代码;我们将这些代码抽取出来,然后使用;
例如;
sql代码块部分:and title = #{title} -->and author = #{author}



