- mysql数据库驱动依赖。
mysql
mysql-connector-java
runtime
- spring对象jdbc支持(此时会默认帮我们下载HiKariCP连接池)。
org.springframework.boot
spring-boot-starter-jdbc
打开application.properties配置文件,添加如下内容(必写)。
spring.datasource.url=jdbc:mysql:///db-system?serverTimezone=GMT%2B8&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=root
hikariCP 其它额外配置(可选),代码如下(具体配置不清晰的可自行百度):
spring.datasource.type=com.zaxxer.hikari.HikariDataSource
spring.datasource.hikari.minimum-idle=5
spring.datasource.hikari.maximum-pool-size=15
spring.datasource.hikari.auto-commit=true
spring.datasource.hikari.idle-timeout=30000
spring.datasource.hikari.pool-name=DatebookHikariCP
spring.datasource.hikari.max-lifetime=1800000
spring.datasource.hikari.connection-timeout=30000
spring.datasource.hikari.connection-test-query=SELECT 1
package com.cy;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class JdbcApplication {//Application.class
public static void main(String[] args) {//Main Thread
SpringApplication.run(JdbcApplication .class, args);
}
}
第一步:在项目中添加单元测试类及测试方法,代码如下:
package com.cy.pj.common.datasource;
import java.sql.SQLException;
import javax.sql.DataSource;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@Spri