paul
paul

Reputation: 13471

inject sql in mybatis

I´m using Spring MyBatis to insert a row in a table. The problem is that in my h2 database I dont have create the table yet, and I would like to do it on the fly

this is my current spring context configuration

<sql id="CREATE_TABLE">
    CREATE TABLE ENTITY(ENTITY_ID INT PRIMARY KEY, TITLE VARCHAR(255),DESCRIPTION VARCHAR(255) )
</sql>

<insert id="CREATE" parameterType="com.dao.entity.dto.EntityDaoDTO">
    INSERT INTO
    ENTITY
    (ENTITY_ID, TITLE, DESCRIPTION)
    VALUES
    (#{entityId},#{title},#{description})

</insert>

How can I do to specify that sql tag must be executed before the insert happens??

I´m running h2 as a java process through maven

                     <execution>
                        <id>start-h2</id>
                        <phase>pre-integration-test</phase>
                        <goals>
                            <goal>start</goal>
                        </goals>

                        <configuration>
                            <name>start-h2-f2e</name>
                            <waitAfterLaunch>2</waitAfterLaunch>
                            <workingDir>../../../h2/sakila-h2-master/</workingDir>
                            <arguments>
                                <argument>java</argument>
                                <argument>-cp</argument>
                                <argument>h2-1.3.161.jar</argument>
                                <argument>org.h2.tools.Server</argument>
                                <argument>-ifExists</argument>
                                <argument>-tcp</argument>
                                <argument>-web</argument>
                                <argument>-tcpAllowOthers</argument>
                            </arguments>
                        </configuration>
                    </execution>

Regards

Upvotes: 0

Views: 454

Answers (1)

StanislavL
StanislavL

Reputation: 57381

See about DB init here

In fact you need to add to your spring something like this

<jdbc:initialize-database data-source="dataSource">
    <jdbc:script location="classpath:database/scripts/init-db.ddl" />
</jdbc:initialize-database>

where dataSource is the h2 datasource to be initialized. All the DB structure creation and some initial data insertion could be done in separate DDL/SQL scripts.

You just execute them on start for the in memory H2 DB.

Upvotes: 1

Related Questions