Tuesday, October 28, 2014

Spring 4 and mybatis 3 for data tier

Personally I think Hibernate has its complications and doesn't fit an enterprise SOA applications, It will need a lot of customization that will take the essence of why Hibernate is for.

So I prefer to use another framework for SQL databases and it's Mybatis.

Mybatis in short is an SQL mapping framework that will handle the conversion from SQL to Java and the other way around.

it relies on the concept of SQL maps, which are "originally" xml files that define the mapping between our DAO methods and the queries we execute and describe the results and how they are mapped.

example on a simple map :
https://gist.github.com/c0a1cc76b8c8646e05c6.git


now let's see how to use this query from our java code.

first we have to place our xml file in the classpath, in my case I use gradle as build system and the src/main/resources folder is the best choice for me.

now in some package I should have an interface that will call this map:

[https://gist.github.com/af0ceb439fe560f697b0.git]

note that the name of the interface is the same as the xml map and the name of the id of the select query is the same as the method name.

now what remained is to tell our spring configuration about these files :

[https://gist.github.com/636718cca702f7e1297f.git]

now we can inject the mapper in our dao and use it directly :

[https://gist.github.com/c6070206271c23af0a1c.git]


Now that you know how to use Mybatis and how to write the sql queries there are few things to know:
1- There is a project called Mybatis generator, it reads the database and automatically generate for you the basic CRUD queries and it will cover 70-80% of what you need, so you don't have to manually write every standard query every time.
check for the project here: http://mybatis.github.io/generator/
2- it's easy to customize and optimize the query in Mybatis unlike hibernate and what's good about it, is that it does one thing and it does it right.

3- you can avoid using xml files at all by writing your queries as annotations over the mapper interface methods, example :

package org.mybatis.example;
public interface BlogMapper {
  @Select("SELECT * FROM blog WHERE id = #{id}")
  Blog selectBlog(int id);
}

this is a quick way but it has its limitations and mess.

References:

1-http://mybatis.github.io/mybatis-3/getting-started.html
2-http://mybatis.github.io/generator/

Istio —simple fast way to start

istio archeticture (source istio.io) I would like to share with you a sample repo to start and help you continue your jou...