多对多通过注解查询数据
案例: 获取订单的详细信息
1.实体类:
public class Category { private int id; private String name; List<Product> products; } public class Product { private int id; private String name; private float price; private Category category; }
public class Order { //订单 private int id; private String code; List<OrderItem> orderItems; } public class OrderItem { //订单物品 private int id; private int number; private Order order; private Product product; }
2.关系分析:
订单1----订单物品n----产品n----分类1
3.dao层:
public interface OrderMapper { @Select("select * from order_") @Results({ @Result(property = "id", column = "id"), @Result(property = "orderItems", javaType = List.class, column = "id", many = @Many(select = "com.how2java.mapper.OrderItemMapper.listByOrder")) }) public List<Order> list(); }
public interface OrderItemMapper { @Select(" select * from order_item_ where oid = #{oid}") @Results({ @Result(property="product",column="pid",one=@One(select="com.how2java.mapper.ProductMapper.get")) }) public List<OrderItem> listByOrder(int oid); }
public interface ProductMapper { @Select("select * from product_ where id = #{id}") public Product get(int id); }
4.效果图: