How to insert data to table on spring boot applica

2019-09-13 13:16发布

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.

3条回答
做自己的国王
2楼-- · 2019-09-13 13:40

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

查看更多
爷的心禁止访问
3楼-- · 2019-09-13 13:41

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 in 00000000000000_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).

查看更多
看我几分像从前
4楼-- · 2019-09-13 13:43

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.

查看更多
登录 后发表回答