首页 > 解决方案 > 使用 H2db 实现 springboot 时出错

问题描述

我是编码新手。尝试使用 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 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,混合模式)

在命令行中运行 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');

标签: javamavenspring-booth2db

解决方案


错误看起来像,它无法确定要与 H2 一起使用的方言。

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

用于 h2 的方言是这样的:

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

同样是编程新手可能会混淆您编写最佳代码。看起来,您正在混淆旧版本的弹簧靴和弹簧。请用,

https://start.spring.io

生成具有所需依赖项的初始 Spring Boot 项目。您可以按照下面的教程很好地解释如何开始使用 spring boot 和 h2。

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


推荐阅读