简体   繁体   中英

Spring JDBC - ClassCastException when casting Object to Blob

I have a table with few fields out of which 2 are of Varchar and Blob type. When I'm retrieving them using queryForMap, I'm getting a map instance with two keys(name of the column). I'm able to cast varchar to String simply but getting ClassCast Exception doing the same with Object.

file = new File(System.currentTimeMillis() + (String) map.get("SAMPLE_DOC_FILE_NAME"));
blob = (Blob) map.get("SAMPLE_DOC");

My DAO layer method is:

public Map<String, Object> getSampleDoc1(String docName) throws SQLException {

    String query = "select form.sample_doc_file_name as SAMPLE_DOC_FILE_NAME, form.sample_document as SAMPLE_DOC from forms form where form.document_name=?";
    return localJdbcTemplateObject.queryForMap(query, docName);
}

Exception - java.lang.ClassCastException: [B cannot be cast to java.sql.Blob

What can I do to get back this object as Blob?

A Blob is just a wrapper for a (possibly large) byte[] . What you're getting back from Spring here is the interesting raw data, the byte[] (or B[ in the exception's notation). So, just use that instead, it'll be much easier to work with:

byte[] blob = (byte[]) map.get("SAMPLE_DOC");

Please check what class it has as this:

System.out.println(map.get("SAMPLE_DOC").getClass().getName());

then cast to this type, then you can use the API of this type to do something with it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM