问题
i'm using Spring jdbcTemplate and using queryForList(-) method and i want to construct images from eachmap by iterating thourgh list of maps, i've declated datasource and JdbcTemplate and my class beans in spring cfg file but facing issue when trying to construct images form the content in map.
This is my code block
@SuppressWarnings("unchecked")
public void test(){
try {
System.out.println("========Started======");
String query="select image from save_image";
List<Map<String,Object>> li= jdbcTemplate.queryForList(query);
for (Map<String, Object> map : li) {
PreparedStatementCreatorFactory psc = null;
int[] types = {Types.BLOB};
psc = new PreparedStatementCreatorFactory("insert into save_image_2(image) values(?)",types);
jdbcTemplate.update(psc.newPreparedStatementCreator(new Object[]{map.get("image")}));
}
System.out.println("========Ended======");
} catch (DataAccessException e) {
e.printStackTrace();
}
}
public List<Map<String,Object>> getBlobData(){
String query="select image from save_image_2";
return jdbcTemplate.queryForList(query);
}
public static void main(String[] args) throws Throwable {
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("spring-datasource.xml");
TestBlob testBlob = (TestBlob)ctx.getBean("testBlob");
System.out.println("====== Before =====");
testBlob.test();
List<Map<String,Object>> li = testBlob.getBlobData();
int i=0;
for (Map<String, Object> map : li) {
i++;
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File("/home/mphs/Softwares/eclipse/Home/Softwares/ews/Platform/src/WhenMyBOss"+i+".gif")));
bos.write(((Blob)map.get("image")).getBytes(1, (int)((Blob)map.get("image")).length()),0,(int)((Blob)map.get("image")).length());
//bos.write((map.get("image").toString()).getBytes());
}
System.out.println("====== After =====");
}
Stack Trace
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@2f333739: defining beans [dataSource,jdbcTemplate,testBlob]; root of factory hierarchy
Jun 02, 2014 5:33:19 PM org.springframework.jdbc.datasource.DriverManagerDataSource setDriverClassName
INFO: Loaded JDBC driver: com.mysql.jdbc.Driver
====== Before =====
========Started======
========Ended======
Exception in thread "main" java.lang.ClassCastException: [B cannot be cast to java.sql.Blob
at com.dao.Example.main(Example.java:24)
回答1:
You are assuming that the database blob type in your JDBC driver is mapped to java.sql.Types.BLOB
(and therefor to a java.sql.Blob
), but it looks like ResultSet.getObject()
for this returns a byte array (which means that the blob type is actually mapped as a java.sql.Types.LONGVARBINARY
) as indicated by "[B cannot be cast to java.sql.Blob" ([B
is a byte array).
So you should be able to use:
bos.write((byte[]) map.get("image"));
来源:https://stackoverflow.com/questions/23994196/unable-to-construct-images-from-list-of-maps-each-map-contains-image-name-and