问题
How can I insert data to a table on Spring Boot
application start? My application is generated by JHipster
. What I need to check is that if that particular data already exist in that table or not. If it doesn't I should add it.
回答1:
You can implement an ApplicationRunner and use a repository to do whatever you need to do.
If the ApplicationRunner
is a spring bean it is run on application startup.
For more sophisticated requirements I would try to rely on a tool like flyway that has good integration with spring boot
回答2:
If your application was generated by JHipster, then it should already include and be properly configured for Liquibase.
You have a few options:
- You can use Liquibase's insert change to insert data.
- You can put your data in a CSV file and use the loadData change to load it. Look for the
loadData
tag in00000000000000_initial_schema.xml
for examples. - You can use the sql change to run native SQL directly.
All three options can be combined with 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 page).
回答3:
You can create a function in your service class which checks if the data already exists or not and if not then save that data.
来源:https://stackoverflow.com/questions/37253508/how-to-insert-data-to-table-on-spring-boot-application-start