以jdbc的形式访问mysql数据库是比较基础的知识,理解spring boot中如何使用jdbc对我们理解spring boot对mybatis等数据框架是很有意义的。
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>
配置数据库相关信息
spring:
datasource:
data-username: root
data-password: root
url: jdbc:mysql://127.0.0.1:3306/sff_test
driver-class-name: com.mysql.jdbc.Driver
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringBootJdbcApplicationTests {
@Autowired
private DataSource dataSource;
@Test
public void testDataSource() throws SQLException {
System.out.println("dataSource类型:" + dataSource.getClass());
Connection connection = dataSource.getConnection();
System.out.println("connection连接:" + connection);
connection.close();
}
}
运行结果:
从结果中可以看到 spring boot 的 2.1.2.RELEASE 版本默认使用 com.zaxxer.hikari.HikariDataSource 作为数据源。