溫馨提示×

MyBatis如何映射localdatetime到數(shù)據(jù)庫字段

小樊
103
2024-08-07 22:41:32

在MyBatis中,要將LocalDateTime類型映射到數(shù)據(jù)庫字段,需要使用TypeHandler來處理。以下是一個示例:

  1. 創(chuàng)建一個自定義的TypeHandler來處理LocalDateTime類型的映射
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

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

public class LocalDateTimeTypeHandler extends BaseTypeHandler<LocalDateTime> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, LocalDateTime parameter, JdbcType jdbcType) throws SQLException {
        ps.setTimestamp(i, Timestamp.valueOf(parameter));
    }

    @Override
    public LocalDateTime getNullableResult(ResultSet rs, String columnName) throws SQLException {
        Timestamp timestamp = rs.getTimestamp(columnName);
        if (timestamp != null) {
            return timestamp.toLocalDateTime();
        }
        return null;
    }

    @Override
    public LocalDateTime getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        Timestamp timestamp = rs.getTimestamp(columnIndex);
        if (timestamp != null) {
            return timestamp.toLocalDateTime();
        }
        return null;
    }

    @Override
    public LocalDateTime getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        Timestamp timestamp = cs.getTimestamp(columnIndex);
        if (timestamp != null) {
            return timestamp.toLocalDateTime();
        }
        return null;
    }
}
  1. 在MyBatis的配置文件中注冊該TypeHandler
<typeHandlers>
    <typeHandler handler="com.example.LocalDateTimeTypeHandler"/>
</typeHandlers>
  1. 在Mapper.xml文件中使用該TypeHandler
<resultMap id="resultMap" type="com.example.MyEntity">
    <id property="id" column="id" jdbcType="BIGINT"/>
    <result property="createDate" column="create_date" jdbcType="TIMESTAMP" javaType="java.time.LocalDateTime" typeHandler="com.example.LocalDateTimeTypeHandler"/>
</resultMap>

這樣就可以將LocalDateTime類型映射到數(shù)據(jù)庫字段,并且通過自定義的TypeHandler來處理。

0