Spring Data Jpa连接mysql失败问题分析

前段时间准备学习一下spring boot,准备写一个简单的增删改查项目练手。

数据库选择了mysql,使用Spring Data Jpa连接。

数据源配置如下:

# DataSource 
spring.datasource.url=jdbc:mysql://localhost/mytest?characterEncoding=utf-8&useSSL=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

# JPA
spring.jpa.show-sql = true
spring.jpa.hibernate.ddl-auto=create-drop

 项目启动失败,查看console,发现以下内容:

Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration': Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Tomcat.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.apache.tomcat.jdbc.pool.DataSource]: Factory method 'dataSource' threw exception; nested exception is java.lang.IllegalStateException: Cannot load driver class: com.mysql.cj.jdbc.Driver

注意红色部分,无法加载驱动:com.mysql.cj.jdbc.Driver。

这个驱动是是 mysql-connector-java 6中的,

mysql-connector-java 5中驱动是:com.mysql.jdbc.Driver 。

查看build.gradle(使用gradle管理jar包),配置如下:

// 添加 MySQL连接驱动 的依赖
compile('mysql:mysql-connector-java:6.0.5')

版本是6.x,无问题!

折腾了半小时左右,想起来mysql驱动版本和mysql版本也是要匹配的。

查看本地mysql版本:5.1.73!果然是这里出了问题。

考虑到mysql升级比较繁琐,于是给mysql驱动版本降级。修改后的配置如下:

//添加mysql连接驱动的依赖
compile ('mysql:mysql-connector-java:5.1.40')

数据源配置修改如下,由com.mysql.cj.jdbc.Driver改为com.mysql.jdbc.Driver

# DataSource 
spring.datasource.url=jdbc:mysql://localhost/mytest?characterEncoding=utf-8&useSSL=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

# JPA
spring.jpa.show-sql = true
spring.jpa.hibernate.ddl-auto=create-drop

 

再次启动项目,ok!

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值