延迟加载:调用了什么方法,就只查询这个方法,这个方法所关联的其他方法不调用(懒加载)(使用场景:多对多、一对多)
立即加载:不管用不用,只要调用该方法,立马执行查询包括关联表的查询(使用场景:一对一、多对一)
下面是一对一(Student<–>Person)和一对多(Grade–>Student)的例子,一次查询会触发collection与association关联的表的查询,如果触及到那么就是立即加载,否则为延迟加载;
1.设置Mybatis-config.xml
这是Mybatis官方文档的描述
<settings>
<!--开启Mybatis支持延迟加载-->
<setting name="lazyLoadingEnabled" value="true"/>
<setting name="cacheEnabled" value="true"/>
<!--输出Sql语句-->
<setting name= "mapUnderscoreToCamelCase" value = "true"/>
<setting name="logImpl" value="STDOUT_LOGGING" />
</settings>
2.Entity层
Person
Student
PS:有Person属性(一对一)
Grade
PS:有List<Student>属性(一对多)
3.Dao层
PersonMapper
public interface PersonMapper {
Person selectByPrimaryKey(Integer pid);
}
PersonMapper.xml
<mapper namespace="Dao.PersonMapper">
<resultMap id="BaseResultMap" type="Entity.Person">
<id column="pid" jdbcType="INTEGER"<