如何在SpringData MongoDb Java bean中映射二进制数据?
我有一个bean,它包含一个Java对象,该对象作为二进制数据存储在MongoDB中。 引入SpringData进行映射给了我这个问题。 因此,Bean代码是:如何在SpringData MongoDb Java bean中映射二进制数据?,java,spring,mongodb,Java,Spring,Mongodb,我有一个bean,它包含一个Java对象,该对象作为二进制数据存储在MongoDB中。 引入SpringData进行映射给了我这个问题。 因此,Bean代码是: @Document(collection = “cache”) public class CacheBean { ... private Object objectData; ... } Mongo Db的插入代码为: protected void setToMongo(String key, Object
@Document(collection = “cache”)
public class CacheBean {
...
private Object objectData;
...
}
Mongo Db的插入代码为:
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();
}
提取代码如下所示:
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();
我在电话里遇到了一个例外
org.bson.types.Binary result = (Binary) resultObject:
java.lang.ClassCastException:[B不能强制转换为org.bson.types.BinaryMongoDB隐式存储(我认为)字节数组为bson BinData
请注意,您自己将objectData设置为字节数组:
cacheBean.setObjectData(getBytesForObject(o));
此时,private objectData;
的类型为byte[]
因此,没有什么可以阻止您在CacheBean
中声明这一点:
private byte[] objectData;
因此
ByteArrayInputStream b = new ByteArrayInputStream(cacheBean.getObjectData());
ObjectInputStream o = new ObjectInputStream(b);
return o.readObject();
为方便起见,您可能还希望将对象类存储为字段。我实际上使用了相同的想法,但我将对象数据存储为org.bson.types.Binary,而不是byte[]