英文:
Hibernate error: java.lang.ClassNotFoundException: Could not load requested class
问题
以下是您提供的内容的翻译部分:
错误:
2020年4月24日 下午1:42:49 org.hibernate.jpa.internal.util.LogHelper logPersistenceUnitInformation
INFO: 处理 PersistenceUnitInfo [名称: JEETut3]
2020年4月24日 下午1:42:49 org.hibernate.Version logVersion
INFO: HHH000412: Hibernate 核心 {5.4.3.Final}
2020年4月24日 下午1:42:49 org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons 注释 {5.1.0.Final}
2020年4月24日 下午1:42:49 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH10001002: 正在使用 Hibernate 内置连接池(不适用于生产环境!)
主线程中的异常 "main" java.lang.ExceptionInInitializerError
Caused by: org.hibernate.service.spi.ServiceException: 无法创建请求的服务 [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:275)
...
Caused by: org.hibernate.boot.registry.classloading.spi.ClassLoadingException: 无法加载类 [com.mysql.jdbc.Driver]
at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.classForName(ClassLoaderServiceImpl.java:136)
...
Caused by: java.lang.ClassNotFoundException: 无法加载请求的类: com.mysql.jdbc.Driver
at org.hibernate.boot.registry.classloading.internal.AggregatedClassLoader.findClass(AggregatedClassLoader.java:210)
...
持久化配置文件(persistence.xml):
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0"
xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit>
<class>com.newthinktank.JEETut3.Customer</class>
<properties>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost/test4" />
<property name="javax.persistence.jdbc.user" value="root" />
<property name="javax.persistence.jdbc.password" value="myPassword!" />
</properties>
</persistence-unit>
</persistence>
项目配置文件(pom.xml):
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
...
<dependencies>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.4.1.Final</version>
</dependency>
...
</dependencies>
</project>
实体类(Customer.java):
package com.newthinktank.JEETut3;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "customer")
public class Customer implements Serializable {
private static final long serialVersionUID = 1L;
@Id
private int id;
@Column(name = "firstName", nullable = false)
private String fName;
@Column(name = "lastName", nullable = false)
private String lName;
// Getters and setters...
}
测试类(TestSystem.java):
package com.newthinktank.JEETut3;
public class TestSystem {
public static void main(String[] args) {
// Test and database operations...
ENTITY_MANAGER_FACTORY.close();
}
// Methods for adding, retrieving, updating, and deleting customers...
}
这是您提供的内容的主要翻译部分。如果您需要更多帮助或有其他问题,请随时问我。
英文:
I am new in Hibernate and facing some problem during execution first programme:
java.lang.ClassNotFoundException: Could not load requested class : com.mysql.jdbc.Driver. I was following tutorial about Hibernate, did everything same(even copied everything and tried to run).I've been searching for answers all over the internet, but none of them helped me.
persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0"
xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<class>com.newthinktank.JEETut3.Customer</class>
<properties>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost/test4" />
<property name="javax.persistence.jdbc.user" value="root" />
<property name="javax.persistence.jdbc.password" value="myPassword!" />
</properties>
</persistence-unit>
</persistence>
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.newthinktank</groupId>
<artifactId>JEETut3</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>JEETut3</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.4.1.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>5.4.1.Final</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.15</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
Customer:
package com.newthinktank.JEETut3;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "customer")
public class Customer implements Serializable {
private static final long serialVersionUID = 1L;
@Id
private int id;
@Column(name = "firstName", nullable = false)
private String fName;
@Column(name = "lastName", nullable = false)
private String lName;
public int getID() {
return id;
}
public void setID(int id) {
this.id = id;
}
public String getFName() {
return fName;
}
public void setFName(String fName) {
this.fName = fName;
}
public String getLName() {
return lName;
}
public void setLName(String lName) {
this.lName = lName;
}
}
TestSystem:
package com.newthinktank.JEETut3;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.NoResultException;
import javax.persistence.Persistence;
import javax.persistence.TypedQuery;
public class TestSystem {
private static final EntityManagerFactory ENTITY_MANAGER_FACTORY = Persistence
.createEntityManagerFactory("JEETut3");
public static void main(String[] args) {
addCustomer(1, "Sue", "Smith");
addCustomer(2, "Sam", "Smith");
addCustomer(3, "Sid", "Smith");
addCustomer(4, "Sally", "Smith");
getCustomer(1);
getCustomers();
changeFName(4, "Mark");
deleteCustomer(3);
ENTITY_MANAGER_FACTORY.close();
}
public static void addCustomer(int id, String fname, String lname) {
EntityManager em = ENTITY_MANAGER_FACTORY.createEntityManager();
EntityTransaction et = null;
try {
et = em.getTransaction();
et.begin();
Customer cust = new Customer();
cust.setID(id);
cust.setFName(fname);
cust.setLName(lname);
em.persist(cust);
et.commit();
} catch (Exception ex) {
if (et != null) {
et.rollback();
}
ex.printStackTrace();
} finally {
em.close();
}
}
public static void getCustomer(int id) {
EntityManager em = ENTITY_MANAGER_FACTORY.createEntityManager();
String query = "SELECT c FROM Customer c WHERE c.id = :custID";
TypedQuery<Customer> tq = em.createQuery(query, Customer.class);
tq.setParameter("custID", id);
Customer cust = null;
try {
cust = tq.getSingleResult();
System.out.println(cust.getFName() + " " + cust.getLName());
} catch (NoResultException ex) {
ex.printStackTrace();
} finally {
em.close();
}
}
public static void getCustomers() {
EntityManager em = ENTITY_MANAGER_FACTORY.createEntityManager();
String strQuery = "SELECT c FROM Customer c WHERE c.id IS NOT NULL";
TypedQuery<Customer> tq = em.createQuery(strQuery, Customer.class);
List<Customer> custs;
try {
custs = tq.getResultList();
custs.forEach(cust -> System.out.println(cust.getFName() + " " + cust.getLName()));
} catch (NoResultException ex) {
ex.printStackTrace();
} finally {
em.close();
}
}
public static void changeFName(int id, String fname) {
EntityManager em = ENTITY_MANAGER_FACTORY.createEntityManager();
EntityTransaction et = null;
Customer cust = null;
try {
et = em.getTransaction();
et.begin();
cust = em.find(Customer.class, id);
cust.setFName(fname);
em.persist(cust);
et.commit();
} catch (Exception ex) {
if (et != null) {
et.rollback();
}
ex.printStackTrace();
} finally {
em.close();
}
}
public static void deleteCustomer(int id) {
EntityManager em = ENTITY_MANAGER_FACTORY.createEntityManager();
EntityTransaction et = null;
Customer cust = null;
try {
et = em.getTransaction();
et.begin();
cust = em.find(Customer.class, id);
em.remove(cust);
et.commit();
} catch (Exception ex) {
if (et != null) {
et.rollback();
}
ex.printStackTrace();
} finally {
em.close();
}
}
}
Error:
lip 24, 2020 1:42:49 PM org.hibernate.jpa.internal.util.LogHelper logPersistenceUnitInformation
INFO: HHH000204: Processing PersistenceUnitInfo [name: JEETut3]
lip 24, 2020 1:42:49 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.4.3.Final}
lip 24, 2020 1:42:49 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.1.0.Final}
lip 24, 2020 1:42:49 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!)
Exception in thread "main" java.lang.ExceptionInInitializerError
Caused by: org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:275)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:237)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:214)
at org.hibernate.id.factory.internal.DefaultIdentifierGeneratorFactory.injectServices(DefaultIdentifierGeneratorFactory.java:152)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.injectDependencies(AbstractServiceRegistryImpl.java:286)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:243)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:214)
at org.hibernate.boot.internal.InFlightMetadataCollectorImpl.<init>(InFlightMetadataCollectorImpl.java:175)
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:118)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.metadata(EntityManagerFactoryBuilderImpl.java:900)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:931)
at org.hibernate.jpa.HibernatePersistenceProvider.createEntityManagerFactory(HibernatePersistenceProvider.java:56)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:79)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:54)
at com.newthinktank.JEETut3.TestSystem.<clinit>(TestSystem.java:15)
Caused by: org.hibernate.boot.registry.classloading.spi.ClassLoadingException: Unable to load class [com.mysql.jdbc.Driver]
at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.classForName(ClassLoaderServiceImpl.java:136)
at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl.loadDriverIfPossible(DriverManagerConnectionProviderImpl.java:149)
at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl.buildCreator(DriverManagerConnectionProviderImpl.java:105)
at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl.buildPool(DriverManagerConnectionProviderImpl.java:89)
at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl.configure(DriverManagerConnectionProviderImpl.java:73)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:107)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:246)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:214)
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.buildJdbcConnectionAccess(JdbcEnvironmentInitiator.java:145)
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:66)
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:35)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.initiateService(StandardServiceRegistryImpl.java:101)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:263)
... 14 more
Caused by: java.lang.ClassNotFoundException: Could not load requested class : com.mysql.jdbc.Driver
at org.hibernate.boot.registry.classloading.internal.AggregatedClassLoader.findClass(AggregatedClassLoader.java:210)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:588)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
at java.base/java.lang.Class.forName0(Native Method)
at java.base/java.lang.Class.forName(Class.java:416)
at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.classForName(ClassLoaderServiceImpl.java:133)
... 26 more
Does anyone know how to resolve problem?
答案1
得分: 4
我已经测试了你的代码,问题出在 mysql 的 Maven 依赖上,你需要移除 scope 属性中的 provided,因为你表示它会在运行时提供,但实际情况并非如此。
以下是我所做的更改,以使其运行:
- 移除 mysql Maven 依赖中的 provided scope
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.15</version>
</dependency>
更新你的 persistence.xml 中的 jdbc 驱动,因为你使用的那个已经过时了:
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
你还缺少 persistence.xml 代码的一个必要部分:
<persistence-unit name="JEETut3" transaction-type="RESOURCE_LOCAL">
我还在 persistence.xml 中添加了数据库的方言:
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect"/>
如果你希望在每次执行时自动创建表格,可以添加以下代码:
<property name="javax.persistence.schema-generation.database.action" value="drop-and-create"/>
总结一下,这是我使用的 persistence 配置:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0"
xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="JEETut3" transaction-type="RESOURCE_LOCAL">
<class>com.newthinktank.JEETut3.Customer</class>
<properties>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost/test4"/>
<property name="javax.persistence.jdbc.user" value="root"/>
<property name="javax.persistence.jdbc.password" value="myPassword!"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect"/>
<property name="javax.persistence.schema-generation.database.action" value="drop-and-create"/>
</properties>
</persistence-unit>
</persistence>
这是在数据库中会得到的结果:
希望这能帮助你解决问题。
英文:
I have tested your code and the problem is in the mysql maven dependency you need to remove scope provided because you are saying it will be provided while running but that is not the case.
These are the changes I did to make it run.
-
Remove provided scope to mysql maven dependency
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.15</version> </dependency>
Change your jdbc driver in persistence.xml as the one you use is deprecated
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
You are also missing a mandatory part of persistence.xml code
<persistence-unit name="JEETut3" transaction-type="RESOURCE_LOCAL">
I have also added the dialect of database in the persistence.xml
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect"/>
In case you want the tables to be created automatically on each execution you can add
<property name="javax.persistence.schema-generation.database.action" value="drop-and-create"/>
In summary this is the persistence I used
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0"
xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="JEETut3" transaction-type="RESOURCE_LOCAL">
<class>com.newthinktank.JEETut3.Customer</class>
<properties>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost/test4"/>
<property name="javax.persistence.jdbc.user" value="root"/>
<property name="javax.persistence.jdbc.password" value="myPassword!"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect"/>
<property name="javax.persistence.schema-generation.database.action" value="drop-and-create"/>
</properties>
</persistence-unit>
</persistence>
This is the result you will get in the database
I hope this helps you solving your issue
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论