Blob的反序列化无效

时间:2017-09-19 15:13:06

标签: java postgresql deserialization blob

List<List<String>>在postgres-db中作为byte[](Blob)保留。但是,反序列化不起作用。没有抛出异常,但列表的大小始终为零。

List<List<String>>转换为byte[],然后在保留之前设置为MyBlobEntity。然后从数据库中检索实体,并将byte[]转换回List<List<String>>。我通过从List转换为字节数组并返回List来测试单元测试中的转换器。这似乎工作正常。

实体

@Entity(name = "MyBlobEntity")
@Table(name = "t_my_blob")
@SequenceGenerator(name = "BlobIdGenerator", allocationSize = 1, sequenceName = "sq_blob_id")
public class MyBlobEntity {

  @Id
  @Column(name = "blob_id", nullable = false)
  @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "BlobIdGenerator")
  private Long internalId;

  @Column(nullable = false)
  private String filename;

  @Lob
  @Basic
  @Column(nullable = false, columnDefinition="BLOB NOT NULL")
  private byte[] data;

  public Long getInternalId() {
    return internalId;
  }

  public void setInternalId(final Long internalId) {
    this.internalId = internalId;
  }

  public String getFilename() {
    return filename;
  }

  public void setFilename(final String filename) {
    this.filename = filename;
  }

  public byte[] getData() {
    return data;
  }

  public void setData(final byte[] data) {
    this.data = data;
  }
}

转换器

public class MyBlobConverter {

  public byte[] convert(final List<List<String>> lines) {
    final ByteArrayOutputStream bos = new ByteArrayOutputStream();
    byte[] data = null;
    try {
      final ObjectOutputStream oos = new ObjectOutputStream(bos);
      oos.writeObject(lines);
      oos.flush();
      data = bos.toByteArray();
      oos.close();
      bos.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
    return data;
  }

  public List<List<String>> convert(final byte[] data) {
    final ByteArrayInputStream bis = new ByteArrayInputStream(data);
    List<List<String>> lines = null;
    try {
      final ObjectInputStream ois = new ObjectInputStream(bis);
      lines = (List<List<String>>) ois.readObject();
      ois.close();
      bis.close();
    } catch (IOException | ClassNotFoundException e) {
      e.printStackTrace();
    }
    return lines;
  }

}

该表是使用

创建的
create table t_my_blob(
    blob_id numeric(38) NOT NULL,
    filename varchar(255) not NULL,
    data bytea not null
);

0 个答案:

没有答案