懒加载会按需要是否执行关联查询语句。如果用到了关联查询语句的信息,就需要执行关联查询,否则就只执行主查询
1.在mybatis的全局配置文件中加入两个属性:
<settings> <setting name="mapUnderscoreToCamelCase" value="true"/> <!-- 开启懒加载机制 ,默认值为true--> <setting name="lazyLoadingEnabled" value="true"/> <!-- 开启的话,每个属性都会直接全部加载出来;禁用的话,只会按需加载出来 --> <setting name="aggressiveLazyLoading" value="false"/> </settings>
Mapper接口:
public tbl_employee findTblEmployeeById(int id);
xml文件:
<!--关联查询-->
<select id="selectDepartment" resultType="com.neuedu.bean.tbl_dept"> select * from tbl_dept where id=#{id} </select> <resultMap type="com.neuedu.bean.tbl_employee" id="findTblEmployeeByIdMap"> <id column="id" property="id" /> <result column="email" property="email" /> <result column="gender" property="gender" /> <result column="user_name" property="userName" /> <!-- <result column="d_id" property="dId"/> --> <association property="dept" select="selectDepartment" column="d_id"></association> </resultMap>
<!--主查询-->
<select id="findTblEmployeeById" resultMap="findTblEmployeeByIdMap" parameterType="int"> select e.id,e.email,e.gender,e.user_name,e.d_id from tbl_employee e where e.id=#{id} </select>
测试:
只用到主查询的信息
@Test public void testFindEmployee() throws IOException{ SqlSessionFactory sqlSessionFactory = sqlSessionFactory(); SqlSession openSession = sqlSessionFactory.openSession(); Tbl_employeeMapper mapper = openSession.getMapper(Tbl_employeeMapper.class); tbl_employee findTblEmployeeById = mapper.findTblEmployeeById(1); System.out.println("名字:"+findTblEmployeeById.getUserName()); }
下面是打印的日志:
DEBUG 09-05 20:13:14,178 ==> Preparing: select e.id,e.email,e.gender,e.user_name,e.d_id from tbl_employee e where e.id=? (BaseJdbcLogger.java:145)
DEBUG 09-05 20:13:14,452 ==> Parameters: 1(Integer) (BaseJdbcLogger.java:145)
DEBUG 09-05 20:13:14,861 <== Total: 1 (BaseJdbcLogger.java:145)
名字:yr
通过日志可知只打印了一条SQL语句,就以为着只执行了一条主查询
使用了关联查询的信息:
@Test public void testFindEmployee() throws IOException{ SqlSessionFactory sqlSessionFactory = sqlSessionFactory(); SqlSession openSession = sqlSessionFactory.openSession(); Tbl_employeeMapper mapper = openSession.getMapper(Tbl_employeeMapper.class); tbl_employee findTblEmployeeById = mapper.findTblEmployeeById(1); System.out.println(findTblEmployeeById); }
打印的日志:
DEBUG 09-05 20:17:13,873 ==> Preparing: select e.id,e.email,e.gender,e.user_name,e.d_id from tbl_employee e where e.id=? (BaseJdbcLogger.java:145)
DEBUG 09-05 20:17:14,107 ==> Parameters: 1(Integer) (BaseJdbcLogger.java:145)
DEBUG 09-05 20:17:14,449 <== Total: 1 (BaseJdbcLogger.java:145)
DEBUG 09-05 20:17:14,454 ==> Preparing: select * from tbl_dept where id=? (BaseJdbcLogger.java:145)
DEBUG 09-05 20:17:14,455 ==> Parameters: 1(Integer) (BaseJdbcLogger.java:145)
DEBUG 09-05 20:17:14,460 <== Total: 1 (BaseJdbcLogger.java:145)
tbl_employee [id=1, userName=yr, gender=0, email=907339416@qq.com, dId=0, dept=tbl_dept [id=1, deptName=秘书部, empList=null]]
这里用到了关联查询的信息,所以用到了两个查询语句。打印了两个。