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