Mybatis
1.介绍
(1)官网:https://mybatis.org/mybatis-3/zh/index.html 中文网:http://www.mybatis.cn
(2)历史:原名iBatis是apache的一个开源免费项目,2010年迁移到了 google code 改名 MyBatis,2013年迁移到了Github上
(3)用途:数据访问框架
① 底层是对JDBC的封装
② 使用了ORM思想实现了对结果集的封装:Object Relational Mapping对象关系映射
(4)下载jar或maven依赖
2.简单使用(单表)
(1)配置方式:
① 调用接口方法
② 使用映射
③ 注解方式
(2)增
① sqlSession默认关闭了jdbc的自动提交功能,需要开启提交功能
1)factory.openSession(true)开启自动提交
2)sqlSession.commit()手动提交
② 标签没有resultType属性,默认返回值是int
③ openSession()时创建sqlSession的会同时创建一个Transaction事务对象,autoCommit是false,如果出现异常,用sqlSession.rollback()回滚事务
④ 返回自动增长的主键
1)注解:
@Insert(“insert into admins(account,password,status) values(#{account},#{password},#{status})”)
@Options(useGeneratedKeys=true, keyProperty=“id”, keyColumn=“id”)
public int insertAdmin(Admin admin);
2)配置:
insert into t_blog(title,content) value(#{title},#{content})
3)返回给了添加时的对象
(3)删
(4)改
(5)查
① selectOne(),selectList(),selectMap
3.配置 mybatis-config.xml
(1)引入配置文件:<properties resource=dbconfig.properties”/>
(2)配置信息
<settings>
<setting name="cacheEnabled" value="false"/>
</settings>
(3)起别名
① 一个一个配置
<typeAliases>
<typeAlias alias="clz" type="com.srzx.mybatis.entity.Classes" />
</typeAliases>
② 配置整个包
<typeAliases>
<package name="com.srzx.mybatis.entity"/>
</typeAliases>
(4)环境
① 环境一
1)事务
a.JDBC:事务管理使用JDBC原生事务管理方式
b.MANAGED:把事务转交给其他容器
2)数据源
-
type
POOLED使用连接池
UNPOOLED不使用连接
JDNI :Java Directory Name Interface -
属性
数据库信息
数据库连接的配置
② 环境二
③ 环境三
(5)映射器
① xml
<mapper resource="com/srzx/mybatis/dao/BlogMapper.xml"/>
<mapper url="file:///var/mappers/AuthorMapper.xml"/>
② 接口类
<mapper class="org.mybatis.builder.AuthorMapper"/>
<package name="org.mybatis.builder"/>
4.关系映射
(1)一对一
(2)一对多
(3)多对一
(4)多对多
5.动态SQL
if
choose (when, otherwise)
trim (where, set)
foreach
6.懒加载
(1)按需加载,延迟加载
lazyLoadingEnabled=true
aggressiveLazyLoading=false
(2)立即加载:默认
(3)mapper.xml:fetchType(eager,lazy)
7.缓存
(1)一级缓存
① SqlSession对象的缓存
- sqlSession.close()
- 清空缓存sqlSession.clearCache()
- 当 调用 增删改,commit()等方法时,一级缓存会被清空
- 缓存的 对象 地址内容都一样
② 默认开启
(2)二级缓存
① SqlSessionFactory对象的缓存
- 让 mybatis 支持二级缓存: cacheEnabled=true
- 让 映射文件 支持二级缓存:
- 让 映射文件的方法 支持二级缓存: useCache=true
- 让缓存的对象 实现 序列化接口: 缓存的对象 值一样,内存地址不一样
- 让一级缓存失效,sqlSession.close(), 验证二级缓存
- 二级缓存中存储的是数据,而非对象
② 默认关闭