10
votes

I'm currently trying to learn how to use Spring Boot and have a problem I'm not sure how to solve.

I've followed the guide at http://spring.io/guides/gs/accessing-data-jpa/ and everything works fine. However, if I restart the server, then all the data that was saved is completely lost. Is there any way to keep the data in the repository/database so that if I shut down the application and start it again, all the previously saved data is still accessible?

Thank you in advance :)

4
serialize the data on exit to a file and deserialize on load to bring application back to last state. - Shahzeb
When you use a database, data serialization is the worst thing you could do. The problem here is just the missing understanding, how the database used in the examples works. - dunni

4 Answers

8
votes

All examples use an embedded database with in memory persistence, which means, the data is only stored as long as the process is running. Just switch to a regular database like MySQL or use H2 with a file based storage url, which is also permanently saved on your disk. For the latter, just add the following property to your application.properties:

spring.datasource.url=jdbc:h2:tcp://localhost/${path/to/your/db/file}

and replace ${path/to/your/db/file} with the path where you want to store the database (note, the folder you configure here will be created, if it doesn't exist).

5
votes

It seems that your application.properties file has below setting. Remove or comment it.

spring.jpa.hibernate.ddl-auto=create
4
votes

If you want to keep your data on server restart then add the following property into application.properties file :

`spring.jpa.hibernate.ddl-auto=update`
3
votes

I have used this in my project where I want to keep data after server Restart.

spring.datasource.url=jdbc:h2:file:~/data/testdb;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE;

This will store data in a file. You can check http://www.h2database.com/html/features.html for more details.