<mappernamespace="cn.jyw.pojo.UserMapper"> <resultMapid="userMap"type="cn.jyw.pojo.User"> <resultcolumn="id"property="id"/> <resultcolumn="username"property="username"/> <resultcolumn="password"property="password"/> <resultcolumn="birthday"property="birthday"/> <collectionproperty="orderList"ofType="cn.jyw.pojo.Order"> <resultcolumn="ordertime"property="ordertime"/> <resultcolumn="total"property="total"/> </collection> </resultMap> <selectid="findAll"resultMap="userMap"> select * from user u left join orders o on u.id=o.uid </select> </mapper>
测试结果
1 2 3 4 5 6 7 8 9 10
UserMappermapper= 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 多对多查询
多对多查询的模型
用户表和角色表的关系为,一个用户有多个角色
一个角色被多个用户使用
多对多查询的需求:查询用户同时查询出该用户的所有角色
user
user_role
role
id:int
user_id:int
id:int
username:varchar(50)
role_id:int
rolename:varchar(255)
password:varchar(50)
birthday:varchar(50)
多对多查询的语句
对应的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
<resultMapid="userRoleMap"type="cn.jyw.pojo.User"> <resultcolumn="id"property="id"/> <resultcolumn="username"property="username"/> <resultcolumn="password"property="password"/> <resultcolumn="birthday"property="birthday"/> <collectionproperty="roleList"ofType="cn.jyw.pojo.Role"> <resultcolumn="rid"property="id"/> <resultcolumn="rolename"property="rolename"/> </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>
测试结果
1 2 3 4 5 6 7 8 9 10
UserMappermapper= 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("----------------------------------"); }
1.4 MyBatis多表配置方式小结
一对一配置:使用<resultMap>做配置
一对多配置:使用<resultMap>+<collection>做配置
多对多配置:使用<resultMap>+<collection>做配置
2. MyBatis注解开发
2.1 MyBatis的常用注解
@Insert:实现新增
@Update:实现更新
@Delete:实现删除
@Select:实现查询
@Result:实现结果集封装
@Results:可以与@Result 一起使用,封装多个结果集
@One:实现一对一结果集封装
@Many:实现一对多结果集封装
2.2 MyBatis的增删改查
1 2 3 4 5 6 7 8 9 10 11 12 13 14
@Insert("insert into user values(#{id},#{username},#{password},#{birthday})") publicvoidsave(User user);
@Update("update user set username=#{username},password=#{password} where id=#{id}") publicvoidupdate(User user);
@Delete("delete from user where id=#{id}") publicvoiddelete(int id);
@Select("select * from user where id=#{id}") public User findById(int id);
@Select("select * from user") public List<User> findAll();