Alex
Alex

Reputation: 7491

How to map binary data in a SpringData MongoDb Java bean?

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

Upvotes: 0

Views: 5339

Answers (1)

Ori Dar
Ori Dar

Reputation: 19000

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.

Upvotes: 2

Related Questions