mapper.xml中java
設置Blob字段sql
<result property="tibetan_info" column="tibetan_info" typeHandler="com.surfilter.utils.ConvertBlobTypeHandler"/>apache
ConvertBlobTypeHandler.javamybatis
package com.surfilter.utils;app
import java.io.ByteArrayInputStream; ide
import java.io.UnsupportedEncodingException; .net
import java.sql.Blob; xml
import java.sql.CallableStatement; utf-8
import java.sql.PreparedStatement; get
import java.sql.ResultSet;
import java.sql.SQLException;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
/**
* className:ConvertBlobTypeHandler
*
* 自定義typehandler,解決mybatis存儲blob字段後,出現亂碼的問題
* 配置mapper.xml:
* <result typeHandler="cn.ffcs.drive.common.util.ConvertBlobTypeHandler"/>
*
* @author pengyh
* @version 1.0.0
* @date 2014-07-09 11:15:23
*
*/
public class ConvertBlobTypeHandler extends BaseTypeHandler<String> {
//###指定字符集
private static final String DEFAULT_CHARSET = "utf-8";
@Override
public void setNonNullParameter(PreparedStatement ps, int i,
String parameter, JdbcType jdbcType) throws SQLException {
ByteArrayInputStream bis;
try {
//###把String轉化成byte流
bis = new ByteArrayInputStream(parameter.getBytes(DEFAULT_CHARSET));
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("Blob Encoding Error!");
}
ps.setBinaryStream(i, bis, parameter.length());
}
@Override
public String getNullableResult(ResultSet rs, String columnName)
throws SQLException {
Blob blob = rs.getBlob(columnName);
byte[] returnValue = null;
if (null != blob) {
returnValue = blob.getBytes(1, (int) blob.length());
}
try {
//###把byte轉化成string
return new String(returnValue, DEFAULT_CHARSET);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("Blob Encoding Error!");
}
}
@Override
public String getNullableResult(CallableStatement cs, int columnIndex)
throws SQLException {
Blob blob = cs.getBlob(columnIndex);
byte[] returnValue = null;
if (null != blob) {
returnValue = blob.getBytes(1, (int) blob.length());
}
try {
return new String(returnValue, DEFAULT_CHARSET);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("Blob Encoding Error!");
}
}
@Override
public String getNullableResult(ResultSet arg0, int arg1)
throws SQLException {
// TODO Auto-generated method stub
return null;
}
}