[英]How to convert a blob from db to a List<Object> in java
All I'm trying to do is to convert my java List to BLOB and vice-versa. 我要做的就是将java列表转换为BLOB,反之亦然。 I have successfully done the first part where I have converted my List and stored it as BLOB in DB. 我已经成功完成了第一部分,在该部分中我已转换了List并将其作为BLOB存储在DB中。 However, I'm to get the BLOB but unable to convert it back to List. 但是,我要获取BLOB,但无法将其转换回List。 I have tried searching at many places but not able to figure out a way to solve this problem I'm facing. 我曾尝试在许多地方搜索,但无法找到解决我所面临的问题的方法。 Hope I'll get a solution here. 希望我能在这里找到解决方案。
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();
1) 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();
This attempt has given me empty list 这次尝试给了我一个空的清单
2) 2)
Stream<T> stream = (Stream<T>) rs.getBinaryStream("CUSTOMERS_LIST");
List<CustomerDTO> list = (List<CustomerDTO>) stream.collect(Collectors.toList());
This attempt thrown me error java.lang.ClassCastException: java.io.ByteArrayInputStream cannot be cast to java.util.stream.Stream
此尝试引发我错误java.lang.ClassCastException: java.io.ByteArrayInputStream cannot be cast to java.util.stream.Stream
3) 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());
I'm lost here as I don't get how to convert List<Integer>
to List<CustomerDTO>
我在这里迷路了,因为我不知道如何将List<Integer>
转换为List<CustomerDTO>
Looking forward for your help.. TIA! 期待您的帮助.. TIA!
I have modified your first attempt slightly as follows: 我对您的第一次尝试做了如下修改:
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));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.