用于在Java JPA中序列化对象的包装器

时间:2015-04-28 23:33:15

标签: java jpa

我想在Java中保留Object。经过一些研究,我发现这可以使用包装类来完成。

这就是我想出的:

public class ObjectWrapper implements Serializable {
    private static final long serialVersionUID = -343767114791490410L;
    private ObjectWrapper object;

  public ObjectWrapper(Object object) {

        this.object = (ObjectWrapper) object;
        try {
            serialize(object);
        } catch (NotSerializableException e) {
            e.printStackTrace();
        }

   }

  private byte[] serialize(Object object) throws NotSerializableException {

    try {
        // Serialize data object to a file
        ObjectOutputStream out = new ObjectOutputStream(
                new FileOutputStream("object.ser"));
        out.writeObject(object);
        out.close();

        // Serialize data object to a byte array
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        out = new ObjectOutputStream(bos);
        out.writeObject(object);
        out.close();

        // Get the bytes of the serialized object
        byte[] buf = bos.toByteArray();

        return buf;

    } catch (IOException e) {
        throw new NotSerializableException("Error serializing the object!");
    }
  }

  public ObjectWrapper getObject() throws NotSerializableException,
        ClassNotFoundException {
    try {
        FileInputStream in = new FileInputStream("object.ser");
        ObjectInputStream reader = new ObjectInputStream(in);
        ObjectWrapper x = new ObjectWrapper(object);
        x = (ObjectWrapper) reader.readObject();
        reader.close();
        return x;

    } catch (IOException e) {
        throw new NotSerializableException("Error serializing the object!");
    }

  }

}

由于我正在学习JPA,我的问题是:这是解决这个问题的正确方法吗?这个包装类可以简化吗?我发现首先将对象序列化为文件有点奇怪。这真的有必要吗?

1 个答案:

答案 0 :(得分:2)

JPA它在不同ORM之上的抽象。因此,它的主要目标是对象关系映射。在您的情况下,您只需将对象保存为字节数组,而不在任何关系模型上进行映射(在数据库含义中)。 在一般的序列化和JPA / ORM中,它具有不同目标的不同任务。 如果要在关系数据库中保留对象,可以将其作为BLOB保存在某个表的一列中。

@Entity
public class ObjectWrapper {

    @Id
    @GeneratedValue(strategy= GenerationType.AUTO)
    private Long objectId;

    @Lob
    private Serializable object;

    public Long getObjectId() {
        return objectId;
    }

    public void setObjectId(Long objectId) {
        this.objectId = objectId;
    }

    public Serializable getObject() {
        return object;
    }

    public void setObject(Serializable object) {
        this.object = object;
    }
}
相关问题