Mybatis的延迟加载、缓存、注解开发

Mybatis中的延迟加载

Q1:在一对多中,当存在一个用户,它有多个账户。
	在查询用户时,是否需要把关联的账户查询出来?
	在查询账户时,是否需要把关联的用户查询出来?
	
	查询用户时,用户下的账户信息应该是何时使用何时查询的。
	在查询账户时,账户的所属用户信息应该是随着账户查询时一起查询出来。

延迟加载

​ 在真正使用数据时才发起查询,不用的时候不进行查询。按需加载(懒加载)

立即加载

​ 不管是否使用,只要一调用方法,马上进行查询。

在对应的四种表关系中:一对多,多对一,一对一,多对多

​ 一对多,多对多:通常情况下采用延迟加载。

​ 多对一,一对一:通常情况下采用立即加载。

一对一实现延迟加载

(找出所有的account,同时所有user被查询出来)

1.配置select标签
<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.jingsheng.dao.IUserDao.findUserById"></association>
</resultMap>
首先需要将所有的accout查询出来,所以在IAccountDao.xml中写:
<select id="findAllAccount" resultMap="accountUserMap">
	select * from account
</select>
且select属性中会调用findUserById方法,所以在IUserDao.xml文件中写:
<select id="findUserById" resultType="user">
	select * from user where id=#{uid}
</select>
 2.开启Mybatis支持延迟加载
 在主配置文件(SqlMapConfig.xml)中开启Mybatis对延迟加载的支持:
 <settings>
        <setting name="lazyLoadingEnabled" value="true"/>
        <setting name="aggressiveLazyLoading" value="false"/>
 </settings>

一对多实现延迟加载

(找出所有的user,同时所有的account被查询出来)

1.配置select标签
<resultMap id="userAccountMap" type="user">
        <id property="id" column="id"></id>
        <result property="username" column="username"></result>
        <result property="birthday" column="birthday"></result>
        <result property="sex" column="sex"></result>
        <result property="address" column="address"></result>
        <!-- 配置User对象中accounts集合的映射 -->
        <collection property="accounts" ofType="account" column="uid" select="com.jingsheng.dao.IAccountDao.findAccountByUid"></collection>
</resultMap>
首先需要将所有的user查询出来,所以在IUserDao.xml中写:
<select id="findAllUser" resultMap="userAccountMap">
        select * from user
</select>
且select属性中会调用findAccountByUid方法,所以在IAccountDao.xml文件中写:
<select id="findAccountByUid" resultType="account">
        select * from account where id=#{uid}
    </select>
 2.开启Mybatis支持延迟加载
	由于在主配置文件SqlMapConfig.xml已经将Mybatis支持延迟加载的配置开启,故此处不需再次开启

​ 总结:延迟加载适用于一对多,多对多的方式。

  1. 将所有的数据查询出来

  2. select * from user
  3. 封装数据集

    先封装查询的数据,再配置select进行延迟加载,需要映射到方法

  4. 配置映射方法

  5. 开启Mybatis支持延迟加载


Mybatis中的缓存

​ 缓存:存在于内存中的临时数据

​ 使用目的:为了减少和数据库的交互次数,提高执行效率

​ 适用于缓存的数据:经常查询并且不经常改变、数据的正确与否对最终影响不大的。

​ 不适用于缓存的数据:经常改变的数据、数据的正确与否对最终结果影响很大的。

​ 例如:商品的库存、银行的汇率、股市的牌价。

缓存的分类

Mybatis中的一级缓存和二级缓存

一级缓存:它指的是Mybatis中SqlSession对象的缓存。当执行查询操作之后,查询的结果会同时存入到 SqlSession提供的一块区域,该区域的结构是一个Map。当再次执行查询操作查询同样的数据,Mybatis 会先去SqlSession中查询数据是否存在,有的话直接拿出来使用。当SqlSession对象消失时,mybatis的 一级huan’cun也随之消失。

一级缓存是SqlSession范围的缓存,当调用SqlSession的修改、添加、删除、commit()、close()等方法时,就会清空一级缓存。

二级缓存:它指的是Mybatis中的SqlSessionFactory对象的缓存。由同一个SqlSessionFactory对象创建 的SqlSession共享其缓存

二级缓存的使用步骤:

  1. 让Mybatis框架支持二级缓存(在SqlMapConfig.xml中配置)

    <settings>
            <setting name="cacheEnabled" value="true"/>
    </settings>
    
  2. 让当前的映射文件支持二级缓存(在IUserDao.xml中配置)

    <!-- 开启user支持二级缓存 -->
    <cache/>
    
  3. 让当前的操作支持二级缓存(在select标签中配置)

     <!-- 根据id查询用户 -->
    
        <select id="findUserById" parameterType="int" resultType="user" useCache="true">
            select * from user where id=#{uid};
        </select>
    

二级缓存存放的是数据不是对象


Mybatis中的注解开发

1. 环境搭建

和xml配置没有什么区别,不需要xml文件,直接在IUserDao上面使用@Select注解即可

注:

​ 当注解和xml文件同时存在时,即使使用

​ 依然会发生错误

2. 单表CRUD操作

增加用户:
@Insert(value = "insert into user (username,birthday,sex,address) values(#{username},#{birthday},#{sex},#{address})")
void saveUser(User user);
删除用户:
@Delete(value = "delete from user where id=#{id}")
void deleteUser(Integer id);
修改用户:
@Update(value = "update user set username=#{username},birthday=#{birthday},sex=#{sex},address=#{address} where id=#{id}")
void updateUser(User user);
查询用户:
 @Select(value = "select * from user where id=#{id}")
 User selectUserById(Integer id);

3. 多表查询操作

当实体类的属性名称和数据库的列名对应不上的时候,使用Results注解

@Results(value = {
            @Result(id = true,column = "id",property = "userId"),
            @Result(column = "username",property = "userName"),
            @Result(column = "birthday",property = "userBirthday"),
            @Result(column = "sex",property = "userSex"),
            @Result(column = "address",property = "userAddress"),
    })

注:可以使用id属性进行全局配置,使用ResultMap注解进行引用

 @Results(id = "userMap",value = {
            @Result(id = true,column = "id",property = "userId"),
            @Result(column = "username",property = "userName"),
            @Result(column = "birthday",property = "userBirthday"),
            @Result(column = "sex",property = "userSex"),
            @Result(column = "address",property = "userAddress"),
    })
    
    @ResultMap(value = {"userMap"})

多表一对一操作(立即加载)

1.查询和封装数据
@Select(value = "select * from account")
@Results(id = "accoutMap",value = {
            @Result(id = true,column = "id",property = "id"),
            @Result(column = "uid",property = "uid"),
            @Result(column = "money",property = "money"),
            @Result(property = "user",column = "uid",one=@One(select="com.jingsheng.dao.IUserDao.selectUserById",
                    fetchType= FetchType.EAGER))
    })
List<Account> findAllAccount();
2.测试
		List<Account> accounts = accountDao.findAllAccount();

        for (Account account:
             accounts) {

            System.out.println("---------每个账户的信息---------");
            System.out.println(account);
            System.out.println(account.getUser());
        }



多表一对多操作(延迟加载)

1.查询和封装数据
@Select(value = "select * from user")
    @Results(id = "userMap",value = {
            @Result(id = true,column = "id",property = "userId"),
            @Result(column = "username",property = "userName"),
            @Result(column = "birthday",property = "userBirthday"),
            @Result(column = "sex",property = "userSex"),
            @Result(column = "address",property = "userAddress"),
            @Result(column = "id",property = "accounts",many=@Many(select = "com.jingsheng.dao.IAccountDao.findAccountById",
            fetchType = FetchType.LAZY))
    })
List<User> findAllUser();
2.在IAccountDao中定义查询id的select语句
@Select(value = "select * from account where uid=#{userId}")
List<Account> findAccountById(Integer userId);
3.测试
		List<User> users = userDao.findAllUser();
        for (User user:
             users) {
            System.out.println(user);

            System.out.println("------每个用户的信息------");

            System.out.println(user.getAccounts());
        }

4. 缓存的配置

二级缓存开启

  1. 配置SqlMapConfig.xml文件,开启二级缓存

    <settings>
    
    	<setting name="cacheEnabled" value="true"/>
    
    </settings>
    
  2. 在所需的接口上使用注解开启二级缓存

    @CacheNamespace(blocking = true)
    

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值