0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

MyBatis のキャメルケース変換を有効化して createdAt / updatedAt が null になる問題を解決した話

Posted at

① 結論

MyBatisの キャメルケース自動変換 を有効化することで、DBのスネークケースカラム (created_at / updated_at) をJavaのキャメルケースプロパティ (createdAt / updatedAt) に正しくマッピングできるようになり、nullになる問題が解決しました。

application.properties
# MyBatis のキャメルケース変換を有効化
mybatis.configuration.map-underscore-to-camel-case=true

②どういう問題が発生したか

Spring Boot + MyBatis環境で、以下のエンティティを用意しました。
ToDo.java
@Data
@NoArgsConstructor
@AllArgsConstructor
public class ToDo {
    private Integer id;
    private String todo;
    private String detail;
    private LocalDateTime createdAt;
    private LocalDateTime updatedAt;
}

対応するテーブルはPostgreSQLで、カラム名はスネークケースです。

CREATE TABLE todos (
    id serial PRIMARY KEY,
    todo varchar(255) NOT NULL,
    detail text,
    created_at timestamp without time zone DEFAULT CURRENT_TIMESTAMP,
    updated_at timestamp without time zone DEFAULT CURRENT_TIMESTAMP
);

MyBatis XMLは以下のようにしていました。

mapper.xml
<insert id="insert">
    INSERT INTO todos (todo, detail, created_at, updated_at)
    VALUES (#{todo}, #{detail}, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP);
</insert>

<select id="selectAll" resultType="com.example.webapp.entity.ToDo">
    SELECT id, todo, detail, created_at, updated_at FROM todos;
</select>

しかし、selectAll()で取得すると、createdAt と updatedAt が null になっていました。

③どうやって改善したか

原因は MyBatisがデフォルトではカラム名とプロパティ名の対応を正しくマッピングできないことでした。
DBは created_at、Javaは createdAt と命名しているためです。

解決策として、application.properties に以下を追加しました。

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

この設定により、MyBatisが自動でスネークケース → キャメルケース変換を行うようになりNULLになる問題は解決しました。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?