如何拿模板做网站,网站建设非功能需求,无极县最新招聘信息,东营百姓网一对多关联映射
一对多关联映射有两种方式#xff0c;都用到了collection元素
以购物网站中用户和订单之间的一对多关系为例 collection集合的嵌套结果映射
创建两个实体类和映射接口
package org.example.demo;import lombok.Data;import java.util.List;Data
public cla…一对多关联映射
一对多关联映射有两种方式都用到了collection元素
以购物网站中用户和订单之间的一对多关系为例 collection集合的嵌套结果映射
创建两个实体类和映射接口
package org.example.demo;import lombok.Data;import java.util.List;Data
public class User {private Integer userId;private String userName;private String password;private Cart cart;private ListOrder orderList;
}
package org.example.demo;import lombok.Data;Data
public class Order {private Integer orderId;private double price;
}
实现根据用户id查询出所有用户信息包括该用户的所有订单信息
package org.example.mapper;import org.example.demo.User;import java.util.List;public interface UserMapper {User findUserAndOrderListByUserId(Integer userId);
}
方式一与association类似集合的嵌套结果映射就是指通过一次SQL查询得到所有的结果
resultMap typecom.mybatis.entity.User iduserMapid propertyid columnid/result propertyuserName columnuser_name/result propertypassword columnpassword/
/resultMap
resultMap typecom.mybatis.entity.User iduserAndOrderListMap extendsuserMapcollection propertyorderList ofTypecom.mybatis.entity.Orderid propertyid columnorder_id/result propertyprice columnprice//collection
/resultMap
select idfindUserAndOrderListById resultMapuserAndOrderListMapselect u.id, u.user_name, u.password,o.order_id, o.pricefrom user uleft join orders o on u.id o.user_idwhere u.id #{id}
/selectresultMap元素中的extends属性可以实现结果映射的继承
collection的ofType属性指定集合中元素的类型必选项 resultMap iduserAndOrderMap typeorg.example.demo.Userid propertyuserId columnuser_id/result propertyuserName columnuser_name/result propertypassword columnpassword/collection propertyorderList ofTypeorg.example.demo.Orderid propertyorderId columnorder_id/result propertyprice columnprice//collection/resultMapselect idfindUserAndOrderListByUserId resultMapuserAndOrderMapselect*from t_user uleft join t_order o on u.user_id o.user_idwhere u.user_id #{userId};/select collection集合的嵌套查询
集合的嵌套查询同样会执行额外的SQL查询
resultMap typecom.mybatis.entity.UseriduserAndOrderListMap extendsuserMapcollection propertyorderList column{uidid}ofTypecom.mybatis.entity.Order selectcom.mybatis.mapper.OrderMapper.findOrdersByUserId/collection
/resultMap
select idfindUserAndOrderListById resultMapuserAndOrderListMapselect * from user where id #{id}
/selectOrderMapper.xml
resultMap typecom.mybatis.entity.OrderidorderMapid propertyid columnorder_id/result propertyprice columnprice/
/resultMap
select idfindOrdersByUserIdresultMaporderMapselect * from orders where user_id #{uid}
/select对比两种方式
第一种方式属于“关联的嵌套结果映射“,即通过一次SQL查询根据表或指定的属性映射到不同的对象中
第二种方式属于“关联的嵌套查询”利用简单的SQL语句通过多次查询得到想要的结果也可以实现延迟加载效果