前情提要
我在跟着黑马的课程学习mybatisplus的时候,其中有用到springboot整合mybatisplus,具体过程如下:
- 创建springboot项目的时候勾选了SpringWeb和MySQL Driver,然后进入项目后在pow文件中导入mybatisplus的坐标如下:
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.2</version>
</dependency>
- 在application.yml中配置好了数据库的信息
- 在java文件夹中创建了实体类domain和数据访问层mapper板块
- 进入到test开始进行测试,测试代码如下:
@SpringBootTest
class MybatisplusDemo7ApplicationTests {
@Autowired
private BookMapper bookMapper;
@Test
void contextLoads() {
System.out.println(bookMapper.selectList(null));
}
}
- 报错信息如下:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'com.lqd.MybatisplusDemo7ApplicationTests': Unsatisfied dependency expressed through field 'bookMapper': No qualifying bean of type 'com.lqd.mapper.BookMapper' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
- 以上步骤均根据黑马的课程来执行,但是其中有很多问题!
解决方法:
- springboot和mybatis-plus的版本兼容问题,在课程里面的springboot为2.0版本,mybatis-plus用的是3.4.2,这是可以的。
- 但是! 现在的idea默认会给springboot3.0以上的版本,此时mp的版本就不能用3.4.2了,需要更换成:
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.3.1</version>
</dependency>
- 同时! 在springboot启动类里面需要加上mapperscan,或者在mapper接口里面加上@Mapper注解
@SpringBootApplication
@MapperScan("com.lqd.mapper")//必须要加上
public class MybatisplusDemo7Application {
public static void main(String[] args) {
SpringApplication.run(MybatisplusDemo7Application.class, args);
}
}
- 最后还有一点,使用mybatisplus需要将实体类和表名对应,要不然也会报错。
@TableName("tb_book")//表名要对应
public class Book {
}
在按照教程使用SpringBoot2.0集成MybatisPlus3.4.2时出现依赖注入错误,原因是版本不兼容。升级MybatisPlus到3.5.3.1并添加@MapperScan注解到启动类解决了问题。另外,实体类需与表名对应以避免错误。

1389

被折叠的 条评论
为什么被折叠?



