什么是懒加载?

        个人理解的懒加载就是在需要查询关联信息的时候去加载查询语句,在不需要的时候就不去执行查询。

        在mybatis中,一对一关联的 association 和一对多的collection可以实现懒加载。resultMap可以实现高级映射,所以Mybatis在实现懒加载时要使用 resultMap,不能使用 resultType。

实例

1、mybatis默认是没有开启懒加载的,要使用懒加载,需要先在全局配置中开启懒加载配置;

server.port=8081

#开启懒加载
mybatis.configuration.lazy-loading-enabled=true
#false 为按需加载
mybatis.configuration.aggressive-lazy-loading=false

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/db_mybatis
spring.datasource.username=root
spring.datasource.password=root
        
#开启驼峰命名,打印sql
mybatis.configuration.map-underscore-to-camel-case=true
mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

        注释:序列化和反序列化的内容待更新(后期我会在这里附上链接)

2、创建User和Account实体类并在数据库中创建出对应的表

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User implements Serializable {  //将User类序列化
    private Integer id;  //用户id
    private String username;  //用户名
    private Date birthday;    //出生日期
    private String sex;       //性别
    private String address;   //地址
    /*
     * 要查询用户信息,用户信息下有对应的账户信息,因此我们需
     * 要创建一对多关系映射:主表实体应该包含从表实体的集合引用
     * */
    private List<Account> accounts;
}
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Account {
    private Integer id;
    private Integer uid;
    private Double money;
    //,一个账号只能对应一个用户,从表实体应该包含一个主表实体的对象引用
    private User user;
}

3、创建 IUserMapper和IAccountMapper接口文件

        方式一、如果在这里采用的是Mapper代理加载xxxMapper.xml配置文件(没有配置全局扫描的情况下),所以接口和xml文件需要满足以下几个条件(如下情况所示)

  • 接口要和xml文件同名且在同一个包下,也就是xml文件中的namespace是接口的全类名
  • 接口中的方法名和xml文件中定义的id一致
  • 接口中输入的参数类型要和xml中定义的parameType保持一致
  • 接口的返回值类型要和xml中定义的resultType保持一致

方式二、我们可以将xml文件抽取出来,然后在主启动类中配置全局扫描

         具体代码如下:

        (1)先在主配置类中进行配置扫描mapper文件;

@SpringBootApplication
@MapperScan(value = "com.lazyload.mapper")
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

        (2)IUserMapper.java接口;

@Mapper
/*数据库操作接口:我们当然也可以通过实现类实现,但是mybatis环境帮我们配置了,所以我们不用写实现类*/
public interface IUserMapper {
    //查询所有用户,同时获取到用户下所有的账户信息
    List<User> findAll();
    //查询一个
    User findUserById(int userId);
}

        (3)IUserMapper.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="com.lazyload.mapper.IUserMapper">

    <!--写入user的resultMap:将user和数据库对应
    作用:建立SQL查询结果字段与实体属性的映射关系
    -->
    <resultMap id="userAccountMap" type="com.lazyload.entites.User">
        <!--主键字段-->
        <!--column所表示的是数据库中的字段名称-->
        <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>
        <!--Userx下对应的对应Account账户的信息:配置user对象下account的映射-->
        <collection property="accounts"  select="findUserById" column="id"></collection>
    </resultMap>
    <!--查询所有-->
    <select id="findAll" resultMap="userAccountMap">
        select * from user
    </select>

    <!--查询一个通过id-->
    <select id="findUserById" parameterType="int" resultType="com.lazyload.entites.User">
        select * from user where id=#{id}
    </select>
</mapper>

        另外一种情况: 

resultMap

      (4)IAccountMapper.java接口;

@Mapper
public interface IAccountMapper {
    /*查询所有*/
    List<Account> findAllAccount();
    /*两表联查
    * 根据用户id查询账户信息
    */
    List<Account> findAccountByUid(int uid);
}

        (5)IAccountMapper.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="com.lazyload.mapper.IAccountMapper">

    <!--将Account的信息和User的信息封装到ResultMap中去-->
    <!--  property表示java实体类中属性的名称,javaType表示属性的类型,ofType表示泛型,column表示应用查询的某列 select表示需要执行的sql语句 fetchType表示是否开启延迟加载eager取消延迟加载,lazy开启延迟加载,默认开启 -->
    <resultMap id="userAccountMap" type="com.lazyload.entites.Account">
        <id property="id" column="id"></id>
        <result property="uid" column="uid"></result>
        <result property="money" column="money"></result>
        <!--一对一的映射关系:配置封装的内容
        select属性指定的内容:查询用户的唯一标识【com.itheima.dao.IAccountMapper+方法名(就是接口中的)】
        column属性指定的内容:根据id查询时,所需要的参数的值(根据id来查询数据库的)
        -->
        <association property="user" column="uid" javaType="com.lazyload.entites.User" select="findAccountByUid"></association>
    </resultMap>

    <!--封装的查询所有-->
    <select id="findAllAccount" resultMap="userAccountMap">
        select * from account
    </select>

    <!--根据用户id查询账户列表-->
    <select id="findAccountByUid" parameterType="integer" resultType="com.lazyload.entites.Account">
        select * from account where uid=#{uid}
    </select>

</mapper>

4、测试

    @Test
    public void test1(){
        List<User> all = iUserMapper.findAll();
        for (User user:all) {
            System.out.println(user.getAccounts());
        }
    }

    @Test
    public void test2(){
        List<User> all = iUserMapper.findAll();
        for (User user:all) {
            System.out.println(user.getUsername());
        }
    }

         如果只访问用户的基础信息而不访问账户,此时是不会触发懒加载的,只会查询单表;若果访问了账户,那么则会触发懒加载,查询出用户的id后,再根据id去获取账号。

        与没有开启延迟加载的区别是,延迟加载只有使用到才会使用sql去查询,并且是一个一个输出。而非延迟加载是全部sql都执行一遍。

5、使用总结

  • 开启全局懒加载;
  • 先单表查询,将查询结果放到resultMap,将关联的列对应的值通过column(必须)传递到另外的表对应的具体查询方法;
  • 当需要时再去执行对应的方法;
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐