Java 将我的休眠类连接到 mysql 时出现异常

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19953867/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 21:48:48  来源:igfitidea点击:

Exception while connecting my hibernate class to mysql

javahibernate

提问by Nishant Lakhara

I am getting an exception while running a Hibernate code. I am very new to hibernate. Please let me know what am I missing.

运行 Hibernate 代码时出现异常。我对冬眠很陌生。请让我知道我错过了什么。

Nov 13, 2013 5:53:41 PM org.hibernate.annotations.common.Version <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {4.0.2.Final}
Nov 13, 2013 5:53:41 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.2.7.Final}
Nov 13, 2013 5:53:41 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Nov 13, 2013 5:53:41 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
Nov 13, 2013 5:53:41 PM org.hibernate.cfg.Configuration configure
INFO: HHH000043: Configuring from resource: /hibernate.cfg.xml
Nov 13, 2013 5:53:41 PM org.hibernate.cfg.Configuration getConfigurationInputStream
INFO: HHH000040: Configuration resource: /hibernate.cfg.xml
Nov 13, 2013 5:53:41 PM org.hibernate.cfg.Configuration addResource
INFO: HHH000221: Reading mappings from resource: Employee.hbm.xml
Nov 13, 2013 5:53:41 PM org.hibernate.cfg.Configuration doConfigure
INFO: HHH000041: Configured SessionFactory: null
Nov 13, 2013 5:53:41 PM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000402: Using Hibernate built-in connection pool (not for production use!)
Failed to create sessionFactory object.org.hibernate.service.classloading.spi.ClassLoadingException: Specified JDBC Driver com.mysql.jdbc.Driver could not be loaded
Exception in thread "main" java.lang.ExceptionInInitializerError
    at ManageEmployee.main(ManageEmployee.java:18)
Caused by: org.hibernate.service.classloading.spi.ClassLoadingException: Specified JDBC Driver com.mysql.jdbc.Driver could not be loaded
    at org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl.configure(DriverManagerConnectionProviderImpl.java:111)
    at org.hibernate.service.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:76)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:160)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:132)
    at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.buildJdbcConnectionAccess(JdbcServicesImpl.java:223)
    at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:89)
    at org.hibernate.service.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:76)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:160)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:132)
    at org.hibernate.cfg.Configuration.buildTypeRegistrations(Configuration.java:1822)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1780)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1865)
    at ManageEmployee.main(ManageEmployee.java:15)
Caused by: org.hibernate.service.classloading.spi.ClassLoadingException: Unable to load class [com.mysql.jdbc.Driver]
    at org.hibernate.service.classloading.internal.ClassLoaderServiceImpl.classForName(ClassLoaderServiceImpl.java:152)
    at org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl.configure(DriverManagerConnectionProviderImpl.java:106)
    ... 12 more
Caused by: java.lang.ClassNotFoundException: Could not load requested class : com.mysql.jdbc.Driver
    at org.hibernate.service.classloading.internal.ClassLoaderServiceImpl$AggregatedClassLoader.findClass(ClassLoaderServiceImpl.java:319)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:423)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:356)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:264)
    at org.hibernate.service.classloading.internal.ClassLoaderServiceImpl.classForName(ClassLoaderServiceImpl.java:149)
    ... 13 more

The class i used is :

我使用的课程是:

import java.util.List; 
import java.util.Date;
import java.util.Iterator; 

import org.hibernate.HibernateException; 
import org.hibernate.Session; 
import org.hibernate.Transaction;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class ManageEmployee {
   private static SessionFactory factory; 
   public static void main(String[] args) {
      try{
         factory = new Configuration().configure().buildSessionFactory();
      }catch (Throwable ex) { 
         System.err.println("Failed to create sessionFactory object." + ex);
         throw new ExceptionInInitializerError(ex); 
      }
      ManageEmployee ME = new ManageEmployee();

      /* Add few employee records in database */
      Integer empID1 = ME.addEmployee("Zara", "Ali", 1000);
      Integer empID2 = ME.addEmployee("Daisy", "Das", 5000);
      Integer empID3 = ME.addEmployee("John", "Paul", 10000);

      /* List down all the employees */
      ME.listEmployees();

      /* Update employee's records */
      ME.updateEmployee(empID1, 5000);

      /* Delete an employee from the database */
      ME.deleteEmployee(empID2);

      /* List down new list of the employees */
      ME.listEmployees();
   }
   /* Method to CREATE an employee in the database */
   public Integer addEmployee(String fname, String lname, int salary){
      Session session = factory.openSession();
      Transaction tx = null;
      Integer employeeID = null;
      try{
         tx = session.beginTransaction();
         Employee employee = new Employee(fname, lname, salary);
         employeeID = (Integer) session.save(employee); 
         tx.commit();
      }catch (HibernateException e) {
         if (tx!=null) tx.rollback();
         e.printStackTrace(); 
      }finally {
         session.close(); 
      }
      return employeeID;
   }
   /* Method to  READ all the employees */
   public void listEmployees( ){
      Session session = factory.openSession();
      Transaction tx = null;
      try{
         tx = session.beginTransaction();
         List employees = session.createQuery("FROM Employee").list(); 
         for (Iterator iterator = 
                           employees.iterator(); iterator.hasNext();){
            Employee employee = (Employee) iterator.next(); 
            System.out.print("First Name: " + employee.getFirstName()); 
            System.out.print("  Last Name: " + employee.getLastName()); 
            System.out.println("  Salary: " + employee.getSalary()); 
         }
         tx.commit();
      }catch (HibernateException e) {
         if (tx!=null) tx.rollback();
         e.printStackTrace(); 
      }finally {
         session.close(); 
      }
   }
   /* Method to UPDATE salary for an employee */
   public void updateEmployee(Integer EmployeeID, int salary ){
      Session session = factory.openSession();
      Transaction tx = null;
      try{
         tx = session.beginTransaction();
         Employee employee = 
                    (Employee)session.get(Employee.class, EmployeeID); 
         employee.setSalary( salary );
         session.update(employee); 
         tx.commit();
      }catch (HibernateException e) {
         if (tx!=null) tx.rollback();
         e.printStackTrace(); 
      }finally {
         session.close(); 
      }
   }
   /* Method to DELETE an employee from the records */
   public void deleteEmployee(Integer EmployeeID){
      Session session = factory.openSession();
      Transaction tx = null;
      try{
         tx = session.beginTransaction();
         Employee employee = 
                   (Employee)session.get(Employee.class, EmployeeID); 
         session.delete(employee); 
         tx.commit();
      }catch (HibernateException e) {
         if (tx!=null) tx.rollback();
         e.printStackTrace(); 
      }finally {
         session.close(); 
      }
   }
}

采纳答案by Masudul

Caused by: org.hibernate.service.classloading.spi.ClassLoadingException: Specified JDBC Driver com.mysql.jdbc.Driver could not be loaded

引起:org.hibernate.service.classloading.spi.ClassLoadingException:无法加载指定的JDBC驱动程序com.mysql.jdbc.Driver

This exception is due to MySQLdriver. Load MySQLconnector jar file on classpath.

此异常是由于MySQL驱动程序造成的。MySQL在类路径上加载连接器 jar 文件。

回答by thst

You have no JDBC driver in the classpath as it is clearly stated in your error messages:

类路径中没有 JDBC 驱动程序,因为它在错误消息中明确说明:

lassLoadingException: Specified JDBC Driver com.mysql.jdbc.Driver could not be loaded

or you have misspelled the JDBC driver name, but it seems ok.

或者您拼错了 JDBC 驱动程序名称,但看起来没问题。

回答by Er CEO Vora Mayur

You get this error

你得到这个错误

Failed to create sessionFactory object.org.hibernate.service.classloading.spi.ClassLoadingException: Specified JDBC Driver com.mysql.jdbc.Driver could not be loaded Exception in thread "main" java.lang.ExceptionInInitializerError at ManageEmployee.main(ManageEmployee.java:18)

无法创建 sessionFactory object.org.hibernate.service.classloading.spi.ClassLoadingException:无法加载指定的 JDBC 驱动程序 com.mysql.jdbc.Driver 线程“main”中的异常 java.lang.ExceptionInInitializerError at ManageEmployee.main(ManageEmployee.爪哇:18)

Hibernate Program Connect With Mysql

Hibernate程序连接Mysql

This error can be solved easily.

这个错误很容易解决。

First you download mysql-connector-java-3.0.16-ga-bin.jar
After that, you add this jar file in your Hibernate program inside Libraries.
Right click on your program -> Build Path -> Add External Archive -> mysql-connector-java-3.0.16-ga-bin.jar
After that Run Program And Remove Error.

首先你下载mysql-connector-java-3.0.16-ga-bin.jar
之后,你把这个 jar 文件添加到你的库中的 Hibernate 程序中。
右键单击您的程序 -> 构建路径 -> 添加外部存档 -> mysql-connector-java-3.0.16-ga-bin.jar
之后运行程序并删除错误。

Successfully connected Hibernate program connect with MySql

成功连接Hibernate程序连接MySql