我spring-boot-starter-data-jdbc
在Web应用程序中使用依赖项。Spring Boot可以自动创建模式并从根类路径位置schema.sql
以及data.sql
在应用程序启动时对其进行初始化,但是我很好奇,在应用程序启动之后,有什么方法可以使用非常相同的sql脚本来重新初始化数据库吗?
我需要在演示模式下使用此功能,以便用户在玩完表后可以将数据库重置为初始状态。这就是我希望我的复位控制器看起来像的样子:
@Controller
@RequestMapping("/reset")
@Profile("demo")
public class ResetController {
@GetMapping
public String resetTables(SessionStatus sessionStatus) {
// some code re-initializing the database
// form schema.sql and data.sql goes here
sessionStatus.setComplete();
return "redirect:/home";
}
}
我知道,我总是可以使用JdbcTemplate
及其方法,按照schema.sql
和中定义的sql语句的逻辑手动删除,创建和重新填充每个表data.sql
,但这会有些乏味。也许,Spring有一些现成的方法可以对数据库执行这些脚本,这将有助于用初始演示数据重新加载表?
更新:
这是基于Flyway迁移的可能解决方案之一,正如Charles B在公认的答案中所建议的:
flyway-core
向项目添加依赖项。schema.sql
和data.sql
成V1__schema.sql
和V2__data.sql
下面的迁徙路线命名要求,把他们在/resources/db/migration
目录中。@Controller
@RequestMapping("/reset")
@Profile("demo")
public class ResetController {
private final Flyway flyway;
public ResetController(Flyway flyway) {
this.flyway = flyway;
}
@GetMapping
public String resetTables(SessionStatus sessionStatus) {
flyway.clean();
flyway.migrate();
sessionStatus.setComplete();
return "redirect:/home";
}
}
此外,对于不同的迁移方案,可以spring.flyway.locations
为每个配置文件分别设置引用不同SQL文件的属性,甚至可以通过将spring.flyway.enabled
属性设置为来禁用某些配置文件的Flyway迁移false
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句