mybatis-plus入门使用、踩坑记录

背景:

        公司持久层框架最开始使用的是 org.mybatis 包下,后来切换为了 com.baomidou.mybatisplus 包下的 mybatis-plus


首先引入mybatis-plus依赖:

Spring Boot项目:


    com.baomidou
    mybatis-plus-boot-starter
    3.2.0

Spring MVC项目:


    com.baomidou
    mybatis-plus
    3.2.0

配置:

Spring Boot 工程:

@MapperScan("com.xxx.mapper")

Spring MVC 工程:

  • 配置 MapperScan

    
  • 调整 SqlSessionFactory 为 MyBatis-Plus 的 SqlSessionFactory

    

 引入:extends BaseMapper

mybatis-plus入门使用、踩坑记录_第1张图片

 还有扩展的server方法及实现,可以自己点进去看下

mybatis-plus入门使用、踩坑记录_第2张图片

需要用到就对应service继承即可,示例:

public interface UserService extends BaseService {
}
public class UserServiceImpl extends BaseServiceImpl implements UserService {
}

 

坑一:出现 Invalid bound statement (not found) 异常

  • 未去除原有mybatis-spring-boot-starter依赖,导致冲突
  • mapper文件夹未扫描到,加入@MapperScan

坑二:Caused by: java.sql.SQLIntegrityConstraintViolationException: Column 'xxx' cannot be null

这个问题很明显是字段不能是空,必须使用selective方法进行插入。一开始怀疑mybatis-plus的插入语句(就只一个insert)是全量插入

后来查找mapper文件找到了问题所在。之前用的mybatis框架自动生成的mapper.xml代码中的insert语句为全量插入,本地写了同名的xml会优先使用本地的SQL进行查询。

mybatis-plus入门使用、踩坑记录_第3张图片

解决:删除所有mybatis生成的SQL语句,避免与mybatis-plus的底层SQL冲突

坑三:主键随机自增,导致ID超范围问题 Could not set property 'id' of 'class com.xxx.User' with value '1037678924715731598' Cause: java.lang.IllegalArgumentException: argument type mismatch

如果没有指定ID生成策略,mybatis-plus默认是使用自己随机的ID生成策略,会生成一个比较大的数,可能会大小溢出。

mybatis-plus入门使用、踩坑记录_第4张图片

解决:在实体类ID字段上加上注解 @TableId(type = IdType.AUTO),使用数据库的自增策略。如果自增主键很多都是id,可以写一个基础的BasePO,在这个类里面指定id的生成策略,其它表对应实体类继承即可,如下:

public class BasePO {

    @TableId(type= IdType.AUTO)
    private Long id;
}

mybatis-plus入门使用、踩坑记录_第5张图片

下面是IdType其它类型介绍

mybatis-plus入门使用、踩坑记录_第6张图片

坑四:关键字冲突问题 Cause: java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'order WHERE id=1

当你的数据库表名是order、group等之类的关键字时,对该表的操作则会报错.

解决:在表对应的实体上增加注解 @TableName("`order`"),使用``指定表名即可

当数据库字段是关键字时,对该字段的操作则会报错.、

解决:在对应实体字段上增加注解@TableField("key"),指定字段即可

 

你可能感兴趣的:(应用技术,常见问题)