ibatis TypeHandler

在sqlMapConfig.xml中定义,对于所有类型为String 的字符串都进行转码

<typeAlias type="gov.tax.wfwz.ibatis.EncodeTypeHandler" alias="ENCODE"/>
	<!-- 全局配置,DTO中所有的String都会转码 -->
<typeHandler callback="ENCODE" javaType="java.lang.String"/>

 TypeHandlerCallback的定义

public interface TypeHandlerCallback {
  public void setParameter(ParameterSetter setter, Object parameter)
      throws SQLException;
  public Object getResult(ResultGetter getter)
      throws SQLException;
  public Object valueOf(String s);
}

 对于自己的TypeHandler必须实现TypeHandlerCallback 接口

public class EncodeTypeHandler implements TypeHandlerCallback{    

	public Object getResult(ResultGetter getter) throws SQLException {    
		String str = null;    
		if (getter.getString() != null) {
			try {    
				str = new String(getter.getString().getBytes("ISO-8859-1"), "GBK");    
			} catch (UnsupportedEncodingException e) {    
				LogSupport.getErrorLogger().error("编码转换失败!",e);
				str = getter.getString();    
			}    
		}
		return str;    
	}    

	public void setParameter(ParameterSetter setter, Object parameter) throws SQLException {  
		String str = null;    
		if (parameter != null) {
			try {    
				str = new String(((String)parameter).getBytes("GBK"), "ISO-8859-1");    
			} catch (UnsupportedEncodingException e) {    
				LogSupport.getErrorLogger().error("编码转换失败!",e);    
				str = (String)parameter;    
			}    
		}
		setter.setString(str);    
	}   

	public Object valueOf(String s) {    
		return s;    
	}    
}

 

你可能感兴趣的:(xml,ibatis,Blog)