LoginSignup
0
0

More than 1 year has passed since last update.

Spring Boot + MyBatisで自作TypeHandlerを使う

Posted at

環境

  • JDK 17
  • Spring Boot 2.7
  • mybatis-spring-boot-starter 2.2.2

やり方

型の作成

Hoge.java
package com.example.entity;

public record Hoge(String value) {
}

TypeHandlerの作成

@MappedTypes を付加するのがポイント。

HogeTypeHandler.java
package com.example.typehandler;

import com.example.entity.Hoge;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@MappedTypes(Hoge.class)
public class HogeTypeHandler extends BaseTypeHandler<Hoge> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Hoge parameter, JdbcType jdbcType) throws SQLException {
        ps.setString(i, parameter.value());
    }

    @Override
    public Hoge getNullableResult(ResultSet rs, String columnName) throws SQLException
        String value = rs.getString(columnName);
        if (value == null) {
            return null;
        }
        return new Hoge(value);
    }

    @Override
    public Hoge getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String value = rs.getString(columnIndex);
        if (value == null) {
            return null;
        }
        return new Hoge(value);
    }

    @Override
    public Hoge getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String value = cs.getString(columnIndex);
        if (value == null) {
            return null;
        }
        return new Hoge(value);
    }
}

application.propertiesの設定

自作TypeHandlerが含まれているパッケージ名を指定する。

application.properties
mybatis.type-handlers-package=com.example.typehandler

参考資料

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