在MyBatis中使用LocalDateTime類型需要在配置文件中指定TypeHandler,以將數據庫中的時間戳轉換為LocalDateTime對象。可以通過編寫自定義的TypeHandler來實現這一功能。
首先需要在配置文件中注冊自定義的TypeHandler:
<typeHandlers>
<typeHandler handler="com.example.LocalDateTimeTypeHandler"/>
</typeHandlers>
然后編寫自定義的TypeHandler類:
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);
return timestamp != null ? timestamp.toLocalDateTime() : null;
}
@Override
public LocalDateTime getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
Timestamp timestamp = rs.getTimestamp(columnIndex);
return timestamp != null ? timestamp.toLocalDateTime() : null;
}
@Override
public LocalDateTime getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
Timestamp timestamp = cs.getTimestamp(columnIndex);
return timestamp != null ? timestamp.toLocalDateTime() : null;
}
}
在Mapper接口中可以直接使用LocalDateTime類型:
public interface UserMapper {
@Select("SELECT * FROM user WHERE id = #{id}")
User getUserById(Integer id);
@Insert("INSERT INTO user (name, create_time) VALUES (#{name}, #{createTime, jdbcType=TIMESTAMP})")
void insertUser(@Param("name") String name, @Param("createTime") LocalDateTime createTime);
}
這樣就可以在MyBatis中使用LocalDateTime類型了。