Hibernate - Seed database without using import.sql

回眸只為那壹抹淺笑 提交于 2019-12-10 14:22:13

问题


I come from php/laravel. Whenever I want to seed the database i only need to run php artisan db:seed. This will run some php scripts that will insert data into the database.

I want to achieve this same feature using spring/hibernate. I know I can add an import.sql file to seed the database after schema creation. However, I want to import these fixtures using java and the ORM available so I do not need to maintain an sql.

Is there a way? If not, there should be some configuration to trigger a script that use the ORM entity manager to persist entities in the database after schema creation. The main idea is not to maintain a big sql seeder file over schema revisions.

Thanks!


回答1:


If you're using Spring data you can use Repository populators.

Otherwise you may register an event that fires after the spring context is loaded :

@Component
public class YourListener {

    // Declare your autowired beans here 

    @EventListener
    public void handleContextRefresh(ContextRefreshedEvent event) {
        // Your seeder 
        // + You can use all the registred beans (repositories, services...)
    }
}

For more detail check: Better application events in Spring Framework 4.2



来源:https://stackoverflow.com/questions/38744764/hibernate-seed-database-without-using-import-sql

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