我想使用 Ebean ORM 在我的 MySQL 数据库上序列化一个 Java 类。
我的类定义类似于以下内容:
public class Test implements Serializable
{
@Id
private Long id;
...
...
...
@Lob
private MyClass1 obj1;
@Lob
private MyClass2 obj2;
...
...
//getters and setters
}
我的类 MyClass1 和 MyClass2 基本上是一个包装器
float[]
和
Hashmap<String, Float>
并且都实现了 Serializable 接口。
我不想创建一个类:
@Lob
byte[] obj1bytes;
@Transient
MyClass1 obj1Obj;
@Lob
byte[] obj2bytes;
@Transient
MyClass2 obj2Obj;
//getters and setters
我想获得的是自动序列化和反序列化这个类,而不必使用 byte[] 数组将我的测试类中的 obj1 和 obj2 保存到两个 LongBlob 字段中的 MySQL 表中
Ebean.save(testClassInstance);
Ebean.find(Test.class, ID);
EDIT1: MyClass1 定义如下:
public class MyClass1 implements Interface1 {
private float[] vector;
public MyClass1 () {
}
public MyClass1 (float[] vector) {
this.vector = vector;
}
public float[] getVector() {
return vector;
}
public void setVector(float[] vector) {
this.vector = vector;
}
@Override
public byte[] serialize() throws Exception {
ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(byteOut);
out.writeObject(object);
out.close();
return byteOut.toByteArray();
}
@Override
public void deserialize(byte[] bytes) throws Exception {
ByteArrayInputStream byteInt = new ByteArrayInputStream(bytes);
ObjectInputStream out = new ObjectInputStream(byteInt);
vector = (float[])out.readObject();
}
@Override
public float cossim(MyClass1 v) throws Exception {
method logic
}
@Override
public MyClass1 add(MyClass1 v) throws Exception {
method logic
}
}
MyClass2 被定义为 MyClass1,只是我有一个 HashMap < String, Float > () 而不是 float[] 向量。唯一值得注意的区别是 serialize() 和 deserialize():
@Override
public byte[] serialize() throws Exception {
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
DataOutputStream out = new DataOutputStream(outStream);
out.writeInt(map.size());
Iterator<String> iterator = map.keySet().iterator();
while (iterator.hasNext()) {
String key = iterator.next();
out.writeUTF(key);
out.writeFloat(map.get(key));
}
return outStream.toByteArray();
}
@Override
public void deserialize(byte[] bytes) throws Exception {
try {
ByteArrayInputStream inStream = new ByteArrayInputStream(bytes);
DataInputStream in = new DataInputStream(inStream);
this.map = new HashMap<>();
int n = in.readInt();
for (int i = 0; i < n; i++) {
map.put(in.readUTF(), in.readFloat());
}
} catch (Exception ex) {
throw ex;
}
}