Mybatis mapping configuration setting

Mybatis is a data mapping framework I recently came across. I did step by step tutorials like getting-started-with-ibatis-mybatis-annotations and mybatis-dao-example-code-tutorial .
These tutorials show as well as others how to map database columns to java class members, e.g.

@Results(value = {
  @Result(property="ID", column="ID"),
  @Result(property="column_one", column="column_one"),
  @Result(property="column_B", column="column_B")

Seeing this kind of mapping often – I wondered if the mapping is really necessary?

I realized you don’t need to define an explicit mapping in any case. According to the mybatis configuration settings and some tests I did, you need to make sure 2 details are set:

  • java class members and database columns uses the same labels
  • mybatis mapping config file setting autoMappingBehavior is ist set to PARTIAL or FULL
    <setting name="autoMappingBehavior" value="FULL"/>

In cases like this you can leave the mapping empty e.g.

//    @Results(value = {
//        @Result(property="ID", column="ID"),
//        @Result(property="column_one", column="column_one"),
//        @Result(property="column_B", column="column_B")
//    })
    List selectAll();

On the other hand you are required to define the mapping in some situations .
If there are different labels for java properties and database columns and/or you tell mybatis not to automatically map, you have to define a mapping.

A mapping definition could look like this:

    @Results(value = {
        @Result(property="ID", column="ID"),
        @Result(property="column_one", column="column_one"),
        @Result(property="prop2", column="column_B")
    List selectAll();

A match to your java class members

    private int ID;
    private String prop2;
    private int column_one;

and your database table definitions e.g.

    CREATE TABLE things(
        column_one INT NOT NULL,
        column_B VARCHAR(60) NOT NULL,

is required in order to complete the sample.

If you want to know more about the sample code snippets, you can check out a sample code project mybatisMappingTest on github. This project consists of two branches:

The branch explicitMapping shows by example how to define an explicit mapping. How mybatis maps data automatically is shown in branch autoMapping .

Lothar Schulz

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.