开发者

Trimming whitespace from char-type columns using MyBatis

Is there an easy way of trimming whitespace off of char-type columns when using a MyBatis XML mapper resultMap or resultType? Or do I need to write a custom type handler/add code to 开发者_开发知识库my JavaBean setters?


This a simple example for removing whitespace from VARCHAR column following TypeHandlers – MyBatis 3.

package com.foo.bar.mybatis.handler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;

@MappedJdbcTypes(JdbcType.VARCHAR)
public class StringTrimTypeHandler extends BaseTypeHandler<String>  {

    @Override
    public String getNullableResult(ResultSet rs, String columnName) throws SQLException {
        System.out.println("StringSpaceTypeHandler.getNullableResult(ResultSet rs, String columnName) [rs=" + rs + ", columnName=" + columnName + "]");
        return rs.getString(columnName);
    }

    @Override
    public String getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        System.out.println("StringSpaceTypeHandler.getNullableResult(ResultSet rs, int columnIndex) [rs=" + rs + ", columnIndex=" + columnIndex + "]");
        return rs.getString(columnIndex);
    }

    @Override
    public String getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        System.out.println("StringSpaceTypeHandler.getNullableResult(CallableStatement cs, int columnIndex) [cs=" + cs + ", columnIndex=" + columnIndex + "]");
        return cs.getString(columnIndex);
    }

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, String parameter, JdbcType jdbcType) throws SQLException {
        System.out.println("StringSpaceTypeHandler.setNonNullParameter() [ps=" + ps + ", i=" + i + ", parameter=" + parameter + ", jdbcType=" + jdbcType + "]");
        parameter = parameter.trim();
        ps.setString(i, parameter);
    }

}

The key part is using trim() in setNonNullParameter() method to remove heading and tailing whitespace before pass it to PreparedStatement.

After creating StringTrimTypeHandler class, you need to config it in mybatis-config.xml.

<!-- mybatis-config.xml -->

<configuration>
.....
    <typeHandlers>
        <typeHandler handler="com.foo.bar.mybatis.handler.StringTrimTypeHandler"/>
    </typeHandlers>
.....
</configuration>

You then could config logging – MyBatis 3 in MyBatis to see the actual the sql parameter.


The best way to do this is to create a type handler that will be used instead of the default StringTypeHandler. It would be handier if there was a flag on the XML, though.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜