0

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

1 Answer 1

2

MongoDB implicitly store (I think) byte array as Bson BinData.

Note that you yourself set the objectData to a byte array:

cacheBean.setObjectData(getBytesForObject(o));

At that point private Object objectData; is of type byte[]

So there is nothing preventing you from declaring this in CacheBean:

private byte[] objectData;

And therefore...

ByteArrayInputStream b = new ByteArrayInputStream(cacheBean.getObjectData());
ObjectInputStream o = new ObjectInputStream(b);
return o.readObject();

For convenience, you may also want to store the object class as a field.

Sign up to request clarification or add additional context in comments.

1 Comment

I actually used the same idea but I stored objectData as org.bson.types.Binary instead of byte[]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.