MyBatis+MyBatisPlus中遇到的一些坑

MyBatis是很常用的持久层框架,MyBatisPlus是一个 MyBatis 的增强工具.在实际工作中这两者就像是咖啡伴侣一样如影随形.

但是总会遇到这样或那样的问题,可能是一个失误,也可能是踩了个坑

坑一:MyBatisPlus分页不生效

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

 @Configuration
 public class WebMvcConfig extends WebMvcConfigurationSupport {
   @Bean
    public PaginationInterceptor paginationInterceptor() {
        return new PaginationInterceptor();
    }
 }

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

这是个真坑,好多人踩过.之所以会错误,是因为MyBatisPlus的分页是在SQL语句最后添加limit实现的,这就导致一对多关联查询出来的多条数据被记入了总条数参加了分页.

想要解决,简单粗暴的就是把关联查询分开,先查"一"的相关信息,然后遍历再查"多"的相关信息.

作为一个认(闲)真(的)负(蛋)责(疼)的程序猿,肯定得用一些看上去高(没)大(卵)上(用)的方式.

实体

@Data
@ApiModel(value="产品对象")
public class EcProduct{

    @TableId(value = "id", type = IdType.AUTO)
    private Integer id;

    @ApiModelProperty(value = "产品名称")
    private String name;
    
    @ApiModelProperty(value = "添加时间")
    private Date createDate;

    @ApiModelProperty(value = "操作人ID")
    private Integer optUserId;
    //一对一
	private EcInsuranceCompany insuranceCompany;
	//一对多
	private List<EcProductDuty> dutys;
}


@Data
@ApiModel(value="公司对象")
public class EcInsuranceCompany{

    @TableId(value = "id", type = IdType.AUTO)
    private Integer id;

    @ApiModelProperty(value = "公司名称")
    private String name;
}

@Data
@ApiModel(value="信息对象")
public class EcProductDuty {
    @TableId(value = "id", type = IdType.AUTO)
    private Integer id;
    private String detail;
}

mapper.xml

   <resultMap id="productPlanRespone" type="XXX.EcProduct">
        <id property="id" column="id"/>
        <result property="name" column="name"/>
        .............
        <association property="insuranceCompany" javaType="XXX.EcInsuranceCompany">
            <id property="id" column="iid"/>
            ............
        </association>
        <collection property="dutys" column="id" select="XXXX.getProductDutyByPlanId">
        </collection>
    </resultMap>

       <select id="XXX" resultMap="productPlanRespone">
		</select>

mybatisplus遇到的问题

使用MyBatis-plus代码生成器 出错

1、使用myabtis-plus代码自动生成器,启动时出现下面这个错误

在pom.xml中添加下面依赖

  <dependency>
            <groupId>org.apache.velocity</groupId>
            <artifactId>velocity-engine-core</artifactId>
            <version>2.2</version>
        </dependency>
<dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>3.4.1</version>
        </dependency>

2、代码生成器启动以后,发现已经自动创建了一些包和代码

打开entiry包下的实体类User,发现显示包不存在

在pom.xml配置文件中添加下面依赖

   <!--配置ApiModel在实体类中不生效-->
    <dependency>
        <groupId>com.spring4all</groupId>
        <artifactId>spring-boot-starter-swagger</artifactId>
        <version>1.5.1.RELEASE</version>
    </dependency>

至此,使用MyBatis-plus代码生成器 遇到的错误全部总结完毕。

总结