使用H2db

时间:2019-05-26 17:47:38

标签: java maven spring-boot h2db

我是编码新手。当尝试使用H2db在springboot中运行Java应用程序时,出现以下错误。


[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

这是我的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>

应用程序:

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应该具有“ DB中的学生人数:2”

我的Java版本是: Java版本“ 1.8.0_102” Java(TM)SE运行时环境(内部版本1.8.0_102-b14) Java HotSpot(TM)64位服务器VM(内部版本25.102-b14,混合模式)

在命令行中运行mvn clean install时出现上述错误。 我在application.properties文件中定义了h2db配置,如下所示

H2配置

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 

在data.sql文件中保留要插入的数据:

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

insert into STUDENT
values(10002,'Ajit', 'AAA2');

2 个答案:

答案 0 :(得分:0)

错误看起来像是,它无法弄清楚要与H2一起使用的方言。

  

方言指定了hibernate中使用的数据库类型,以便hibernate生成适当类型的SQL语句。

用于h2的方言是这样的:

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

对于编程来说,这也是新手,可能会使您无法编写最佳代码。看起来,您正在混合旧版本的Spring Boot和Spring中的东西。请使用

https://start.spring.io

生成具有所需依赖项的初始spring boot项目。您可以按照以下教程进行操作,该教程很好地说明了如何使用Spring Boot和H2。

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

答案 1 :(得分:0)

您需要提供休眠方言才能在连接之前配置休眠状态

使用

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