MyBatis Plus实现多表联接、分页查询的方法
创始人
2024-11-18 03:42:15
0次

代码实现

entity、mapper、service、controller 使用了 MyBatisPlus 的代码生成器,自动生成大部分基础的代码,操作方法见之前的文章:

在 SpringBoot 中引入 MyBatisPlus 之 常规操作

1.实体

① Question

// import 省略

@TableName("t_question")
public class Question implements Serializable {

  private static final long serialVersionUID = 1L;

  @ApiModelProperty(value = "问答主键id")
  @TableId(value = "id", type = IdType.AUTO)
  private Integer id;

  @ApiModelProperty(value = "学生外键id")
  @TableField("student_id")
  private Integer studentId;

  @ApiModelProperty(value = "问题内容")
  private String content;

  @ApiModelProperty(value = "问题发布时间,发布的时候后台自动生成")
  private Date date;

  @ApiModelProperty(value = "问题悬赏的积分")
  private Integer value;

	// getter、setter 省略
}

② Student

// import 省略

@TableName("t_student")
public class Student implements Serializable {

  private static final long serialVersionUID = 1L;

  @ApiModelProperty(value = "学生主键id")
  @TableId(value = "id", type = IdType.AUTO)
  private Integer id;

  @ApiModelProperty(value = "学生名称")
  private String name;

  @ApiModelProperty(value = "学生密码")
  private String password;

  @ApiModelProperty(value = "学生积分数")
  private Integer points;

  @ApiModelProperty(value = "学生邮件地址")
  private String email;

  @ApiModelProperty(value = "学生手机号码")
  private String phone;

  @ApiModelProperty(value = "学生学号")
  private String num;

  @ApiModelProperty(value = "学生真实姓名")
  @TableField("true_name")
  private String trueName;

	// getter、setter 省略
}

2.mapper

① StudentMapper

// import 省略
public interface StudentMapper extends BaseMapper {
}

② QuestionMapper

// import 省略
public interface QuestionMapper extends BaseMapper {
  /**
   *
   * @param page 翻页对象,可以作为 xml 参数直接使用,传递参数 Page 即自动分页
   * @return
   */
  @Select("SELECT t_question.*,t_student.`name` FROM t_question,t_student WHERE t_question.student_id=t_student.id")
  List getQuestionStudent(Pagination page);

}

3、service

① StudentService

// import 省略
public interface StudentService extends IService {
}

② QuestionService

// import 省略
public interface QuestionService extends IService {

  Page getQuestionStudent(Page page);

}

4、serviceImpl

① StudentServiceImpl

// import 省略
@Service
public class StudentServiceImpl extends ServiceImpl implements StudentService {

}

② QuestionServiceImpl

// 省略 import

@Service
public class QuestionServiceImpl extends ServiceImpl implements QuestionService {

  @Override
  public Page getQuestionStudent(Page page) {
    return page.setRecords(this.baseMapper.getQuestionStudent(page));
  }

}

5、controller

// 省略 import

@RestController
@RequestMapping("/common")
@EnableSwagger2
public class CommonController {

  @Autowired
  QuestionService questionService;

  @Autowired
  StudentService studentService;

  @GetMapping("/getAllQuestionByPage/{page}/{size}")
  public Map getAllQuestionByPage(@PathVariable Integer page, @PathVariable Integer size) {
    Map map = new HashMap<>();
    Page questionPage = questionService.selectPage(new Page<>(page, size));
    if (questionPage.getRecords().size() == 0) {
      map.put("code", 400);
    } else {
      map.put("code", 200);
      map.put("data", questionPage);
    }
    return map;
  }

  @GetMapping("/getAllQuestionWithStudentByPage/{page}/{size}")
  public Map getAllQuestionWithStudentByPage(@PathVariable Integer page, @PathVariable Integer size) {
    Map map = new HashMap<>();
    Page questionStudent = questionService.getQuestionStudent(new Page<>(page, size));
    if (questionStudent.getRecords().size() == 0) {
      map.put("code", 400);
    } else {
      map.put("code", 200);
      map.put("data", questionStudent);
    }
    return map;
  }

}

6、MyBatisPlus 配置

// 省略 import

@EnableTransactionManagement
@Configuration
@MapperScan("com.cun.app.mapper")
public class MybatisPlusConfig {

  /**
   * 分页插件
   */
  @Bean
  public PaginationInterceptor paginationInterceptor() {
    return new PaginationInterceptor();
  }

  /**
   * 打印 sql
   */
  @Bean
  public PerformanceInterceptor performanceInterceptor() {
    PerformanceInterceptor performanceInterceptor = new PerformanceInterceptor();
    //格式化sql语句
    Properties properties = new Properties();
    properties.setProperty("format", "true");
    performanceInterceptor.setProperties(properties);
    return performanceInterceptor;
  }
}

7、关联查询 VO 对象

// import 省略

public class QuestionStudentVO implements Serializable {

  @ApiModelProperty(value = "问答主键id")
  @TableId(value = "id", type = IdType.AUTO)
  private Integer id;

  @ApiModelProperty(value = "学生外键id")
  @TableField("student_id")
  private Integer studentId;

  private String name;

  @ApiModelProperty(value = "问题内容")
  private String content;

  @ApiModelProperty(value = "问题发布时间,发布的时候后台自动生成")
  private Date date;

  @ApiModelProperty(value = "问题悬赏的积分")
  private Integer value;

	// getter、setter 省略

五、测试接口

MyBatis Plus实现多表联接、分页查询的方法

1、没有关联的分页查询接口

http://localhost/common/getAllQuestionByPage/1/2

① json 输出

{
 "code": 200,
 "data": {
  "total": 10,
  "size": 2,
  "current": 1,
  "records": [
   {
    "id": 1,
    "studentId": 3,
    "content": "唐代,渝州城里,有一个性格开朗、乐观的小伙子,名叫景天。",
    "date": 1534497561000,
    "value": 5
   },
   {
    "id": 2,
    "studentId": 1,
    "content": "雪见从小父母双亡,由爷爷唐坤抚养成人。",
    "date": 1533201716000,
    "value": 20
   }
  ],
  "pages": 5
 }
}

② sql 执行

MyBatis Plus实现多表联接、分页查询的方法

2、多表关联、分页查询接口

http://localhost/common/getAllQuestionWithStudentByPage/1/2

① json 输出

{
 "code": 200,
 "data": {
  "total": 10,
  "size": 2,
  "current": 1,
  "records": [
   {
    "id": 1,
    "studentId": 3,
    "name": "vv",
    "content": "唐代,渝州城里,有一个性格开朗、乐观的小伙子,名叫景天。",
    "date": 1534497561000,
    "value": 5
   },
   {
    "id": 2,
    "studentId": 1,
    "name": "cun",
    "content": "雪见从小父母双亡,由爷爷唐坤抚养成人。",
    "date": 1533201716000,
    "value": 20
   }
  ],
  "pages": 5
 }
}

② sql 执行

MyBatis Plus实现多表联接、分页查询的方法

六、小结

写本文的原因:

①网上有做法不合时宜的文章(自定义page类、配置版)②官方文档使用的是配置版的,笔者采用注解版的

MyBatis 配置版MyBatis 注解版
① 动态 sql 灵活、② xml 格式的 sql,可拓展性好① 少一个设置,少一个错误爆发点、② 代码清晰优雅

相关内容

热门资讯

空调连续工作多久需要停机休息 空调连续工作的时间取决于多个因素,包括空调的型号、功率、使用环境和维护情况等。一般来说,空调可以连续...
空调哪个符号是除湿的 空调除湿功能通常用一个水滴形状的符号表示。不同品牌和型号的空调遥控器可能会有所差异,但一般来说,除湿...
格力空调多长时间加一次氟利昂 1、一般情况下,空调对氟利昂的使用量是非常小的,所以在空调使用了四年左右的时候再考虑加也没问题。2、...
空调用多长时间需要加氟一次 一般情况下是五年。当出现以下这几种情况时,空调才需要加氟。1、空调的室内机和室外机各有两个接口,当接...
格调生活·C标思享荟:卡萨帝在... 9月12日的郑州龙湖金融岛,夜风轻拂,灯光璀璨。“C标时刻共传奇——卡萨帝思享荟暨20周年品牌盛典郑...
品牌价值破千亿、高端份额持续领... 9月12日,“C标时刻共传奇——卡萨帝思享荟暨20周年品牌盛典郑州站”在郑州龙湖金融岛举办。2026...
空调主板坏了修800还是换新的 空调主板坏了是修还是换新,需要考虑多个因素,以下是一些建议:1. 维修成本:如果维修费用较低,比如 ...
空调开多久需要休息多长时间 问题:空调开多久需要休息多长时间回答:1、在使用空调的过程中,一般空调开7~8个小时左右需要休息2~...
中央空调多长时间清洗一次 1、一般空调开机前清洗一次即可,空调开机中间时段再清洗一次,空调关机时清洗一次,这样比较合理。2、空...
中央空调氟利昂多久加一次 看空调制热和制冷程度,很多人的观点认为氟利昂必须一年放一次,其实这个观点是错误的,理解上面有点偏差,...