首先說下實現了什么效果,就是不用每次查詢前手動創建
sessionFactory和添加datasource文件了。
整個工程結構是這樣的
這次我也把代碼放在了gitee上,方便大家更全貌的看到所有的實現細節。代碼鏈接如下:
Java: 一些Java代碼 (gitee.com)
最后就是可以成功查詢到數據庫的數據啦
我把遇到的一些問題簡單記錄下, 避免后人踩坑。
1.Failed to obtain JDBC Connection; nested exception is java.sql.SQLException:
這個和驅動版本有關系,我用的是com.mysql.cj.jdbc.Driver,所以當時用5.x版本就報錯了
所以我選了
- com.mysql.jdbc.Driver和mysql-connector-java 5.x一起用。
- com.mysql.cj.jdbc.Driver和mysql-connector-java 6.x 及以上一起用。
2.?Failed to obtain JDBC Connection; nested exception is java.sql.SQLException: The server time zone value '���??��' is unrecognized or represents more than one time zone. You must configure either the server or JDBC driver (via the 'serverTimezone' configuration property) to use a more specifc time zone value if you want to utilize time zone support.
這個要在數據源配置文件里,加上時區serverTimezone=Asia/Shanghai
druid.url=jdbc:mysql://localhost:3306/blog?serverTimezone=Asia/Shanghai
參考這個文檔的解釋The server time zone value ‘�й���??��‘ is unrecognized or represents more than one time zone-CSDN博客