I have a bean that includes a Java object that is stored as binary data in Mongo DB. Introducing SpringData for mapping gave me the problem. So, the Bean code is:
@Document(collection = “cache”)
public class CacheBean {
...
private Object objectData;
...
}
The insertion code to Mongo Db is:
protected void setToMongo(String key, Object value){
ByteArrayOutputStream b = new ByteArrayOutputStream();
ObjectOutputStream o = new ObjectOutputStream(b);
o.writeObject(value);
CacheBean cacheBean = new CacheBean();
cacheBean.setObjectData(getBytesForObject(o));
mongoTemplate.save(cacheBean);
}
private byte[] getBytesForObject(Object o) throws IOException{
ByteArrayOutputStream b = new ByteArrayOutputStream();
ObjectOutputStream os = new ObjectOutputStream(b);
os.writeObject(o);
return b.toByteArray();
}
The extraction code is as follows:
Object resultObject = cacheBean.getObjectData();
org.bson.types.Binary result = (Binary) resultObject;
ByteArrayInputStream b = new ByteArrayInputStream(result.getData());
ObjectInputStream o = new ObjectInputStream(b);
return o.readObject();
I am getting the exception on the line
org.bson.types.Binary result = (Binary) resultObject:
java.lang.ClassCastException: [B cannot be cast to org.bson.types.Binary