MyBatis系列第四篇:MyBatis延迟加载

目录

1、什么是延迟加载?

2、延迟加载的使用场景

3、代码演示

3.1 实体类:学生类和班级类

3.2 学生类接口与学生类接口的Mapper.xml

3.3 班级类接口与班级类接口的Mapper.xml

3.4 MyBatis配置文件中设置延迟加载

3.5 延迟加载测试:只查询学生信息

3.6 延迟加载测试:查询学生信息外,也查询班级信息


1、什么是延迟加载?

延迟加载,也叫做懒加载、惰性加载,使用延迟加载可以提高程序的运行效率。延迟加载是针对于数据持久层的操作,在某些特定的情况下才去访问特定的数据库表,在其他情况下不访问某些表,从一定程度上减少了java应用程序与数据库的交互次数,从而可以提升程序的运行效率。

2、延迟加载的使用场景

比如,学生和班级是两张不同的表。在查询学生和班级信息的时候,如果业务场景只需要学生信息,那么只需要查询学生单表即可;如果业务场景是既需要学生信息也需要班级信息,那么则必须查询学生和班级两张表。

3、代码演示

3.1 实体类:学生类和班级类

@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class ClassEntity implements Serializable {

    private static final long serialVersionUID = -3337804323389088625L;

    private int id;                                 //班级ID
    private String className;                       //班级名称
    private int status;                             //是否有效(1:有效,-1:无效)
    private String addTime;                           //添加时间
    private String updateTime;                        //更新时间
    private List<StudentEntity> studentEntities;    //该班级中有哪些学生

}

@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class StudentEntity implements Serializable {

    private static final long serialVersionUID = -7497520016303190017L;

    private int id;                     //学号
    private String name;                //姓名
    private int classId;                //班级
    private int status;                 //是否有效(1:有效,-1:无效)
    private String addTime;               //添加时间
    private String updateTime;            //更新时间
    private ClassEntity classEntity;    //该学生属于哪个班级
}

3.2 学生类接口与学生类接口的Mapper.xml

public interface StudentRepository {
    StudentEntity queryStudentLazy(@Param("id") int id);
}
<?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="com.wind.repository.StudentRepository">

    <resultMap id="studentMap3" type="com.wind.entity.StudentEntity">
        <result column="Id" property="id"/>
        <result column="Name" property="name"/>
        <result column="ClassId" property="classId"/>
        <result column="Status" property="status"/>
        <result column="AddTime" property="addTime"/>
        <result column="UpdateTime" property="updateTime"/>
        <association property="classEntity" javaType="classEntity"
                     select="com.wind.repository.ClassRepository.queryClassByClassIdLazy" column="classId">
        </association>
    </resultMap>

    <select id="queryStudentLazy" parameterType="int" resultMap="studentMap3">
        select * from RUN_Student where id = #{id}
    </select>
</mapper>

3.3 班级类接口与班级类接口的Mapper.xml

public interface ClassRepository {
    ClassEntity queryClassByClassIdLazy(@Param("id") int id);
}
<?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="com.wind.repository.ClassRepository">
    <select id="queryClassByClassIdLazy" parameterType="int" resultType="classEntity">
        select * from RUN_Class where id = #{id}
    </select>
</mapper>

3.4 MyBatis配置文件中设置延迟加载

注意:

(1)延迟加载默认是关闭的,只有显示开启之后才能使用。

(2)为了能够看到查询SQL的执行路径,在设置中也开启了控制台SQL输出的设置。

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>

    <settings>
        <!--开启在控制台打印SQL日志-->
        <setting name="logImpl" value="STDOUT_LOGGING"/>
        <!--开启延迟加载-->
        <setting name="lazyLoadingEnabled" value="true"/>
    </settings>

    <typeAliases>
        <package name="com.wind.entity"/>
    </typeAliases>

    <!--配置mybatis运行环境-->
    <environments default="development">
        <environment id="development">
            <!--配置JDBC事务管理-->
            <transactionManager type="JDBC"></transactionManager>
            <!--配置POOLED类型的JDBC数据源连接池-->
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url"
                          value="jdbc:mysql://localhost:3306/RUNOOB?useUnicode=true&amp;characterEncoding=UTF-8"/>
                <property name="username" value="root"/>
                <property name="password" value="admin0001112"/>
            </dataSource>
        </environment>
    </environments>

    <!--注册mapper文件-->
    <mappers>
        <mapper resource="com/entity/mapper/StudentRepository.xml"/>
        <mapper resource="com/entity/mapper/ClassRepository.xml"/>
    </mappers>
</configuration>

3.5 延迟加载测试:只查询学生信息

public class UserTest3 {

    public static void main(String[] args) {
        //加载MyBatis配置文件
        InputStream inputStream = UserTest3.class.getClassLoader().getResourceAsStream("mybatis-config.xml");
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
        SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();

        //获取实现接口的代理对象
        StudentRepository studentRepository = sqlSession.getMapper(StudentRepository.class);
        StudentEntity studentEntity = studentRepository.queryStudentLazy(2);
        System.out.println(studentEntity.getName());
        sqlSession.close();
    }
}

结果:在只查询学生信息时,发现只执行了学生单表的SQL,并没有执行查询班级单表的SQL。

3.6 延迟加载测试:查询学生信息外,也查询班级信息

    public static void main(String[] args) {
        //加载MyBatis配置文件
        InputStream inputStream = UserTest3.class.getClassLoader().getResourceAsStream("mybatis-config.xml");
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
        SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();

        //获取实现接口的代理对象
        StudentRepository studentRepository = sqlSession.getMapper(StudentRepository.class);
        StudentEntity studentEntity = studentRepository.queryStudentLazy(2);
        System.out.println(studentEntity.getClassEntity().getClassName());
        sqlSession.close();
    }

结果:在只查询学生所在班级的班级名称信息时,发现先是执行了学生单表的SQL,拿到classId之后再去执行查询班级单表的SQL,所以共查询了两次,而且整个过程(需要执行查询班级单表的SQL还是不需要执行查询班级单表的SQL)没有人员参与,全部都是MyBatis内部自己控制的。这就是MyBatis的延迟加载机制。

 

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值