mybatis文件映射之利用延迟加载解决分布查询每次查询Employee时都得查Department(四)

2020-08-26 11:41:30 浏览数 (1)

之前关联查询时,每次查Employee时都会带上Department,现在我们想当只有需要查Department时才去查找它,可以使用延迟加载。

在mybatis配置文件中配置:

代码语言:javascript复制
    <settings>
        <setting name="lazyLoadingEnabled" value="true"/>
        <setting name="aggressiveLazyLoading" value="false"/>
    </settings>

此时再利用上节的分布查询的代码进行测试,只不过在测试时:如果我们只是要打印lastName:

代码语言:javascript复制
            Employee employee = mapper.getEmpByIdStep(3);
            System.out.println(employee.getLastName());

输出:

DEBUG 01-20 15:04:34,894 ==> Preparing: select * from tbl_employee where id=? (BaseJdbcLogger.java:145) DEBUG 01-20 15:04:35,016 ==> Parameters: 3(Integer) (BaseJdbcLogger.java:145) DEBUG 01-20 15:04:35,245 <== Total: 1 (BaseJdbcLogger.java:145) 小红

假设我们要打印dept:

代码语言:javascript复制
            Employee employee = mapper.getEmpByIdStep(3);
            System.out.println(employee.getDept());

输出:

DEBUG 01-20 15:05:00,830 ==> Preparing: select * from tbl_employee where id=? (BaseJdbcLogger.java:145) DEBUG 01-20 15:05:00,872 ==> Parameters: 3(Integer) (BaseJdbcLogger.java:145) DEBUG 01-20 15:05:01,047 <== Total: 1 (BaseJdbcLogger.java:145) DEBUG 01-20 15:05:01,049 ==> Preparing: select * from tbl_department where id=? (BaseJdbcLogger.java:145) DEBUG 01-20 15:05:01,050 ==> Parameters: 1(Integer) (BaseJdbcLogger.java:145) DEBUG 01-20 15:05:01,053 <== Total: 1 (BaseJdbcLogger.java:145) Department [id=1, deptName=开发部]

发现没,当我们使用了延迟加载后,当我们不使用Deparment时,只会发送一条sql语句。

0 人点赞