如何在 运行 Spring 引导应用程序中重新加载初始数据?

How to reload Initial Data in running Spring Boot applicaiton?

我在我的网络应用程序中使用 spring-boot-starter-data-jdbc 依赖项。 Spring Boot 可以在应用程序启动时自动创建模式并从根类路径位置 schema.sqldata.sql 初始化它,但我很好奇是否有任何方法可以使用重新初始化数据库应用程序启动后的 sql-脚本是否完全相同?

我需要此功能用于演示模式,以便用户在玩够 table 之后可以将数据库重置为初始状态。这就是我希望重置控制器的样子:

@Controller
@RequestMapping("/reset")
@Profile("demo")
public class ResetController {

    @GetMapping
    public String resetTables(HttpSession session) {
        // some code re-initializing the database 
        // form schema.sql and data.sql goes here
        session.invalidate();
        return "redirect:/home";
    }
}

我知道,我总是可以使用 JdbcTemplate 及其方法手动删除、创建和重新填充每个 table,遵循 sql 语句中定义的逻辑 schema.sqldata.sql,但这有点乏味。也许,Spring 有一些开箱即用的方法来针对数据库执行这些脚本,这将有助于用初始演示数据重新加载 tables?

更新:

这是基于 Flyway 迁移的可能解决方案之一,正如 Charles B 在接受的答案中所建议的那样:

  1. 向项目添加 flyway-core 依赖项。
  2. 按照Flyway命名要求将schema.sqldata.sql重命名为V1__schema.sqlV2__data.sql并放在/resources/db/migration目录下。
  3. spring.flyway.baseline-on-migrate属性设置为true
  4. 那么,上面描述的reset-controller就可以重写了,就这么简单:
@Controller
@RequestMapping("/reset")
@Profile("demo")
public class ResetController {

    private final Flyway flyway;

    public ResetController(Flyway flyway) {
        this.flyway = flyway;
    }

    @GetMapping
    public String resetTables(HttpSession session) {
        flyway.clean();
        flyway.migrate();
        session.invalidate();
        return "redirect:/home";
    }
    
}

此外,对于不同的迁移场景,可以设置 spring.flyway.locations 属性 引用不同的 SQL 文件 - 分别为每个配置文件,甚至通过设置禁用某些配置文件的 Flyway 迁移spring.flyway.enabled 属性 到 false.

如果您迁移到 Flyway, you could build a controller that calls flyway's clean method like referenced 之类的东西。易于迁移和长期维护。

您可以尝试使用 Spring Boot Actuator 端点来重新启动整个应用程序。那应该重新初始化您的 ORM 并重置数据库初始状态。

依赖关系:

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

配置:

management:
  endpoints:
    web:
      exposure:
        include: restart
  endpoint:
    restart:
      enabled: true

你应该能够到达 /actuator/restart 端点。

http://localhost:8080/actuator/restart

Spring Boot 使管理我们的数据库更改变得非常简单。 我们可以在 Spring.

中使用 data.sql 和 schema.sql 文件

如果我们 运行 我们的应用程序,Spring Boot 会为我们创建一个空的 table,但不会用任何东西填充它。

此处有更多详细信息 -> https://www.baeldung.com/spring-boot-data-sql-and-schema-sql