如何把Mybatis中的BLOB类型转换成String

第一步:实现数据类型转换类,该类继承BaseTypeHandle抽象类
import java.io.ByteArrayInputStream;
import java.io.UnsupportedEncodingException;
import java.sql.Blob;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.log4j.Logger;

public class BlobTypeHandle extends BaseTypeHandler<String>{

	  private static final Logger log = Logger.getLogger(BlobTypeHandle.class); 
	    // 指定字符集  
	    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;  
	        String result = null;  
	        if (null != blob)  
	        {  
	            returnValue = blob.getBytes(1, (int) blob.length());  
	        }  
	        try  
	        {  
	            if (null != returnValue)  
	            {  
	                // 把byte转化成string  
	                result = new String(returnValue, DEFAULT_CHARSET);  
	            }  
	        } catch (UnsupportedEncodingException e)  
	        {  
	            throw new RuntimeException("Blob Encoding Error!");  
	        }  
	        return result;  
	    }  
	  
	    @Override  
	    public String getNullableResult(CallableStatement cs, int columnIndex)  
	            throws SQLException  
	    {  
	        Blob blob = cs.getBlob(columnIndex);  
	        byte[] returnValue = null;  
	        String result = null;  
	        if (null != blob)  
	        {  
	            returnValue = blob.getBytes(1, (int) blob.length());  
	        }  
	        try  
	        {  
	            if (null != returnValue)  
	            {  
	                result = new String(returnValue, DEFAULT_CHARSET);  
	            }  
	        } catch (UnsupportedEncodingException e)  
	        {  
	            throw new RuntimeException("Blob Encoding Error!");  
	        }  
	        return result;  
	    }  
	  
	    /** 
	     * @Description: 
	     *  
	     * @param arg0 
	     * @param arg1 
	     * @return 
	     * @throws SQLException 
	     *  
	     * @see org.apache.ibatis.type.BaseTypeHandler#getNullableResult(java.sql.ResultSet, 
	     *      int) 
	     *  
	     */  
	  
	    @Override  
	    public String getNullableResult(ResultSet rs, int columnName)  
	            throws SQLException  
	    {  
	        log.debug("enter function");  
	        String result = null;  
	        Blob blob = rs.getBlob(columnName);  
	        byte[] returnValue = null;  
	        if (null != blob)  
	        {  
	            returnValue = blob.getBytes(1, (int) blob.length());  
	        }  
	        try  
	        {  
	            // 把byte转化成string  
	            if (null != returnValue)  
	            {  
	                result = new String(returnValue, DEFAULT_CHARSET);  
	            }  
	        } catch (UnsupportedEncodingException e)  
	        {  
	            throw new RuntimeException("Blob Encoding Error!");  
	        }  
	        log.debug("exit function");  
	        return result;  
	    }
}


第二部:创建一个实体类
import java.util.Date;

public class MsgPushEntity {

//	private Integer mid; //推送信息申请表主键ID
//	
//	private Integer sellerid;//商户ID
//	
//	private Integer msgtype;//消息推送类型:1 消息推送 2 发送短信
	
	private String content;//消息推送内容
	
	private Date pushdate;//推送时间
	
	private String pushobj;//全部:0; 高频次:1;中频次:2;低频次:3;一些天未消费:4;高消费:5;中消费:6;低消费:7;其他客户:8(老客户);店铺新客户:9;角色A:10;角色B:11;角色C:12:角色D:13
	
	private Date applytime;//申请时间
	
	private String status;//审核状态:0 待审核 1 审核通过 2 审核不通过
	
//	private String reason;//审核不通过理由
//	
//	private Date edate;//审核时间
	
//	public Integer getMid() {
//		return mid;
//	}
//	public void setMid(Integer mid) {
//		this.mid = mid;
//	}
//	public Integer getSellerid() {
//		return sellerid;
//	}
//	public void setSellerid(Integer sellerid) {
//		this.sellerid = sellerid;
//	}
//	public Integer getMsgtype() {
//		return msgtype;
//	}
//	public void setMsgtype(Integer msgtype) {
//		this.msgtype = msgtype;
//	}
	
	public Date getPushdate() {
		return pushdate;
	}
	public String getContent() {
		return content;
	}
	public void setContent(String content) {
		this.content = content;
	}
	public void setPushdate(Date pushdate) {
		this.pushdate = pushdate;
	}
	public String getPushobj() {
		return pushobj;
	}
	public void setPushobj(String pushobj) {
		this.pushobj = pushobj;
	}
	public Date getApplytime() {
		return applytime;
	}
	public void setApplytime(Date applytime) {
		this.applytime = applytime;
	}
	public String getStatus() {
		return status;
	}
	public void setStatus(String status) {
		this.status = status;
	}

//	public String getReason() {
//		return reason;
//	}
//	public void setReason(String reason) {
//		this.reason = reason;
//	}
//	public Date getEdate() {
//		return edate;
//	}
//	public void setEdate(Date edate) {
//		this.edate = edate;
//	}

第三部:配置mybatis sql文件
<resultMap id="MsgPushEntity"  type="com.xmniao.xmn.core.manage.entity.MsgPushEntity" >
		<result column="content" property="content"  typeHandler="com.xmniao.xmn.core.manage.service.BlobTypeHandle"/>		
		<result column="push_date" property="pushdate" jdbcType="DATE"/>
		<result column="push_object" property="pushobj" jdbcType="VARCHAR"/>
		<result column="apply_time" property="applytime" jdbcType="DATE"/>
		<result column="status" property="status" jdbcType="VARCHAR"/>
	</resultMap>
<select id="queryMsgApplyList" parameterType="map" resultMap="MsgPushEntity">
		SELECT content,
		date_format(push_date,'%Y-%m-%d %H:%i:%s') pushdate,
		push_object pushobj,
		date_format(apply_time,'%Y-%m-%d %H:%i:%s') applytime,
		case status when 0 then '待审核' when 1 then '已推送' else '已拒绝' end status
		from t_msg_push_apply 
		where sellerid = #{sellerid} 
		and msg_type = #{msgType} 
		<if test="status != null">
			and `status` != #{status}
		</if>
		order by mid desc
	</select>

第四部:实现类
	public Object pushMessageLogs(TypeRequest typeRequest){
		try {
			Map<Object,Object> paramMap =  new HashMap<>();
			paramMap.put("sellerid", typeRequest.getSellerid());
			paramMap.put("msgType", typeRequest.getType());
			List<MsgPushEntity> resultList =  pushMessageDao.queryMsgApplyList(paramMap);
			List<Map<Object,Object>> pushlist = new ArrayList<Map<Object,Object>>();    
			MsgPushEntity mpe = new MsgPushEntity();
			for(int i=0; i<resultList.size(); i++){
				Map<Object,Object> map = new HashMap<Object,Object>();
				mpe = resultList.get(i);
				String content = mpe.getContent();
				map.put("content", content);
				map.put("pushtime", mpe.getPushdate());
				map.put("pushobject", mpe.getPushobj());
				map.put("applytime", mpe.getApplytime());
				map.put("pushstatus", mpe.getStatus());
				pushlist.add(map);
			}
			Map<Object, Object> resultResponse = new HashMap<Object, Object>();
			resultResponse.put("pushlogs", pushlist);
			MapResponse response =  new MapResponse(ResponseCode.SUCCESS, "提交成功");
			response.setResponse(resultResponse);
			return  response;
		} catch (Exception e) {
			e.printStackTrace();
			return new BaseResponse(ResponseCode.FAILURE, "获取消息推送历史记录失败");
		}
	}
	

猜你喜欢

转载自kacherylau.iteye.com/blog/2298004