MyBatis(20)- mybatis 延遲加載

1 延遲加載

就是在需要用到數據時才進行加載,不需要用到數據時就不加載數據。延遲加載也稱懶加載. 好處:先從單表查詢,需要時再從關聯表去關聯查詢,大大提高數據庫性能,因爲查詢單表要比關聯查詢多張錶速度要快。
在這裏插入圖片描述

2 一對一延遲加載

在這裏插入圖片描述

2.1 實體類

在這裏插入圖片描述

2.2 接口

package com.tzb.dao;

import com.tzb.domain.Account;

import java.util.List;

public interface IAccountDao {

    /**
     * 查詢所有賬戶,同時還要獲取到當前賬戶的所屬用戶信息
     * @return
     */
    List<Account> findAll();

}


  • 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="com.tzb.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>

        <!--一對一的關係映射
            select屬性:查詢用戶的唯一標誌
            column屬性:用戶根據 id查詢時,所需要的參數的值
        -->
        <association property="user" column="uid" javaType="User" select="com.tzb.dao.IUserDao.findById">

        </association>
    </resultMap>

    <!-- 查詢所有 -->
    <select id="findAll" resultMap="accountUserMap">
        select  * from account
    </select>


</mapper>

在這裏插入圖片描述

2.3 SqlMapConfig

<?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">
<!-- mybatis 的主配置文件-->
<configuration>

    <properties resource="jdbc.properties"></properties>

    <settings>
        <!--開啓全局延遲加載-->
        <setting name="lazyLoadingEnabled" value="true"/>
        <setting name="aggressiveLazyLoading" value="false"/>
    </settings>


    <!--配置別名,配置 domain 類中的別名
        配置了別名後,就不在區分大小寫
    -->
    <typeAliases>
        <!--該包下所有的實體類都被註冊別名,類名就是別名,不在區分大小寫-->
        <package name="com.tzb.domain"/>
    </typeAliases>

    <!--配置環境-->
    <environments default="mysql">
        <environment id="mysql">
            <!--配置事務類型-->
            <transactionManager type="JDBC"></transactionManager>

            <!--配置數據源(連接池)-->
            <dataSource type="POOLED">
                <property name="driver" value="${driver}"/>
                <property name="url" value="${url}"/>
                <property name="username" value="${username}"/>
                <property name="password" value="${password}"/>
            </dataSource>
        </environment>
    </environments>

    <!--指定dao接口所在的包,不需要再寫 mapper 以及resource或者 class-->
    <mappers>
        <package name="com.tzb.dao"/>
    </mappers>

</configuration>

2.4 單元測試

public class AccountTest {

    private InputStream in;
    private SqlSession sqlSession;
    private IAccountDao accountDao;

    @Before
    public void init() throws IOException {
        // 1.讀取配置文件
        in = Resources.getResourceAsStream("SqlMapConfig.xml");
        //2.創建 SqlSessionFactory 工廠
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
        // 3.使用工廠生產 SqlSession 對象
        sqlSession = factory.openSession();
        // 4.使用 SqlSession 創建DAO接口的代理對象
        accountDao = sqlSession.getMapper(IAccountDao.class);
    }

    @After
    public void destory() throws IOException {
        // 提交事務
        sqlSession.commit();
        //6.釋放資源
        sqlSession.close();
        in.close();
    }

    @Test
    public void testFindAll(){
        List<Account> accounts = accountDao.findAll();

        for (Account account : accounts) {
            System.out.println("---- 每個賬戶信息------");
            System.out.println(account);
            System.out.println(account.getUser());
            System.out.println("========================");
        }
    }


}

在這裏插入圖片描述

3 一對多延遲加載

在這裏插入圖片描述

3.1 實體類

在這裏插入圖片描述

3.2 在 Account 接口添加查詢

在這裏插入圖片描述

  • IAccountDao.xml
  <select id="findAccountByUid" parameterType="int" resultType="Account">
        select * from account where uid=#{uid}
    </select>

3.3 User DAO

public interface IUserDao {
    List<User> findAll();

    User findById(Integer userId);

}

  • IUserDao.xml
    <!-- 定義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集合的映射
            column: 因爲使用用戶的id 去查
         -->
        <collection property="accounts"
                    ofType="account"
                    select="com.tzb.dao.IAccountDao.findAccountByUid"
                    column="id">

        </collection>
    </resultMap>

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

3.4 單元測試

  /**
     * 測試查詢所有
     */
    @Test
    public void testFindAll(){
        List<User> users = userDao.findAll();
        for(User user : users){
            System.out.println("-----每個用戶的信息------");
            System.out.println(user);
            System.out.println(user.getAccounts());
        }
    }

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章