MyBatis | Mapping Query Results to Arbitrary Java Objects | Automatic snake_case and CamelCase Mapping

Data table

test_table

id value
1 hoge
2 fuga
3 piyo

Source code

TestTable.java

package sample.mybatis;

public class TestTable {
    private int id;
    private String testValue;

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

mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
  <settings>
    <setting name="mapUnderscoreToCamelCase" value="true"/>
  </settings>

  ...
</configuration>

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">

  <select id="selectTest" resultType="sample.mybatis.TestTable">
    select * from test_table
  </select>
</mapper>

Execution result of selectTest

TestTable [id=1, testValue=hoge]
TestTable [id=2, testValue=fuga]
TestTable [id=3, testValue=piyo]

Explanation

  • Setting mapUnderscoreToCamelCase to true enables automatic conversion between snake_case and CamelCase.
  • The default value is false.