mybatis-plus 实现一对一和一对多关系

本文介绍了如何利用MybatisPlus在查询订单详情时,处理车源表和照片表的一对一和一对多关系,展示了实体类设计、Service实现以及返回数据格式。重点强调了不使用VO和DTO的直接映射方法的便捷性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


前言

需求:多表查询数据,使用mybatisplus实现一对一关系和一对多关系的映射


一、需求

查询订单的详情信息,需要展示车源表信息和车源照片表信息。

二、实现

1.实现分析

1)通过给原生实体类加上实体属性,然后通过赋值到对应的实体属性就行。(不用写原生的xml映射方式)

2.代码实现

entity:

// @TableName("order")
// @ApiModel(description = "xx表")
@Data
public class CarSourceOrder implements Serializable {
    private static final long serialVersionUID = 1L;
    
    @TableField(exist = false)
    private CarSource carSource;

    @TableField(exist = false)
    private List<CarSourceFile> carSourceFileList;
}

ServiceImpl:

    @Override
    public CarSourceOrder findByCarSourceOrderInfo(Integer id) {
        CarSourceOrder  carSourceOrder = carSourceOrderDao.selectById(id);
        // 判断,以防carSourceOrder.getCarSourceId() 空指针异常
        if (StringUtils.isEmpty(carSourceOrder)){
            return carSourceOrder;
        }
        Integer carSourceId = carSourceOrder.getCarSourceId();
        carSourceOrder.setCarSource(carSourceDao.selectById(carSourceId));
        carSourceOrder.setCarSourceFileList(carSourceFileDao.selectList(new EntityWrapper<CarSourceFile>().eq("car_source_id", carSourceId)));
        return carSourceOrder;
    }

2.返回格式

代码如下(示例):

{
  "msg": "执行成功",
  "code": 0,
  "data": {
    "id": 5,
    "orderNumber": "123456789012345678"
    "yhcsCarSource": {
      "carModelName": "2014款 奔驰E级 E260L 豪华型",
      "carPlace": "广东"
    },
    "yhcsCarSourceFileList": [
      {
        "carSourceId": 40,
        "id": 6,
        "url": "https://xxx.jpg"
      },
      {
        "carSourceId": 40,
        "id": 7,
        "url": "https://xxx.jpg"
      }
    ]
  }
}

总结

1,VO和DTO不能使用,使用就不能调mybatis-plus提供的方法,不够快捷。
2,(补充)同理,对某个忽略字段进行分页处理也可以。例如: @TableField(exist = false)
private PageUtils carSourceList;
@TableField(exist = false)
private List<Map<String,String>> phones;

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值