Loiane Groner, Brazilian, works as a Java/ Sencha evangelist. She has 7+ years of experience in web development. She is the ESJUG (Espirito Santo Java Users Group) and CampinasJUG (Campinas Java Users Group) leader and coordinator. Loiane is passionate about technology and programming. Also author of ExtJS 4 First Look book. Loiane is a DZone MVB and is not an employee of DZone and has posted 42 posts at DZone. You can read more from them at their website. View Full User Profile

IBatis (MyBatis): Discriminator Column Example – Inheritance Mapping Tutorial

03.22.2011
| 15942 views |
  • submit to reddit

This tutorial will walk you through how to setup iBatis (MyBatis) in a simple Java project and will present an example using a discriminator column, in another words it is a inheritance mapping tutorial.

Pre-Requisites

For this tutorial I am using:

IDE: Eclipse (you can use your favorite one)
DataBase: MySQL
Libs/jars: MybatisMySQL conector and JUnit (for testing)

This is how your project should look like:

Sample Database

Please run the script into your database before getting started with the project implementation. You will find the script (with dummy data) inside the sql folder.

1 – POJOs – Beans

I represented the beans here with a UML model, but you can download the complete source code in the end of this article.

As you can see on the Data Modeling Diagram and the UML diagram above, we have a class Employee and two subclasses: Developer and Manager. The goal of this tutorial is to retrieve all the Employees from the database, but these employees can be an instance of Developer or Manager, and we are going to use a discriminator column to see which class we are going to instanciate.

2 – Employee Mapper – XML

Sometimes a single database query might return result sets of many different (but hopefully somewhat related) data types. The discriminator element was designed to deal with this situation, and others, including class inheritance hierarchies. The discriminator is pretty simple to understand, as it behaves much like a switch statement in Java.

A discriminator definition specifies column and javaType attributes. The column is where MyBatis will look for the value to compare. The javaType is required to ensure the proper kind of equality test is performed (although String would probably work for almost any situation).

<?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="Employee">

<resultMap id="resultEmployee" type="Employee">
<result property="id"/>
<result property="name"/>
<discriminator javaType="int" column="employee_type">
<case value="1" resultMap="resultManager"/>
<case value="2" resultMap="resultDeveloper"/>
</discriminator>
</resultMap>

<resultMap id="resultManager" type="Manager">
<result property="managerId" column="manager_id" />
<result property="info" column="info" />
</resultMap>

<resultMap id="resultDeveloper" type="Developer">
<result property="developerId" column="developer_id" />
<result property="project" column="product" />
</resultMap>

<select id="getAllEmployees" resultMap="resultEmployee">
SELECT
id, name, employee_type,
manager_id, info,
developer_id, product
FROM employee E
left join manager M on M.employee_id = E.id
left join developer D on D.employee_id = E.id
</select>
</mapper>

In this example, MyBatis would retrieve each record from the result set and compare its employee type value. If it matches any of the discriminator cases, then it will use the resultMap specified by the case.

This is done exclusively, so in other words, the rest of the resultMap is ignored (unless it is extended, which we talk about in a second). If none of the cases match, then MyBatis simply uses the resultMap as defined outside of the discriminator block.

So, if the managerResult was declared as follows:

<resultMap id="resultManager" type="Manager">
<result property="managerId" column="manager_id" />
<result property="info" column="info" />
</resultMap

Then ONLY the managerId and info properties would be loaded. This is done to allow completely independent groups of discriminator cases, even ones that have no relationship to the parent resultMap. In this case we do of course know that there’s a relationship between manager and employee, as a Manager is-a Employee.

Therefore, we want the rest of the properties loaded too. One simple change to the resultMap and we’re set to go.

<resultMap id="resultManager" type="Manager" extends="resultEmployee">
<result property="managerId" column="manager_id" />
<result property="info" column="info" />
</resultMap>

Now all of the properties from both the managerResult and developerResult will be loaded.

Once again though, some may find this external definition of maps somewhat tedious. Thereforethere’s an alternative syntax for those that prefer a more concise mapping style. For example:
<?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="Employee">

<resultMap id="resultEmployee" type="Employee">
<result property="id"/>
<result property="name"/>
<discriminator javaType="int" column="employee_type">
<case value="1" resultType="Manager">
<result property="managerId" column="manager_id" />
<result property="info" column="info" />
</case>
<case value="2" resultType="Developer">
<result property="developerId" column="developer_id" />
<result property="project" column="product" />
</case>
</discriminator>
</resultMap>

<select id="getAllEmployees" resultMap="resultEmployee">
SELECT
id, name, employee_type,
manager_id, info,
developer_id, product
FROM employee E
left join manager M on M.employee_id = E.id
left join developer D on D.employee_id = E.id
</select>
</mapper>

Remember that these are all Result Maps, and if you don’t specify any results at all, then MyBatis willautomatically match up columns and properties for you. So most of these examples are more verbosethan they really need to be. That said, most databases are kind of complex and it’s unlikely that we’ll beable to depend on that for all cases.

3 - Employee Mapper – Annotations

We did the configuration in XML, now let’s try to use annotations to do the same thing we did using XML.

This is the code for EmployeeMapper.java:

package com.loiane.data;

import java.util.List;

import org.apache.ibatis.annotations.Case;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.TypeDiscriminator;

import com.loiane.model.Developer;
import com.loiane.model.Employee;
import com.loiane.model.Manager;

public interface EmployeeMapper {

final String SELECT_EMPLOYEE = "SELECT id, name, employee_type, manager_id, info, developer_id, product " +
"FROM employee E left join manager M on M.employee_id = E.id " +
"left join developer D on D.employee_id = E.id ";

/**
* Returns the list of all Employee instances from the database.
* @return the list of all Employee instances from the database.
*/
@Select(SELECT_EMPLOYEE)
@TypeDiscriminator(column = "employee_type",
cases = {
@Case (value="1", type = Manager.class,
results={
@Result(property="managerId", column="manager_id"),
@Result(property="info"),
}),
@Case (value="2", type = Developer.class,
results={
@Result(property="developerId", column="developer_id"),
@Result(property="project", column="product"),
})
})
List<Employee> getAllEmployeesAnnotation();
}

If you are reading this blog lately, you are already familiar with the @Select and @Result annotations. So let’s skip it. Let’s talk about the @TypeDiscriminator and @Case annotations.

@TypeDiscriminator

A group of value cases that can be used to determine the result mapping to perform.

Attributes: column, javaType, jdbcType, typeHandler, cases. The cases attribute is an array of Cases.

@Case

A single case of a value and its corresponding mappings.

Attributes: value, type, results.

The results attribute is an array of Results, thus this Case Annotation is similar to an actual ResultMap, specified by the Results annotation below.

In this example:

We set the column atribute for @TypeDiscriminator to determine which column MyBatis will look for the value to compare. And we set an array of @Case.

For each @Case we set the value, so if the column matches the value, MyBatis will instanciate a object of type we set and we also set an array of @Result to match column with class atribute.

Note one thing: using XML we set the id and name properties. We did not set these properties using annotations. It is not necessary, because the column matches the atribute name. But if you need to set, it is going to look like this:

@Select(SELECT_EMPLOYEE)
@Results(value = {
@Result(property="id"),
@Result(property="name")
})
@TypeDiscriminator(column = "employee_type",
cases = {
@Case (value="1", type = Manager.class,
results={
@Result(property="managerId", column="manager_id"),
@Result(property="info"),
}),
@Case (value="2", type = Developer.class,
results={
@Result(property="developerId", column="developer_id"),
@Result(property="project", column="product"),
})
})
List<Employee> getAllEmployeesAnnotation();

4 – EmployeeDAO

In the DAO, we have two methods: the first one will call the select statement from the XML and the second one will call the annotation method. Both returns the same result.

package com.loiane.dao;

import java.util.List;

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

import com.loiane.data.EmployeeMapper;
import com.loiane.model.Employee;

public class EmployeeDAO {

/**
* Returns the list of all Employee instances from the database.
* @return the list of all Employee instances from the database.
*/
@SuppressWarnings("unchecked")
public List<Employee> selectAll(){

SqlSessionFactory sqlSessionFactory = MyBatisConnectionFactory.getSqlSessionFactory();
SqlSession session = sqlSessionFactory.openSession();

try {
List<Employee> list = session.selectList("Employee.getAllEmployees");
return list;
} finally {
session.close();
}
}

/**
* Returns the list of all Employee instances from the database.
* @return the list of all Employee instances from the database.
*/
public List<Employee> selectAllUsingAnnotations(){

SqlSessionFactory sqlSessionFactory = MyBatisConnectionFactory.getSqlSessionFactory();
SqlSession session = sqlSessionFactory.openSession();

try {
EmployeeMapper mapper = session.getMapper(EmployeeMapper.class);

List<Employee> list = mapper.getAllEmployeesAnnotation();
return list;
} finally {
session.close();
}
}
}

The output if you call one of these methods and print:

Employee ID = 1 Name = Kate Manager ID = 1 Info = info Kate
Employee ID = 2 Name = Josh Developer ID = 1 Project = web
Employee ID = 3 Name = Peter Developer ID = 2 Project = desktop
Employee ID = 4 Name = James Manager ID = 2 Info = info James
Employee ID = 5 Name = Susan Developer ID = 3 Project = web

Download

If you want to download the complete sample project, you can get it from my GitHub account: https://github.com/loiane/ibatis-discriminator

If you want to download the zip file of the project, just click on download:

There are more articles about iBatis to come. Stay tooned!

 

From http://loianegroner.com/2011/03/ibatis-mybatis-discriminator-column-example-inheritance-mapping-tutorial/

Published at DZone with permission of Loiane Groner, author and DZone MVB.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Comments

Valdemar Júnior replied on Tue, 2011/03/22 - 11:56am

Awesome article. I'd like to have more time to study about MyBatis, but I've never worked in a project with MyBatis. Congrats by article.

Simone Tripodi replied on Tue, 2011/03/22 - 2:03pm

Olà Loiane, very good articles, but please call the project MyBatis (formerly known as iBATIS) :P Did you already join the MyBatis mailing list? If not, please join, we always welcome valuable feedbacks!!! Keep rocking, até a proxima! Simo (from mybatis.org team)

Daniel Haynes replied on Wed, 2011/03/23 - 5:08pm

Hi, I managed to set up my own version of your example but I am struggling on how to do an insert. How would you map an insert of, for example, a Manager object? The Manager class does not have the employee_id. Do you need to map more than one insert?

Haseeb Yousaf replied on Sun, 2011/10/16 - 11:19pm

Hello, I am also struggling with the insertion of manager into the database using the mapping/ annotation. I dont no the procedure of how would you insert the data in the database for manager that is following the inheritence architecture. Please help me if you can. Also the tutorial is very helpful. thanks for that.

Haseeb Yousaf replied on Mon, 2011/10/17 - 12:19am in response to: Daniel Haynes

Hello Daniel, were you able to create the insertion for inheritance. I hope that get the answer. If yes, please share with me. thanks'

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.