Java 基于文件的 h2 持久化但未在 Spring Boot 中加载
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24703988/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
File based h2 persisted but not loaded in Spring Boot
提问by Phil
I made a small application based on Spring Boot:
我做了一个基于 Spring Boot 的小应用:
- spring-boot-starter-web
- spring-boot-starter-data-jpa
- spring-boot-starter-web
- spring-boot-starter-data-jpa
The application has simply one domain class Post.java
.
Accordingly there is a RestController and a DAO.
The data is supposed to be persisted in a file based hsql db.
该应用程序只有一个域类Post.java
。因此有一个 RestController 和一个 DAO。数据应该保存在基于文件的 hsql db 中。
When the application is running everything seems fine. Data is stored. The h2 file is created and contains insert statements.
当应用程序运行时,一切似乎都很好。数据被存储。h2 文件已创建并包含插入语句。
However, when I kill the application and start it a second time. No data is loaded. (As if a brand new db file was created, which overwrote the old one).
但是,当我终止应用程序并再次启动它时。没有加载数据。(好像创建了一个全新的 db 文件,覆盖了旧文件)。
application.properties
应用程序属性
spring.datasource.url = jdbc:h2:file:~/testdb
spring.datasource.username = sa
spring.datasource.password = sa
spring.datasource.driverClassName = org.h2.Driver
pom.xml
pom.xml
<!-- Spring Boot Web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Spring Boot Data JPA -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- H2 DB -->
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.179</version>
</dependency>
PostDAO.java
PostDAO.java
public interface PostDAO extends JpaRepository<Post, Integer>{
public Post findByMessage(String message);
}
Post.java
后.java
@Entity
public class Post {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
private String message;
public Post(){
}
public Post(String message) {
super();
this.message = message;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
采纳答案by Dave Syer
The default for spring.jpa.hibernate.ddl-auto
is create-drop
if you use an embedded database. You probably want it to be empty, or just validate
(none
might work as well but I think that's deprecated by hibernate).
如果您使用嵌入式数据库,spring.jpa.hibernate.ddl-auto
则默认为create-drop
。您可能希望它是空的,或者只是validate
(none
可能也可以工作,但我认为这已被 hibernate 弃用)。