当前位置: 首页 > article >正文

Mybatis MyBatis延迟加载策略 二、多对一的延迟加载查询演示

多对一的延迟加载查询演示:

在AccountMapper接口中编写方法

public List<Account> findAll();

编写配置文件和SQL语句

<?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.qcbyjy.mapper.AccountMapper">
    
    <!-- 内连接的查询 -->
    <select id="findAll" resultMap="accountMap">
        SELECT * from account
    </select>
    
    <!-- 通过用户的id查询账户信息 -->
    <select id="findByUid" parameterType="int" resultType="account">
        select * from account where uid = #{uid}
    </select>
    
    <!-- 配置映射 -->
    <resultMap type="Account" id="accountMap">
        <id column="id" property="id"/>
        <result column="uid" property="uid"/>
        <result column="money" property="money"/>
        <!-- 配置延迟加载 -->
        <association property="user" javaType="User" select="com.qcbyjy.mapper.UserMapper.findById" column="uid">
            <id column="id" property="id"/>
            <result column="username" property="username"/>
            <result column="birthday" property="birthday"/>
            <result column="sex" property="sex"/>
            <result column="addresss" property="addresss"/>
        </association>
    </resultMap>
    
</mapper>

在UserMapper接口中编写方法

public User findById(Integer uid);

编写配置文件

<select id="findById" parameterType="int" resultType="User">
        select * from user where id = #{id}
    </select>

在SqlMapConfig.xml配置文件中开启延迟加载的配置

<settings>
        <!-- 开启延迟加载 -->
        <setting name="lazyLoadingEnabled" value="true"/>
        <!-- 将积极加载改为消极加载及按需加载 -->
        <setting name="aggressiveLazyLoading" value="false"/>
    </settings>

编写测试方法

@Test
public void testFindAll() throws Exception {
    // 调用方法
    List<Account> list = mapper.findAll();
    for (Account account : list) {
        System.out.println("开始...");
        System.out.println(account.getMoney());
        System.out.println("结束...");
        System.out.println();
    }
}

http://www.kler.cn/a/553830.html

相关文章:

  • 【后端】k8s
  • 中级软考笔记-基础知识-3-数据结构
  • 【核心算法篇十三】《DeepSeek自监督学习:图像补全预训练方案》
  • 1.16学习
  • 代码随想录-- 第一天图论 --- 岛屿的数量
  • 【SQL】多表查询案例
  • 解锁机器学习核心算法 | 决策树:机器学习中高效分类的利器
  • Python 性能剖析利器:DTrace 与 SystemTap 深度指南
  • PHP旅游门票预订系统小程序源码
  • 定期自动统计大表执行情况
  • SOME/IP--协议英文原文讲解9
  • JavaScript中内置对象
  • JVM内存管理笔记
  • 深入HBase——Bigtable
  • 数学函数(C#、Lua 、Unity)
  • React通用登录/注销功能实现方案(基于shadcn/ui)
  • 什么是语料清洗、预训练、指令微调、强化学习、内容安全; 什么是megatron,deepspeed,vllm推理加速框架
  • Hot100 图论
  • Redis如何解决大Key问题
  • Java面试第二山!《计算机网络》!