MyBatis | Mapping Query Results to Arbitrary Java Objects | Specifying a Prefix for Column Names

Data tables

foo_table

id bar_id
1 3
2 2
3 1

bar_table

id
1
2
3

Source code

Foo.java

package sample.mybatis;

public class Foo {
    private int id;
    private Bar bar;

    @Override
    public String toString() {
        return "Foo [id=" + id + ", bar=" + bar + "]";
    }
}

Bar.java

package sample.mybatis;

public class Bar {
    private int id;

    @Override
    public String toString() {
        return "Bar [id=" + id + "]";
    }
}

sample_mapper.xml

<?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="sample.mybatis">

  <resultMap type="sample.mybatis.Foo" id="fooResultMap">
    <id property="id" column="id" />
    <!-- Specify the shared prefix with columnPrefix. -->
    <association property="bar" columnPrefix="bar_" resultMap="barResultMap" />
  </resultMap>

  <resultMap type="sample.mybatis.Bar" id="barResultMap">
    <id property="id" column="id" />
  </resultMap>

  <select id="selectFoo" resultMap="fooResultMap">
    select foo.id
          ,bar.id bar_id -- Specify "bar_" as the prefix.
      from foo_table foo
          ,bar_table bar
     where bar.id = foo.bar_id
  order by foo.id asc
  </select>
</mapper>

Execution result of selectFoo

Foo [id=1, bar=Bar [id=3]]
Foo [id=2, bar=Bar [id=2]]
Foo [id=3, bar=Bar [id=1]]

Explanation

  • When performing a JOIN, you will usually add a prefix such as bar_ to distinguish columns with the same name in different tables.
  • MyBatis provides the columnPrefix attribute so that resultMap can also be used in such cases.
  • When columnPrefix is specified, mapping is performed using names that add the prefix to the column settings.