目录
- SpringBoot整合第三方技术
- 一、整合Junit
- 二、整合Mybatis
- 三、整合Mybatis-Plus
- 四、整合Druid
- 五、总结
SpringBoot整合第三方技术
一、整合Junit
新建一个SpringBoot项目
使用@SpringBootTest标签在test测试包内整合Junit
@SpringBootTest
class Springboot03JunitApplicationTests {
@Autowired
private BookService bookService;
@Test
void contextLoads() {
bookService.save();
}
}
- 名称:@SpringBootTest
- 类型:测试类注解
- 位置:测试类定义上方
- 作用:设置Junnit加载的SpringBoot启动类
注意:整合的Junit测试类需要和Java包中的配置文件类放在同一目录下,否则需要指定配置java文件的class
@SpringBootTest(classes = Springboot03JunitApplication.class)
class Springboot03JunitApplicationTests {
@Autowired
private BookService bookService;
@Test
void contextLoads() {
bookService.save();
}
}

二、整合Mybatis
创建新模块的时候选择需要的技术集

之后就可以看到mybatis相应的坐标已经导入完成
接着设置数据源
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/test
username: root
password: 123456
定义数据层接口与映射配置
public interface UserDao {
@Select("select * from test.sys_role;")
public List getAll();
}
测试类中注入dao接口,测试功能
@SpringBootTest
class Springboot04MybatisApplicationTests {
@Autowired
private UserDao userDao;
@Test
void contextLoads() {
List roleList = userDao.getAll();
System.out.println(roleList);
}
}
注意:
- 数据库SQL映射需要添加@Mapper被容器识别到
- 数据库连接相关信息转换成配置
- SpringBoot版本低于2.4.3(不含),Mysql驱动版本大于8.0时,需要在url连接串中配置时区,或在MySQL数据库端配置时区解决此问题
jdbc:mysql://localhost:3306/test?serverTimezone=UTC
三、整合Mybatis-Plus
Mybatis-Plus与Mybati 区别
注意:由于SpringBoot中未收录MyBatis-Plus的坐标版本,需要指定对应的Version
SpringBoot没有整合Mybatis-Plus,所以需要我们手动添加SpringBoot整合MyBatis-Plus的坐标,可以通过mvnrepository获取
com.baomidou
mybatis-plus-boot-starter
3.4.3
定义数据层接口与映射配置,继承BaseMapper
@Mapper
public interface UserDao extends BaseMapper {
}
在yml配置文件配置数据库前缀

#设置mp相关配置
mybatis-plus:
global-config:
db-config:
table-prefix: sys_
测试
@SpringBootTest
class Springboot05MybatisPlusApplicationTests {
@Autowired
private UserDao userDao;
@Test
void contextLoads() {
Role role = userDao.selectById(1);
System.out.println(role);
}
}
四、整合Druid
同样的,Druid也需要自己手工整合
Maven导入依赖
com.alibaba
druid-spring-boot-starter
1.2.6
在yml配置文件指定数据源
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/ssm_db?serverTimezone=UTC
username: root
password: root
type: com.alibaba.druid.pool.DruidDataSource
或者
spring:
datasource:
druid:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/ssm_db?serverTimezone=UTC
username: root
password: root
五、总结
整合第三方技术的步骤:
druid:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/ssm_db?serverTimezone=UTC
username: root
password: root