mybatis-config.xml配置Type handler
时间: 2023-07-10 20:08:57 浏览: 54
MyBatis提供了TypeHandler的机制来处理Java对象和数据库字段之间的转换。在mybatis-config.xml中配置TypeHandler可以通过以下步骤完成:
1. 定义自定义TypeHandler类,实现org.apache.ibatis.type.TypeHandler接口,并在类上使用@MappedTypes和@MappedJdbcTypes注解指定Java类型和对应的JDBC类型。
例如,定义一个将Java的LocalDateTime类型转换为数据库的TIMESTAMP类型的TypeHandler:
```
@MappedTypes(LocalDateTime.class)
@MappedJdbcTypes(JdbcType.TIMESTAMP)
public class LocalDateTimeTypeHandler implements TypeHandler<LocalDateTime> {
@Override
public void setParameter(PreparedStatement ps, int i, LocalDateTime parameter, JdbcType jdbcType) throws SQLException {
ps.setTimestamp(i, Timestamp.valueOf(parameter));
}
@Override
public LocalDateTime getResult(ResultSet rs, String columnName) throws SQLException {
Timestamp timestamp = rs.getTimestamp(columnName);
return timestamp != null ? timestamp.toLocalDateTime() : null;
}
@Override
public LocalDateTime getResult(ResultSet rs, int columnIndex) throws SQLException {
Timestamp timestamp = rs.getTimestamp(columnIndex);
return timestamp != null ? timestamp.toLocalDateTime() : null;
}
@Override
public LocalDateTime getResult(CallableStatement cs, int columnIndex) throws SQLException {
Timestamp timestamp = cs.getTimestamp(columnIndex);
return timestamp != null ? timestamp.toLocalDateTime() : null;
}
}
```
2. 在mybatis-config.xml中配置TypeHandler。
例如,将上面定义的LocalDateTimeTypeHandler配置为全局TypeHandler:
```
<configuration>
<typeHandlers>
<typeHandler handler="com.example.LocalDateTimeTypeHandler"/>
</typeHandlers>
</configuration>
```
或者,将LocalDateTimeTypeHandler配置为特定字段的TypeHandler:
```
<resultMap id="orderResultMap" type="Order">
<id property="id" column="id"/>
<result property="createTime" column="create_time" typeHandler="com.example.LocalDateTimeTypeHandler"/>
</resultMap>
```