Mybatis 的 TypeHandler 加解密
1、编写一个实体类,凡是此实体类的数据都表示需要加解密的
@Data
@AllArgsConstructor
public class Encrypt {
private String value;
}
2、编写一个加解密的TypeHandler
/** * 加解密TypeHandler */ @MappedJdbcTypes(JdbcType.VARCHAR) @MappedTypes(Encrypt.class) public class EncryptTypeHandler extends BaseTypeHandler{ private static final byte[] KEYS = "12345678abcdefgh".getBytes(StandardCharsets.UTF_8); /** * 设置参数 */ @Override public void setNonNullParameter(PreparedStatement ps, int i, Encrypt parameter, JdbcType jdbcType) throws SQLException { if (parameter == null || parameter.getValue() == null) { ps.setString(i, null); return; } AES aes = SecureUtil.aes(KEYS); String encrypt = aes.encryptHex(parameter.getValue()); ps.setString(i, encrypt); } /** * 获取值 */ @Override public Encrypt getNullableResult(ResultSet rs, String columnName) throws SQLException { return decrypt(rs.getString(columnName)); } /** * 获取值 */ @Override public Encrypt getNullableResult(ResultSet rs, int columnIndex) throws SQLException { return decrypt(rs.getString(columnIndex)); } /** * 获取值 */ @Override public Encrypt getNullableResult(CallableStatement cs, int columnIndex) throws SQLException { return decrypt(cs.getString(columnIndex)); } public Encrypt decrypt(String value) { if (null == value) { return null; } return new Encrypt(SecureUtil.aes(KEYS).decryptStr(value)); } }
-
@MappedTypes:表示该处理器处理的java类型是什么。 -
@MappedJdbcTypes:表示处理器处理的Jdbc类型。
3、sql语句中写法
<?xml version="1.0" encoding="UTF-8"?>insert into customer(phone, address) values (#{phone}, #{address})
SQL中没有什么特殊的写法。
4、配置文件中指定Typehandler的包路径
mybatis: type-handlers-package: com.xc.xcspringboot.typehandler
5、编写后台代码
@RestController
public class CustomerController {
@Autowired
private CustomerMapper customerMapper;
@ApiOperation(value = "addCustomer", notes = "")
@GetMapping("addCustomer")
public String addCustomer(@RequestParam("phone") String phone, @RequestParam("address") String address) {
int result = customerMapper.addCustomer(new Encrypt(phone), address);
return "添加结果: " + result;
}
@ApiOperation(value = "findCustomer", notes = "")
@GetMapping("findCustomer")
public Customer findCustomer(@RequestParam("phone") String phone) {
return customerMapper.findCustomer(new Encrypt(phone));
}
}
文章来源:https://juejin.cn/post/6963811586184052767