【一线大厂Java面试题解析+后端开发学习笔记+最新架构讲解视频+实战项目源码讲义】
**开源地址:https://docs.qq.com/doc/DSmxTbFJ1cmN1R2dB **
====================================================================================
============================================================================
新建一个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相应的坐标已经导入完成
接着设置数据源
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<Role> getAll();
}
测试类中注入dao接口,测试功能
@SpringBootTest
class Springboot04MybatisApplicationTests {
@Autowired
private UserDao userDao;
@Test
void contextLoads() {
List<Role> 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与Mybati 区别
- 导入坐标不同
- 数据层实现简化
注意:由于SpringBoot中未收录MyBatis-Plus的坐标版本,需要指定对应的Version
- SpringBoot没有整合Mybatis-Plus,所以需要我们手动添加SpringBoot整合MyBatis-Plus的坐标,可以通过mvnrepository获取
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.3</version>
</dependency>
- 定义数据层接口与映射配置,继承BaseMapper
@Mapper
public interface UserDao extends BaseMapper {
}
- 在yml配置文件配置数据库前缀