Tag Archives: MyBatis

Spring MyBatis configuration

Here I describe the project configuration to use MyBatis as ORM and benefit of the transactions management provided by Spring.
For that, we have to add the MyBatis-Spring library to the basic MyBatis.

First, the Maven POM is like:


And now, the Spring configuration file where we define the SqlSessionFactoryBean:

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
                        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="mapperLocations" value="classpath:xml/*Mapper.xml" />

The SqlSessionFactoryBean needs a datasource, and also the location of the MyBatis xml mappers.

Now, the configuration is done and the mappers will be managed by Spring using with this:

<!-- this is the parent of our Mappers. It defines the sqlSessionFactory which is common to all our mapper beans -->
<bean id="mapper" abstract="true">
	<property name="sqlSessionFactory" ref="sqlSessionFactory" />
<!-- Place MyBatis Mappers here -->
<bean id="entityMapper" class="org.mybatis.spring.mapper.MapperFactoryBean" parent="mapper">
	<property name="mapperInterface"
		value="net.classnotfound.data.mapper.EntityMapper" />

We can see that the mappers are instantiated by the org.mybatis.spring.mapper.MapperFactoryBean which needs a reference to the SqlSessionFactory object we defined earlier.
To avoid some oversights (and reduce the mount of lines I have to write 🙂 ), I use the “abstract” Spring feature to put the session factory in the abstract mapper, then I can reference it as a parent in all my MapperFactories.

Now the entityMapper we defined is “injectable” in our Spring managed beans and we can use our preferred way of transaction management.

Persist list with MyBatis

As MyBatis is a basic ORM, when we need to persista list of objects, we have to implement it manually, but without any copy/paste between classes. For this purpose, I designed a generic merger which is responsible of that task.
It has to go through a list of objects and determine:

  1. what is new and needs to be created
  2. what is not there meaning it has been deleted
  3. what was already here and needs to be updated

To identify in which case we are, we need to provide it a java.util.Comparator and also a Dao to be able to interact with the database.

This is done in one main class (which uses also what I described in a previous post)

package net.classnotfound.data.dao.utils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;

import net.classnotfound.capability.Identifiable;
import net.classnotfound.data.dao.Dao;

 * This class is used to merge a list with another list. It is helpful when we need to marge a list of elements
 * which come from the GUI with the list in the database
 * @author roussehe
 * @param <T> the type of element we have to manage
public class MergerList<T extends Identifiable> {
    private Dao<T> dao;
    private Finder<T> finder;
     * @param dao the dao used to merge the new or existing entries and to delete the removed ones 
     * @param comparator the comparator used to know if an element already exists in the DB
    public MergerList(Dao<T> dao, Comparator<T> comparator) {
        this.dao = dao;
        this.finder = new Finder<>(comparator);

     * merge the 2 lists, making comparison between existing/new/removed entries and persist the data in the database
     * @param oldEntryList the list coming from the db (usually)
     * @param newEntryList the new list we need to persist
    public void mergeList(List<T> oldEntryList, List<T> newEntryList) {
        List<T> mergedEntries = new ArrayList<>();
        List<T> deletedEntries = new ArrayList<>();
        //we have to go through the 2 lists and check it one by one
        if(oldEntryList!=null&& !oldEntryList.isEmpty()) {
            //here, we check the entries which are present or not in the old list
            for (T entry : oldEntryList) {
                T found = finder.findMember(entry, newEntryList);
                if (found!=null) {//if found, we have to update it
                } else {//not found means it must be deleted from db
        if(newEntryList!=null&& !newEntryList.isEmpty()) {
            //here we check the entries which are only present in the new list
            for (T entry : newEntryList) {
                T found = finder.findMember(entry, oldEntryList);
                if(found == null) {//if not found in db, it's a new entry
                }//if found, it is already managed in the previous loop
        //process records

    /** As my Dao can manage create and update, it is done in one time.
     * @param mergeEntries
    private void mergeEntries(List<T> mergeEntries) {
        for (T t: mergeEntries) {

    private void deleteEntries(Collection<T> deletedItems) {
        for (T t: deletedItems) {
     * This class is a helper class to find an object in a list of items
     * @param <R>
    private class Finder<R>{
        private Comparator<R> comp;
        Finder(Comparator<R> comp) {
            this.comp = comp;

         * This method is responsible of getting object from the provided list.
         * @param entry
         * @param list
         * @return the object if found, or null otherwise
        R findMember(R entry, List<R> list) {
            R found = null;
            if(list!=null&&!list.isEmpty()) {
                for (Iterator<R> iterator = list.iterator(); iterator.hasNext()&&found==null;) {
                    R currEntry = iterator.next();
                    if(comp.compare(entry, currEntry)==0)
                        found = currEntry;
            return found;

Done 😀


As I was working on the data access layer of my project, I noted that I have a lot of stuff to do to be able to access the Mapper from my web layer just for some simple CRUD actions.
Lot of stuff and even if I can detect some similarities, it’s not exactly the same, so I can’t just decide to put it in an interface or some abstract class, but lazy one day, lazy allways (it sounds better in french :D)…
After using my unique neurone to find solution, I finally arrive to a solution that I will present here.

To briefly describe my architecture, I have a web layer which access a service layer and then, the service layer can reach the data layer.
A requirement in my application is the user management (firstname, lastname, address, etc…), it’s what I will use to illustrate my solution.
First, I wanted to define a generic Dao to access my User object, to do that, the search all user is the simpler mechanism.
I need a simple POJO:

public class User {
    private Integer usrId;

    private String usrName;

    private String usrFname;

Now, the Dao, it will be responsible of accessing the MyBatis Mapper, and it will need to be able to manage all the Mapper, it’s why I defined a new interface which will contain the CRUD method:

public interface Mapper<T> {

    List<T> findAll();
    int insert(T record);
    T selectByPrimaryKey(Integer id);
    void updateByPrimaryKey(T object);
    void deleteByPrimaryKey(Integer id);


The MyBatis interface must now implement this interface specifying the User object:

public interface UserMapper extends Mapper<User>{

    int insert(User record);
    List<User> findAll();
    User selectByPrimaryKey(Integer userId);
    void updateByPrimaryKey(User user);
    void deleteByPrimaryKey(Integer usrId);

The Mapper is fine, it can be used by my Dao, in first, I define its interface:

public interface Dao {

    public List findAll();
    public T find(Integer id);
    public T merge(T obj);
    public void delete(T obj);

And the implementation which references the generic mapper I want to use:

public class DaoImpl implements Dao{

    protected Mapper mapper;

    public DaoImpl(Mapper mapper) {
        this.mapper = mapper;

    public List findAll() {
        return mapper.findAll();

there no problem to use the generic T because the real object is only known by the mapper “implementation”

And now the definition of my dao using Spring:

<bean id="userDao" class="net.classnotfound.dao.DaoImpl">
    <constructor-arg index="0" ref= "userMapper"/>

<bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
  <property name="mapperInterface" value="net.classnotfound.mapper.UserMapper" />
  <property name="sqlSessionFactory" ref="sqlSessionFactory" />

As you can see, the Dao is User agnostic, the Mapper is responsible of accessing the right objet. Now, ma Dao can be used with any Mapper, just by changing the Spring configuration.

But when we speak about CRUD, it’s not only getting the full list of records from the database, we need to be able to insert, update and delete, for that, you often need to add some data as the creation date or update date.
Usually, using JPA/Hibernate, I used a @PreUpdate or @PrePersist, but they are part of the JPA specifications, I cannot use it.
It’s why I decided to create some new interface to be able to acces to this particular fields.
For that, I defined 4 new interfaces, I will just present 2 of them but you can imagine the others:

public interface Identifiable {

    Integer getId();
    void setId(Integer id);
public interface Updatable {

    void setUpdateDate(Date date);

My user class must now implement these interfaces:

public class User implements Identifiable, Deletable, Updatable, Creatable

I can now add the update method in my DAO:

    public T merge(T obj) {
        if(!(obj instanceof Identifiable)) 
            throw new IllegalArgumentException("The object is not instance of Identifiable and cannot be updated!");
        Identifiable idable =  (Identifiable)obj;
        if (idable.getId()==null) {
            if (!(obj instanceof Creatable))
                throw new IllegalArgumentException("The object is not instance of Creatable and cannot be inserted!");
            Creatable creatable = (Creatable) obj;
            creatable.setCreationDate(new Date());
        } else {
            if (!(obj instanceof Updatable))
                throw new IllegalArgumentException("The object is not instance of Updatable and cannot be updated!");
            Updatable updtable = (Updatable) obj;
            updtable.setUpdateDate(new Date());
        return obj;

I need to cast the T object to be able to access to the related method.

When it is done for all the CRUD method, I have to use it in my service layer, the problem remains as I want to avoid the duplication of code.
It means that my service must be also

public interface Service<t> {
    List<t> findAll();
    T find(Integer id);
    T merge(T t);
    void delete(T t);
    void setDao(Dao<t> dao);
    Dao<t> getDao();

The service implementation looks like:

public class ServiceImpl<t> implements Service<t>{
    private Dao<t> dao;
    public List<t> findAll() {
        List<t> objects = dao.findAll();
        return objects;
    public T find(Integer id) {
        T user = dao.find(id);
        return user;
    public T merge(T object) {
        return object;
    public void setDao(Dao<t> dao) {
        this.dao = dao;
    public Dao<t> getDao() {
        return dao;

And the service declaration, in the Spring configuration:

    <bean id="userService" class="net.classnotfound.ServiceImpl">
        <property name="dao" ref="userDao"/>

In the same way as the Dao, my service in now Dao agnostic, I can create different services just using the Spring configuration, I will now have the time drink a coffee instead of repeating the same code in several classes 🙂


Improve server startup using Informix and MyBatis

Working on a project with an Informix database and using MyBatis as the persistence layer, I noted that the start-up of the server takes a long time (about 2 minutes). It is not really a problem if the performance of the application are good, as you don’t start your server all the day, but when you are in the implementation phase…
After step-by-step execution, I discovered that MyBatis gathers the metadata of the database to adapt its behavior, but this part was responsible of the delay (maybe Informix specific?).
I decided to replace this step, fortunately, using MyBatis with Spring, it’s not really a big deal 🙂
As the main purpose of this step is to identify the database provider, I defined a class which returns always the same information: Informix database.

  1. first, you need to define a new DatabaseIdProvider:
    public class IfxDatabaseIdProvider 
            implements org.apache.ibatis.mapping.DatabaseIdProvider {
      private static final Log log = LogFactory.getLog(IfxDatabaseIdProvider.class);
      private Properties properties;
      public String getDatabaseId(DataSource dataSource) {
        return "Informix Dynamic Server";
      public void setProperties(Properties p) {
        this.properties = p;
      public Properties getProperties() {
        return properties;
  2. now, you need to tell to MyBatis to use the new class, your Spring config file looks like:

        <bean id="ifxDatabaseIdProvider" 
        <bean id="sqlSessionFactory" 
          <property name="dataSource" ref="dataSource" />
          <property name="mapperLocations" value="classpath:mapper/*Mapper.xml"/>
          <property name="databaseIdProvider" ref="ifxDatabaseIdProvider"/>