mybatis 日期转换
时间: 2023-08-27 15:16:22 浏览: 63
MyBatis provides built-in support for mapping Java date types to corresponding database column types. To handle date conversions in MyBatis, you can use the `TypeHandler` interface.
Here are the steps to configure date conversion in MyBatis:
1. Create a custom `TypeHandler` for date conversion. You can implement the `TypeHandler` interface and override its methods to handle the conversion between Java `Date` and the database column type.
```java
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import java.sql.*;
import java.util.Date;
public class DateTypeHandler 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 {
return rs.getTimestamp(columnName);
}
@Override
public Date getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
return rs.getTimestamp(columnIndex);
}
@Override
public Date getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
return cs.getTimestamp(columnIndex);
}
}
```
2. Register the custom `TypeHandler` in your MyBatis configuration XML file:
```xml
<typeHandlers>
<typeHandler handler="com.example.DateTypeHandler"/>
</typeHa