파일 기반 H2 데이터베이스를 사용하도록 spring-boot를 구성하는 방법
H2 임베디드 데이터베이스 인 메모리를 사용하는 스프링 부트 애플리케이션을 성공적으로 만들었습니다. 이제 이것을 지속될 파일 기반 버전으로 변경하고 싶습니다.
spring.datasource.*
내 application.properties
파일 의 속성을 변경하려고 시도했지만 다음과 같이 보입니다.
spring.datasource.url=jdbc:h2:file:~/test;DB_CLOSE_ON_EXIT=FALSE
spring.datasource.username=test
spring.datasource.password=test
spring.datasource.driverClassName=org.h2.Driver`
스프링 부트는 다음과 같이 시작하기 때문에 이러한 설정을 무시하는 것처럼 보입니다.
o.s.j.d.e.EmbeddedDatabaseFactory : Starting embedded database: url='jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=false', username='sa'
My pom.xml
는이 게시물과 관련이있을 수있는 다음 종속성을 포함합니다.
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.5.RELEASE</version>
</parent>
....
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>
설명서와 여러 게시물에서 내가 이해 한 것은 구성이 작동해야하지만 나에게는 운이 없다는 것입니다. 기본 오류 중 일부를 방지하기 위해 다음을 시도하고 확인했습니다.
- 내 응용 프로그램 속성은 classspath에 있습니다.
- 주석에서 자동 구성을 제외하려고했습니다.
@EnableAutoConfiguration
- 나는
dataSource
주석의 조합과 함께 빈 을 주입하고@Primary
,@ConfigurationProperties(prefix = "spring.datasource")
프로그래밍 방식으로 속성을 설정 하려고했습니다DataSourceBuilder
. 이로 인해 유형과 관련된 다른 오류가 발생합니다null
.
핵심 개념이나 무언가를 놓친 것 같습니다. 누구든지 도울 수 있습니다.
업데이트 1 : 내 자동 구성 보고서에서 추출 :
Positive matches:
-----------------
DataSourceAutoConfiguration matched
- @ConditionalOnClass classes found: javax.sql.DataSource,org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType (OnClassCondition)
DataSourceAutoConfiguration.DataSourceInitializerConfiguration matched
- @ConditionalOnMissingBean (types: org.springframework.boot.autoconfigure.jdbc.DataSourceInitializer; SearchStrategy: all) found no beans (OnBeanCondition)
DataSourceAutoConfiguration.EmbeddedConfiguration matched
- embedded database H2 detected (DataSourceAutoConfiguration.EmbeddedDataSourceCondition)
- @ConditionalOnMissingBean (types: javax.sql.DataSource,javax.sql.XADataSource; SearchStrategy: all) found no beans (OnBeanCondition)
DataSourceAutoConfiguration.JdbcTemplateConfiguration matched
- existing auto database detected (DataSourceAutoConfiguration.DataSourceAvailableCondition)
DataSourceAutoConfiguration.JdbcTemplateConfiguration#jdbcTemplate matched
- @ConditionalOnMissingBean (types: org.springframework.jdbc.core.JdbcOperations; SearchStrategy: all) found no beans (OnBeanCondition)
DataSourceAutoConfiguration.JdbcTemplateConfiguration#namedParameterJdbcTemplate matched
- @ConditionalOnMissingBean (types: org.springframework.jdbc.core.namedparam.NamedParameterJdbcOperations; SearchStrategy: all) found no beans (OnBeanCondition)
DataSourceTransactionManagerAutoConfiguration matched
- @ConditionalOnClass classes found: org.springframework.jdbc.core.JdbcTemplate,org.springframework.transaction.PlatformTransactionManager (OnClassCondition)
DataSourceTransactionManagerAutoConfiguration.TransactionManagementConfiguration matched
- @ConditionalOnMissingBean (types: org.springframework.transaction.annotation.AbstractTransactionManagementConfiguration; SearchStrategy: all) found no beans (OnBeanCondition)
H2ConsoleAutoConfiguration matched
- @ConditionalOnClass classes found: org.h2.server.web.WebServlet (OnClassCondition)
- found web application StandardServletEnvironment (OnWebApplicationCondition)
- matched (OnPropertyCondition)
HibernateJpaAutoConfiguration matched
- @ConditionalOnClass classes found: org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean,org.springframework.transaction.annotation.EnableTransactionManagement,javax.persistence.EntityManager (OnClassCondition)
- found HibernateEntityManager class (HibernateJpaAutoConfiguration.HibernateEntityManagerCondition)
Negative matches:
-----------------
DataSourceAutoConfiguration.NonEmbeddedConfiguration did not match
- missing supported DataSource (DataSourceAutoConfiguration.NonEmbeddedDataSourceCondition)
`
업데이트 2 : 액추에이터를 추가하고 끝점을 보았습니다 /configprops
. 여기서 흥미로운 것은 내 구성을 가져 왔고 데이터베이스가 존재하지만 응용 프로그램이 실행될 때 이것을 사용하지 않는다는 것 dataSource
입니다.
"spring.datasource.CONFIGURATION_PROPERTIES":
{"prefix":"spring.datasource",
"properties":{
"schema":null,
"data":null,
"xa":{"dataSourceClassName":null,
"properties":{}
},
"type":null,
"separator":";",
"url":"jdbc:h2:file:~/test;DB_CLOSE_ON_EXIT=FALSE",
"platform":"all",
"continueOnError":false,
"jndiName":null,
"sqlScriptEncoding":null,
"password":"******",
"name":"testdb",
"driverClassName":"org.h2.Driver",
"initialize":true,
"username":"test"
}
}
http://www.h2database.com/html/cheatSheet.html을 참조하십시오 .
jdbc.url에 문제가있는 것 같습니다. 다음과 같이 변경합니다.
# from:
spring.datasource.url=jdbc:h2:file:~/test;DB_CLOSE_ON_EXIT=FALSE
# to:
spring.datasource.url=jdbc:h2:~/test;DB_CLOSE_ON_EXIT=FALSE
혼란과 추가 연구를 피하기 위해이 답변을 추가하고 있습니다.
Actually I have the same problem and none of the answer worked for me completely rather than the mix for some answers worked.
Here is the minimal configuration which is required to persist H2 db in spring boot.
application.properties
# H2
spring.h2.console.enabled=true
spring.h2.console.path=/h2
# Datasource
spring.datasource.url=jdbc:h2:file:~/spring-boot-h2-db
spring.datasource.username=sa
spring.datasource.password=
spring.datasource.driver-class-name=org.h2.Driver
spring.jpa.hibernate.ddl-auto=update
Here spring.jpa.hibernate.ddl-auto=update
does the trick. Nothing else is required.
No need to add spring-boot-starter-jdbc
in pom.xml
No need to add any parameter in jdbc url.
Using the following setting on application.properties, I manage to keep the data persisted even after shutting down and restarting SpringBoot, and even after restarting the computer.
spring.datasource.name=japodb
spring.datasource.initialize=false
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.url=jdbc:h2:file:~/japodb;DB_CLOSE_ON_EXIT=FALSE;IFEXISTS=TRUE;DB_CLOSE_DELAY=-1;
Don't Close a Database when the VM Exits, yes, but also don’t make a new database if it’s already there.
jdbc:h2:<url>;IFEXISTS=TRUE
spring.jpa.hibernate.ddl-auto = update
Just generated a brand new Spring Boot project with start.spring.io with a few dependencies h2, JPA, web, devtools, actuator
. After adding a simple Entity and Spring Data repository, the database is indeed created in memory by default.
Adding the following to my application.properties
definitely creates the database file in the right place:
spring.datasource.url=jdbc:h2:file:~/test;DB_CLOSE_ON_EXIT=FALSE
spring.datasource.username=test
spring.datasource.password=test
spring.datasource.driverClassName=org.h2.Driver
I can even connect to it with the H2 console when devtools is enabled http://localhost:8080/h2-console/
.
The next logical step is to visit the http://localhost:8080/autoconfig
endpoint and check the auto-configuration status.
In my case, the following is positiveMatches
:
DataSourceAutoConfiguration.NonEmbeddedConfiguration: [
{
condition: "DataSourceAutoConfiguration.NonEmbeddedDataSourceCondition",
message: "supported DataSource class found"
},
{
condition: "OnBeanCondition",
message: "@ConditionalOnMissingBean (types: javax.sql.DataSource,javax.sql.XADataSource; SearchStrategy: all) found no beans"
}
],
and the following in negativeMatches
:
DataSourceAutoConfiguration.EmbeddedConfiguration: [
{
condition: "DataSourceAutoConfiguration.EmbeddedDataSourceCondition",
message: "existing non-embedded database detected"
}
],
Could you try the following and check the auto-configuration report for those?
Create a file .h2.server.properties in your class path and put below things and try again. You can create this file in resources folder.
#H2 Server Properties
0=H2 File|org.h2.Driver|jdbc\:h2\:file\:~/test;DB_CLOSE_ON_EXIT=FALSE
# Enable if you want other applications to connect
#webAllowOthers=true
#webPort=8082
#webSSL=false
ReferenceURL : https://stackoverflow.com/questions/37903105/how-to-configure-spring-boot-to-use-file-based-h2-database
'Programing' 카테고리의 다른 글
'git remote update', 'git fetch'및 'git pull'의 차이점은 무엇입니까? (0) | 2020.12.25 |
---|---|
전역 npm 패키지는 Ubuntu에서 어디에 설치됩니까? (0) | 2020.12.25 |
C ++에서 const 오버로딩을 사용하는 것은 무엇입니까? (0) | 2020.12.25 |
Eclipse에서 줄 높이 / 줄 간격을 어떻게 변경할 수 있습니까? (0) | 2020.12.25 |
ruby-prof 출력 이해 (0) | 2020.12.25 |