将 Hibernate 连接到 MySQL 数据库的问题

Posted

技术标签:

【中文标题】将 Hibernate 连接到 MySQL 数据库的问题【英文标题】:Problems with connection Hibernate to MySQL database 【发布时间】:2021-02-09 18:53:15 【问题描述】:

首先,这是我在这里的第一篇文章,对此深表歉意。

我正在学习 Udemy 课程 Hibernate 和 JPA,但这里有问题。

我的意思是我做任何事情都像一个正在学习但运行程序有问题的人。

我不知道如何处理它。 我使用的是 Eclipse,mysql 是 MySQL Workbench。

有一个我的项目 -> click

还有一个来自 Udemy 的人的项目 -> click

当我想运行程序时我遇到了这个问题

    WARN - HHH000402: Using Hibernate built-in connection pool (not for production use!)
Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.
INFO - HHH000401: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost:3306/ifinances]
INFO - HHH000046: Connection properties: password=skills, user=infinite
INFO - HHH000006: Autocommit mode: false
INFO - HHH000115: Hibernate connection pool size: 20 (min=1)
DEBUG - Initializing Connection pool with 1 Connections
org.hibernate.exception.JDBCConnectionException: Error calling Driver#connect
    at org.hibernate.engine.jdbc.connections.internal.BasicConnectionCreator$1$1.convert(BasicConnectionCreator.java:122)
    at org.hibernate.engine.jdbc.connections.internal.BasicConnectionCreator.convertSqlException(BasicConnectionCreator.java:140)
    at org.hibernate.engine.jdbc.connections.internal.DriverConnectionCreator.makeConnection(DriverConnectionCreator.java:58)
    at org.hibernate.engine.jdbc.connections.internal.BasicConnectionCreator.createConnection(BasicConnectionCreator.java:75)
    at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl.configure(DriverManagerConnectionProviderImpl.java:106)
    at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:111)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:234)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:206)
    at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.buildJdbcConnectionAccess(JdbcServicesImpl.java:260)
    at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:94)
    at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:111)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:234)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:206)
    at org.hibernate.cfg.Configuration.buildTypeRegistrations(Configuration.java:1885)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1843)
    at com.infiniteskills.data.HibernateUtil.buildSessionFactory(HibernateUtil.java:17)
    at com.infiniteskills.data.HibernateUtil.<clinit>(HibernateUtil.java:11)
    at com.infiniteskills.data.Application.main(Application.java:12)
Caused by: java.sql.SQLException: The server time zone value '?rodkowoeuropejski czas letni' 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 specific time zone value if you want to utilize time zone support.
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:129)
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97)
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:89)
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:63)
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:73)
    at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:76)
    at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:836)
    at com.mysql.cj.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:456)
    at com.mysql.cj.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:246)
    at com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:198)
    at org.hibernate.engine.jdbc.connections.internal.DriverConnectionCreator.makeConnection(DriverConnectionCreator.java:55)
    ... 15 more
Caused by: com.mysql.cj.exceptions.InvalidConnectionAttributeException: The server time zone value '?rodkowoeuropejski czas letni' 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 specific time zone value if you want to utilize time zone support.
    at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:500)
    at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:481)
    at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:61)
    at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:85)
    at com.mysql.cj.util.TimeUtil.getCanonicalTimezone(TimeUtil.java:134)
    at com.mysql.cj.protocol.a.NativeProtocol.configureTimezone(NativeProtocol.java:2186)
    at com.mysql.cj.protocol.a.NativeProtocol.initServerSession(NativeProtocol.java:2209)
    at com.mysql.cj.jdbc.ConnectionImpl.initializePropsFromServer(ConnectionImpl.java:1318)
    at com.mysql.cj.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:967)
    at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:826)
    ... 19 more
Exception in thread "main" java.lang.ExceptionInInitializerError
    at com.infiniteskills.data.Application.main(Application.java:12)
Caused by: java.lang.RuntimeException: There was an error building the factory
    at com.infiniteskills.data.HibernateUtil.buildSessionFactory(HibernateUtil.java:22)
    at com.infiniteskills.data.HibernateUtil.<clinit>(HibernateUtil.java:11)
    ... 1 more



Its my hibernate.cfg.xml file :

package com.infiniteskills.data;

import java.util.Date;

import org.hibernate.Session;
import com.infiniteskills.data.entities.User;

public class Application 

    public static void main(String[] args) 
        
        Session session = HibernateUtil.getSessionFactory().openSession();
        session.getTransaction().begin();
        
        User user = new User();
        user.setBirthDate(new Date());
        user.setCreatedDate(new Date());
        user.setCreatedBy("kevin");
        user.setEmailAddress("kmb@yahoo.com");
        user.setFirstName("Kevin");
        user.setLastName("Bowersox");
        user.setLastUpdatedBy("kevin");
        user.setLastUpdatedDate(new Date());
        
        
        session.save(user);
        session.getTransaction().commit();
        session.close();
    

hibernate.properties 文件:

hibernate.connection.username= infinite
hibernate.connection.password= skills
hibernate.connection.url=jdbc:mysql://localhost:3306/ifinances
hibernate.connection.driver_class=com.mysql.jdbc.Driver
hibernate.dialect=org.hibernate.dialect.MySQL5Dialect

log4j.properties 文件:

    log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.SimpleLayout
log4j.rootLogger=debug, stdout

Application.java 文件:

package com.infiniteskills.data;

import java.util.Date;

import org.hibernate.Session;
import com.infiniteskills.data.entities.User;

public class Application 

    public static void main(String[] args) 
        
        Session session = HibernateUtil.getSessionFactory().openSession();
        session.getTransaction().begin();
        
        User user = new User();
        user.setBirthDate(new Date());
        user.setCreatedDate(new Date());
        user.setCreatedBy("kevin");
        user.setEmailAddress("kmb@yahoo.com");
        user.setFirstName("Kevin");
        user.setLastName("Bowersox");
        user.setLastUpdatedBy("kevin");
        user.setLastUpdatedDate(new Date());
        
        
        session.save(user);
        session.getTransaction().commit();
        session.close();
    

HibernateUtil.java 文件:

   package com.infiniteskills.data;

import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;

import com.infiniteskills.data.entities.User;

public class HibernateUtil 

    private static final SessionFactory sessionFactory = buildSessionFactory();

    private static SessionFactory buildSessionFactory() 
        try 
            Configuration configuration = new Configuration();
            return configuration
                    .buildSessionFactory(new StandardServiceRegistryBuilder()
                            .applySettings(configuration.getProperties())
                            .build());
         catch (Exception e) 
            e.printStackTrace();
            throw new RuntimeException(
                    "There was an error building the factory");
        
    

    public static SessionFactory getSessionFactory() 
        return sessionFactory;
    

还有我的 pom.xml 文件

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.infiniteskills</groupId>
  <artifactId>hibernate-course</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <name>hibernate-course</name>
  <dependencies>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>4.3.6.Final</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-annotations</artifactId>
        <version>3.5.6-Final</version>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>1.7.7</version>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-log4j12</artifactId>
        <version>1.7.7</version>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.22</version>
    </dependency>
  </dependencies>
</project>

编辑 1: 还有一个问题->

线程“主”org.hibernate.MappingException 中的异常:未知实体:com.infiniteskills.data.entities.User

User.java 文件:

package com.infiniteskills.data.entities;

import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity

@Table(name="FINANCES_USER")
public class User 

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="USER_ID")
    private Long userId;

    @Column(name="FIRST_NAME")
    private String firstName;

    @Column(name="LAST_NAME")
    private String lastName;

    @Column(name="BIRTH_DATE")
    private Date birthDate;

    @Column(name="EMAIL_ADDRESS")
    private String emailAddress;

    @Column(name="LAST_UPDATED_DATE")
    private Date lastUpdatedDate;

    @Column(name="LAST_UPDATED_BY")
    private String lastUpdatedBy;

    @Column(name="CREATED_DATE")
    private Date createdDate;

    @Column(name="CREATED_BY")
    private String createdBy;

    public Long getUserId() 
        return userId;
    

    public void setUserId(Long userId) 
        this.userId = userId;
    

    public String getFirstName() 
        return firstName;
    

    public void setFirstName(String firstName) 
        this.firstName = firstName;
    

    public String getLastName() 
        return lastName;
    

    public void setLastName(String lastName) 
        this.lastName = lastName;
    

    public Date getBirthDate() 
        return birthDate;
    

    public void setBirthDate(Date birthDate) 
        this.birthDate = birthDate;
    

    public String getEmailAddress() 
        return emailAddress;
    

    public void setEmailAddress(String emailAddress) 
        this.emailAddress = emailAddress;
    

    public Date getLastUpdatedDate() 
        return lastUpdatedDate;
    

    public void setLastUpdatedDate(Date lastUpdatedDate) 
        this.lastUpdatedDate = lastUpdatedDate;
    

    public String getLastUpdatedBy() 
        return lastUpdatedBy;
    

    public void setLastUpdatedBy(String lastUpdatedBy) 
        this.lastUpdatedBy = lastUpdatedBy;
    

    public Date getCreatedDate() 
        return createdDate;
    

    public void setCreatedDate(Date createdDate) 
        this.createdDate = createdDate;
    

    public String getCreatedBy() 
        return createdBy;
    

    public void setCreatedBy(String createdBy) 
        this.createdBy = createdBy;
    


【问题讨论】:

删除用户/密码前的空格并使用有效的时区 设置默认时区,如下所述:mkyong.com/jdbc/… 【参考方案1】:

更新 hibernate.properties 并直接在 JDBC 连接字符串中添加 serverTimeZone 属性..

hibernate.connection.url=jdbc:mysql://localhost:3306/ifinances?serverTimezone=UTC 

【讨论】:

它有很大帮助,但我仍然有另一个错误:线程“主”org.hibernate.MappingException 中的异常:未知实体:com.infiniteskills.data.entities.User 用户应该被标记为带有 Id(Primary Key) 映射的实体注释,如果已经完成显示代码。 我认为它已经完成了我的编码。用户文件添加在顶部。【参考方案2】:

我对这个项目还有另一个问题。

线程“主”org.hibernate.MappingException 中的异常:未知实体:com.infiniteskills.data.entities.User

我在上面添加了来自 User.java 的代码

【讨论】:

以上是关于将 Hibernate 连接到 MySQL 数据库的问题的主要内容,如果未能解决你的问题,请参考以下文章

hibernate + maven + mysql 服务器配置问题

使用 JPA/Hibernate 将 Spring Boot 连接到 PostgreSql 数据库时失败

JavaFX不会连接到MYSQL [重复]

无法使用 Hibernate 连接到 Informix

Tomcat 8、HikariCP、Hibernate 和 MySQL

Java Hibernate - 无法连接到 H2