Home > Net >  How to automatically dropping data and recreate one table in JPA of Spring boot
How to automatically dropping data and recreate one table in JPA of Spring boot

Time:12-15

I'd like to do test in my local env, but want to always drop data and recreate one table (only one table, not all tables) in JPA of spring boot, how can I achieve that? Thanks

CodePudding user response:

You can use liquibase for manage this approach. in liquibase confiquration file you can check if exists table in database schema drop table and recreate the target table. Note if there are other tables, you should not take any action. https://docs.liquibase.com/tools-integrations/springboot/springboot.html

CodePudding user response:

If you set the 'drop' attribute of the '@Table' annotation to 'false', Hibernate will not drop the table when the application starts up. This means the table will remain in the database, and any existing data in the table will not be deleted And 'true' will drop the table.

Here's an example:

@Entity
@Table(name = "my_entity", drop = false)
public class MyEntity {
    // ...
}

In general, setting the drop attribute of the @Table annotation to false is not very useful, because it only prevents Hibernate from dropping the table when the application starts up. The table will still be dropped when the application shuts down if the spring.jpa.hibernate.ddl-auto property is set to create-drop. To prevent the table from being dropped at all, you should set the spring.jpa.hibernate.ddl-auto property to 'none' or 'validate', or use a SQL DROP statement to manually drop the table.

CodePudding user response:

You can use the following properties in your spring-boot app.

spring:
  sql.init.mode: always   
  datasource:
    url: ...
    username: ... 
    password: ...
  jpa:
    defer-datasource-initialization: true 
    hibernate:
      ddl-auto: update
    database-platform: org.hibernate.dialect.PostgreSQLDialect

Then you can place under src/main/resources a file named data.sql which could contain DELETE FROM MY_TABLE which will clean the table completely.

With the property defer-datasource-initialization: true you ensure that the script will be executed only after hibernate has finished processing your schema and doing changes in DB during app initialization.

  • Related