项目本身是基于Spring boot 2.5.0的。
首先在pom.xml中需要引入MySQL客户端连接jar包的依赖
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
然后在application.yml中设置连接数据库。
注意在driver-class-name中需要使用com.mysql.cj.jdbc.Driver,com.mysql.cj.jdbc.Driver是mysql-connector-java 6 中的特性,相比mysql-connector-java 5 多了一个时区:serverTimezone。com.mysql.jdbc.Driver已经被MySQL弃用了,如果引用了这个驱动,启动应用后会报出Loading class `com.mysql.jdbc.Driver'. This is deprecated的错误提示。
另外,mysql8.x版本的数据库在连接的时候,需要在url的后边加上allowPublicKeyRetrieval=true,否则mysql8.x版本的数据库在连接的时候会报错:java.sql.SQLNonTransientConnectionException: Public Key Retrieval is not allowed
spring:
application:
name: yourAppName
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: xxxx
url: jdbc:mysql://127.0.0.1:3306/SpringCloud_Sell?allowPublicKeyRetrieval=true&characterEncoding=utf-8&useSSL=false
自此在项目中连接数据库的配置就完成了。