mybatis 懒加载

mybatis 懒加载

依赖

 <dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.2.0</version>
</dependency>
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid-spring-boot-starter</artifactId>
    <version>1.2.6</version>
</dependency>

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
</dependency>

application.properties 配置

server.port=8080
spring.datasource.name=test
spring.datasource.url=jdbc:mysql://172.xxx:3306/mybatis
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.filters=stat
spring.datasource.maxActive=20
spring.datasource.initialSize=1
spring.datasource.maxWait=60000
spring.datasource.minIdle=1
spring.datasource.timeBetweenEvictionRunsMillis=60000
spring.datasource.minEvictableIdleTimeMillis=300000
spring.datasource.validationQuery=select 'x'
spring.datasource.testWhileIdle=true
spring.datasource.testOnBorrow=false
spring.datasource.testOnReturn=false
spring.datasource.poolPreparedStatements=true
spring.datasource.maxOpenPreparedStatements=20


mybatis.mapper-locations=classpath:mappings/**/*.xml
mybatis.type-aliases-package=com.bootmybatis.model
mybatis.configuration.map-underscore-to-camel-case=true

# 开启懒加载
mybatis.configuration.lazy-loading-enabled=true

# false 按需加载
mybatis.configuration.aggressive-lazy-loading=false

# 关闭 system.out 触发懒加载变成立即加载
mybatis.configuration.lazy-load-trigger-methods=

logging.level.com.bootmybatis.dao=debug

mapper 配置文件

@Data
public class AccountDetailModel implements Serializable {
    private Integer id;

    private Integer accountId;

    private Integer amount;

    private static final long serialVersionUID = 1L;
}

@Data
public class AccountModel implements Serializable {
    private Integer id;

    private String userName;

    private String passwd;

    private static final long serialVersionUID = 1L;
}

@Data
public class AccountDto {


    private Integer id;

    private String userName;

    private String passwd;

    private AccountDetailModel accountDetailModel;

    /**
     * 重写 toString, 避免立即加载!!
     *
     * @return
     */
    @Override
    public String toString() {
        return "AccountDto{" +
                "id=" + id +
                ", userName='" + userName + '\'' +
                ", passwd='" + passwd + '\'' +
                '}';
    }
}

AccountDao.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.bootmybatis.dao.AccountDao">

  <resultMap id="getAccountListMap" type="com.bootmybatis.AccountDto">
    <id column="id" jdbcType="INTEGER" property="id" />
    <result column="user_name" jdbcType="VARCHAR" property="userName" />
    <result column="passwd" jdbcType="VARCHAR" property="passwd" />
    <association property="accountDetailModel" column="id" select="getAccountDetailMap"></association>
  </resultMap>

  <select id="getAccountList" resultMap="getAccountListMap">
    select * from t_account
  </select>
  
  <select id="getAccountDetailMap" parameterType="int" resultType="com.bootmybatis.model.AccountDetailModel">
      //#{id} 即 getAccountListMap 中 column=id 中的字段!!!
    select * from t_account_detail where account_id=#{id} 
  </select>
</mapper>

测试用例

@Test
public void lazyLoadTest() {
    List<AccountDto> accountList = accountDao.getAccountList();
    System.out.println(accountList);
    for (AccountDto accountDto : accountList) {
        System.out.println(accountDto.getAccountDetailModel());
    }
}

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ZrLqbwX5-1632394322615)(image-20210923160554384.png)]

结果:

最好开启debug日志查看sql观察懒加载

c.d.b.dao.AccountDao.getAccountList      : ==>  Preparing: select * from t_account
c.d.b.dao.AccountDao.getAccountList      : ==> Parameters: 
c.d.b.dao.AccountDao.getAccountList      : <==      Total: 2
[AccountDto{id=1, userName='test', passwd='test'}, AccountDto{id=2, userName='haha', passwd='haha'}]
c.d.b.d.AccountDao.getAccountDetailMap   : ==>  Preparing: select * from t_account_detail where account_id=?
c.d.b.d.AccountDao.getAccountDetailMap   : ==> Parameters: 1(Integer)
c.d.b.d.AccountDao.getAccountDetailMap   : <==      Total: 1
AccountDetailModel(id=1, accountId=1, amount=10)
c.d.b.d.AccountDao.getAccountDetailMap   : ==>  Preparing: select * from t_account_detail where account_id=?
c.d.b.d.AccountDao.getAccountDetailMap   : ==> Parameters: 2(Integer)
c.d.b.d.AccountDao.getAccountDetailMap   : <==      Total: 1
AccountDetailModel(id=2, accountId=2, amount=43)

可以发现 AccountDetailModel 只有在调用了 getAccountDetailModel 才会去查询

mybaits 懒加载问题

1+N 问题
  • 一次 select * from t_account
  • N 次 select * from t_account_detail where account_id=?

accountDetailModel 只有在调用了 getAccountDetailModel 才会去查询

Mybatis懒加载是一种延迟加载的机制,只有在需要使用关联对象时才会进行加载。在Mybatis中,懒加载主要应用于关联查询,通过设置延迟规则,推迟对关联对象的查询,减轻数据库的压力。懒加载只对关联对象有延迟设置,而不会延迟主对象的查询。\[1\] 要开启懒加载,需要在Mybatis的主配置文件中的settings标签中设置lazyLoadingEnabled为true。同时,可以设置aggressiveLazyLoading为false来控制懒加载的行为。\[3\] 需要注意的是,开启懒加载是全局的设置,即对所有关联对象都生效。如果只想对部分关联对象进行懒加载,可以使用association和collection的fetchType属性来覆盖全局的懒加载状态。fetchType属性可以设置为eager表示立即加载,lazy表示使用懒加载。\[3\] 总结来说,Mybatis懒加载是一种延迟加载机制,可以减轻数据库的压力。通过在主配置文件中设置相关属性,可以控制懒加载的行为,包括全局开启懒加载、设置懒加载的延迟规则以及对部分关联对象进行懒加载。\[1\]\[3\] #### 引用[.reference_title] - *1* [Mybatis懒加载](https://blog.csdn.net/qq_52519008/article/details/127118918)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [八、(了解即可)MyBatis懒加载(或者叫延迟加载)](https://blog.csdn.net/a924382407/article/details/130505098)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] - *3* [MyBatis懒加载](https://blog.csdn.net/layonly/article/details/120719900)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值