刚开始学习J2EE,第一次使用Hibernate连接数据库,发现出现无法连接数据库的情况。在查阅了各种资料的情况下,尝试各种方式解决无果后,终于发现了问题真正所在——Mysql版本过高(Mysql8.0)与起始的hibernate.cfg.xml文件无法匹配。
首先放出原始的hibernate.cfg.xml代码:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/j2ee</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.format_sql">true</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<mapping class="domain.User"/>
</session-factory>
</hibernate-configuration>
由于该代码在mysql5的版本上运行没有问题,因此着实让我走了不少弯路。
在查阅了各种资料之后,我修改了该文件的部分代码。
以下是Mysql8.0版本所用的hibernate.cfg.xml代码:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- 连接8.0以上版本Mysql,修改驱动、url、方言 -->
<property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/j2ee?useSSL=false&serverTimezone=UTC</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
<property name="hibernate.format_sql">true</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<mapping class="domain.User"/>
</session-factory>
</hibernate-configuration>
按理来说修改完之后,应该是没有问题了,结果发现还是无法连接。
进一步的查阅资料之后,发现原来还要导一个包:mysql-connector-java-8.0.11.jar
将包导入后,运行成功,问题解决。
在初学J2EE时,遇到Hibernate无法连接到Mysql8.0数据库的难题。经过一系列尝试和查阅资料,发现是hibernate.cfg.xml配置文件与高版本Mysql不兼容。更新配置文件后,仍无法成功,最终解决方案是引入mysql-connector-java-8.0.11.jar驱动包。
1613

被折叠的 条评论
为什么被折叠?



