I made a small application based on Spring Boot:
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.
When the application is running everything seems fine. Data is stored. The h2 file is created and contains insert statements.
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).
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
<!-- 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
public interface PostDAO extends JpaRepository<Post, Integer>{
public Post findByMessage(String message);
}
Post.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;
}
}
H2 can be configured to run as an in-memory database, but it can also be persistent, e.g., its data will be stored on disk.
Step 3: Verify H2 Database InstallationClick Windows → type H2 Console → Click H2 console icon. Connect to the URL http://localhost:8082. At the time of connecting, the H2 database will ask for database registration as shown in the following screenshot.
To access an in-memory database from another process or from another computer, you need to start a TCP server in the same process as the in-memory database was created. The other processes then need to access the database over TCP/IP or TLS, using a database URL such as: jdbc:h2:tcp://localhost/mem:db1 .
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With