Mybatis的延迟加载

Mybatis的延迟加载就是在resultMap的配置中多配置一个属性


第一步:创建dao层中的sellerDao类,在该类创建两个方法

selectSeller用来查询商家

getAllFood用来查询食物

package org.peter.dao;

import org.peter.model.Food;
import org.peter.model.Seller;

import java.util.List;

/**
 * Created by Lenovo on 2017/7/27.
 */
public interface SellerDao {
    public Seller selectSeller(long id);
    public List<Food> getAllFood(long id);
}


第二步:在dao层中创建一个SellerDao.xml文件来配置sql语句和resultMap

在这里将查询语句分为两部分,

第一个select用来查询seller

第二个select用来查询food

<collection property="foods" ofType="org.peter.model.Food" select="org.peter.dao.SellerDao.getAllFood" column="id" fetchType="lazy">
            <result property="foodname" column="foodname"/>
        </collection>
这个里面配置一个
fetchType="lazy"
就是配置了懒加载

<?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="org.peter.dao.SellerDao">

    <resultMap id="BaseResultMap" type="org.peter.model.Seller">
        <id column="id" property="id"/>
        <result property="phonenumber" column="phonenumber"/>
        <result property="windowimg" column="windowimg"/>
        <result property="password" column="password"/>
        <result property="state" column="state"/>
        <result property="sellername" column="sellername"/>
        <result property="windowname" column="windowname"/>
        <!--collection 主要使用来加载list集合 ofType是food 的model-->
        <collection property="foods" ofType="org.peter.model.Food" select="org.peter.dao.SellerDao.getAllFood" column="id" fetchType="lazy">
            <result property="foodname" column="foodname"/>
        </collection>
    </resultMap>

    <select id="selectSeller" resultMap="BaseResultMap" parameterType="long">
        select * from seller where id=#{id}
    </select>
    <select id="getAllFood" parameterType="long" resultType="org.peter.model.Food">
        select *from food WHERE sellerid=#{id}
    </select>

第三步:创建一个main类做测试

package org.peter.main;

import org.apache.ibatis.session.SqlSession;
import org.peter.dao.SellerDao;
import org.peter.model.Seller;
import org.peter.utils.DBUtils;

/**
 * Created by Lenovo on 2017/7/27.
 */
public class main {
    public static void main(String[] args) {
        select();
    }
    public static void select(){
        SqlSession sqlSession = DBUtils.openSession();
        SellerDao mapper = sqlSession.getMapper(SellerDao.class);
        Seller seller = mapper.selectSeller(1l);
//        System.out.println(seller);
    }
}

作用:
  当需要查询关联信息时再去数据库查询,默认不去关联查询,提高数据库性能。
  只有使用resultMap支持延迟加载设置。

场合:
  当只有部分记录需要关联查询其它信息时,此时可按需延迟加载,需要关联查询时再向数据库发出sql,以提高数据库性能。
  当全部需要关联查询信息时,此时不用延迟加载,直接将关联查询信息全部返回即可,可使用resultType或resultMap完成映射。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值