1.mybatis延迟加载
<!-- 定义封装account和user的resultMap -->
<resultMap id="accountUserMap" type="account">
<id property="id" column="id"></id>
<result property="uid" column="uid"></result>
<result property="money" column="money"></result>
<!-- 一对一的关系映射:配置封装user的内容
select属性指定的内容:查询用户的唯一标识:
column属性指定的内容:用户根据id查询时,所需要的参数的值
-->
<association property="user" column="uid" javaType="user" select="com.itheima.dao.IUserDao.findById"></association>
</resultMap>
<!-- 查询所有 -->
<select id="findAll" resultMap="accountUserMap">
select * from account
</select>
<!-- 根据用户id查询账户列表 -->
<select id="findAccountByUid" resultType="account">
select * from account where uid = #{uid}
</select>
1.1主配置
<!--配置参数-->
<settings>
<!--开启Mybatis支持延迟加载-->
<setting name="lazyLoadingEnabled" value="true"/>
<setting name="aggressiveLazyLoading" value="false"></setting>
</settings>
<!--使用typeAliases配置别名,它只能配置domain中类的别名 -->
<typeAliases>
<package name="com.itheima.domain"></package>
</typeAliases>
2.mybatis中的缓存
存在内存中的临时数据,减少和数据库的交互次数,提高效率。
是用于缓存:经常查询且不经常改变的,数据的正确与否对最终结果影响不大的/
不适用于缓存:经常改变的数据,数据的正确与最终结果影响很大的。例如:银行的汇率,股市的牌价
2.1mybatis中的一级缓存
它指的是mybatis中SqlSession对象的缓存
当我们执行查询之后,查询的结果会同时存入到SqlSession为我们提供一块区域中。
该区域的结构是一个Map。当我们再次查询同样的数据,mybatis会先去sqlsession中
查询是否有,有的话直接拿出来用。
当SqlSession对象消失时,mybatis的一级缓存也就消失了。
sqlsession.clearCache();清空缓存
2.2二级缓存:
它指的是Mybatis中SqlSessionFactory对象的缓存。由同一个SqlSessionFactory对象创建的SqlSession共享其缓存。
二级缓存的使用步骤:
第一步:让Mybatis框架支持二级缓存(在SqlMapConfig.xml中配置)
第二步:让当前的映射文件支持二级缓存(在IUserDao.xml中配置)
第三步:让当前的操作支持二级缓存(在select标签中配置)
二级缓存:存放的内容是数据,而不是对象
3 Mybatis 注解开发
@Insert:实现新增
@Update:实现更新
@Delete:实现删除
@Select:实现查询
@Result:实现结果集封装
@Results:可以与@Result 一起使用,封装多个结果集
@ResultMap:实现引用@Results 定义的封装
@One:实现一对一结果集封装
@Many:实现一对多结果集封装
@SelectProvider: 实现动态 SQL 映射
@CacheNamespace:实现注解二级缓存的使用
/**
-
查询所有用户
- @return
*/
@Select(“select * from user”)
@Results(id=“userMap”,
value= {
@Result(id=true,column=“id”,property=“userId”),
@Result(column=“username”,property=“userName”),
@Result(column=“sex”,property=“userSex”),
@Result(column=“address”,property=“userAddress”),
@Result(column=“birthday”,property=“userBirthday”)
})
List findAll();
select :是要操作的全限定方法名
fetchType 加载的时机
@CacheNamespace(blocking = true)开启二级缓存,定义在哪个接口上,哪个接口方法开启二级缓存
property:实体类名 colum 数据库字段名
查询所有用户 - @return */ @Select("select * from user") @Results(id="userMap", value= { @Result(id=true,column="id",property="userId"), @Result(column="username",property="userName"), @Result(column="sex",property="userSex"), @Result(column="address",property="userAddress"), @Result(column="birthday",property="userBirthday") }) List findAll();
- @return