org.beast.project.template.config.MyBatisConfig.java Source code

Java tutorial

Introduction

Here is the source code for org.beast.project.template.config.MyBatisConfig.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package org.beast.project.template.config;

import javax.sql.DataSource;
import org.apache.commons.dbcp2.BasicDataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;

/**
 *
 * @author U329022
 */
@Configuration
@MapperScan("org.mybatis.spring.sample.mapper")
public class MyBatisConfig extends DBConfig {
    //http://blog.lanyonm.org/articles/2014/04/21/spring-4-mybatis-java-config.html
    //http://java.dzone.com/articles/getting-started-ibatis-mybatis-0
    @Override
    public DataSource dataSource() {

        EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();
        //DataSource ds = builder.setType(EmbeddedDatabaseType.HSQL).addScript("schema.sql").build();
        BasicDataSource basicDataSource = new BasicDataSource();
        basicDataSource.setDriverClassName(org.hsqldb.jdbcDriver.class.getName());
        basicDataSource.setUsername("sa");
        basicDataSource.setPassword("");
        basicDataSource.setUrl("jdbc:hsqldb:mem:mydb");
        JdbcTemplate jdbcTemplate = new JdbcTemplate(basicDataSource);
        System.out.println("Creating tables");
        jdbcTemplate.execute("drop table person if exists");
        jdbcTemplate.execute("create table person(id serial, firstName varchar(50), lastName varchar(50))");
        jdbcTemplate.update("INSERT INTO users(firstName, lastName) values (?,?)", "Mike", "Lanyon");
        return basicDataSource;
    }

    @Bean
    public DataSourceTransactionManager transactionManager() {
        return new DataSourceTransactionManager(dataSource());
    }

    @Bean
    public SqlSessionFactoryBean sqlSessionFactory() throws Exception {
        SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSource());
        sessionFactory.setTypeAliasesPackage("org.lanyonm.playground.domain");
        return sessionFactory;
    }
}