MyBatis——延迟加载 解耦

  • 不同的业务需求,需要查询不同的表,根据具体的业务需求来动态减少数据表查询的工作就是延迟加载。

(1)在config.xml中开启延迟加载

	<settings>
        <!-- 打印SQL-->
        <setting name="logImpl" value="STDOUT_LOGGING" />
        <!-- 开启延迟加载 -->
        <setting name="lazyLoadingEnabled" value="true"/>
    </settings>

(2)StudentRepository

Student findByIdLazy(long id);

(3)StudentRepository.xml

<!-- 延迟加载 -->
    <resultMap id="lazy" type="com.lin.entity.Student">
        <id property="id" column="id"></id>
        <result column="studentName" property="studentName"></result>
        <association property="classes" javaType="com.lin.entity.Classes" select="com.lin.repository.ClassesRepository.findByIdLazy" column="classID"></association>
    </resultMap>
    <select id="findByIdLazy" resultMap="lazy" parameterType="java.lang.Long">
        select * from student where id=${id}
    </select>
  • select :查找其他表的方法
  • colum:依照的参数

(4)ClassesRepository

Classes findByIdLazy(long id);

(5)ClassesRepository.xml

	<!-- 延迟加载 -->
	<select id="findByIdLazy" resultType="com.lin.entity.Classes" parameterType="java.lang.Long">
        select * from classes where id=#{id}
    </select>

(6)使用

在这种情况下会执行一次sql语句

StudentRepository studentRepository = sqlSession.getMapper(StudentRepository.class);
Student student = studentRepository.findByIdLazy(3);
System.out.println(student.getStudentName());

在这种情况下会执行两次

System.out.println(student.getClasses());
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值