溫馨提示×

mybatis中datetime轉date怎么實現

小億
308
2024-06-06 16:27:24
欄目: 編程語言

在MyBatis中將數據庫中的Datetime類型轉換為Date類型可以通過使用TypeHandler來實現。以下是一個示例代碼:

首先創建一個自定義的TypeHandler類,繼承自BaseTypeHandler,實現自定義的轉換邏輯:

public class DateTimeToDateTypeHandler extends BaseTypeHandler<Date> {

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

    @Override
    public Date getNullableResult(ResultSet rs, String columnName) throws SQLException {
        Timestamp timestamp = rs.getTimestamp(columnName);
        return timestamp != null ? new Date(timestamp.getTime()) : null;
    }

    @Override
    public Date getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        Timestamp timestamp = rs.getTimestamp(columnIndex);
        return timestamp != null ? new Date(timestamp.getTime()) : null;
    }

    @Override
    public Date getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        Timestamp timestamp = cs.getTimestamp(columnIndex);
        return timestamp != null ? new Date(timestamp.getTime()) : null;
    }
}

然后在MyBatis的配置文件中注冊該TypeHandler:

<typeHandlers>
    <typeHandler handler="com.example.DateTimeToDateTypeHandler"/>
</typeHandlers>

最后在對應的Mapper XML文件中使用該TypeHandler:

<resultMap id="myResultMap" type="com.example.MyEntity">
    <result property="date" column="datetime" javaType="java.util.Date" typeHandler="com.example.DateTimeToDateTypeHandler"/>
</resultMap>

這樣就可以在MyBatis中將數據庫中的Datetime類型自動轉換為Date類型。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女