需求场景:当数据库中保存的部分数据需要加密,页面需要正常显示时。这是就需要我们自定义类型转换器,在Mybatis执行SQL得到结果时,通过自定义类型转换器将CHAR或者VARCHAR2进行加解密处理,Java代码如下:
public class CryptTypeHandler implements TypeHandler{ public CryptType getResult(ResultSet rs, String columnName) throws SQLException { String value=""; CryptType v=new CryptType(value); value=rs.getString(columnName); if(value!=null){ value=decrypt(value.toString()); v.setValue(value); } return v; } public CryptType getResult(ResultSet rs, int columnIndex) throws SQLException { String value=""; CryptType v=new CryptType(value); value =rs.getString(columnIndex); if(value!=null){ v.setValue(value); } return v; } public CryptType getResult(CallableStatement cs, int columnIndex) throws SQLException { String value=""; CryptType v=new CryptType(); value =cs.getString(columnIndex); if(value!=null){ v.setValue(value); } return v; } public void setParameter(PreparedStatement ps, int i, CryptType parameter, JdbcType arg3) throws SQLException { String value=""; if(parameter!=null && parameter.toString()!=null){ value=encrypt(parameter.toString()); } ps.setString(i, value.toString()); } private String encrypt(String value) { value=CryptUtils.encrypt(value); return value; } private String decrypt(String value){ value=CryptUtils.decrypt(value); return value; } }
自定义类型
import java.io.Serializable; public class MyString implements Serializable, CharSequence, Comparable{ private static final long serialVersionUID = 1L; private String value; public MyString (){ } public CryptType(String value){ this.value=value; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public int compareTo(String arg0) { // TODO Auto-generated method stub return 0; } public char charAt(int arg0) { // TODO Auto-generated method stub return 0; } public int length() { // TODO Auto-generated method stub return 0; } public CharSequence subSequence(int arg0, int arg1) { // TODO Auto-generated method stub return null; } @Override public String toString() { return value; } }
mybatis自定义类型配置
实体中使用
public class LoanEnterprise{
private MyString name;
//注意:
//如果页面有查询条件也被加密时,mybatis sql中的条件判断会无法匹配,暂时的一种解决办法是在
public CryptType getName() {
if(name!=null && name.getValue().equals("")){
return null;
}else {
return name;
}
}
public void setName(CryptType name) {
this.name = name;
}
}
以上所述是小编给大家介绍的MyBatis自定义类型转换器实现加解密,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对考高分网网站的支持!



