Introduction and use of mybatis resultMap collection tags

When we design the database, we must strictly follow the 3NF design, such as

Examples: order table (order), order goods table (order_goods), an order has multiple goods, the order information is stored in the order table, and the product information is stored in the goods table, one to many form one to many

Order form 

 

Order item table

 Find out the product information corresponding to the order, our sql is

select o.id, o.name, g.id as gid, g.order_id, g.goods_name
    from du_order o  inner join du_goods g on o.id = g.order_id 

Query results

When some students encounter such problems, they will first find out the information of the order and check the goods table according to the id of the order, and perform db twice (is there any such student? Definitely)

The collection tag in the resultMap solves this kind of problem for us, and a db finds the result we want.

Next, use the collection tag of resultMap to simplify development and map fields

First define the dto entity and transmit data to the front end

public class OrderDto{

    private Integer id; // 订单id
    private String orderName; // 订单名
    private List<Goods> goodsList; // 订单商品信息
    
    // getter setter toString 省略

}

Corresponding mapper xml writing

Parameter details:

  • The field mapped by property, such as the goodsList field in dto
  • The type of ofType type mapping is shown in the goods type
  • Note (do not have the same name field when mapping, for example, g.id and o.id have the same name, use as to create the alias, or fail to map)

operation result

[OrderDto(id=1, orderName=杜国涛, goodsList=[Goods(id=1, orderId=1, goodsName=雪丸子), Goods(id=2, orderId=1, goodsName=巧克力)])]

Summary: simplify development and reduce db requests

Guess you like

Origin blog.csdn.net/weixin_44912855/article/details/115358981