1.导入依赖
<dependencies>
<!--jdbc-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<!--mysql 驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!--lombok插件-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!--测试相关-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
2.编写yaml配置文件连接数据库
spring:
datasource:
#?serverTimezone=UTC解决时区的报错
url: jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
username: root
password: 123
driver-class-name: com.mysql.cj.jdbc.Driver
hikari:
auto-commit: false
3.测试
@SpringBootTest
class SpringBootDemo02JdbcApplicationTests {
@Autowired
DataSource dataSource;
@Test
void contextLoads() throws Exception{
System.out.println(dataSource.getClass());
Connection connection = dataSource.getConnection();
boolean autoCommit = connection.getAutoCommit();
System.out.println(autoCommit);
connection.commit();
}
}