将对象存为数据库二进制数据的处理方法
Oracle数据库对应字段BLOB类型,实体对应字节数组类型(byte[]、@Type(type="org.springframework.orm.hibernate3.support.BlobByteArrayType"))。
一、存
1、把数据列表(List<Object>),放入Map<String,Object>中;
2、将Map对象转换为字节数据set到实体中
二、取
1、从实体中取出字节数组转化对象,然后强制转化为Map类型,用get(Object key)拿到存储在Map中的对象,最后转化为List就 Ok啦。。。
entity: @Column(name = "JOB_DATA") @Type(type="org.springframework.orm.hibernate3.support.BlobByteArrayType") private byte[] jobData; save: List<AcmsInternetgatewaydevice> jobs = CollectUtils.newArrayList(); if (StringUtils.isNotEmpty(deviceIds)) { jobs = acmsInternetgatewaydeviceService.getAcmsInternetgatewaydevicesByDeviceIds(StrUtils.splitToLong(deviceIds)); } Map<String, Object> jobNes = new HashMap<String, Object>(); jobNes.put(JobUtils.NE_KEY, jobs); entity.setJobData(Bytes.objct2Bytes(jobNes)); get: List<AcmsInternetgatewaydevice> selectNes = null; if(jobData!=null) selectNes = (List<AcmsInternetgatewaydevice>) ((Map<String,Object>)Bytes.bytes2Objct(jobData)).get(JobUtils.NE_KEY); JobUtils: public class JobUtils { public static final String QUARTS_SCHEDULER_KEY = "quartzScheduler"; public static final String NE_KEY = "JOB_NES"; } Bytes: package com.gloryscience.util; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.sql.Blob; import java.sql.SQLException; public class Bytes { /** * 由于String.subString对汉字处理存在问题(把一个汉字视为一个字节),因此在 包含汉字的字符串时存在隐患,现调整如下: * * @param src 要截取的字符串 * @param start_idx 开始坐标(包括该坐标) * @param end_idx 截止坐标(包括该坐标) * @return */ public static String substring(String src, int start_idx, int end_idx) { byte[] b = src.getBytes(); String tgt = ""; for (int i = start_idx; i <= end_idx; i++) { tgt += (char) b[i]; } return tgt; } public static byte[] objct2Bytes(java.lang.Object obj) { if(obj == null){ return null; }else{ ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); try { ObjectOutputStream ops = new ObjectOutputStream( byteArrayOutputStream); ops.writeObject(obj); byte[] byteA = byteArrayOutputStream.toByteArray(); return byteA; } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } } return null; } public static java.lang.Object bytes2Objct(byte[] byteA) { InputStream in = new ByteArrayInputStream(byteA); ObjectInputStream ois = null; try { ois = new ObjectInputStream(in); } catch (IOException e) { e.printStackTrace(); } try { return ois.readObject(); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } return null; } public static java.lang.Object blobToObjct(Blob blob) { ObjectInputStream ois = null; try { InputStream in = blob.getBinaryStream(); ois = new ObjectInputStream(in); return ois.readObject(); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } return null; } }