16

I use Oracle in production environment and I would like to use H2 for testing. I can type;

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

so my tables and scripts are created automatically. But I cannot set URL value of this db. (For H2-Oracle compatibility I should add ;MODE=Oracle to url part)

is there a way to achieve this goal?

Or just an opposite solution;

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="org.h2.Driver"/>
    <property name="url" value="jdbc:h2:file:h2\db"/>
    <property name="username" value="sa"/>
    <property name="password" value=""/>        
</bean>

in this time, I can edit URL part, but how can I load default test scripts (create and data sqls) to this datasource?

asyard
  • 1,743
  • 5
  • 21
  • 43

2 Answers2

23

This technique solved the problem;

<bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${jdbc.driverClassName}" />
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
</bean>

and then adding this tag and definition;

<jdbc:initialize-database data-source="dataSource" ignore-failures="DROPS">
    <jdbc:script location="classpath:testdb/schema.sql" />
    <jdbc:script location="classpath:testdb/data.sql" />
</jdbc:initialize-database>
asyard
  • 1,743
  • 5
  • 21
  • 43
  • What is the content of those files? schema.sql and data.sql, do they contain something that you have to setup ? – wlk Feb 29 '12 at 15:05
  • hi Wojtek, yes, I need some initial test data. Several contents are IP addresses of many servers, some user roles, city names etc. – asyard Mar 03 '12 at 14:36
13

Maybe this will help: H2 supports an INIT script (a SQL script which is executed when opening the connection). The database URL would look like this in the XML file:

<property name="url" value="jdbc:h2:file:h2\db;INIT=
RUNSCRIPT FROM 'classpath:schema.sql'\;
RUNSCRIPT FROM 'classpath:test-data.sql'"/>

(the ; needs to be escaped with a backslash).

Thomas Mueller
  • 48,905
  • 14
  • 116
  • 132
  • thank you for your response, my best choice was using Spring-provided approach (jdbc:initialize-database.. etc) without extending url with values. This technique is also helpful. Thank you. – asyard Nov 18 '11 at 11:01