Mybatis的延迟查询

本文探讨了MyBatis中的延迟加载技术,特别是在一对多关系中的应用。通过具体实例,展示了如何配置MyBatis实现延迟加载,以提高数据库查询效率。文章详细解释了延迟加载与立即加载的区别,以及它们在不同表关系中的适用场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Mybatis中的延迟加载

问题:在一对多中,当我们有一个用户,它有100个账户。
      在查询用户的时候,要不要把关联的账户查出来?
      在查询账户的时候,要不要把关联的用户查出来?
	
      在查询用户时,用户下的账户信息应该是,什么时候使用,什么时候查询的。
      在查询账户时,账户的所属用户信息应该是随着账户查询时一起查询出来。

什么是延迟加载
	在真正使用数据时才发起查询,不用的时候不查询。按需加载(懒加载)
什么是立即加载
	不管用不用,只要一调用方法,马上发起查询。

在对应的四种表关系中:一对多,多对一,一对一,多对多
	一对多,多对多:通常情况下我们都是采用延迟加载。
	多对一,一对一:通常情况下我们都是采用立即加载。

延迟加载好处:
先从单表查询,需要时再从关联表去关联查询,大大提高数据库性能,因为查询单表要比关联查询多张表速度要快。
延迟加载坏处:
因为只有当需要用到数据时,才会进行数据库查询,这样在大批量数据查询时,因为查询工作也要消耗时间,所以可能造成用户等待时间变长,造成用户体验下降。

举一例:
1、先给出 User.java 和 Account.java (从 Mabatis中的多表查询 —— 一对多 中找)
2、给出接口 IUserDao

import java.util.List;
import domain.User;

public interface IUserDao {

    /**
     * 查询所有用户,同时获取到用户下所有账户的信息
     */
    List<User> findAll();
    /**
     * 根据id查询用户信息
     */
    User findById(Integer userId);
}

3、给出对应的配置文件 IUserDao.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="dao.IUserDao">

    <!-- 定义User的resultMap-->
    <resultMap id="userAccountMap" type="user">
        <id property="id" column="id"></id>
        <result property="username" column="username"></result>
        <result property="address" column="address"></result>
        <result property="sex" column="sex"></result>
        <result property="birthday" column="birthday"></result>
        <!-- 配置user对象中accounts集合的映射 -->
        <collection property="accounts" ofType="account" select="dao.IAccountDao.findAccountByUid" column="id"></collection>
    </resultMap>

    <!-- 查询所有 -->
    <select id="findAll" resultMap="userAccountMap">
        select * from user
    </select>

    <!-- 根据id查询用户 -->
    <select id="findById" parameterType="INT" resultType="user">
        select * from user where id = #{uid}
    </select>

</mapper>

4、给出 IAccountDao.java

import java.util.List;

import domain.Account;

public interface IAccountDao {

    /**
     * 查询所有账户,同时还要获取到当前账户的所属用户信息
     * @return
     */
    List<Account> findAll();

    /**
     * 根据用户id查询账户信息
     * @param uid
     * @return
     */
    List<Account> findAccountByUid(Integer uid);

}

5、给出 IAccountDao.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="dao.IAccountDao">

    <!-- 定义封装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="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>

</mapper>

6、给出conf.xml 和 jdbcConfig.properties(在 Mybatis参数深入——改造conf.xml文件 里面找)
7、给出 log4j.properties
8、给出Test

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;


import dao.IAccountDao;
import domain.Account;

public class AccountTest {
	public static void main(String[] args) throws IOException {
		
		 //1.读取配置文件,生成字节输入流
		InputStream in = Resources.getResourceAsStream("conf.xml");
        //2.获取SqlSessionFactory
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
        //3.获取SqlSession对象
        SqlSession sqlSession = factory.openSession(true);
        //4.获取dao的代理对象
        IAccountDao accountDao = sqlSession.getMapper(IAccountDao.class);
        
        
        List<Account> accounts = accountDao.findAll();
	      for(Account account : accounts){
	          System.out.println("--------每个account的信息------------");
	          System.out.println(account);
	          System.out.println(account.getUser());
	      }
	        
        sqlSession.close();
        in.close();      
	}

}

(一)运行结果:(这是没有开启延迟查询的日志信息的输出)
在这里插入图片描述

(二)开启延迟查询,在conf.xml中添加

<!--配置参数-->
    <settings>
        <!--开启Mybatis支持延迟加载-->
        <setting name="lazyLoadingEnabled" value="true"/>
        <setting name="aggressiveLazyLoading" value="false"></setting>
    </settings>

在这里插入图片描述

第一次的时候报异常:Cannot enable lazy loading because CGLIB is not available. Add CGLIB to your classpath.,也试了添加jar包:cglib-3.2.5.jar,没用。然后把 mybatis-3.2.8.jar 换成 mybatis-3.4.6.jar问题解决了!!!

(三)当注释掉Test底下的:
在这里插入图片描述
会发现,只执行了查询用户,并没有执行查询用户下的账户信息!!!在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值