Tuesday, August 14, 2012

H2, Spring Framework configuration

In order to simplify communication with database sometimes we use light-weight databases. That databases could be started in embedded mode(you do not have to install database at all). I will show how   to configure H2 database for using with Spring Framework and IBatis(MyBatis).

First of all, define sqlSessionFactory bean.


        <bean id= "sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean" >
              <property name= "dataSource" ref ="dataSource" />
              <property name= "configLocation" value="WEB-INF/mybatis/sqlmap-config.xml" />
        </bean>
 
So, define dataSource

<jdbc:embedded-database id ="dataSource" type= "H2">
              <jdbc:script location= "/WEB-INF/table_data.sql" />
    </jdbc:embedded-database>
 
And declare transaction manager
        
        <bean id= "transactionManager"
               class= "org.springframework.jdbc.datasource.DataSourceTransactionManager"
              p:dataSource-ref="dataSource" />

    

And of course, we need SQL statements in file table_data.sql 


DROP TABLE IF EXISTS User;

CREATE TABLE User(
ID INTEGER AUTO_INCREMENT PRIMARY KEY ,
NAME VARCHAR(50),
ADDRESS VARCHAR (50),
AGE INTGERE
);

INSERT INTO User (ID, NAME, ADDRESS, AGE) VALUES (1, 'Jevgeni', 'Rae XX' , '34'); 

Use with pleasure!

No comments:

Post a Comment