6
6

More than 3 years have passed since last update.

Spring Boot Mybatis SQLのスネークケースカラムとキャメルケースのマッピング

Last updated at Posted at 2020-12-22

SQLのカラム名はスネークケースでマッピング先のjavaはキャメルケースの場合、
mybatisで自動的にキャメル→スネークに変換してくれる設定。

結論

方法1

私はこれを使ってます。

application.yml
mybatis:
  configuration:
    map-underscore-to-camel-case: true

方法2

application.properties
mybatis.configuration.map-underscore-to-camel-case=true

方法3

application.yml
mybatis:
  config-location: classpath:/mybatis/mybatis-config.xml
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>

参考実装

Todo.java
class Todo {
    private Integer id;
    private String statusNm; // このフィールドに status_nm の値を入れたい
    public void setId(Integer id) {
        this.id = id;
    }
    public Integer getId() {
        return this.id;
    }
    public void setStatusNm(String statusNm) {
        this.statusNm = statusNm;
    }
    public String getStatusNm() {
        return this.statusNm;
    }
}
TodoListMapper.java
@Mapper
public interface TodoListMapper {
    /**
     * リストを検索する。
     * @return TODOリスト
     */
    List<Todo> selectList();
}
TodoListMapper.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="com.hellospring.mapper.TodoListMapper">
  <select id="selectList" resultType="com.hellospring.domain.Todo">
    SELECT
      id
     ,status_nm
    FROM
      todo
  </select>
</mapper>

仕組み

MyBatisはスネークケースのカラム名をキャメルケースに変換し、キャメルケースに対応するsetterを呼び出してくれる。
ちなみにORACLEだとテーブル名やカラム名は大文字に揃えるが、大文字でもOK。

status_nmsetStatusNm()を呼び出す。
STATUS_NMsetStatusNm()を呼び出す。

6
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
6