Mybatis延时加载
Mybatis延时加载(lazyLoadingEnabled):默认关闭
对所需要查询的语句,在需要调用时进行加载
在真正使用数据的时候才发起查询,不用的时候不查询关联的数据,延迟加载又叫按需查询(懒加载)
-----Mybatis主配置文件中
<settings> <setting name="logImpl" value="LOG4J"/> <!-- 默认是关闭的 需要手动打开 --> <setting name="lazyLoadingEnabled" value="true" /> <!-- 侵入式延迟加载开关 true表示如果对具有懒加载特性的对象的任意调用会导致这个对象的完整加载,false表示每种属性按照需要加载。 --> <setting name="aggressiveLazyLoading" value="false"/> </settings>
-----Mapper.xml中
<resultMap type="student" id="selectLazy"> <id property="id" column="id"/> <result property="name" column="name"/> <result property="pwd" column="pwd"/> <result property="cid" column="cid"/> <association property="cla" javaType="classes" column="cid" select="selectClass" > <!---column设置执行select参数----> <id property="cid" column="cid"/> <result property="cname" column="cname"/> </association> </resultMap> <select id="selectStu" resultType="org.zhang.bean.Student"> select * from student </select> <select id="selectClass" resultType="classes" > select * from classes where cid=#{cid} </select>
-----main函数中
Reader resourceAsFile = Resources.getResourceAsReader("mybatisConcern.xml");
SqlSessionFactory ss = new SqlSessionFactoryBuilder().build(resourceAsFile);
SqlSession s = ss.openSession();
StudentMapper sm = s.getMapper(StudentMapper.class);
Student student = sm.select("1"); // 1
student.getCla().getName(); // 2
结果:
当执行到1的时候:

当执行2的时候:

浙公网安备 33010602011771号