休眠-不使用import.sql的种子数据库 [英] Hibernate - Seed database without using import.sql

查看:93
本文介绍了休眠-不使用import.sql的种子数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

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.

有办法吗? 如果不是,应该进行一些配置以触发脚本,该脚本使用ORM实体管理器在架构创建后将实体保留在数据库中. 主要思想不是在架构修订中维护较大的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.

谢谢!

推荐答案

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

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

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

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

这篇关于休眠-不使用import.sql的种子数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆