Configuring MyBatis 3

MyBatis is a very popular and also most efficient SQL mapping framework. MyBatis is available for both in java as well as .net language. MyBatis is not really an alternative of Hibernate but we can use this framework to reduce our database related code with efficient and high performance provided by MyBatis.

This tutorial will show you the steps to be followed to configure MyBatis 3 with your database. MyBatis 3 supports both xml based and annotation based configuration but the real power of MyBatis can be seen while working with xml configuration. This tutorial will only show you the configuration using xml.


Tools Used:

  1. MyBatis 3.0.4
  2. MySql Java Connector 5.1

Using MyBatis do not need a lot of jars, only MyBatis jar with driver is needed:

  1. commons-logging-1.1.1.jar
  2. mybatis-3.0.4.jar
  3. mysql-connector-java-5.1.13-bin.jar

In this tutorial, we will configure MyBatis to store out pojo class object to database table. Following is the database table which we will use in this example:

CREATE TABLE Product(id int primary key, brand varchar(20),

 model varchar(20), name varchar(30));

So first of all, create this table in database that you want to use for storage.
Following is the Product class that will be mapped to the table product:

package com.raistudies.domain;

import java.io.Serializable;

public class Product implements Serializable{

    private static final long serialVersionUID = -1900054678340682193L;

    private long id;
    private String brand;
    private String model;
    private String name;
    // Getter and setter are removed to make the short

}

We will see, the configuration that are to be carried out for mapping the above to database table product.
In MyBatis 3, we have two types for configuration files:

Environment Specification Configuration File: There will be only one file that will define the environmental settings that are to be used by MyBatis mapping framework. This file defines the settings related to database connection, driver, transaction management, connection pooling, other mapping files and a lot more that we will see in upcoming tutorials.

Mapping Files: There can be more than one mapping file in one application for MyBatis framework. A mapping file carries information about set of related service that is defined in an Java interface. It defines parametrized SQL Statement to be used for a particular service, inputs to to the SQL parameters and also defines return mapping for the resultant data if returned back by SQL statement.
That mean, we will have two xml file in our example: one for environment setting and other will be a mapping file for the services related to class Product.
Following is the environment specification configuration xml file :

<?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>
    <settings>
        <setting name="lazyLoadingEnabled" value="false" />
    </settings>

    <typeAliases>
        <typeAlias type="com.raistudies.domain.Product" alias="product"/>
    </typeAliases>

    <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/test"/>
                <property name="username" value="root"/>
                <property name="password" value="pass"/>
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <mapper resource="com/raistudies/services/ProductServices.xml"/>
    </mappers>

</configuration>

As you can see, the <configuration/> holds the configuration and there are a number of tags that defines settings for MyBatis mapping framework. We will see all the above setting one by one:

<settings/>: this tag is used to specify some common setting that is to be used for whole MyBatis application. The above file file contain an example of setting the property “lazyLoadingEnabled” to disable. We will see more setting options in next tutorials.

<typeAliases>: tag will allow use define alias for our domain classes that we can use later in any MyBatis configuration file.

<environments/>: tag is used to define database related settings. We can have more than one environment settings but MyBatis will use one environment at a time that will be specified by the default property.

<mappers>: this tag is used to define the location of the xml file that are mapping files. We can define more than one mapping file.

Defining Service in an interface:

After that you have to create a interface that will define the service that we want provide. Following the is interface which defines only one method “save” for the domain class Product:

package com.raistudies.services;

import com.raistudies.domain.Product;

public interface ProductServices {
    public void save(Product product);
}

Now we have to define mapping file for this service. Following is the mapping file for the interface:

<?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.raistudies.services.ProductServices">

        <insert id="save" parameterType="product">
            INSERT INTO Product (id,brand,model,name)
            VALUE ( #{id}, #{brand}, #{model}, #{name} )
        </insert>

    </mapper>

The mapping file will contain element <mapper/> to define the SQL statement for the services. Here the property “namespace” defines the interface for which this mapping file has been defined.

<insert/> tag defines that the operation is of type insert. The value of “id” property specifies the function name for which the operation is been defined. Here it is save. The property “parameterType” defines the parameter of the method is of which type. We have used alias for the class Product here. Then, we have to define the SQL Statement. #{id} defines that the property “id” of class Product will be passed as a parameter to the SQL query.

Creating MyBatis Session and using the product service:

Following is our test class that creates Session of MyBasit then uses the save method of ProductService interface to save instance of Product class:

package com.raistudies.runner;

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

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

import com.raistudies.domain.Product;
import com.raistudies.services.ProductServices;

public class AppTester {
    private static SqlSessionFactory sessionFac = null;
    private static Reader reader;
    private static String CONFIGURATION_FILE = "sqlmap-config.xml";

    static{
        try {
            reader = Resources.getResourceAsReader(CONFIGURATION_FILE);
            sessionFac = new SqlSessionFactoryBuilder().build(reader);
        } catch (IOException e) {
        e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        SqlSession session = sessionFac.openSession();
        try {
            ProductServices productServiceObj = session.getMapper(ProductServices.class);
            Product product = new Product();
            product.setId((long)(Math.random()*100));
            product.setBrand("LG");
            product.setModel("P500");
            product.setName("Optimus One");
            productServiceObj.save(product);
            session.commit();

        } finally {
        session.close();
        }
    }

}

session.getMapper() method gives the default implementation of interface that is defined by MaBatis framework at runtime.

While running this example the record goes save to database table.

MyBatis Configuration Insert Statement Result

You can also try the example by downloading the example code from bellow links:
Source + lib: Download

Reference: Configuring MyBatis 3 from our JCG partner Rahul Mondal at the Rai Studies blog.

Related Whitepaper:

Functional Programming in Java: Harnessing the Power of Java 8 Lambda Expressions

Get ready to program in a whole new way!

Functional Programming in Java will help you quickly get on top of the new, essential Java 8 language features and the functional style that will change and improve your code. This short, targeted book will help you make the paradigm shift from the old imperative way to a less error-prone, more elegant, and concise coding style that’s also a breeze to parallelize. You’ll explore the syntax and semantics of lambda expressions, method and constructor references, and functional interfaces. You’ll design and write applications better using the new standards in Java 8 and the JDK.

Get it Now!  

Leave a Reply


three + = 7



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

Sign up for our Newsletter

20,709 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books