Ebates Coupons and Cash Back

My {Java} Academy

Learn java and related technologies

Let’s look at a simple example to see how we can integrate MyBatis in Spring Application.

Maven POM for the demo –

<project xmlns="http://maven.apache.org/POM/4.0.0" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.mms.blogs</groupId>
  <artifactId>MyBatisSpringDemo</artifactId>
  <version>1.0.0-SNAPSHOT</version>
  <packaging>war</packaging>
  <name>MyBatisSpringDemo</name>
      <dependencies>
      <dependency>
          <groupId>org.mybatis</groupId>
          <artifact    Id>mybatis-spring</artifactId>
          <version>1.1.1</version>
      </dependency>
      <dependency>
          <groupId>junit</groupId>
          <artifactId>junit</artifactId>
          <version>4.10</version>
      </dependency>
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-test</artifactId>
          <version>3.2.0.RELEASE</version>
      </dependency>
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-tx</artifactId>
          <version>3.2.0.RELEASE</version>
      </dependency>
      <dependency>
          <groupId>org.hsqldb</groupId>
          <artifactId>hsqldb</artifactId>
          <version>2.2.9</version>
      </dependency>
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-core</artifactId>
          <version>3.2.0.RELEASE</version>
      </dependency>
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-context</artifactId>
          <version>3.2.0.RELEASE</version>
      </dependency>
  </dependencies>
</project>

MyBatis Mapper –

MyBatis is driven by a Mapper Interface that defines the methods to interact against database. SQL mapping code is defined in a xml file defined by the same name of the Mapper Interface.

Mapping to work correctly, below three things should match for each mapper –

  1. Interface file name and package
  2. Xml file name and its location should be same as Interface.
  3. namespace in xml file.

EmployeeMapper.java –

package com.mms.blogs.demo.mybatisspring.mapper;

import com.mms.blogs.demo.mybatisspring.vo.Employee;

public interface EmployeeMapper {

    public Employee getEmployeeName(long empId);

    public void insertEmployee(Employee employee);

}

EmployeeMapper.xml –

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" 
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.mms.blogs.demo.mybatisspring.mapper.EmployeeMapper">

    <select id="getEmployeeName" parameterType="long"
        resultType="com.mms.blogs.demo.mybatisspring.vo.Employee">
        SELECT empid, first_name firstName,last_name lastName from employee where
        empid=#{empid}
    </select>

    <insert id="insertEmployee" parameterType="com.mms.blogs.demo.mybatisspring.vo.Employee">
        insert into employee (empid,first_name,last_name) values
        (#{empid},#{firstName},#{lastName})
    </insert>

</mapper>

Employee.java – VO Object

package com.mms.blogs.demo.mybatisspring.vo;

import org.springframework.stereotype.Component;

@Component
public class Employee {
    private long empid;
    private String firstName;
    private String lastName;
    public long getEmpid() {
        return empid;
    }
    public void setEmpid(long empid) {
        this.empid = empid;
    }
    public String getFirstName() {
        return firstName;
    }
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
    public String getLastName() {
        return lastName;
    }
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

}

Spring Application Context –

Following is the application context for this demo –

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:context="http://www.springframework.org/schema/context"
        xmlns:jdbc="http://www.springframework.org/schema/jdbc"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
                     http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
                     http://www.springframework.org/schema/context
                     http://www.springframework.org/schema/context/spring-context-3.2.xsd
                     http://www.springframework.org/schema/jdbc
                     http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd">

    <context:annotation-config/>

    <context:component-scan base-package="com.mms.blogs.demo.mybatisspring"></context:component-scan>

    <jdbc:embedded-database id="dataSource">
        <jdbc:script location="classpath:schema.sql"/>
    </jdbc:embedded-database>

    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <bean class="org.mybatis.spring.SqlSessionFactoryBean" id="sqlSessionFactory">
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
        <property name="basePackage" value="com.mms.blogs.demo.mybatisspring.mapper"/>
     </bean>

</beans>
  1. Enable annotation config to Autowire our Spring configuration and also Autowire MyBatis mappers where ever needed.
  2. component-scan provides base package to look for components.
  3. TransactionManager to handle transactions
  4. Spring’s embedded database instance. This loads the sample teable Employee into embedded database using sql defined in compile.sql script.
  5. Bean for org.mybatis.spring.SqlSessionFactoryBean to configure the datasource.
  6. MapperScannerConfigurer – This class initializes a bean for each of the mapper interface defined in basePackage and injects sqlSessionFactory instance in it. This enables Autowiring of the mapper interfaces in code.

Schema.sql –

create table employee(
    empid BIGINT,
    first_name varchar(50),
    last_name varchar(50)
    );

So with all above configuration MyBatis is now integrated with Spring. Let’s write a simple JUnit to test our integration –

package com.mms.blogs.demo.mybatisspring.mapper;

import junit.framework.Assert;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.mms.blogs.demo.mybatisspring.vo.Employee;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(value={"classpath:applicationContext.xml"})
public class EmployeeTest extends AbstractTransactionalJUnit4SpringContextTests {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Before
    public void insertEmployee(){
        Employee emp = new Employee();
        emp.setEmpid(1);
        emp.setFirstName("Manik");
        emp.setLastName("Magar");
        employeeMapper.insertEmployee(emp);
    }

    @Test
    public void testEmployee(){
        System.out.println("testEmployee");
        Employee emp = employeeMapper.getEmployeeName(1);
        Assert.assertNotNull(emp);
    }

}

Cheers!

Where is the source? … It’s here

 

References

http://www.mybatis.org/spring/


Creative Commons License All posts published in this blog are licensed under a Creative Commons by-nc-sa 4.0 International License.

2009 - 2017 | Mixed with Foundation v5.5.1 | Baked with JBake v2.5.1 | Sitemap | Terms and Usage Policy