Search code examples
springspring-boothibernatespring-data-jpaspring-data

Why are all of my tables being deleted when I shut down my Spring application?


I'm running a Spring Boot application on an EC2 instance. It seems to be connecting to the database just fine. However, when I shut it down (Ctrl+C), it deletes all of the tables in the database

Hibernate: drop table if exists table1 Hibernate: drop table if exists table2 Hibernate: drop table if exists table3

This is something that I expect to happen at the beginning of instantiation. This is the way I have it set up in my applications.properties. But I don't want this to happen when shutting it down. I suspect there's something in my properties file that I need to change, but I'm not sure what exactly.

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://my-database.cggorzw3flvw.us-east-1.rds.amazonaws.com:3306/db_name
spring.datasource.username=username
spring.datasource.password=password

spring.jpa.hibernate.ddl-auto=create-drop #this is probably what's deleting my tables
#spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=trace
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect
#spring.jpa.database-platform=org.hibernate.dialect.MySQL5InnoDBDialect
logging.level.org.hibernate.type=trace
server.port=8080

Solution

  • You have correctly identified the problem already: spring.jpa.hibernate.ddl-auto=create-drop will create the schema on startup, deleting any data that is currently there, and delete the schema on shutdown. This is certainly not an appropriate setting for a production environment.

    You could try changing that setting to spring.jpa.hibernate.ddl-auto=update to only update the existing schema.

    A more appropriate configuration for Spring Boot in a production environment is to use the integration with database migration tools Luquibase or Flyway.