<mappernamespace="com.itheima.mapper.UserMapper"> <resultMapid="userMap"type="com.itheima.domain.User"> <resultcolumn="id"property="id"></result> <resultcolumn="username"property="username"></result> <resultcolumn="password"property="password"></result> <resultcolumn="birthday"property="birthday"></result> <collectionproperty="orderList"ofType="com.itheima.domain.Order"> <resultcolumn="oid"property="id"></result> <resultcolumn="ordertime"property="ordertime"></result> <resultcolumn="total"property="total"></result> </collection> </resultMap> <selectid="findAll"resultMap="userMap"> select *,o.id oid from user u left join orders o on u.id=o.uid </select> </mapper>
1.2.6 测试结果
1 2 3 4 5 6 7 8 9 10
UserMapper mapper = sqlSession.getMapper(UserMapper.class); List<User> all = mapper.findAll(); for(User user : all){ System.out.println(user.getUsername()); List<Order> orderList = user.getOrderList(); for(Order order : orderList){ System.out.println(order); } System.out.println("----------------------------------"); }
1.3 多对多查询
1.3.1 多对多查询的模型
用户表和角色表的关系为,一个用户有多个角色,一个角色被多个用户使用
多对多查询的需求:查询用户同时查询出该用户的所有角色
1.3.2 多对多查询的语句
对应的sql语句:select u.*,r.*,r.id rid from user u left join user_role ur on u.id=ur.user_id inner join role r on ur.role_id=r.id;
<mappernamespace="com.itheima.mapper.UserMapper"> <resultMapid="userRoleMap"type="com.itheima.domain.User"> <resultcolumn="id"property="id"></result> <resultcolumn="username"property="username"></result> <resultcolumn="password"property="password"></result> <resultcolumn="birthday"property="birthday"></result> <collectionproperty="roleList"ofType="com.itheima.domain.Role"> <resultcolumn="rid"property="id"></result> <resultcolumn="rolename"property="rolename"></result> </collection> </resultMap> <selectid="findAllUserAndRole"resultMap="userRoleMap"> select u.*,r.*,r.id rid from user u left join user_role ur on u.id=ur.user_id inner join role r on ur.role_id=r.id </select> </mapper>
1.3.6 测试结果
1 2 3 4 5 6 7 8 9 10
UserMapper mapper = sqlSession.getMapper(UserMapper.class); List<User> all = mapper.findAllUserAndRole(); for(User user : all){ System.out.println(user.getUsername()); List<Role> roleList = user.getRoleList(); for(Role role : roleList){ System.out.println(role); } System.out.println("----------------------------------"); }