如何使用Hibernate将初始数据导入数据库? [英] How to import initial data to database with Hibernate?

查看:116
本文介绍了如何使用Hibernate将初始数据导入数据库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在部署应用程序时,我经常使用Hibernate的能力来创建数据库模式以简化部署。这很容易通过配置hibernate.hbm2ddl.auto属性来实现。然而,有时我还需要将一些初始数据插入数据库,例如root用户。有没有一种方法,我可以通过hibernate与某种载入文本文件来实现这一点?



我知道我可以很容易地编写这样做的代码,但只是想知道是否已经有一些实用工具可以帮助我通过配置实现相同的功能?

解决方案

我通过搜索Hibernate fixtures:
$ b


当实体管理器工厂创建
时,Hibernate将创建数据库
(实际上当Hibernate的
SessionFactory由
实体管理器工厂创建)。如果在
的根中存在名为import.sql的文件
,则类路径('/import.sql')
Hibernate将执行从文件读取的SQL
语句
创建数据库模式。
在Hibernate创建模式
清空它(删除所有表,
约束或任何其他数据库
对象)之前,请记住
是非常重要的。在
中创建模式的过程)。

来源: http://www.velocityreviews.com/forums/t667849-hibernate-quotfixturesquot-or-database-population .html



试一试,让我们知道它是否有效!


When deploying applications, I often use Hibernate’s capacity to create database schema in order to simplify the deployment. This is easily achievable by configuring hibernate.hbm2ddl.auto property.

However, on occasion I also need to insert some initial data to database, for example root user. Is there a way I could achieve this via hibernate with some kind of load textual file?

I know I could easily program the code that will do so, but just wondering if there is already some utility that can help me achieve the same via configuration?

解决方案

I found this by doing a search on "Hibernate fixtures" :

Hibernate will create the database when the entity manager factory is created (actually when Hibernate's SessionFactory is created by the entity manager factory). If a file named import.sql exists in the root of the class path ('/import.sql') Hibernate will execute the SQL statements read from the file after the creation of the database schema. It is important to remember that before Hibernate creates the schema it empties it (delete all tables, constraints, or any other database object that is going to be created in the process of building the schema).

Source: http://www.velocityreviews.com/forums/t667849-hibernate-quotfixturesquot-or-database-population.html

Give it a try and let us know if it works!

这篇关于如何使用Hibernate将初始数据导入数据库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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