使用Mybatis框架
使用Mybatis框架之前,需要添加相关依赖项:
<!-- Mybatis整合Spring Boot的依赖项 -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.2</version>
</dependency>
<!-- MySQL的依赖项 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
在Spring Boot项目中,当添加了数据库编程的依赖项后,启动项目时,会自动读取连接数据库的配置参数值,如果没有配置,则会启动失败,例如:
***************************
APPLICATION FAILED TO START
***************************
Description:
Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.
Reason: Failed to determine a suitable driver class
在Spring Boot项目中,在src/main/resources
下默认已经存在application.properties
配置文件,Spring Boot项目在启动时会自动读取此文件中的配置信息,如果配置信息中的属性名是特定的,Spring Boot还会自动应用这些属性值。
则在application.properties
中添加配置
# 连接数据库的配置
spring.datasource.url=jdbc:mysql://localhost:3306/mall_pms?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
spring.datasource.username=root
spring.datasource.password=root
找到项目中默认已经创建出来的测试类,在其中添加测试连接数据库的方法,并执行:
package cn.tedu.csmall.product;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import javax.sql.DataSource;
@SpringBootTest
class CsmallProductApplicationTests {
@Test
void contextLoads() {
}
@Autowired
DataSource dataSource;
@Test
void testConnection() throws Throwable {
dataSource.getConnection();
System.out.println("连接数据库成功!");
}
}