在MyBatis中將數(shù)據(jù)庫中的Datetime類型轉(zhuǎn)換為Date類型可以通過使用TypeHandler來實(shí)現(xiàn)。以下是一個(gè)示例代碼:
首先創(chuàng)建一個(gè)自定義的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的配置文件中注冊(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類型。