连接Hibernate到MySQL数据库时遇到的问题。

huangapple go评论122阅读模式
英文:

Problems with connection Hibernate to MySQL database

问题

首先,这是我在这里的第一篇帖子,所以为此道歉。

我正在参加一门Udemy的Hibernate & JPA课程,我在这里遇到了问题。

我的意思是,我像一个正在学习的人一样做了一切,但我在运行程序时遇到了问题。

我不知道该如何处理它。
我正在使用Eclipse,并且对于MySQL是MySQL Workbench。

这是我的项目 -> 点击

以及一个Udemy上的一个人的项目 -> 点击

当我想运行程序时,我遇到了以下问题:

WARN - HHH000402: 使用Hibernate内置连接池(不适用于生产环境!)
正在加载类`com.mysql.jdbc.Driver'。此操作已不推荐使用。新的驱动程序类是`com.mysql.cj.jdbc.Driver'。驱动程序会通过SPI自动注册,通常不需要手动加载驱动程序类。
INFO - HHH000401: 使用驱动程序 [com.mysql.jdbc.Driver],URL [jdbc:mysql://localhost:3306/ifinances]
INFO - HHH000046: 连接属性:{password=skills, user=infinite}
INFO - HHH000006: 自动提交模式:false
INFO - HHH000115: Hibernate连接池大小:20(最小值=1)
DEBUG - 使用1个连接初始化连接池
org.hibernate.exception.JDBCConnectionException: 调用Driver#connect时出错
     ...

以下是一些文件的代码片段:

hibernate.cfg.xml文件:

...
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文件:

...
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文件:

...
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("构建工厂时出错");
    }
}

public static SessionFactory getSessionFactory() {
    return sessionFactory;
}
...

pom.xml文件:

...
<dependencies>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>4.3.6.Final</version>
    </dependency>
    ...
</dependencies>
...
英文:

Firstly it's my first post here so sorry for that.

I am doing a Udemy course Hibernate & JPA and i have problem here.

I mean Im doing everything like a person from which am studing but a have problems to run a program.

I don't know how to deal with it.
I'm using Eclipse and for MySql is MySQL Workbench.

There is a my project -> click

and a guy's project from a Udemy -> click

When i want to run program a i have this problems

    WARN - HHH000402: Using Hibernate built-in connection pool (not for production use!)
Loading class `com.mysql.jdbc.Driver&#39;. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver&#39;. 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.&lt;clinit&gt;(HibernateUtil.java:11)
	at com.infiniteskills.data.Application.main(Application.java:12)
Caused by: java.sql.SQLException: The server time zone value &#39;?rodkowoeuropejski czas letni&#39; is unrecognized or represents more than one time zone. You must configure either the server or JDBC driver (via the &#39;serverTimezone&#39; 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.&lt;init&gt;(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 &#39;?rodkowoeuropejski czas letni&#39; is unrecognized or represents more than one time zone. You must configure either the server or JDBC driver (via the &#39;serverTimezone&#39; 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 &quot;main&quot; 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.&lt;clinit&gt;(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(&quot;kevin&quot;);
		user.setEmailAddress(&quot;kmb@yahoo.com&quot;);
		user.setFirstName(&quot;Kevin&quot;);
		user.setLastName(&quot;Bowersox&quot;);
		user.setLastUpdatedBy(&quot;kevin&quot;);
		user.setLastUpdatedDate(new Date());
		
		
		session.save(user);
		session.getTransaction().commit();
		session.close();
	}
}

hibernate.properties file :

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 file :

    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 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(&quot;kevin&quot;);
		user.setEmailAddress(&quot;kmb@yahoo.com&quot;);
		user.setFirstName(&quot;Kevin&quot;);
		user.setLastName(&quot;Bowersox&quot;);
		user.setLastUpdatedBy(&quot;kevin&quot;);
		user.setLastUpdatedDate(new Date());
		
		
		session.save(user);
		session.getTransaction().commit();
		session.close();
	}
}

HibernateUtil.java file:

   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(
					&quot;There was an error building the factory&quot;);
		}
	}

	public static SessionFactory getSessionFactory() {
		return sessionFactory;
	}
}

and my pom.xml file

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

EDIT 1:
There is another problem ->

Exception in thread "main" org.hibernate.MappingException: Unknown entity: com.infiniteskills.data.entities.User

User.java File:

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=&quot;FINANCES_USER&quot;)
public class User {

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

	@Column(name=&quot;FIRST_NAME&quot;)
	private String firstName;

	@Column(name=&quot;LAST_NAME&quot;)
	private String lastName;

	@Column(name=&quot;BIRTH_DATE&quot;)
	private Date birthDate;

	@Column(name=&quot;EMAIL_ADDRESS&quot;)
	private String emailAddress;

	@Column(name=&quot;LAST_UPDATED_DATE&quot;)
	private Date lastUpdatedDate;

	@Column(name=&quot;LAST_UPDATED_BY&quot;)
	private String lastUpdatedBy;

	@Column(name=&quot;CREATED_DATE&quot;)
	private Date createdDate;

	@Column(name=&quot;CREATED_BY&quot;)
	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;
	}

}

答案1

得分: 1

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

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

Update hibernate.properties and add serverTimeZone property in JDBC connection string directly..

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

答案2

得分: 0

"Exception in thread "main" org.hibernate.MappingException: Unknown entity: com.infiniteskills.data.entities.User" 表示:"主线程中的异常:org.hibernate.MappingException:未知实体:com.infiniteskills.data.entities.User"

"I added above a code from User.java" 表示:"我在上面添加了来自User.java的代码"

英文:

I have another problem with this project.

Exception in thread "main" org.hibernate.MappingException: Unknown entity: com.infiniteskills.data.entities.User

I added above a code from User.java

huangapple
  • 本文由 发表于 2020年10月27日 21:20:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/64555370.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定