MyBatis延迟加载

MyBatis的延迟加载

什么是延迟加载?

  • 开启延迟加载后,在真正使用数据的时候才发起级联查询,不用的时候不查询。
mapper
public interface UserDao {
    /**
     * 延迟加载一对多
     * @param id
     * @return
     */
    User getAll2(Integer id);
}
<?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.by.dao.UserDao">

        <!--延迟加载的一对多     -->
        <!--
            property="accounts":属性名
            ofType="com.by.pojo.Account":集合的泛型,等价于resultType
            select="com.by.dao.AccountDao.selectGetAccountById":要调用的select标签的id
            column="id":传递给select查询的参数
            fetchType="lazy" :局部开启懒加载
        -->
    <resultMap id="getAll2ResultMap" type="user">
        <id column="id" property="id"></id>
        <result column="username" property="username"></result>
        <result column="birthday" property="birthday"></result>
        <result column="sex" property="sex"></result>
        <result column="address" property="address"></result>

        <collection property="accounts"
                    ofType="com.by.pojo.Account"
                    select="com.by.dao.AccountDao.selectGetAccountById"
                    column="id"
                    fetchType="lazy">
        </collection>
    </resultMap>
    <select id="getAll2" parameterType="java.lang.Integer" resultMap="getAll2ResultMap">
        select * from user where id=#{id}
    </select>

</mapper>
测试
@Test
    public void testGetAll2()  {
        UserDao userDao=sqlSession.getMapper(UserDao.class);
        User user =userDao.getAll2(41);
        System.out.println(user.getUsername());
        List<Account> accountList=user.getAccounts();
        for (Account account : accountList) {
            System.out.println(account);
        }
    }

你可能感兴趣的:(mybatis,开发语言)