Java Hibernate-无法连接到H2

时间:2019-03-04 19:43:19

标签: java hibernate orm persistence

我需要帮助。我不知道这个项目有什么问题。我无法连接到H2数据库。即使我不保留任何对象,也只是关闭连接,但我还是报错。

对不起,我知道有人问过几次,但是没有一个答案适合我的情况。

我得到的错误:

  

2019年3月4日11:00:24 org.hibernate.Version logVersion INFO:   HHH000412:Hibernate Core {5.2.12.Final} 2019年3月4日11:00:24 PM   org.hibernate.cfg。环境信息:HHH000206:   找不到hibernate.properties 2019年3月4日11:00:24 PM   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名称空间的支持:   任何时候。三月04,2019 11:00:24下午   org.hibernate.annotations.common.reflection.java.JavaReflectionManager    INFO:HCANN000001:休眠公共注释   {5.0.1.Final} 2019年3月4日11:00:25 PM   org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl   配置WARN:HHH10001002:使用Hibernate内置连接池   (不适用于生产!)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   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个

     #####初始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();
    }
}

项目结构:

enter image description here

1 个答案:

答案 0 :(得分: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>

再见!