Mybatisで日付を扱う方法

Mybatisで日付を扱う方法

MyBatisで日付を扱う方法

MyBatisで日付を扱う際、Javaではjava.util.Dateやjava.time.LocalDateなどの日付型を使います。
MyBatisは自動的にSQLのDATE型やTIMESTAMP型にマッピングします。

例: 日付フィールドのINSERT

以下の例では、testUserというクラスと、test_usersというテーブルを使って、日付フィールドをINSERTする方法を示します。

1. Javaの値オブジェクト (VO)

public class testUser {
    private int id;
    private String name;
    private Date birthDate; // java.util.Date

    // getter と setter
    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Date getBirthDate() {
        return birthDate;
    }

    public void setBirthDate(Date birthDate) {
        this.birthDate = birthDate;
    }
}

2. Mapper XML

<insert id="insertUser" parameterType="testUser">
    INSERT INTO test_users (id, name, birth_date)
    VALUES (#{id}, #{name}, #{birthDate})
</insert>

3. 使用例

import java.util.Date;

testUser user = new testUser();
user.setId(1);
user.setName("Taro");
user.setBirthDate(new Date());

testUserMapper mapper = session.getMapper(testUserMapper.class);
mapper.insertUser(user);

日付のフォーマット設定

もし、日付のフォーマットをカスタマイズしたい場合、MyBatisのtypeHandlerを使用してフォーマットを指定することができます。

カスタムtypeHandlerの例

import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

public class CustomDateTypeHandler extends BaseTypeHandler<Date> {

    private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

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

    @Override
    public Date getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return rs.getDate(columnName);
    }

    @Override
    public Date getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return rs.getDate(columnIndex);
    }

    @Override
    public Date getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return cs.getDate(columnIndex);
    }
}

このtypeHandlerを使うと、日付をフォーマットしてデータベースに保存することができます。

Mapper XMLでの設定

<insert id="insertUser" parameterType="testUser">
    INSERT INTO test_users (id, name, birth_date)
    VALUES (#{birthDate, typeHandler=CustomDateTypeHandler})
</insert>

このようにして、MyBatisで日付を柔軟に扱うことが可能です。