[英]Hibernate - Seed database without using import.sql
I come from php/laravel. 我来自php / laravel。 Whenever I want to seed the database i only need to run
php artisan db:seed
. 每当我想要为数据库播种时,我只需要运行
php artisan db:seed
。 This will run some php scripts that will insert data into the database. 这将运行一些将数据插入数据库的PHP脚本。
I want to achieve this same feature using spring/hibernate. 我想使用spring / hibernate实现同样的功能。 I know I can add an
import.sql
file to seed the database after schema creation. 我知道我可以在架构创建后添加一个
import.sql
文件来为数据库设定种子。 However, I want to import these fixtures using java and the ORM available so I do not need to maintain an sql. 但是,我想使用java和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.
如果没有,应该有一些配置来触发使用ORM实体管理器的脚本在模式创建后持久化数据库中的实体。 The main idea is not to maintain a big sql seeder file over schema revisions.
主要的想法是不要在模式修订版上维护一个大的sql播种器文件。
Thanks! 谢谢!
If you're using Spring data you can use Repository populators . 如果您使用的是Spring数据,则可以使用Repository populator 。
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 有关更多详细信息,请参阅: Spring Framework 4.2中更好的应用程序事件
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.