如何在 spring 引导应用程序启动时向 table 插入数据?
How to insert data to table on spring boot application start?
如何在 Spring Boot
应用程序启动时向 table 插入数据?我的申请是由 JHipster
生成的。我需要检查的是该特定数据是否已经存在于 table 中。如果没有,我应该添加它。
您可以实施 ApplicationRunner
并使用存储库来执行您需要执行的任何操作。
如果 ApplicationRunner
是一个 spring bean,它在应用程序启动时是 运行。
对于更复杂的要求,我会尝试依赖像 flyway that has good integration with spring boot
这样的工具
如果您的应用程序是由 JHipster 生成的,那么它应该已经包含并针对 Liquibase 进行了正确配置。
您有几个选择:
- 您可以使用 Liquibase 的 insert 更改来插入数据。
- 您可以将数据放入 CSV 文件中,然后使用 loadData 更改来加载它。在
00000000000000_initial_schema.xml
中查找 loadData
标记以获取示例。
- 您可以直接使用 sql 更改为 运行 原生 SQL。
所有三个选项都可以与 preconditions to make sure the data doesn't exist before trying to insert it. If you need the changeset to run every time you boot your application, you can use the runAlways="true"
attribute (docs for that are on this 页结合使用。
您可以在 服务中创建一个函数 class 检查数据是否已经存在,如果不存在则保存该数据。
如何在 Spring Boot
应用程序启动时向 table 插入数据?我的申请是由 JHipster
生成的。我需要检查的是该特定数据是否已经存在于 table 中。如果没有,我应该添加它。
您可以实施 ApplicationRunner
并使用存储库来执行您需要执行的任何操作。
如果 ApplicationRunner
是一个 spring bean,它在应用程序启动时是 运行。
对于更复杂的要求,我会尝试依赖像 flyway that has good integration with spring boot
这样的工具如果您的应用程序是由 JHipster 生成的,那么它应该已经包含并针对 Liquibase 进行了正确配置。
您有几个选择:
- 您可以使用 Liquibase 的 insert 更改来插入数据。
- 您可以将数据放入 CSV 文件中,然后使用 loadData 更改来加载它。在
00000000000000_initial_schema.xml
中查找loadData
标记以获取示例。 - 您可以直接使用 sql 更改为 运行 原生 SQL。
所有三个选项都可以与 preconditions to make sure the data doesn't exist before trying to insert it. If you need the changeset to run every time you boot your application, you can use the runAlways="true"
attribute (docs for that are on this 页结合使用。
您可以在 服务中创建一个函数 class 检查数据是否已经存在,如果不存在则保存该数据。