1. 程式人生 > >使用TypeHandler實現資料入庫前的過濾

使用TypeHandler實現資料入庫前的過濾

 需求: 資料入庫前過濾emoji表情

1.編寫typeHandler類

@MappedJdbcTypes({JdbcType.VARCHAR})
public class EmojiStringTypeHandler extends StringTypeHandler {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, String parameter, JdbcType jdbcType) throws SQLException {
        super.setNonNullParameter(ps, i, StringUtils.filterEmoji(parameter), jdbcType);
    }
}

其中emoji過濾:
public static String filterEmoji(String source) {
        int len = source.length();
        StringBuilder buf = new StringBuilder(len);
        for (int i = 0; i < len; i++) {
            char codePoint = source.charAt(i);
            if (isNotEmojiCharacter(codePoint)) {
                buf.append(codePoint);
            }
        }
        return buf.toString();
    }

private static boolean isNotEmojiCharacter(char codePoint) {
        return (codePoint == 0x0) || (codePoint == 0x9) || (codePoint == 0xA) || (codePoint == 0xD)
                || ((codePoint >= 0x20) && (codePoint <= 0xD7FF)) || ((codePoint >= 0xE000) && (codePoint <= 0xFFFD))
                || ((codePoint >= 0x10000) && (codePoint <= 0x10FFFF));
    }
2.做mybatis配置,由於使用了springboot,配置的是type-handlers-package

3.在mapper.xml中,對要過濾的欄位進行顯式的type宣告,如:


INSERT INTO table (
    id,
    apply_no,
    cert_id,
    customer_name,
    app_remark,
    pc_remark
) VALUES (
    #{id},
    #{applyNo},
    #{certId},
    #{customerName, jdbcType=VARCHAR},
    #{appRemark, jdbcType=VARCHAR},
    #{pcRemark, jdbcType=VARCHAR}
)