使用注解开发
1.面向接口编程
解耦
2.用法
接口中添加注解
@Select("select * from mybatis.user")
List<User> getUserList();
配置文件中绑定接口
<mappers>
<mapper class="com.kuang.Dao.UserDao"></mapper>
</mappers>
3.本质
反射机制 底层:动态代理
4.mybatis详细流程
5.注解实现curd
自动提交事务设置
SqlSession sqlSession = sqlSessionFactory.openSession(true);
${} #{} 区别
复杂查询
多对一 (学生-老师)
1.按照查询嵌套处理
2.按照结果嵌套处理
一对多(老师-学生)
1.结果嵌套
2.查询嵌套
补充:mysql引擎 InnoDB底层原理 索引 索引优化
动态sql
1.if
2.where when
3.trim(where set)
4.sql片段
1.使用sql标签抽取公共部分
<sql id="if-title">
<if test="title != null">
title = #{title}
</if>
</sql>
2.在需要的地方使用include标签引入即可
<select id="getUserList" resultType="com.kuang.pojo.User">
select * from mybatis.user
<where>
<include refid="if-title"></include>
</where>
</select>
注意事项:最好基于单表定义sql片段,片段中不要存在where标签
5.foreach
<select id="selectPostIn" resultType="domain.blog.Post">
SELECT *
FROM POST P
WHERE ID in
<foreach item="item" index="index" collection="list"
open="(" separator="," close=")">
#{item}
</foreach>
</select>
缓存
1.一级缓存
- 一级缓存也叫本地缓存:SqlSession
- 与数据库同一次会话期间查询到的数据会放在本地缓存中
- 以后如果需要获取相同的数据,直接从缓存中拿,没必要再去查询数据库
- 日志中看出打开连接,创建连接 执行sql 关闭连接,只执行一次sql,第二次直接从缓存中拿
public void test1() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = mapper.getUserById(1);
System.out.println(user);
System.out.println("=====================================");
User user2 = mapper.getUserById(1);
System.out.println(user2 == user);
}
一级缓存失效原因:
1.查询不同东西,id=1 id=2
2.增删改操作,会刷新缓存
3.查询不同mapper.xml
4.手动清除
2.二级缓存
1.开启全局缓存 在mybatis-config中
<settings>
<setting name="cacheEnabled" value="true"/>
</settings>
2.在mapper.xml中 开启使用二级缓存
<cache eviction="FIFO" flushInterval="60000" size="512" readOnly="true"/>
我们需要将实体类序列化,否则就会报错
- 只要开启了二级缓存,在同一个Mapper下就有效
- 所有的数据都会放在一级缓存中
- 只有当前会话提交,或者关闭的时候,才会提交到二级缓存中
自定义缓存 ehcache
Ehcache是一种广泛使用的开源Java分布式缓存。主要面向通用缓存
<dependency>
<groupId>org.mybatis.caches</groupId>
<artifactId>mybatis-ehcache</artifactId>
<version>1.2.1</version>
</dependency>
<cache type="org.mybatis.caches.ehcache.EhcacheCache"/>