0. ssm框架大纲
1. Mybatis
2. 第一个Mybatis程序mybatis-01
- 搭建环境
1 | CREATE DATABASE `mybatis`; |
新建项目(创建子模块)
- 配置mybatis的核心配置文件
- 编写mybatis工具类
编写实体类
- 实体类
- Dao接口
- 接口实现类
测试
- junit测试
1 | 错误1 |
- 传递Map的情况
1 | int addUser1(Map<String, Object> map); |
1 | <!-- map只要和键值保持一致即可 --> |
1 |
|
模糊查询
Java代码执行的时候,传递通配符%%
在拼接sql中拼接通配符!
1
List<User> getUserLike(String value);
1
2
3<select id="getUserLike" resultType="com.xiaofan.pojo.User">
select * from mybatis.user where name like #{value}
</select>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public void testGetUserLike() {
SqlSession sqlSession = null;
try {
sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> userList = mapper.getUserLike("%胡%");
for (User user : userList) {
System.out.println(user);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (sqlSession != null) {
sqlSession.close();
}
}
}
3. mybatis配置解析mybatis-02
1 | import org.apache.ibatis.type.Alias; |
4. 结果集映射(解决属性名和字段名不一致的情况)mybatis-03
1 |
|
5. 日志mybatis-04
- STDOUT_LOGGING标准日志
- LOG4J
1 | # 将等级为DEBUG的日志信息输出到console和file这两个目的地,console和file的定义在下面的代码 |
测试通过!
参考链接:https://www.cnblogs.com/zhangguangxiang/p/12007924.html
https://www.cnblogs.com/yidaxia/p/5820036.html
6. 分页 mybatis-04
7. Mybatis执行流程
8. Lombok的使用(真正开发项目中不用)
- idea 安装Lombok插件
- 导包
- 用法
1 | package com.xiaofan.pojo; |
9 复杂查询环境搭建
注解和xml配合使用,对于简单的可以使用注解,复杂的使用xml
1 | CREATE TABLE `teacher` ( |
9.1. 多对一mybatis-05
- 按照嵌套查询进行处理(子查询)
1 | <select id="getStudent1" resultMap="StudentTeacher1"> |
- 按照结果嵌套处理(多表关联)
1 | <select id="getStudent2" resultMap="StudentTeacher2"> |
9.2. 一对多mybatis-06
- 按照嵌套查询进行处理(子查询)
1 | package com.xiaofan.dao; |
1 | <select id="getTeacher1" resultMap="TeacherStudent1"> |
- 按照结果嵌套处理(多表关联)
1 | <select id="getTeacher2" resultMap="TeacherStudent"> |
10. 动态Sqlmybatis-07
动态SQL就是指根据不同的条件生成不同的SQL语句
1 | create table blog ( |
- if
- choose (when, otherwise)
- trim (where, set)
- foreach
1 | package com.xiaofan.dao; |
1 |
|
1 | package com.xiaofan.dao; |
11. SQL片段
有的时候,我们可能会将一些功能的部分抽取出来,方便复用!
- 使用sql标签抽取公共部分
1 | <sql id="if-title_author"> |
- 在需要使用的地方使用include标签应用即可
1 | <select id="queryBlogIF" parameterType="map" resultType="com.xiaofan.pojo.Blog"> |
注意事项:
- 最好基于单标来定义sql片段
- 不要存在where标签
12. 缓存mybatis-08
一级缓存(默认开启)
开启日志
测试在一个Session中查询两次相同的记录
查看日志输出
缓存失效的情况
- 查询不同的东西
- 增删改查操作,可能会改变原来的数据,所以必定会刷新缓存!
- 查询不同的Mapper.xml
- 手动清除缓存
二级缓存
- 开启全局缓存
1
<setting name="cacheEnabled" value="true"/>
- 在当前Mapper中使用缓存
1
2<!-- 开启二级缓存 -->
<cache />注意事项:实体需要序列化哦!