mybatis中datetime轉(zhuǎn)date怎么實(shí)現(xiàn)

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

在MyBatis中將數(shù)據(jù)庫中的Datetime類型轉(zhuǎn)換為Date類型可以通過使用TypeHandler來實(shí)現(xiàn)。以下是一個(gè)示例代碼:

首先創(chuàng)建一個(gè)自定義的TypeHandler類,繼承自BaseTypeHandler,實(shí)現(xiàn)自定義的轉(zhuǎn)換邏輯:

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的配置文件中注冊(cè)該TypeHandler:

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

最后在對(duì)應(yīng)的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中將數(shù)據(jù)庫中的Datetime類型自動(dòng)轉(zhuǎn)換為Date類型。

0