r2dbc 및 플라이웨이를 사용하여 스프링 부트 애플리케이션에서 h2 설정
스프링 부트와 r2dbc라는 반응형 jdbc 드라이버를 가지고 놀고 있습니다.저는 메인 애플리케이션에서 Postgres를 데이터베이스로 사용하고 있으며 이제 테스트에 h2를 사용하려고 합니다.또한 Flyway 마이그레이션은 Spring 응용 프로그램이 레코드를 삽입할 수 있을 때 설정과 함께 작동합니다.
여기 제 설정과 코드가 있습니다.
@SpringBootTest
class CustomerRepositoryTest {
@Autowired
CustomerRepository repository;
@Test
void insertToDatabase() {
repository.saveAll(List.of(new Customer("Jack", "Bauer"),
new Customer("Chloe", "O'Brian"),
new Customer("Kim", "Bauer"),
new Customer("David", "Palmer"),
new Customer("Michelle", "Dessler")))
.blockLast(Duration.ofSeconds(10));
}
}
여기 제가 받고 있는 오류가 있습니다.
:: Spring Boot :: (v2.3.4.RELEASE)
2020-10-14 15:59:18.538 INFO 25279 --- [ main] i.g.i.repository.CustomerRepositoryTest : Starting CustomerRepositoryTest on imalik8088.fritz.box with PID 25279 (started by imalik in /Users/imalik/code/private/explore-java/spring-example)
2020-10-14 15:59:18.540 INFO 25279 --- [ main] i.g.i.repository.CustomerRepositoryTest : No active profile set, falling back to default profiles: default
2020-10-14 15:59:19.108 INFO 25279 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data R2DBC repositories in DEFAULT mode.
2020-10-14 15:59:19.273 INFO 25279 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 160ms. Found 1 R2DBC repository interfaces.
2020-10-14 15:59:19.894 INFO 25279 --- [ main] o.f.c.internal.license.VersionPrinter : Flyway Community Edition 6.5.0 by Redgate
2020-10-14 15:59:20.052 INFO 25279 --- [ main] o.f.c.internal.database.DatabaseFactory : Database: jdbc:h2:mem:///DBNAME (H2 1.4)
2020-10-14 15:59:20.118 INFO 25279 --- [ main] o.f.core.internal.command.DbValidate : Successfully validated 1 migration (execution time 00:00.022s)
2020-10-14 15:59:20.131 INFO 25279 --- [ main] o.f.c.i.s.JdbcTableSchemaHistory : Creating Schema History table "PUBLIC"."flyway_schema_history" ...
2020-10-14 15:59:20.175 INFO 25279 --- [ main] o.f.core.internal.command.DbMigrate : Current version of schema "PUBLIC": << Empty Schema >>
2020-10-14 15:59:20.178 INFO 25279 --- [ main] o.f.core.internal.command.DbMigrate : Migrating schema "PUBLIC" to version 1.0.0 - schma
2020-10-14 15:59:20.204 INFO 25279 --- [ main] o.f.core.internal.command.DbMigrate : Successfully applied 1 migration to schema "PUBLIC" (execution time 00:00.036s)
2020-10-14 15:59:20.689 INFO 25279 --- [ main] i.g.i.repository.CustomerRepositoryTest : Started CustomerRepositoryTest in 2.466 seconds (JVM running for 3.326)
2020-10-14 15:59:21.115 DEBUG 25279 --- [ main] o.s.d.r2dbc.core.DefaultDatabaseClient : Executing SQL statement [INSERT INTO customer (first_name, last_name) VALUES ($1, $2)]
org.springframework.data.r2dbc.BadSqlGrammarException: executeMany; bad SQL grammar [INSERT INTO customer (first_name, last_name) VALUES ($1, $2)]; nested exception is io.r2dbc.spi.R2dbcBadGrammarException: [42102] [42S02] Tabelle "CUSTOMER" nicht gefunden
Table "CUSTOMER" not found; SQL statement:
INSERT INTO customer (first_name, last_name) VALUES ($1, $2) [42102-200]
my src/test/resources/application.yaml은 다음과 같습니다.
spring:
r2dbc:
url: r2dbc:h2:mem:///DBNAME?options=DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE
username: sa
password:
flyway:
url: jdbc:h2:mem:///DBNAME
baseline-on-migrate: true
user: sa
password:
누락된 부분이나 설정에 문제가 있는 부분이 있습니까?더 필요한 정보가 있으면 알려주시기 바랍니다.
추가/솔루션:
jdbc와 r2dbc 사이에 URL 패턴이 다릅니다.저를 위한 해결책은 다음과 같습니다.
url: r2dbc:h2:file:///./tmp/test-database
url: jdbc:h2:file:./tmp/test-database
그리고 Flyway를 설정하려면 Flyway를 구성해야 합니다.
// Flyway is not compatible with r2dbc yet, therefore this config class is created
@Configuration
public class FlywayConfig {
private final Environment env;
public FlywayConfig(final Environment env) {
this.env = env;
}
@Bean(initMethod = "migrate")
public Flyway flyway() {
return new Flyway(Flyway.configure()
.baselineOnMigrate(true)
.dataSource(
env.getRequiredProperty("spring.flyway.url"),
env.getRequiredProperty("spring.flyway.user"),
env.getRequiredProperty("spring.flyway.password"))
);
}
}
테스트를 위해 메모리의 h2 데이터베이스를 설정하고 액세스해야 하는 동일한 문제에 직면했습니다.
- JDBC 드라이버를 사용한 데이터베이스 마이그레이션용 Liquibase
- R2DBC 드라이버를 사용하여 반응형 Crud 저장소 테스트
오류 발생:
org.springframework.data.r2dbc.배드Sql 문법예외: executeMany; 잘못된 SQL 문법 [INSERT IN MY_TABLE...테이블 "MY_TABLE"을(를) 찾을 수 없습니다...
Chris의 솔루션에 영감을 받아 구성했습니다.src/testresources/application.properties
파일은 다음과 같습니다.
spring.r2dbc.url=r2dbc:h2:mem:///~/db/testdb
spring.r2dbc.username=sa
spring.r2dbc.password=
spring.liquibase.url=jdbc:h2:mem:~/db/testdb;DB_CLOSE_DELAY=-1
spring.liquibase.user=sa
spring.liquibase.password=
spring.liquibase.enabled=true
저는 현재 liquibase에서 r2dbc를 사용하는 것과 같은 문제를 겪고 있습니다.R2DB와 JDBC의 구문이 조금 달라서 JDBC url이 다른 데이터베이스를 가리키는 것으로 의심됩니다.파일 시스템에서 h2를 실행할 수는 있지만...
url: r2dbc:h2:file:///~/db/testdb
...
url: jdbc:h2:file:~/db/testdb
편집:
비반응성 Spring Data에서는 일반적으로 schema.sql/data.sql 쌍을 사용하여 Schema를 H2 메모리 데이터베이스로 채웁니다.이것은 R2DBC에서도 가능하지만, 사용자가 직접 Populator를 구성해야 합니다.
또한 시작하기 R2DBC 튜토리얼에도 나와 있습니다.기본적으로 Connection Factory를 등록해야 합니다.이니셜라이저 빈.
@Bean
public ConnectionFactoryInitializer initializer(@Qualifier("connectionFactory") ConnectionFactory connectionFactory) {
var initializer = new ConnectionFactoryInitializer();
initializer.setConnectionFactory(connectionFactory);
var populator = new CompositeDatabasePopulator();
populator.addPopulators(new ResourceDatabasePopulator(new ClassPathResource("schema.sql")));
populator.addPopulators(new ResourceDatabasePopulator(new ClassPathResource("data.sql")));
initializer.setDatabasePopulator(populator);
return initializer;
}
저는 그것을 작동시킬 수 있었습니다.
우선 테스트 구성 클래스를 따라 만들었습니다(H2에 대해서만 테스트를 실행하고 싶기 때문에 프로덕션 모드에서 Postgre를 사용합니다).SQL):
@TestConfiguration
public class TestConfig {
@Bean
@Profile("test")
public ConnectionFactory connectionFactory() {
System.out.println(">>>>>>>>>> Using H2 in mem R2DBC connection factory");
return H2ConnectionFactory.inMemory("testdb");
}
@Bean(initMethod = "migrate")
@Profile("test")
public Flyway flyway() {
System.out.println("####### Using H2 in mem Flyway connection");
return new Flyway(Flyway.configure()
.baselineOnMigrate(true)
.dataSource(
"jdbc:h2:mem:testdb",
"sa",
"")
);
}
}
위의 코드에서 볼 수 있듯이 두 콩 모두 "테스트" 프로필로만 범위가 지정됩니다.여러분이 상상할 수 있듯이 저는 일반적인 Application Configuration 클래스에서 거의 같은 콩을 가지고 있지만 주석이 달렸습니다.@Profile("default")
Postgre Postgre를 되었습니다.SQL.
두 번째는 제 자신을 반복하지 않고 쉽게 선언된 콩을 집을 수 있도록 여러 개의 다른 주석을 결합한 주석을 만들었습니다.TestConfig
명령어:
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootTest
@ActiveProfiles("test")
@Import(TestConfig.class)
public @interface IntegrationTest {
}
이제 테스트 자체:
@IntegrationTest
class CartsIntegrationTest {
// test methods here ....
}
주요 힌트는 다음과 같습니다.H2ConnectionFactory.inMemory("testdb");
Flyway는 현재 Blocking JDBC API만 지원하며, 가능하면 동일한 애플리케이션에서 혼합하지 않으면 반응형 r2dbc와 호환되지 않습니다.
등을시다니합을 .
ConnectionFactoryInitializer
@Chris가 게시한 대로 데이터베이스 스키마와 데이터를 시작하려면 여기에서 작업 예제를 찾을 수 있습니다.이동 경로를 R2dbc 월드로 마이그레이션하려는 trinkonev/r2dbc-migrate를 시도합니다.
제가 프로젝트에서 겪고 있던 문제는 두 가지였습니다.
종속성을 포함해야 했습니다.
<dependency> <groupId>io.r2dbc</groupId> <artifactId>r2dbc-h2</artifactId> <scope>test</scope> </dependency>
다음에 대한 값을 변경해야 했습니다.
spring.r2dbc.url
r2dbc:h2:mem:///test_db
이러한 변경으로 rd2bc는 테스트를 위해 메모리 h2 데이터베이스에서 작업했습니다.참고 항목:
https://github.com/r2dbc/r2dbc-h2
언급URL : https://stackoverflow.com/questions/64355106/setup-h2-in-spring-boot-application-with-r2dbc-and-flyway
'programing' 카테고리의 다른 글
소문자 및 대문자(jQuery 포함) (0) | 2023.07.28 |
---|---|
제약 조건 레이아웃을 백분율 값으로 작동시키는 방법은 무엇입니까? (0) | 2023.07.28 |
Oracle에서 변수 값을 선택하는 방법은 무엇입니까? (0) | 2023.07.28 |
c에서 함수에 대한 인수로 수신된 정수 배열의 크기 찾기 (0) | 2023.07.23 |
복귀를 기다리는 약속과 복귀를 약속하는 약속의 차이 (0) | 2023.07.23 |