一:TypeHandler概念
TypeHandler类型转换器,在mybatis中用于实现JAVA类型和JDBC类型的相互转换。
列如:mysql表字段类型是个varchar,但是java代码对应字段是个对象VO,对象类型肯定无法存入mysql中。此时需要将对象VO转换为字符串类型,才能存入mysql数据库中,typeHandler就起到了这个作用。
二:案例
<update id="updatePeople" parameterType="com.PeopelDO">
UPDATE people
<set>
gmt_modified = now(),
version=IFNULL(version,0) + 1
<if test="nameLists != null">, names = #{nameLists, typeHandler=com.PeopleTypeHandler}</if>
</set>
WHERE id = #{id}
</update>
mybatis的BaseTypeHandler类,继承BaseTypeHandler用于处理字段,返回字符串即可。
package org.apache.ibatis.type;
public abstract class BaseTypeHandler <T> extends org.apache.ibatis.type.TypeReference<T> implements org.apache.ibatis.type.TypeHandler<T> {
protected org.apache.ibatis.session.Configuration configuration;
public BaseTypeHandler() { /* compiled code */ }
public void setConfiguration(org.apache.ibatis.session.Configuration c) { /* compiled code */ }
public void setParameter(java.sql.PreparedStatement ps, int i, T parameter, org.apache.ibatis.type.JdbcType jdbcType) throws java.sql.SQLException { /* compiled code */ }
public T getResult(java.sql.ResultSet rs, java.lang.String columnName) throws java.sql.SQLException { /* compiled code */ }
public T getResult(java.sql.ResultSet rs, int columnIndex) throws java.sql.SQLException { /* compiled code */ }
public T getResult(java.sql.CallableStatement cs, int columnIndex) throws java.sql.SQLException { /* compiled code */ }
public abstract void setNonNullParameter(java.sql.PreparedStatement preparedStatement, int i, T t, org.apache.ibatis.type.JdbcType jdbcType) throws java.sql.SQLException;
public abstract T getNullableResult(java.sql.ResultSet resultSet, java.lang.String s) throws java.sql.SQLException;
public abstract T getNullableResult(java.sql.ResultSet resultSet, int i) throws java.sql.SQLException;
public abstract T getNullableResult(java.sql.CallableStatement callableStatement, int i) throws java.sql.SQLException;
}