Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring JPA Repository - Keep data on server restart

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 :)

like image 602
Jordan Avatar asked May 07 '15 03:05

Jordan


People also ask

Should I use JpaRepository or CrudRepository?

Crud Repository doesn't provide methods for implementing pagination and sorting. JpaRepository ties your repositories to the JPA persistence technology so it should be avoided. We should use CrudRepository or PagingAndSortingRepository depending on whether you need sorting and paging or not.

What is the difference between save and saveAndFlush in JPA?

Save and saveAndFlush both can be used for saving entities. They both are both belong to the Spring data library. save may or may not write your changes to the DB straight away. When we call saveAndFlush system are enforcing the synchronization of your model state with the DB.

Does Spring Data JPA require persistence XML?

persistence. xml is needed when you're using Hibernate through JPA, even though you're using Spring JPA. If you're using Hibernate directly, then persistence. xml isn't needed.


2 Answers

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).

like image 89
dunni Avatar answered Nov 15 '22 19:11

dunni


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`
like image 25
Supimi Avatar answered Nov 15 '22 18:11

Supimi