You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Hibernate的Maven-Java-SQL项目无法连接MySQL问题求助

Hibernate连接MySQL:Driver弃用+连接失败问题解决

问题背景

使用Apache NetBeans IDE开发基于Hibernate的Maven-Java-SQL项目,运行时出现错误:Loading class 'com.mysql.jdbc.Driver'. This is deprecated。MySQL Server正常运行(用Workbench管理),但项目无法建立数据库连接。

当前persistence.xml配置:

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
  <persistence-unit name="Persistence" transaction-type="RESOURCE_LOCAL">
    <!-- Persistence provider -->
    <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
    <properties>
      <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
      <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/technikon"/>
      <property name="javax.persistence.jdbc.user" value="root"/>
      <property name="javax.persistence.jdbc.password" value="root"/>
      <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
      <property name="hibernate.show_sql" value="true"/>
      <property name="hibernate.hbm2ddl.auto" value="create"/>
    </properties>
  </persistence-unit>
</persistence>

错误提示截图:
错误提示截图

解决方案

1. 替换弃用的JDBC驱动类

com.mysql.jdbc.Driver是MySQL 5.x的驱动类,8.0+版本已弃用,替换为新版驱动类:

<property name="javax.persistence.jdbc.driver" value="com.mysql.cj.jdbc.Driver"/>

2. 补充JDBC URL时区参数

MySQL 8.0+强制要求指定时区,否则会触发连接失败。在URL后添加时区参数(示例用UTC,可根据实际情况改为Asia/Shanghai等):

<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/technikon?serverTimezone=UTC"/>

3. 更新Hibernate方言

针对MySQL 8.0+,使用对应的Hibernate方言以支持新特性:

<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL8Dialect"/>

4. 确认Maven依赖版本

确保pom.xml中的MySQL驱动为8.0+版本,避免版本不兼容:

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.33</version> <!-- 可使用最新稳定版 -->
</dependency>

5. 基础连接验证

  • 检查technikon数据库是否已在MySQL中创建
  • 确认root账号的密码正确,且能通过Workbench正常登录
  • 验证MySQL服务端口为3306,未被其他进程占用

内容的提问来源于stack exchange,提问作者Tasos Barbakas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 23:35:41