mybatis-3 icon indicating copy to clipboard operation
mybatis-3 copied to clipboard

select sql return primitive type,How to use customize typeHandler

Open EverSpring opened this issue 2 years ago • 2 comments

MyBatis version

3.5.7

Database vendor and version

mysql 5.7

Test case or example project

XML:

<select id="selectOneById" resultType="java.lang.String">
        select mobile from system_admin_user where id = #{id}
    </select>

JAVA:

public class SecurityCustomerTypeHandler extends BaseTypeHandler<String> {
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, String parameter, JdbcType jdbcType) throws SQLException {
        ps.setString(i, encrypt(parameter));
    }

    @Override
    public String getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String value = rs.getString(columnName);
        return decrypt(value);
    }

    @Override
    public String getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String value = rs.getString(columnIndex);
        return decrypt(value);
    }

    @Override
    public String getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String value = cs.getString(columnIndex);
        return decrypt(value);
    }
}

I want to deal mobile by SecurityCustomerTypeHandler,How can it take effect

Steps to reproduce

Expected result

SecurityCustomerTypeHandler take effect on column mobile

Thank you!

EverSpring avatar Aug 15 '22 15:08 EverSpring

把自定义的处理程序类的全局限定符,通过mybatis-config.xml中的typeHandlers标签注册到mybatis中. 定义个resultMap标签, 在resultMap的子标签result中,通过typeHandler属性指定使用哪个处理程序类.

619123555 avatar Aug 31 '22 07:08 619123555

把自定义的处理程序类的全局限定符,通过mybatis-config.xml中的typeHandlers标签注册到mybatis中. 定义个resultMap标签, 在resultMap的子标签result中,通过typeHandler属性指定使用哪个处理程序类.

谢谢,通过对象来接收能够解决。想了解下,只有一个string类型怎么做到加解密呢?比如: <select id="selectOneById" resultType="java.lang.String"> select mobile from system_admin_user where id = #{id} </select> mapper.selectOneById('明文') 这种情况有没有办法做到执行selectOneById sql查询的参数加密呢?

EverSpring avatar Sep 06 '22 06:09 EverSpring

<typeHandlers>
  <typeHandler handler="com.test.SecurityCustomerTypeHandler" javaType="String" jdbcType="VARCHAR" />
</typeHandlers>

如果是这么注册的话,会把mybatis默认的String, VARCHAR类型处理器给覆盖掉,也就是所有String, VARCHAR类型的字段,都会走你自定义的处理器,那这样你就可以在自定义的类型处理器中,根据字段名来判断是否需要加解密

619123555 avatar Sep 26 '22 04:09 619123555