十四、mybaitis学习——延迟加载

mybaitis学习——延迟加载

一对多在collection配置:

  • property:集合属性名
  • ofType : 集合中元素的全限定名类名,可以用起好的别名
  • select:执行的sql语句的mapperId(唯一标识,接口的全限定类名.方法名)
  • colulm:传入到sql语句中的参数(主表字段名)
  • fetchType=”lazy” :开启懒加载模式

主表查询语句

    <resultMap type="user" id="userLazy">
        <!-- 用户主键信息 -->
        <id column="id" property="id" />
        <!-- 用户的普通属性 -->
        <result column="username" property="username" />
        <result column="birthday" property="birthday" />
        <result column="sex" property="sex" />
        <result column="address" property="address" />
        <!-- 
            collection:
                property:集合属性名
                ofType : 集合中元素的全限定名类名,可以用起好的别名
                select:执行的sql语句的mapperId(唯一标识,接口的全限定类名.方法名) 
                colulm:传入到sql语句中的参数(主表字段名)
                fetchType="lazy" :开启懒加载模式

         -->

        <collection fetchType="lazy" property="accounts" ofType="account" 
         select="cn.it.demo.dao.AccountDao.findAccByUid" column="id">
        </collection>
    </resultMap>


    <!-- 只查询当前对象 -->   
    <select id="findAllLazy" resultMap="userLazy">
        select * from user
    </select>

从表查询语句

<!-- 根据用户id查询账户 -->
    <select id="findAccByUid" resultType=“account” parameterType="int">
        SELECT * FROM account  where uid =  #{uid};
    </select>

test测试类

    @Test
    public void testFindAllLazy() {
        SqlSession session = sqlSessionFactory.openSession();
        UserDao userDao = session.getMapper(UserDao.class);
        List<User> users = userDao.findAllLazy();
        System.out.println("未使用account属性==========================================");
        for (User user : users) {
            System.out.println(user.getId()+"---"+user.getUsername());
        }
        System.out.println("使用account属性 ===========================================================");
        for (User user : users) {
            System.out.println(user);
        }
    }

一对一

主表

<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="cn.it.dao.UserDao.findUserById" column="uid"
        ></association>
    </resultMap>

    <!-- 查询全部的账户(使用延迟加载的形式加载账户所属的用户) -->
    <select id="findAllAccounts" resultMap="accountMap">
        select * from account
    </select>

分表

<!-- 只查询当前对象 -->
    <select id="findUserById" resultType="user" parameterType="int">
        select * from user where id = #{userid}
    </select>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值