今天刚好学了延迟加载就来做个记录吧,
延迟加载(懒加载) 首先需要配置Mybaits-config文件
<!-- 延迟加载设置--> <setting name="lazyLoadingEnabled" value="true"/> <setting name="aggressiveLazyLoading" value="false"/>
1.单端关联查询t添加select 需要在RoleDao中添加findRoleById方法,可无参数
Role findRoleById(int roleId); //RoleDao中添加
<!-- 延迟加载(懒加载)--> <resultMap id="lazyMap" type="com.demo.entity.User"> <id column="id" property="id"/> <result column="username" property="username"/> <result column="password" property="password"/> <association property="role" column="role_id" select="com.demo.dao.RoleDao.findRoleById"> 需要在RoleDao里面添加findRoleById方法 </association> </resultMap> <select id="findList" resultMap="lazyMap" > select id, username, password, role_id 对应association.column from tb_users </select>
对应的resultMap配置
<resultMap id="roleMap2" type="com.demo.entity.Role"> <id column="id" property="id"/> <result column="role_name" property="roleName"/> <result column="role_state" property="roleState"/> </resultMap> <select id="findRoleById" resultMap="roleMap2"> select id, role_name, role_state from tb_role where id = #{role_id} </select>
测试 正常 输出关联对象会出现多条SQL
List<User> list = mapper.findList(); for (User user : list) { System.out.println(user.getId() + ", " + user.getUsername() + ", " + user.getPassword() ); System.out.println(user.getRole().getId() + ", "+ user.getRole().getRoleName()); }
总结: 使用MyBatis3.4.6版本会出现 lazy proxy.这是MyBatis版本问题,之后我把他换成3.5.1之后可以正常运行。如:出现一些其他异常对应的column值写错了,要一一对应 初学者设置column和property最好使用复制粘贴的方式以免出现其他错误
优点: 使用延迟加载能够在不需要关联数据的时候,仅执行一条sql 提高执行速度(我的理解,如有不对请多指点)