我来自php/laravel。每当我想播种数据库时,我只需要运行php artisan db:seed即可。这将运行一些php脚本,这些脚本会将数据插入数据库中。

我想使用spring/hibernate实现相同的功能。我知道我可以添加import.sql文件以在架构创建后为数据库添加种子。但是,我想使用Java和可用的ORM导入这些灯具,因此不需要维护sql。

有办法吗?
如果不是,应该进行一些配置以触发脚本,该脚本使用ORM实体管理器在架构创建后将实体保留在数据库中。
主要思想是不要在架构修订中维护较大的sql seeder文件。

谢谢!

最佳答案

如果您使用的是Spring数据,则可以使用Repository populators

否则,您可能会注册一个在加载spring上下文之后触发的事件:

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

有关更多详细信息,请检查:Better application events in Spring Framework 4.2

09-26 23:23
查看更多