Java Hibernate – unable to connect to H2

I need help. I have no idea what’s wrong with this project. I cannot connect to h2 database. I get error even if I’m not persisting any object, just closing connection.

Sorry, I know, that it had been asked several times, but none of the answers fit my case.

Error I get:

Mar 04, 2019 11:00:24 PM org.hibernate.Version logVersion INFO: HHH000412: Hibernate Core {5.2.12.Final} Mar 04, 2019 11:00:24 PM org.hibernate.cfg.Environment INFO: HHH000206: hibernate.properties not found Mar 04, 2019 11:00:24 PM org.hibernate.boot.jaxb.internal.stax.LocalXmlResourceResolver resolveEntity WARN: HHH90000012: Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/hibernate-configuration. Use namespace http://www.hibernate.org/dtd/hibernate-configuration instead. Support for obsolete DTD/XSD namespaces may be removed at any time. Mar 04, 2019 11:00:24 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager INFO: HCANN000001: Hibernate Commons Annotations {5.0.1.Final} Mar 04, 2019 11:00:25 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!) 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:271) at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:233) at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:210) at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:51) at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:94) at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:242) at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:210) at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.handleTypes(MetadataBuildingProcess.java:352) at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:111) at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.build(MetadataBuildingProcess.java:83) at org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:418) at org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:87) at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:691) at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:726) at orm.hibernate.employees.HibernateUtils.(HibernateUtils.java:13) at orm.hibernate.employees.EmployeeRepository.addNewEmployee(EmployeeRepository.java:16) at orm.hibernate.employees.EmployeesApp.main(EmployeesApp.java:21) Caused by: org.hibernate.boot.registry.classloading.spi.ClassLoadingException: Unable to load class [org.h2.Driver] at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.classForName(ClassLoaderServiceImpl.java:348) at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl.loadDriverIfPossible(DriverManagerConnectionProviderImpl.java:160) at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl.buildCreator(DriverManagerConnectionProviderImpl.java:116) at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl.buildPool(DriverManagerConnectionProviderImpl.java:100) at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl.configure(DriverManagerConnectionProviderImpl.java:72) at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:94) at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:242) at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:210) 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:88) at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:259) … 16 more Caused by: java.lang.ClassNotFoundException: Could not load requested class : org.h2.Driver at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl$AggregatedClassLoader.findClass(ClassLoaderServiceImpl.java:336) at java.lang.ClassLoader.loadClass(ClassLoader.java:424) at java.lang.ClassLoader.loadClass(ClassLoader.java:357) at java.lang.Class.forName0(Native Method) at java.lang.Class.forName(Class.java:348) at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.classForName(ClassLoaderServiceImpl.java:345) … 28 more

##### Initial SessionFactory creation failed.org.hibernate.service.spi.ServiceException: Unable to create

requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment] Exception in thread “main” java.lang.ExceptionInInitializerError: Connection to database error! at orm.hibernate.employees.HibernateUtils.(HibernateUtils.java:17) at orm.hibernate.employees.EmployeeRepository.addNewEmployee(EmployeeRepository.java:16) at orm.hibernate.employees.EmployeesApp.main(EmployeesApp.java:21)

Process finished with exit code 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>

Hibernate Utils class:

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

Repository

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 class:

@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;
    }
}

main class:

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

project structure:

enter image description here

Answer

Your application is not able to find your database driver at runtime, hence the error Caused by: java.lang.ClassNotFoundException: Could not load requested class : org.h2.Driver.

Change your H2 dependency as the following:

    <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>

See ya!

Leave a Reply

Your email address will not be published. Required fields are marked *