Simple Example of Mybatis JAVA Maven Implementation

Mybatis is a powerful and flexible persistent framework. One of the advantage of it, compared to Hibernate, is that you don’t have to pick up new script language. You still create the sql, as you normally create in JDBC implementation, but you will save a lot of low-level JDBC coding.

I am going to walk you through step by step a simple example, probably the simplest example you can find. You will need eclipse as IDE, mysql as testing database.

1. Create a maven project with eclipse, and update pom.xml file.

<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>springriver</groupId>
	<artifactId>springriver.mybatis.simple</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>


	<name>springriver.mybatis.simple</name>
	<url>http://maven.apache.org</url>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>

	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.11</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis</artifactId>
			<version>3.1.1</version>
		</dependency>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.21</version>
			<scope>runtime</scope>
		</dependency>
	</dependencies>
</project>

Note: there are 3 dependencies here. JUnit, MYBATIS and MySQL JDBC driver.

2. run the following sql to create testing database, testing table and inserting a testing record.

delimiter $$
CREATE DATABASE `test` /*!40100 DEFAULT CHARACTER SET latin1 */$$
delimiter $$

CREATE TABLE `category` (
  `category_id` int(11) NOT NULL AUTO_INCREMENT,
  `category_name` varchar(45) NOT NULL,
  PRIMARY KEY (`category_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1$$

INSERT INTO `category` VALUES (1,'Apparel');

3. create a database configuration file, database-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>

	<environments default="development">
		<environment id="development">
			<transactionManager type="JDBC" />
			<dataSource type="POOLED">
				<property name="driver" value="com.mysql.jdbc.Driver" />
				<property name="url" value="jdbc:mysql://localhost:3306/test" />
				<property name="username" value="root" />
				<property name="password" value="" />
			</dataSource>
		</environment>
	</environments>
	<mappers>
		<mapper resource="com/springriver/example/mybatis/mapper/CategoryMapper.xml" />
	</mappers>
</configuration>

Note: the configuration file contains database access information, and a mapper file which we will explain next.

4. Create a database connection factory java class

package com.springriver.example.mybatis.util;

import java.io.IOException;
import java.io.Reader;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class ConnectionFactory {
	private static SqlSessionFactory factory;

	static {
		Reader reader = null;
		try {
			reader = Resources.getResourceAsReader("database-config.xml");
		} catch (IOException e) {
			throw new RuntimeException(e.getMessage());
		}
		factory = new SqlSessionFactoryBuilder().build(reader);
	}

	public static SqlSessionFactory getSqlSessionFactory() {
		return factory;
	}
}

Note: this util class read in the database configuration file, and maintains a global SqlSessionFactory instance. SqlSessionFactory is used to open new database session.

5. Create a mybatis mapper xml file to define the database functions, CategoryMapper.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.springriver.example.mybatis.mapper.CategoryMapper">

<select id="selectCategoryById" parameterType="int" resultType="com.springriver.example.mybatis.bean.Category">
	select category_name as categoryName from Category where category_id = #{id}
</select>

</mapper>

Note: this mapper file is registered in database-config.xml file

6. create a java interface file, CategoryMapper.java, to expose the functions defined in CategoryMapper.xml

package com.springriver.example.mybatis.mapper;

import com.springriver.example.mybatis.bean.Category;

public interface CategoryMapper {
	public Category selectCategoryById(int id);
}

7. create a manager file, CategoryManager.java, to create business functions out of the database functions.

package com.springriver.example.mybatis.util;

import org.apache.ibatis.session.SqlSession;

import com.springriver.example.mybatis.bean.Category;
import com.springriver.example.mybatis.mapper.CategoryMapper;

public class CatgegoryManager {
	public static Category selectCategoryById(int id) {
		SqlSession sqlSession = ConnectionFactory.getSqlSessionFactory()
				.openSession();
		try {
			CategoryMapper categoryMapper = sqlSession
					.getMapper(CategoryMapper.class);
			return categoryMapper.selectCategoryById(id);
		} finally {
			sqlSession.close();
		}
	}
}

8. create a junit testing class, CategoryManagerTest.java, to test the manager function.

package com.springriver.example.mybatis;

import org.junit.Test;

import com.springriver.example.mybatis.bean.Category;
import com.springriver.example.mybatis.util.CatgegoryManager;

public class CategoryManagerTest {

	
	@Test
	public void testUpdateUser() {
		Category category = CatgegoryManager.selectCategoryById(1);
		assert(category != null);
		assert(category.getCategoryName().equals("Apparel"));
		
	}

}

Here is the code structure.
mybatis-1

download the eclipse project
springriver.mybatis.simple

Tagged with: , , , , , ,
Posted in MyBatis
2 comments on “Simple Example of Mybatis JAVA Maven Implementation
  1. vit bernatik says:

    Dude you are missing step where you shall create “Category.java”. I mean thanks – you have helped me a lot. But I always ask myself – what kind of guy write such a great tutorial and miss one step? Without any step whole tutorial would be kinda useless… Anyway the mentioned file is provided in download of eclipse project that you have attached at the end of tutorial – so it has seved a day for me… Thanks again…

  2. india says:

    This example is awesome

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>