简化代码加入lombok依赖
<dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency>
1、pom.xml 添加jdbc、mysql驱动、mybatis框架、mybatis-plus
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency> <groupId>com.mysql</groupId> <artifactId>mysql-connector-j</artifactId> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>3.0.3</version> </dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.5</version>
</dependency>
2、编写yaml配置文件连接数据库
spring: datasource: username: root password: 123456 #?serverTimezone=UTC解决时区的报错 url: jdbc:mysql://localhost:3306/springboot?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8 driver-class-name: com.mysql.cj.jdbc.Driver
3、测试
不需要编写配置,springboot会自动配置
package com.exam; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import javax.sql.DataSource; import java.sql.Connection; import java.sql.SQLException; @SpringBootTest class ExamApplicationTests { @Autowired DataSource dataSource; @Test public void context() throws SQLException { System.out.println("数据源>>>>>>" + dataSource.getClass()); Connection connection = dataSource.getConnection(); System.out.println("连接>>>>>>>>>" + connection); System.out.println("连接地址>>>>>" + connection.getMetaData().getURL()); connection.close(); } }
标签:JDBC,spring,mysql,boot,plus,org,mybatis,import From: https://www.cnblogs.com/wangdch/p/18322590