mybatis_04_延迟加载
概述
也称懒加载,通俗点讲就是需要查询哪个表的数据才执行相关sql语句,从而提高查询效率
开启延迟加载
在核心配置文件添加以下代码,true代表开启延迟加载
<!--开启延迟加载-->
<setting name="lazyLoadingEnabled" value="true"/>
配置文件方式
Mapper接口
public interface OneToOneMapper {
//查询card表
List<Card> selectById(Integer id);
//查询person表
List<Person> selectId(Integer id);
}
映射文件
<!-- card表外键pid对应person表主键id-->
<mapper namespace="com.itheima.table01.OneToOneMapper">
<resultMap id="OTO" type="card">
<id column="id" property="id" />
<result column="number" property="number" />
<!--
column指定执行下一条sql语句传入的参数 (这里是传入card表的pid)
select指定下一条要执行的sql语句
-->
<association property="p" column="pid" select="selectId" javaType="person">
<id column="id" property="id" />
<result column="name" property="name" />
<result column="age" property="age" />
</association>
</resultMap>
<select id="selectId" resultType="person">
select * from person where id=#{id}
</select>
<select id="selectById" resultMap="OTO">
select * from card where pid=#{pid}
</select>
</mapper>
测试
public void test() throws Exception{
InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
SqlSession sqlSession = sqlSessionFactory.openSession(true);
OneToOneMapper mapper = sqlSession.getMapper(OneToOneMapper.class);
List<Card> cards = mapper.selectById(6);
for (Card card : cards) {
//注:不要直接输出card对象,因为会触发toString()方法,导致立即加载person对象。
System.out.println(card.getId());//只查询了card表,执行了一条sql语句,查询结果1
// System.out.println(card.getP());//查询了person表和card表,执行了两条sql语句,查询结果2
}
sqlSession.close();
is.close();
}
查询结果1
查询结果2
使用注解方式
Mapper接口
@Select("select * from card where id=#{id}")
@Results({
//fetchType 指定是否使用延迟加载 FetchType.LAZY 表示延迟加载 FetchType.EAGER 表示即时加载
@Result(property = "p", column = "pid", one=@One(select = "selectId", fetchType = FetchType.LAZY))
})
List<Card> selectById(Integer id)
@Select("select * from person where id=#{id}")
List<Person> selectId(Integer id);