对某个通用字段进行加解密或者是脱敏处理
作者:想要飞的猪
- 2024-04-13 广东
本文字数:1563 字
阅读完需:约 5 分钟
根据 mybatis 的 TypeHandler 进行对字段进行插入前与查询后进行相关处理 1、 创建 handler 类实现接口 TypeHandler,并实现相关方法
/** * 根据typehandler 进行字段的 加密 或者是脱敏处理 */ @MappedJdbcTypes(JdbcType.VARCHAR) public class MybatisAESHandler implements TypeHandler<String> { /** * 表示插入数据库之间进行的操作(可以进行加密或者是模糊处理) * @param parameter * @param jdbcType * @throws SQLException */ @Override public void setParameter(PreparedStatement ps, int i, String parameter, JdbcType jdbcType) throws SQLException { if (parameter != null){ String nParameter = Base62.encode(parameter); // String nParameter = Base62.decode(parameter); ps.setString(i,nParameter); } } /*** * 根据列名称来获取数据时 * @param resultSet * @param s * @return * @throws SQLException */ @Override public String getResult(ResultSet resultSet, String columnName) throws SQLException { String result = resultSet.getString(columnName); // 可以在此进行 脱敏处理 或者是解密等等 return result == null?null:Base62.decodeStr(result); } /*** * 根据列索引来获取数据时 * @param resultSet * @param * @return * @throws SQLException */ @Override public String getResult(ResultSet resultSet, int i) throws SQLException { String result = resultSet.getString(i); // 可以在此进行 脱敏处理 或者是解密等等 return result == null?null:Base62.decodeStr(result); } /** * 针对 CallableStatement 根据列索引获取数据时 * @param callableStatement * @param i * @return * @throws SQLException */ @Override public String getResult(CallableStatement callableStatement, int i) throws SQLException { String result = callableStatement.getString(i); // 可以在此进行 脱敏处理 或者是解密等等 return result == null?null:Base62.decodeStr(result); } }
复制代码
2、编写对应的 xml(以 email 为列,查询结果要用 resultMap 映射,特别注意 autoMapping=true 是关键)
<resultMap id="user" type="com.yfzb.test.entity.User" autoMapping="true"> <result typeHandler="com.yfzb.commom.handler.MybatisAESHandler" column="email" property="email"></result> </resultMap> <select id="selectAll" resultMap="user"> select * from user where id > 99; </select>
复制代码
3、利用 mybatis-plus 相关注解实现(同样 autoResultMap = true 也是必须的),在需要处理的字段上加入 typeHandler 就可以实现相应的逻辑
@Data @TableName(value = "cust",autoResultMap = true) public class User implements Serializable { private static final long serialVersionUID = 1L; /** * 主键ID */ private Long id; /** * 邮箱 */ @TableField(typeHandler = MybatisAESHandler.class) private String email; /** * 姓名 */ private String name; /** * 年龄 */ private Integer age; }
复制代码
划线
评论
复制
发布于: 2024-04-13阅读数: 4
想要飞的猪
关注
还未添加个人签名 2020-06-05 加入
还未添加个人简介







评论