Data being deleted from H2 database with Spring Boot

Asked

Viewed 313 times

0

I am making an application with Spring Boot and using the H2 bank.

When I register a person, they get id 1, if I register someone else gets id 2 and so on, only if I restart the bank I lose everything and the first person I register has id 1 and so on, I wanted it to continue as id 3, 4.

Is there any way to save the data in the H2 database?

Man application.properties

spring.datasource.url=jdbc:h2:mem:testdb  
spring.datasource.driverClassName=org.h2.Driver  
spring.datasource.username=sa  
spring.datasource.password=password  
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect  
spring.jpa.hibernate.ddl-auto=update
  • To use without being in memory you can opt for mariaDB Mysql or Postgresql, when data is saved in memory the intention is that they are not saved after the execution, however they can be used while your server/container is running.

  • 1

    The problem is that you specified h2: mem :testdb. That’s what’s keeping you in memory. Use the option file with AUTO_RECONNECT=TRUE - I had converted the answers to comment, but I had to reverse the process (they are answers, but they appear incorrect).

1 answer

2


From what I read in the documentation:

you are explicitly using the in-memory mode, as per this:

spring.datasource.url=jdbc:h2:mem:testdb

The mem: indicates that mode, "memory".

To persist simply do not use this mode mem:, H2 has two ways of working:

Local (Embedded Connection):

Examples:

jdbc:h2:[file:][<caminho>]<banco de dados>
jdbc:h2:~/exemplo
jdbc:h2:file:/data/exemplo
jdbc:h2:file:C:/data/exemplo (apenas Windows)

Remote (Server mode)

Examples (which also allows temporary):

jdbc:h2:tcp://<server>[:<porta>]/[<caminho>]<banco de dados>
jdbc:h2:tcp://localhost/~/exemplo
jdbc:h2:tcp://dbserv:8084/~/exemplo

If remote and temporary also uses the mind::

jdbc:h2:tcp://localhost/mem:exemplotemporario

In short, H2 is not only used in memory

Browser other questions tagged

You are not signed in. Login or sign up in order to post.