1

I am new to coding. I am getting below error when trying to run java application in springboot with H2db.


[ERROR] Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 8.777 s <<< FAILURE! - in com.example.demo.DemoApplicationTests
[ERROR] contextLoads(com.example.demo.DemoApplicationTests)  Time elapsed: 0.002 s  <<< ERROR!
java.lang.IllegalStateException: Failed to load ApplicationContext
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Invocation of init method failed; nested exception is org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
Caused by: org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
Caused by: org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set

[INFO]
[INFO] Results:
[INFO]
[ERROR] Errors:
[ERROR]   DemoApplicationTests.contextLoads » IllegalState Failed to load ApplicationCon...
[INFO]
[ERROR] Tests run: 1, Failures: 0, Errors: 1, Skipped: 0
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  13.028 s
[INFO] Finished at: 2019-05-26T22:46:54+05:30
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.22.2:test (default-test) on project demo: There are test failures.
[ERROR]
[ERROR] Please refer to C:\Users\v\Desktop\demo\target\surefire-reports for the individual test results.
[ERROR] Please refer to dump files (if any exist) [date].dump, [date]-jvmRun[N].dump and [date].dumpstream.
[ERROR] -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException

Here is my 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>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.5.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

Application :

package com.example.demo;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;

import com.example.demo.StudentRepository;

@SpringBootApplication
@EntityScan("com.example.demo.Student")
@EnableJpaRepositories("com.example.demo.StudentRepository")
public class H2demoApplication implements CommandLineRunner {

    // mvn spring-boot:run
    private Logger LOG = LoggerFactory.getLogger("H2demoApplication");

    StudentRepository studentRepository;

    @Autowired
    public H2demoApplication(StudentRepository studentRepository) {
        this.studentRepository = studentRepository;
    }

    public static void main(String[] args) {
        SpringApplication.run(H2demoApplication.class, args);
    }

    @Override
    public void run(String... args) throws Exception {
        LOG.info("Student count in DB: {}", studentRepository.count());
    }
}


Entity:

package com.example.demo;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

@Entity
public class Student {

    @Id
    @GeneratedValue
    private Long ID;
    private String NAME;
    private String SECTION;

    public Student() {
    }

    public Student(Long ID, String NAME, String SECTION) {
        this.ID = ID;
        this.NAME = NAME;
        this.SECTION = SECTION;
    }

    public Long getId() {
        return ID;
    }

    public void setId(Long ID) {
        this.ID = ID;
    }

    public String getName() {
        return NAME;
    }

    public void setName(String NAME) {
        this.NAME = NAME;
    }

    public String getSection() {
        return SECTION;
    }

    public void setSection(String SECTION) {
        this.SECTION = SECTION;
    }

}


Repository:

package com.example.demo;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import com.example.demo.Student;

@Repository
public interface StudentRepository extends JpaRepository<Student, Long> {

}

O/p should have "Student count in DB: 2"

my java version is : java version "1.8.0_102" Java(TM) SE Runtime Environment (build 1.8.0_102-b14) Java HotSpot(TM) 64-Bit Server VM (build 25.102-b14, mixed mode)

Getting above error when running mvn clean install in command line. I defined h2db configurations in application.properties file as below

H2 configurarion

spring.h2.console.enabled=true

spring.h2.console.path=/h2 

Datasource

spring.datasource.url=jdbc:h2:~/test

spring.datasource.username=

spring.datasource.password=

spring.datasource.driver-class-name=org.h2.Driver 

in data.sql file kept data to be inserted :

insert into STUDENT
values(10001,'Ajay', 'AAA1');

insert into STUDENT
values(10002,'Ajit', 'AAA2');
Amit Kumar Lal
  • 5,537
  • 3
  • 19
  • 37
Kamal
  • 11
  • 4

2 Answers2

0

The error looks like, it can't figure out the dialect to be used with H2.

The dialect specifies the type of database used in hibernate so that hibernate generate appropriate type of SQL statements.

The dialect to be used for h2 is this:

spring.jpa.database-platform=org.hibernate.dialect.H2Dialect

Also being new to programming might confuse you to write optimal code. It looks like, you are mixing up things from older versions of spring boot and spring. Please use,

https://start.spring.io

to generate your initial spring boot project with the required dependencies. You can follow the below tutorial which explains nicely to get started with spring boot and h2.

https://www.springboottutorial.com/spring-boot-and-h2-in-memory-database

Malathi
  • 2,119
  • 15
  • 40
  • Hi Malathi, Thanks for your response. After adding dialect i am still getting error.Error creating bean with name 'h2demoApplication': Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.example.demo.StudentRepository' available: expected at least 1 bean which qualifies as autowire candidate. Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.example.demo.StudentRepository' – Kamal May 27 '19 at 10:11
  • As you can see in the error logs, it says that the spring boot application can't find the `StudentRepository` bean. By default the beans are created by spring boot on application startup. To create beans, spring boot scans the base package recursively and fins classes with annotations like `@Service`, `@Repository` etc. Spring boot by default uses the package of the main program with annotation `@SpringBootApplication` as the base package. But you are using @EntityScan("com.example.demo.Student") in the main program, which means spring looks for classes under the Student package. – Malathi May 27 '19 at 10:27
  • Also, you are autowiring the StudentRepository class in the main program which is not the best way to write code. You are supposed to create a controller class that will have the APIs you need and also you are supposed to create a service class that will autowire the repository objects and get data and pass it back to the controller. This is the expected setup. Follow the blog post I mentioned in my answer to understand the best practises. – Malathi May 27 '19 at 10:30
  • Got it!! Thanks Malathi. – Kamal May 28 '19 at 06:42
0

You need to provide the hibernate dialect to configure hibernate befor connecting

use

spring.jpa.database-platform=org.hibernate.dialect.H2Dialect

lm1010
  • 81
  • 3