IDEA SSM框架jdbc配置bug总结

最近学习到Java web的框架时尝试使用Spring+Spring MVC+Mybatis配置,也就是我们所熟悉的SSM框架。在配置过程中测试时遇到了如下的错误报告:

org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.exceptions.PersistenceException: 
### Error querying database.  
Cause: org.springframework.jdbc.CannotGetJdbcConnectionException: 
Could not get JDBC Connection; 
nested exception is org.apache.commons.dbcp.SQLNestedException: 
Cannot create PoolableConnectionFactory 
(Communications link failure

The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.)
### The error may exist in class path resource [mappers/UserDao.xml]
### The error may involve com.ssmdemo.dao.UserDao.selectByid
### The error occurred while executing a query
### Cause: org.springframework.jdbc.CannotGetJdbcConnectionException: Could not get JDBC Connection; nested exception is org.apache.commons.dbcp.SQLNestedException: 
Cannot create PoolableConnectionFactory (Communications link failure

那么这个bug究竟是怎么解决的呢?
首先,当我们遇到问题时不要慌张,仔细阅读日志的错误信息后发现该问题与数据库连接有关系,ssm框架里主要涉及到数据库连接的一个是数据库驱动用户名等配置文件,即jdbc.properties。我们需要查看该配置文件中的driver,username,URL,password等信息是否配置错误,并且还要检查该文件中是否有多余的空格,这些小失误都会影响到文件的解析。具体配置如下,如果程序报错让你使用com.mysql.cj.jdbc.Driver则表明你用的mysql驱动是非常新式的,不建议使用其开发。

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/databasename?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=UTC
jdbc.username=root
jdbc.password=root

initialSize=0
maxActive=50
maxIdle=20
minIdle=1
maxWait=60000

在发现文件配置没有错误之后,还连接不上,那就基本是驱动的问题了。

关于驱动,网络上也有很多说法,对于比较新的IDEA以及Mysql 8.0版本,驱动不兼容的问题经常出现,而这个bug很可能就是由于驱动过于新式,导致很多文件加载的模式与往常的不太一样从而出现驱动调用错误。

<dependency>
    <groupId>mysqlgroupId>
    <artifactId>mysql-connector-javaartifactId>
    <version>5.1.41version>
dependency>

项目原本的mysql版本是8.0.12,是目前最新的版本,遇到bug后用maven将版本降低上图所示的5.1.41后,测试顺利通过。所以在开发时候要格外注意不同版本的开发工具彼此间是否支持。

你可能感兴趣的:(数据库操作,Spring)