Java Hibernate - 无法连接到 H2

Posted

技术标签:

【中文标题】Java Hibernate - 无法连接到 H2【英文标题】:Java Hibernate - unable to connect to H2 【发布时间】:2019-07-26 04:34:48 【问题描述】:

我需要帮助。我不知道这个项目有什么问题。我无法连接到 h2 数据库。即使我没有保留任何对象,只是关闭连接,我也会收到错误消息。

抱歉,我知道,这个问题已经被问过好几次了,但没有一个答案适合我的情况。

我得到的错误:

2019 年 3 月 4 日晚上 11:00:24 org.hibernate.Version logVersion INFO: HHH000412:休眠核心 5.2.12.Final 2019 年 3 月 4 日晚上 11:00:24 org.hibernate.cfg.Environment 信息:HHH000206: hibernate.properties 未找到 2019 年 3 月 4 日晚上 11:00:24 org.hibernate.boot.jaxb.in​​ternal.stax.LocalXmlResourceResolver resolveEntity WARN: HHH90000012: 识别过时休眠 命名空间http://hibernate.sourceforge.net/hibernate-configuration。 使用命名空间http://www.hibernate.org/dtd/hibernate-configuration 反而。对过时的 DTD/XSD 命名空间的支持可能会在 随时。 2019 年 3 月 4 日晚上 11:00:24 org.hibernate.annotations.common.reflection.java.JavaReflectionManager 信息:HCANN000001:Hibernate Commons 注释 5.0.1.Final 2019 年 3 月 4 日晚上 11:00:25 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl 配置 WARN: HHH10001002: Using Hibernate built-in connection pool (不用于生产!) org.hibernate.service.spi.ServiceException: 无法创建请求的服务 [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment] 在 org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:271) 在 org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:233) 在 org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:210) 在 org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:51) 在 org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:94) 在 org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:242) 在 org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:210) 在 org.hibernate.boot.model.process.spi.MetadataBuildingProcess.handleTypes(MetadataBuildingProcess.java:352) 在 org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:111) 在 org.hibernate.boot.model.process.spi.MetadataBuildingProcess.build(MetadataBuildingProcess.java:83) 在 org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:418) 在 org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:87) 在 org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:691) 在 org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:726) 在 orm.hibernate.employees.HibernateUtils.(HibernateUtils.java:13) 在 orm.hibernate.employees.EmployeeRepository.addNewEmployee(EmployeeRepository.java:16) 在 orm.hibernate.employees.EmployeesApp.main(EmployeesApp.java:21) 造成的: org.hibernate.boot.registry.classloading.spi.ClassLoadingException: 无法在以下位置加载类 [org.h2.Driver] org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.classForName(ClassLoaderServiceImpl.java:348) 在 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl.loadDriverIfPossible(DriverManagerConnectionProviderImpl.java:160) 在 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl.buildCreator(DriverManagerConnectionProviderImpl.java:116) 在 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl.buildPool(DriverManagerConnectionProviderImpl.java:100) 在 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl.configure(DriverManagerConnectionProviderImpl.java:72) 在 org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:94) 在 org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:242) 在 org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:210) 在 org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.buildJdbcConnectionAccess(JdbcEnvironmentInitiator.java:145) 在 org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:66) 在 org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:35) 在 org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.initiateService(StandardServiceRegistryImpl.java:88) 在 org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:259) ... 16 更多原因:java.lang.ClassNotFoundException:无法 加载请求的类:org.h2.Driver at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl$AggregatedClassLoader.findClass(ClassLoaderServiceImpl.java:336) 在 java.lang.ClassLoader.loadClass(ClassLoader.java:424) 在 java.lang.ClassLoader.loadClass(ClassLoader.java:357) 在 java.lang.Class.forName0(本机方法)在 java.lang.Class.forName(Class.java:348) 在 org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.classForName(ClassLoaderServiceImpl.java:345) ... 28 更多

##### Initial SessionFactory 创建失败.org.hibernate.service.spi.ServiceException: 无法创建

请求的服务 [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment] 线程“主”java.lang.ExceptionInInitializerError 中的异常: 连接数据库错误!在 orm.hibernate.employees.HibernateUtils.(HibernateUtils.java:17) 在 orm.hibernate.employees.EmployeeRepository.addNewEmployee(EmployeeRepository.java:16) 在 orm.hibernate.employees.EmployeesApp.main(EmployeesApp.java:21)

进程以退出代码 1 结束

pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<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>brudnopis.com</groupId>
    <artifactId>brudnopis2</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>

        <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>5.2.12.Final</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/com.h2database/h2 -->
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <version>1.4.196</version>
            <scope>test</scope>
        </dependency>

    </dependencies>

</project>

休眠实用程序类:

public class HibernateUtils 

    private static final SessionFactory sessionFactory;

    static 
        try 
            sessionFactory = new Configuration().configure("hibernate.cfg.xml").buildSessionFactory();
         catch (Throwable ex) 
            ex.printStackTrace();
            System.err.println("########### Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError("Connection to database error!");
        
    

    public static Session openSession() throws Exception 
        Session session;
        try 
            session = sessionFactory.openSession();
         catch (Exception e) 
            e.printStackTrace();
            throw new Exception("Connection to database error!");
        
        return session;
    

    public static void closeSession()
        sessionFactory.close();
    

存储库

public class EmployeeRepository 

    // Create

    public static void addNewEmployee(EmployeeEntity employee)

        Session session = null;
        try 
            session = HibernateUtils.openSession();
            session.getTransaction().begin();
            session.saveOrUpdate(employee);
            session.getTransaction().commit();
        catch (Exception e)
            e.printStackTrace();
        finally 
            if (session != null && session.isOpen()) 
                session.close();
            
        
    

    // Read

    public static List<EmployeeEntity> listAllEmployees()

        List<EmployeeEntity> listEmployees = new ArrayList<EmployeeEntity>();

        Session session = null;
        try 
            session = HibernateUtils.openSession();
            listEmployees = session.createQuery("SELECT e FROM EmployeeEntity e").getResultList();
         catch (Exception e) 
            e.printStackTrace();
        finally 
            if (session != null && session.isOpen()) 
                session.close();
            
        
        return listEmployees;
    

    // Update

    public static void editExistingEmployee(EmployeeEntity employee)

        Session session = null;
        try 
            session = HibernateUtils.openSession();
            session.getTransaction().begin();
            session.merge(employee);
            session.getTransaction().commit();
        catch (Exception e)
            e.printStackTrace();
        finally
            if (session != null && session.isOpen()) 
                session.close();
            
        
    

    //Delete

    public static void deleteEmployee(int idToDelete)

        Session session = null;
        try 
            session = HibernateUtils.openSession();
            EmployeeEntity employeeToDelete = session.find(EmployeeEntity.class, idToDelete);
            session.getTransaction().begin();
            session.remove(employeeToDelete);
            session.getTransaction().commit();
        catch (Exception e)
            e.printStackTrace();
        finally
            if (session != null && session.isOpen()) 
                session.close();
            
        
    

实体类:

@Entity
@Table(name = "employees")
public class EmployeeEntity 

    @Id
    @Column(name = "id")
    private int id;
    @Column(name = "employee_id")
    private int employeeId;
    @Column(name = "first_name")
    private String firstName;
    @Column(name = "last_name")
    private String lastName;

    public EmployeeEntity(int id, int employeeId, String firstName, String lastName) 
        this.id = id;
        this.employeeId = employeeId;
        this.firstName = firstName;
        this.lastName = lastName;
    

    public EmployeeEntity()

    @Override
    public String toString() 
        return "EmployeeEntity" +
                "id=" + id +
                ", employeeId=" + employeeId +
                ", firstName='" + firstName + '\'' +
                ", lastName='" + lastName + '\'' +
                '';
    

    public int getId() 
        return id;
    

    public void setId(int id) 
        this.id = id;
    

    public int getEmployeeId() 
        return employeeId;
    

    public void setEmployeeId(int employeeId) 
        this.employeeId = employeeId;
    

    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 class EmployeesApp 
    public static void main(String[] args) throws Exception 

        Scanner sc = new Scanner(System.in);

        System.out.println("Menu");
        System.out.println("====");
        System.out.println("1. Write data to database");
        System.out.println("2. Read data from database");
        System.out.println("3. Exit");

        int userChoice = sc.nextInt();

        switch(userChoice)
            case 1:
                EmployeeEntity employee1 = new EmployeeEntity(1,10001,"Jon", "Doe");
                EmployeeRepository.addNewEmployee(employee1);
                System.out.println(EmployeeRepository.listAllEmployees());
            case 3:
                break;
        
        HibernateUtils.closeSession();
    

项目结构:

【问题讨论】:

您介意发布e.printStackTrace() 结果而不是throw new Exception("Connection to database error!"); 顺便说一句,抛出一个新的Exception 丢弃原来的错误是一种不好的做法,你丢弃原来的错误并用随机消息覆盖它,不知道你的应用程序崩溃的真正原因 谢谢你的观点,@ngueno 我已经添加了 e.printStackTrace() 并更新了消息。也许现在它会告诉你更多。 你去我的朋友,你的错误:Caused by: java.lang.ClassNotFoundException: Could not load requested class : org.h2.Driver 是的,我对此感到困惑,因为这个驱动程序类在库中可用。范围错了:)谢谢你的回答和帮助! 【参考方案1】:

您的应用程序在运行时无法找到您的数据库驱动程序,因此出现错误Caused by: java.lang.ClassNotFoundException: Could not load requested class : org.h2.Driver

将您的 H2 依赖项更改如下:

    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
        <version>1.4.196</version>
        <scope>runtime</scope> <!-- Here you are saying this dependency is needed at runtime, not just at testing -->
    </dependency>

再见!

【讨论】:

以上是关于Java Hibernate - 无法连接到 H2的主要内容,如果未能解决你的问题,请参考以下文章

无法连接到元数据库 h2 数据库

R中的H2O错误-无法连接到本地主机

我无法连接到 H2 数据库

如何从 Java 和 H2 DB 连接到 H2 数据库

无法在自动混合模式下连接到 H2 数据库

无法使用 Hibernate 连接到 Informix