如何把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, "获取消息推送历史记录失败");
}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
MyBatis提供了Blob类型的支持,可以将二进制数据(如图片)存储到Oracle的Blob字段。 首先,在Mapper.xml定义一个insert语句,如下所示: ``` <insert id="insertImage" parameterType="Map"> INSERT INTO image_table(id, image) VALUES(#{id}, #{image,jdbcType=BLOB}) </insert> ``` 其,#{image,jdbcType=BLOB}表示将image属性映射到数据库BLOB字段。 然后,在Java代码,将图片转换字节数组,再将字节数组封装到一个Map,作为参数调用insertImage方法,如下所示: ``` byte[] imageBytes = Files.readAllBytes(Paths.get("path/to/image.png")); Map<String, Object> paramMap = new HashMap<>(); paramMap.put("id", 1); paramMap.put("image", imageBytes); mapper.insertImage(paramMap); ``` 以上代码将读取一个PNG格式的图片文件,将其转换字节数组,然后将字节数组封装到一个Map,作为参数调用insertImage方法,将图片存储到数据库。 查询Blob类型的数据时,可以使用MyBatis提供的ResultHandler接口来处理Blob类型的数据,如下所示: ``` public class ImageResultHandler implements ResultHandler { @Override public void handleResult(ResultContext context) { ImageEntity entity = (ImageEntity) context.getResultObject(); Blob blob = entity.getImage(); byte[] bytes = null; try (InputStream inputStream = blob.getBinaryStream()) { bytes = IOUtils.toByteArray(inputStream); } catch (SQLException | IOException e) { e.printStackTrace(); } entity.setImageBytes(bytes); } } public interface ImageMapper { @Select("SELECT id, image FROM image_table WHERE id=#{id}") @ResultType(ImageEntity.class) void getImage(long id, ResultHandler handler); } ``` 以上代码定义了一个ImageResultHandler类,实现了ResultHandler接口,用于处理查询结果Blob类型数据。在调用ImageMapper的getImage方法时,将ImageResultHandler实例作为参数传入,MyBatis会自动调用ImageResultHandler的handleResult方法,将查询结果封装ImageEntity实例。 在ImageEntity类,可以定义一个byte[]类型的属性,用于存储从Blob字段读取的字节数组。这样,查询到的图片数据就可以直接使用了。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值