How to insert data to table on spring boot application start?

拟墨画扇 提交于 2020-01-17 05:29:12

问题


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 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).




回答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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!