问题描述
我在Web应用程序中使用spring-boot-starter-data-jdbc
依赖项。 Spring Boot可以自动创建模式,并在应用程序启动时从根类路径位置schema.sql
和data.sql
对其进行初始化,但是我很好奇有什么方法可以使用完全相同的sql-应用程序启动后脚本?
在演示模式下,我需要此功能,以便用户在玩完表后可以将数据库重置为初始状态。这就是我希望我的复位控制器看起来像的样子:
@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
和schema.sql
中定义的sql语句的逻辑,使用data.sql
及其方法手动删除,创建和重新填充每个表,但这有点乏味。也许,Spring有一些现成的方法可以对数据库执行那些脚本,这将有助于用初始演示数据重新加载表?
已更新:
这是基于Flyway迁移的可能解决方案之一,正如 Charles B 在公认的答案中所建议的:
- 向项目添加
flyway-core
依赖项。 - 按照Flyway的命名要求,将
schema.sql
和data.sql
重命名为V1__schema.sql
和V2__data.sql
,并将它们放在/resources/db/migration
目录下。 - 将
spring.flyway.baseline-on-migrate
属性设置为true
。 - 然后,如上所述的复位控制器可以被重写,就像这样简单:
@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";
}
}
此外,对于不同的迁移方案,可以为每个配置文件分别设置引用不同sql文件的spring.flyway.locations
属性,甚至可以通过将spring.flyway.enabled
属性设置为{{1 }}。
解决方法
Spring Boot可以非常轻松地以一种轻松的方式管理我们的数据库更改。 我们可以在Spring中使用data.sql和schema.sql文件。
如果我们运行应用程序,Spring Boot将为我们创建一个空表,但不会在其中填充任何内容。
更多详细信息-> https://www.baeldung.com/spring-boot-data-sql-and-schema-sql
,如果您迁移到类似Flyway的地方,则可以构建一个控制器,该控制器调用flyway的清洁方法,如引用的here。易于迁移和长期维护。
,您可以尝试使用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