Spring JDBC - 将对象转换为 Blob 时出现 ClassCastException

Spring JDBC - ClassCastException when casting Object to Blob

我有一个 table,其中有几个字段,其中 2 个是 Varchar 和 Blob 类型。当我使用 queryForMap 检索它们时,我得到了一个带有两个键(列名)的地图实例。我能够简单地将 varchar 转换为 String,但让 ClassCast Exception 对 Object 做同样的事情。

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

我的DAO层方法是:

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);
}

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

我该怎么做才能将此对象取回为 Blob?

A​​ Blob 只是一个(可能很大)byte[] 的包装器。您从 Spring 返回的是有趣的原始数据,即 byte[](或异常表示法中的 B[)。因此,只需使用它,它会更容易使用:

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

请检查class它有什么:

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

然后转换为这个类型,然后你可以使用这个类型的API来做一些事情。