myBatis Java

This article introduces mybatis java (iBatis 3 for java) and summarizes its configurationand usage. The article also give suggestions and  conclusions on mybatis usage.

Introduction

The iBATIS Data Mapper (born in 2002) is a framework that  introduces SQL Mapping approach to persistence layer development. The iBATIS name and code was donated to the Apache Software Foundation, that hosts project development for many years.

In 2010 the core development team of iBATIS has decided to continue development under new home: Google Code; and with a new name: mybatis .

Actually both the Java and .NET project teams have forked the software to Google Code ( mybatis Java and mybatis .NET ). The new version of the project added support to metadata annotations.

 

Configuration

building SqlSessionFactory from XML is quite simple:

String resource = "org/mybatis/example/Configuration.xml";
Reader reader = Resources.getResourceAsReader(resource);
sqlMapper = new SqlSessionFactoryBuilder().build(reader);

The configuration file contains settings for the core of the MyBatis system

<?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="${driver}" />
				<property name="url" value="${url}" />
				<property name="username" value="${username}" />
				<property name="password" value="${password}" />
			</dataSource>
		</environment>
	</environments>
	<mappers>
		<mapper resource="org/mybatis/example/BlogMapper.xml" />
	</mappers>
</configuration>

note:

  • ${parameterName} : indicate a parameter, usually taken via propery file ..
  • mapper: imply the existence of the BlogMapper.xml file

Generator

There is a generator for MyBatis artifacts, available as standalone JAR, Ant task, Maven plugin or Eclipse plugin. See description on code.google.com/p/mybatis/wiki/Generator, where you can get the JAR, and the Update Site for the Eclipse plugin.