Search code examples
springh2embedded-database

How to initiate NamedParameterJdbcTemplate for H2 Query?


I am working on an application using java 8 + Spring 4. I'm removing the Spring DI requirement so the application can run without Spring DI.

I will use Springs JdbcTemplate and NamedParameterJdbcTemplate for database operations. I'm using these templates as we would use any other feature/.jar in the java application.

While I'm removing all the @Autowired and other spring-related annotations (and making them through constructor now)

Spring version is this way:

public class H2Dao {
    private NamedParameterJdbcTemplate t;
    @Autowired
    public H2Dao(@Qualifier("H2JdbcTemplate") NamedParameterJdbcTemplate t) {
        this.t=t;
    }
}

application-context.xml has below code for this:

<jdbc:embedded-database id="h2DataSource" type="H2">
        <jdbc:script location="classpath:db/sql/h2.init.sql" />
    </jdbc:embedded-database>

<bean id="H2JdbcTemplate" class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate">
        <constructor-arg ref="h2DataSource" name="dataSource" />
    </bean>

h2.init.sql file has below code:

CREATE ALIAS ROWNUM_OVER FOR "com.xx.xxxx.h2.H2Function.rowNumOver";
CREATE ALIAS DBO_UFUN_ADDDATETIME FOR "com.xx.xxxx.h2.H2Function.addDateTime";

My Question is, How can I write the same code in non-spring version that does not use application-context.xml for DI. I want to use constructor H2Dao with NamedParameterJdbcTemplate as parameter. how to instantiate NamedParameterJdbcTemplate to pass H2Dao constructor?


Solution

  • I am not sure if I understood correct. But if you don't want to use DI you would probably need to use EmbeddedDatabaseBuilder (see the link: http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/jdbc/datasource/embedded/EmbeddedDatabaseBuilder.html ) and your code probably would look like this:

    EmbeddedDatabase db = new EmbeddedDatabaseBuilder()
                .setType(EmbeddedDatabaseType.H2)
                .addScript("schema.sql")
                .build();
     NamedParameterJdbcTemplate namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(db);