MyBatis | 検索結果を任意のJavaオブジェクトにマッピング | snake_caseとCamelCaseマッピングの自動化

データテーブル

test_table

id value
1 hoge
2 fuga
3 piyo

ソースコード

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>

selectTestの実行結果

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

説明

  • mapUnderscoreToCamelCaseをtrueに設定すると、snake_caseとCamelCaseの自動変換が有効になる。
  • デフォルト値はfalseである。