I would like to know how to initialize a database without having to create an XML file.
I already use this kind of initialization that works fine, but in my current case I don't want to create an XML:
<jdbc:initialize-database data-source="dataSource">
<jdbc:script location="classpath:com/foo/sql/db-schema.sql"/>
<jdbc:script location="classpath:com/foo/sql/db-test-data.sql"/>
</jdbc:initialize-database>
I know I can create an embedded database with:
EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();
EmbeddedDatabase db = builder.setType(H2).addScript("my-schema.sql").addScript("my-test-data.sql").build();
In my case, the database and schema are created using Liquibase.
I just want to initialize it with Spring and with my customized dataset, without having to create a new XML file each time just for that.
Is it possible?
The following lines of code inside your
@Configuration
class might work.You have to create your own
schema.sql
and put it in yoursrc/main/resources
-folder.After looking at Spring classes related to EmbeddedDatabaseBuilder I found out that the DatabaseBuilder is using some code looking like this:
This will work fine for me, even if it will be on a @BeforeTest method and not on the Spring configuration.
It certainly is possible.
If you already have an
@Configuration
class that is being loaded by Spring'sApplicationContext
, then you simply have to create a new@Bean
method that will contain the code you have there already (with an additionalreturn
statement of course).EmbeddedDatabase
implements theDataSource
interface, so it can easily be used withJdbcTemplate
's.