MyBatis + MyBatisPlus 中遇到的一些坑

偏执的太偏执、 2021-11-04 10:26 981阅读 0赞

      • 叨叨
    • 坑一:MyBatisPlus分页不生效
    • 坑二:一对多关联查询查询总条数错误

叨叨

MyBatis是很常用的持久层框架,MyBatisPlus是一个 MyBatis 的增强工具.在实际工作中这两者就像是咖啡伴侣一样如影随形.
但是总会遇到这样或那样的问题,可能是一个失误,也可能是踩了个坑

坑一:MyBatisPlus分页不生效

自己没开启分页插件,是谁更坑呢?

  1. @Configuration
  2. public class WebMvcConfig extends WebMvcConfigurationSupport {
  3. @Bean
  4. public PaginationInterceptor paginationInterceptor() {
  5. return new PaginationInterceptor();
  6. }
  7. }

坑二:一对多关联查询查询总条数错误

这是个真坑,好多人踩过.之所以会错误,是因为MyBatisPlus的分页是在SQL语句最后添加limit实现的,这就导致一对多关联查询出来的多条数据被记入了总条数参加了分页.
想要解决,简单粗暴的就是把关联查询分开,先查”一”的相关信息,然后遍历再查”多”的相关信息.
作为一个认(闲)真(的)负(蛋)责(疼)的程序猿,肯定得用一些看上去高(没)大(卵)上(用)的方式.

  1. 实体
  2. @Data
  3. @ApiModel(value="产品对象")
  4. public class EcProduct{
  5. @TableId(value = "id", type = IdType.AUTO)
  6. private Integer id;
  7. @ApiModelProperty(value = "产品名称")
  8. private String name;
  9. @ApiModelProperty(value = "添加时间")
  10. private Date createDate;
  11. @ApiModelProperty(value = "操作人ID")
  12. private Integer optUserId;
  13. //一对一
  14. private EcInsuranceCompany insuranceCompany;
  15. //一对多
  16. private List<EcProductDuty> dutys;
  17. }
  18. @Data
  19. @ApiModel(value="公司对象")
  20. public class EcInsuranceCompany{
  21. @TableId(value = "id", type = IdType.AUTO)
  22. private Integer id;
  23. @ApiModelProperty(value = "公司名称")
  24. private String name;
  25. }
  26. @Data
  27. @ApiModel(value="信息对象")
  28. public class EcProductDuty {
  29. @TableId(value = "id", type = IdType.AUTO)
  30. private Integer id;
  31. private String detail;
  32. }
  33. mapper.xml
  34. <resultMap id="productPlanRespone" type="XXX.EcProduct">
  35. <id property="id" column="id"/>
  36. <result property="name" column="name"/>
  37. .............
  38. <association property="insuranceCompany" javaType="XXX.EcInsuranceCompany">
  39. <id property="id" column="iid"/>
  40. ............
  41. </association>
  42. <collection property="dutys" column="id" select="XXXX.getProductDutyByPlanId">
  43. </collection>
  44. </resultMap>
  45. <select id="XXX" resultMap="productPlanRespone">
  46. </select>

发表评论

表情:
评论列表 (有 0 条评论,981人围观)

还没有评论,来说两句吧...

相关阅读