Spring + myBatis (XML)

Using myBatis with Spring framework.  (XML configuration and mapping).

Objective

  • How to use myBatis with Spring framework?
  • How to write mybatis config and mapper in xml?

Environment

  • Eclipse (Indigo)
  • MySql

Libraries

( 1 ) Database

( 2 ) Java Project

  • Create new Java Project
  • Add new folder “lib”
  • Copy all jars to “lib” folder
  • Add jar file to java build path

( 3 ) Java Classes

  1. Person.java
  2. PersonDAO.java
  3. Main.java

Person.java

package com.hmkcode.vo;

public class Person  {

	private int id;
	private String name;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}

	public String toString(){
		return "id: "+id+" Name: "+name;
	}

}

PersonDAO.java

package com.hmkcode.dao;

import java.util.List;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import com.hmkcode.vo.Person;

public class PersonDAO {

    private SqlSessionFactory sqlSessionFactory = null;

    public PersonDAO(SqlSessionFactory sqlSessionFactory){
    	this.sqlSessionFactory = sqlSessionFactory;
    }

    /**
     * Returns the list of all Person instances from the database.
     * @return the list of all Person instances from the database.
     */
    @SuppressWarnings("unchecked")
    public  List<Person> selectAll(){
    	List<Person> list = null;
        SqlSession session = sqlSessionFactory.openSession();

        try {
            list = session.selectList("Person.selectAll");
        } finally {
            session.close();
        }
        System.out.println("selectAll() --> "+list);
        return list;

    }
    /**
     * Select instance of Person from the database.
     * @param person the instance to be persisted.
     */
   public Person selectById(int id){
       	Person person = null;
        SqlSession session = sqlSessionFactory.openSession();
        try {
        	person = session.selectOne("Person.selectById", id);

        } finally {
            session.close();
        }
        System.out.println("selectById("+id+") --> "+person);
        return person;
    } 
    /**
     * Insert an instance of Person into the database.
     * @param person the instance to be persisted.
     */
   public int insert(Person person){
	   int id = -1;
        SqlSession session = sqlSessionFactory.openSession();

        try {
            id = session.insert("Person.insert", person);
        } finally {
            session.commit();
            session.close();
        }
        System.out.println("insert("+person+") --> "+person.getId());
        return id;
    }
    /**
   * Update an instance of Person into the database.
   * @param person the instance to be persisted.
   */
  	public void update(Person person){
	   int id = -1;
      SqlSession session = sqlSessionFactory.openSession();

      try {
          id = session.update("Person.update", person);

      } finally {
          session.commit();
          session.close();
      }
      System.out.println("update("+person+") --> updated");
  }

    /**
     * Delete an instance of Person from the database.
     * @param id value of the instance to be deleted.
     */
    public void delete(int id){

        SqlSession session = sqlSessionFactory.openSession();

        try {
            session.delete("Person.delete", id);
        } finally {
            session.commit();
            session.close();
        }
        System.out.println("delete("+id+")");

    }
}

Main.java

package com.hmkcode;

import java.util.List;

import org.apache.ibatis.session.defaults.DefaultSqlSessionFactory;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.hmkcode.dao.PersonDAO;
import com.hmkcode.vo.Person;

public class Main {

	public static void main(String args[]){

		// Laod spring-config.xml file
		ApplicationContext ctx = new ClassPathXmlApplicationContext("com/hmkcode/config/spring-config.xml");

		//get sqlSessionFactory
                // sessionFactory should be cast as DefaultSqlSessionFactory!!!! 
		DefaultSqlSessionFactory sessionFactory  = (DefaultSqlSessionFactory) ctx.getBean("sqlSessionFactory");

		PersonDAO personDAO = new PersonDAO(sessionFactory);

		//create person bean to insert
		Person person = new Person();
		person.setName("Person 1");

		//( 1 ) insert person 
		personDAO.insert(person);

		//**set name of person
		person.setName("Person 2");	
		//** insert another person
		int id = personDAO.insert(person);

		//( 2 ) select persons by id
		personDAO.selectById(id);

		//( 3 ) select all
		List<Person> persons = personDAO.selectAll();

		//**set name of all persons
		for(int i = 0; i < persons.size(); i++){
			persons.get(i).setName("Person Name "+i);
			//( 4 ) update person
			personDAO.update(persons.get(i));
		}

		//**check update
		persons = personDAO.selectAll();

	}
}

( 4 ) XML Configuration

  1. myBatis (config.xml)
  2. myBatis mapper (Person.xml)
  3. Spring (spring-config.xml)

myBatis (config.xml)

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

<configuration>
    <typeAliases>
        <typeAlias alias="Person" type="com.hmkcode.vo.Person"/>        
    </typeAliases>

    <mappers>
       <mapper resource="com/hmkcode/mybatis/mapper/Person.xml"/>
    </mappers>
</configuration>

myBatis mapper (Person.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="Person">

    <resultMap id="result" type="Person">
        <result property="id" column="id"/>
        <result property="name" column="name"/>   
    </resultMap>

    <select id="selectAll" resultMap="result">
        SELECT * FROM persons;
    </select>

 	<select id="selectById" parameterType="int" resultMap="result">
        SELECT * FROM persons WHERE id = #{id}
    </select>

 	<insert id="insert" parameterType="Person" useGeneratedKeys="true" keyProperty="id">
        INSERT INTO persons (name) VALUES (#{name});
    </insert>

    <update id="update" parameterType="Person">
        UPDATE persons
        SET name = #{name}
        WHERE id = #{id} 
  	</update>

	<delete id="delete" parameterType="int">
        DELETE from persons WHERE id = #{id}
    </delete>
</mapper>

Spring (spring-config.xml)

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

http://www.springframework.org/schema/beans


http://www.springframework.org/schema/beans/spring-beans.xsd


http://www.springframework.org/schema/context


http://www.springframework.org/schema/context/spring-context.xsd">

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
		<property name="url" value="jdbc:mysql://localhost:3306/hmkcode" />
		<property name="username" value="root" />
		<property name="password" value="" />
    </bean>

    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
  		<property name="dataSource" ref="dataSource" />
  		<property name="configLocation" value="classpath:com/hmkcode/mybatis/config.xml" />
	</bean>
</beans>

( 5 ) Test Application

Download Code: Spring-myBatis.zip