Hibernate错误:java.lang.ClassNotFoundException:无法加载请求的类

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

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:

&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;


&lt;persistence version=&quot;2.0&quot;
             xmlns=&quot;http://java.sun.com/xml/ns/persistence&quot; xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
             xsi:schemaLocation=&quot;http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd&quot;&gt;

  
      
        &lt;class&gt;com.newthinktank.JEETut3.Customer&lt;/class&gt;
        &lt;properties&gt;
            &lt;property name=&quot;javax.persistence.jdbc.driver&quot; value=&quot;com.mysql.jdbc.Driver&quot; /&gt;
            &lt;property name=&quot;javax.persistence.jdbc.url&quot; value=&quot;jdbc:mysql://localhost/test4&quot; /&gt;
            &lt;property name=&quot;javax.persistence.jdbc.user&quot; value=&quot;root&quot; /&gt;
            &lt;property name=&quot;javax.persistence.jdbc.password&quot; value=&quot;myPassword!&quot; /&gt;
        &lt;/properties&gt;
    &lt;/persistence-unit&gt;
&lt;/persistence&gt;

pom.xml:

&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.newthinktank&lt;/groupId&gt;
&lt;artifactId&gt;JEETut3&lt;/artifactId&gt;
&lt;version&gt;0.0.1-SNAPSHOT&lt;/version&gt;
&lt;packaging&gt;jar&lt;/packaging&gt;

&lt;name&gt;JEETut3&lt;/name&gt;
&lt;url&gt;http://maven.apache.org&lt;/url&gt;

&lt;properties&gt;
    &lt;project.build.sourceEncoding&gt;UTF-8&lt;/project.build.sourceEncoding&gt;
&lt;/properties&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;5.4.1.Final&lt;/version&gt;
    &lt;/dependency&gt;

    &lt;dependency&gt;
        &lt;groupId&gt;org.hibernate&lt;/groupId&gt;
        &lt;artifactId&gt;hibernate-entitymanager&lt;/artifactId&gt;
        &lt;version&gt;5.4.1.Final&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.15&lt;/version&gt;
        &lt;scope&gt;provided&lt;/scope&gt;
    &lt;/dependency&gt;

    &lt;dependency&gt;
        &lt;groupId&gt;junit&lt;/groupId&gt;
        &lt;artifactId&gt;junit&lt;/artifactId&gt;
        &lt;version&gt;3.8.1&lt;/version&gt;
        &lt;scope&gt;test&lt;/scope&gt;
    &lt;/dependency&gt;
&lt;/dependencies&gt;

</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 = &quot;customer&quot;)
public class Customer implements Serializable {
    private static final long serialVersionUID = 1L;
    
    @Id
    private int id;

    @Column(name = &quot;firstName&quot;, nullable = false)
    private String fName;

    @Column(name = &quot;lastName&quot;, 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(&quot;JEETut3&quot;);

    public static void main(String[] args) {
        addCustomer(1, &quot;Sue&quot;, &quot;Smith&quot;);
        addCustomer(2, &quot;Sam&quot;, &quot;Smith&quot;);
        addCustomer(3, &quot;Sid&quot;, &quot;Smith&quot;);
        addCustomer(4, &quot;Sally&quot;, &quot;Smith&quot;);
        getCustomer(1);
        getCustomers();
        changeFName(4, &quot;Mark&quot;);
        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 = &quot;SELECT c FROM Customer c WHERE c.id = :custID&quot;;

        TypedQuery&lt;Customer&gt; tq = em.createQuery(query, Customer.class);
        tq.setParameter(&quot;custID&quot;, id);

        Customer cust = null;
        try {
            cust = tq.getSingleResult();
            System.out.println(cust.getFName() + &quot; &quot; + cust.getLName());
        } catch (NoResultException ex) {
            ex.printStackTrace();
        } finally {
            em.close();
        }
    }

    public static void getCustomers() {
        EntityManager em = ENTITY_MANAGER_FACTORY.createEntityManager();

        String strQuery = &quot;SELECT c FROM Customer c WHERE c.id IS NOT NULL&quot;;

        TypedQuery&lt;Customer&gt; tq = em.createQuery(strQuery, Customer.class);
        List&lt;Customer&gt; custs;
        try {
            custs = tq.getResultList();
            custs.forEach(cust -&gt; System.out.println(cust.getFName() + &quot; &quot; + 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 &lt;clinit&gt;
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 &quot;main&quot; 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.&lt;init&gt;(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.&lt;clinit&gt;(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>

这是在数据库中会得到的结果:

Hibernate错误:java.lang.ClassNotFoundException:无法加载请求的类

希望这能帮助你解决问题。

英文:

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

      &lt;dependency&gt;
          &lt;groupId&gt;mysql&lt;/groupId&gt;
          &lt;artifactId&gt;mysql-connector-java&lt;/artifactId&gt;
          &lt;version&gt;8.0.15&lt;/version&gt;
      &lt;/dependency&gt;
    

Change your jdbc driver in persistence.xml as the one you use is deprecated

&lt;property name=&quot;javax.persistence.jdbc.driver&quot; value=&quot;com.mysql.jdbc.Driver&quot;/&gt;

You are also missing a mandatory part of persistence.xml code

&lt;persistence-unit name=&quot;JEETut3&quot; transaction-type=&quot;RESOURCE_LOCAL&quot;&gt;

I have also added the dialect of database in the persistence.xml

&lt;property name=&quot;hibernate.dialect&quot; value=&quot;org.hibernate.dialect.MySQL5Dialect&quot;/&gt;

In case you want the tables to be created automatically on each execution you can add

&lt;property name=&quot;javax.persistence.schema-generation.database.action&quot; value=&quot;drop-and-create&quot;/&gt;

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&quot;>

&lt;persistence-unit name=&quot;JEETut3&quot; transaction-type=&quot;RESOURCE_LOCAL&quot;&gt;
    &lt;class&gt;com.newthinktank.JEETut3.Customer&lt;/class&gt;
    &lt;properties&gt;
        &lt;property name=&quot;javax.persistence.jdbc.driver&quot; value=&quot;com.mysql.jdbc.Driver&quot;/&gt;
        &lt;property name=&quot;javax.persistence.jdbc.url&quot; value=&quot;jdbc:mysql://localhost/test4&quot;/&gt;
        &lt;property name=&quot;javax.persistence.jdbc.user&quot; value=&quot;root&quot;/&gt;
        &lt;property name=&quot;javax.persistence.jdbc.password&quot; value=&quot;myPassword!&quot;/&gt;
        &lt;property name=&quot;hibernate.dialect&quot; value=&quot;org.hibernate.dialect.MySQL5Dialect&quot;/&gt;
        &lt;property name=&quot;javax.persistence.schema-generation.database.action&quot; value=&quot;drop-and-create&quot;/&gt;
    &lt;/properties&gt;
&lt;/persistence-unit&gt;

</persistence>

This is the result you will get in the database

Hibernate错误:java.lang.ClassNotFoundException:无法加载请求的类

I hope this helps you solving your issue

huangapple
  • 本文由 发表于 2020年7月24日 20:15:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/63073364.html
匿名

发表评论

匿名网友

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

确定