繁体   English   中英

使用 H2 数据库和 Liquibase 配置 Spring Boot

[英]Configure Spring boot with H2 database and Liquibase

我正在使用 Spring boot2,我正在尝试使用 H2 + Liquibase + JUNIT 配置单元测试。

我认为 liquibase 没有执行 changeLog 文件并应用 SQL 命令,单元测试无法识别我的表。

我在我的文件中放了错误的 sql 以查看更改日志文件是否已执行,但是似乎没有执行。

为什么我的应用程序无法访问表? 也许 liquibase 没有执行?

在我的src/test/resource我有这个文件: application.yml

spring:
  application:
    name: my-api
  datasource:
    driver-class-name: org.h2.Driver
    url: jdbc:h2:mem:myDB;MODE=MySQL;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE
    username: sa
    password: sags
  liquibase:
    enabled: true
    user: sa
    password: sags
    change-log: classpath:/db/changelog/db.changelog-master.xml
  jpa:
    hibernate:
      ddl-auto: none
      database-platform: org.hibernate.dialect.H2Dialect
    show-sql: true
    properties:
      hibernate:
        use_sql_comments: true
        format_sql: true
  h2:
    console:
      enabled: true
      path: /console

我的测试课:

import java.util.List;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
public class FooRepositoryTest {

    @Autowired
    private FooRepository fooRepository;

    @Test
    public void findAllMustReturnAnything() {
        List<Object> result = fooRepository.tables();
    }
}

FooRepository 方法:

@Query(value = "SHOW TABLES", nativeQuery = true)
    List<Object> tables();

当我运行单元测试时,我得到以下结果:

在此处输入图像描述

我的变更日志文件位于: src/main/resources/db

更新:我发现为什么 liquibase 没有执行我的 sql 代码。 这是因为我的 SQL 文件有“dbms:mysql”,所以,我使用 H2 liquibase 执行的方式将不适用。

-- changeset 1.0:2 dbms:mysql
command
-- rollback command

现在,我需要知道为什么我在会话中选择的数据库不是 myDB。

我认为在您的情况下,Spring 会打开自动配置数据源。( https://docs.spring.io/spring-boot/docs/1.5.9.RELEASE/api/org/springframework/boot/test/autoconfigure/orm/jpa /AutoConfigureTestDatabase.Replace.html )

尝试将其关闭。

spring.test.database.replace=none

还有一些不必要的配置。

  liquibase:
    user: sa
    password: sags

您可以删除用户和密码,liquibase 从数据源中使用它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM