如何使用Spring通过脚本初始化内存中的HSQLDB [英] How to initialize in-memory HSQLDB using script via Spring

查看:141
本文介绍了如何使用Spring通过脚本初始化内存中的HSQLDB的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试对DAO进行单元测试(使用Spring和Hibernate)。我按照这个教程使用HSQLDB。该教程声明可以使用SQL脚本初始化内存中的HSQLDB数据库,但是我无法在Spring中找到有关如何执行此操作的信息。以下是相关的Spring上下文配置:

I am attempting to do unit testing of my DAO (using Spring and Hibernate). I am using HSQLDB per this tutorial. The tutorial states that the in-memory HSQLDB database can be initialized using a SQL script but I cannot find information on how to do so in Spring. Here is the pertinent Spring context config:

 <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
    <property name="driverClassName" value="org.hsqldb.jdbcDriver" />
    <property name="url" value="jdbc:hsqldb:mem:mydb" />
    <property name="username" value="sa" />
    <property name="password" value="" />
    <property name="initialSize" value="5" />
    <property name="maxActive" value="10" />
    <property name="poolPreparedStatements" value="true" />
    <property name="maxOpenPreparedStatements" value="10" />
</bean> 

任何帮助将不胜感激。谢谢。

Any help would be appreciated. Thanks.

推荐答案

如果您正在尝试使用内存数据库和Spring,那么有一个新的 jdbc Spring 3的命名空间,这使得使用嵌入式数据库非常容易。

If you are trying to work with in-memory databases and Spring, there is a new jdbc namespace for Spring 3 that makes working with embedded databases very easy.

最好的部分是它充当 DataSource ,因此可以轻松删除它来替换现有的 dataSource bean。

The best part is that it acts as a DataSource, so it can easily be dropped in to replace your existing dataSource bean.

<jdbc:embedded-database id="dataSource" type="HSQL">
    <jdbc:script location="classpath:schema.sql"/>
    <jdbc:script location="classpath:test-data.sql"/>
</jdbc:embedded-database>

如果您对使用Java Config执行此操作更感兴趣,请查看 EmbeddedDatabaseBuilder (new在Spring 3.0)。

If you are more interested in doing this with Java Config, take a look at the EmbeddedDatabaseBuilder (new in Spring 3.0).

@Configuration
public class DatabaseTestConfig {
    @Bean
    public DataSource dataSource() {
        return new EmbeddedDatabaseBuilder()
            .setType(EmbeddedDatabaseType.HSQL)
            .addScript("classpath:schema.sql")
            .addScript("classpath:test-data.sql")
            .build();
    }
}

这篇关于如何使用Spring通过脚本初始化内存中的HSQLDB的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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