Blob与bytes、Object的转换

因为自定义sql项目使用jdbcTemplate.queryForList查询返回了List<Map<String, Object>>集合,其中有字段在数据库中对应的是Blob类型,但是集合中获取到的是Object类型,必须转换为Blob类型。因为项目中使用了Hibernate,刚开始便用Object.toString().getBytes()的方法将Object转为byte[],然后调用Hibernate.createBlob(byte[])方法转为blob,存入数据库。后来发现,在Object类的toString()方法默认返回该对象实现类的“类名+@+hashcode”值,直到后边blob中存储的都是“类名+@+hashcode”,如此转换必不可取!
debugger查看List中Blob字段对应的Object,发现可以直接转为byte[]类型,简单解决上述困扰!
代码如下:

byte[] blobBytes = (byte[]) wqhtList.get(i).get("cgxx");
if(blobBytes!=null){
	tpuZjgh.setCgxx(Hibernate.createBlob(blobBytes));
}else {
    tpuZjgh.setCgxx(null);
}

解决问题过程中也百度到Blob转换的一些方法,记下来希望以后可以用得到:

public byte[] objectToBytesArray(Object o){//Object转换为byte数组
	byte[] bytes = null;
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    try {
    	ObjectOutputStream out = new ObjectOutputStream(bos);
        out.writeObject(o);
        out.flush();
        bytes = bos.toByteArray();
        out.close();
        bos.close();
    } catch (IOException e) {
         e.printStackTrace();
    }
	return bytes;
}

public byte[] blobToByte(Blob blob) {//Blob转化为Byte数组类型
    BufferedInputStream is = null;
    try {
        is = new BufferedInputStream(blob.getBinaryStream());
        byte[] bytes = new byte[(int) blob.length()];
        int len = bytes.length;
        int offset = 0;
        int read = 0;
        while (offset < len && (read = is.read(bytes, offset, len - offset)) >= 0) {
            offset += read;
        }
        return bytes;
    } catch (Exception e) {
        return null;
    } finally {
        try {
            is.close();
            is = null;
        } catch (IOException e) {
            return null;
        }
    }
}
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值