如何在Java中将Blob从db转换为List <object>

时间:2018-11-12 05:06:56

标签: java java-8

我要做的就是将java列表转换为BLOB,反之亦然。我已经成功完成了第一部分,在该部分中我已转换了List并将其作为BLOB存储在DB中。但是,我要获取BLOB,但无法将其转换回List。我曾尝试在许多地方搜索,但无法找到解决我所面临的问题的方法。希望我能在这里找到解决方案。

转换列表并将其作为BLOB存储在DB中:

List<CustomerDTO> customersList = new ArrayList<CustomerDTO>();
.
.
some code to store the data in to List<CustomerDTO>
.
.

ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(customersList);
byte[] bytes = baos.toByteArray();

// set parameters  
    pstmt.setBinaryStream(1, new ByteArrayInputStream(bytes));
    pstmt.executeUpdate();

尝试将BLOB转换为列表失败:

1)

Blob blob = rs.getBlob("CUSTOMERS_LIST");   
byte[] bdata = blob.getBytes(1, (int) blob.length());
ByteArrayInputStream bais = new ByteArrayInputStream(bdata);
ObjectInputStream ois = new ObjectInputStream(bais);

List<CustomerDTO> list = (ArrayList<CustomerDTO>) ois.readObject();

这次尝试给了我一个空列表

2)

Stream<T> stream = (Stream<T>) rs.getBinaryStream("CUSTOMERS_LIST");
List<CustomerDTO> list = (List<CustomerDTO>) stream.collect(Collectors.toList());

此尝试引发了错误java.lang.ClassCastException: java.io.ByteArrayInputStream cannot be cast to java.util.stream.Stream

3)

IntStream bais = (IntStream) rs.getBinaryStream("CUSTOMERS_LIST");
Stream<Integer> stream = (Stream<Integer>) bais.boxed().collect(Collectors.toList());
List<Integer> ll = (List<Integer>)stream.collect(Collectors.toList());

我在这里迷路了,因为我不知道如何将List<Integer>转换为List<CustomerDTO>

期待您的帮助。TIA!

1 个答案:

答案 0 :(得分:-1)

我对您的第一次尝试做了如下修改:

Blob blob = rs.getBlob("CUSTOMERS_LIST");   
byte[] bdata = blob.getBytes(1, (int) blob.length());
ArrayList<Object> arraylist = new ArrayList<>();
for(byte b : bdata) {
    arraylist.add(new Byte(b));
}