如何将Fixtures添加到Spring Hibernate项目中

时间:2011-03-13 12:37:35

标签: hibernate spring

我正在尝试将Fixtures /示例数据添加到使用Hibernate作为JPA的Spring项目中。

我已经创建了一个fixtures.sql文件(在WEB-INF / classes / fixtures.sql中),其中包含一系列SQL查询,我希望在开发时使用示例数据填充数据库。 在开发模式中,我使用内存数据库Hypersonic InMemory,当我部署到Postgres或MySQL时,将加载相同的数据。

如何在应用程序重启/启动时加载此数据?每次应用程序重新启动时,Hypersonic都会擦除内存数据库,这意味着每次我想在前端测试某些内容时,我都需要完成所有步骤来创建示例数据。

database.properties:

database.password=
database.url=jdbc\:hsqldb\:mem\:myproject
database.username=sa
database.driverClassName=org.hsqldb.jdbcDriver

的persistence.xml

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.0" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="persistenceUnit" transaction-type="RESOURCE_LOCAL">
        <provider>org.hibernate.ejb.HibernatePersistence</provider>
        <properties>
            <property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>
            <!-- value="create" to build a new database on each run; value="update" to modify an existing database; value="create-drop" means the same as "create" but also drops tables when Hibernate closes; value="validate" makes no changes to the database -->
            <property name="hibernate.hbm2ddl.auto" value="create"/>
            <property name="hibernate.ejb.naming_strategy" value="org.hibernate.cfg.ImprovedNamingStrategy"/>
            <property name="hibernate.connection.charSet" value="UTF-8"/> 
        </properties>
    </persistence-unit>
</persistence>

3 个答案:

答案 0 :(得分:4)

您可以使用<jdbc:initialize-database>,请参阅12.9 Initializing a DataSource

答案 1 :(得分:3)

三种可能的方式:

  1. 使用import.sql(请参阅“创建”部分中的http://blog.eyallupu.com/2007/05/hibernates-hbm2ddl-tool.html

  2. 使用DBUnit(请参阅http://onjava.com/pub/a/onjava/2004/01/21/dbunit.html

  3. 使用创建域对象并保存它们,编写代码以在@SetUp(或应用启动)中填充数据库。

答案 2 :(得分:2)

如果您更喜欢更有条理的方法,并且项目规模足够大,则应该查看https://github.com/42BV/jarbhttp://www.liquibase.org/。 您还应该考虑是否需要瞬态新装置或固定装置(请参阅xUnit测试模式)。对于spring,这种设置可以与环境抽象和bean配置文件一起使用(参见3.1中的@Profile)