如何使用Spring JDBCTemplate将Blob数据读入String对象

时间:2016-08-11 16:34:38

标签: java spring spring-boot spring-jdbc jdbctemplate

我正在尝试使用Spring JDBCTemplate从表中读取blob数据。

List<Map<String, Object>> rows = jdbcTemplate.queryForList(sql);

for(Map<String, Object> row:rows){
    row.get("OPERATION_NAME");
    row.get("REQUEST_MESSAGE"); // this is blob
}

如何将blob读入Java String对象?

4 个答案:

答案 0 :(得分:3)

您可以尝试从数据库中检索blob,如下所示。

String retrieveBlobAsString = null;
Blob b = row.get("REQUEST_MESSAGE");//cast with (Blob) if required. Blob from resultSet as rs.getBlob(index). 
InputStream bis = b.getBinaryStream();
ObjectInputStream ois = new ObjectInputStream(bis);
retrieveBlobAsString = (String) ois.readObject();

答案 1 :(得分:2)

这似乎工作正常 -

LobHandler lobHandler = new DefaultLobHandler();
List<FrontendData> frontEndDataList = jdbcTemplate.query(getResponseQuery(sessionId), new RowMapper() {
            @Override
            public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
                // TODO Auto-generated method stub

                FrontendData frontEndData = new FrontendData();
                String operationName = rs.getString("OPERATION_NAME");
                frontEndData.setApiName(operationName);
                byte[] requestData = lobHandler.getBlobAsBytes(rs,"RESPONSE_MESSAGE");
                frontEndData.setResponse(new String(requestData));


                return frontEndData;
            }});

答案 2 :(得分:1)

Java 8 + 语法:

List<MyObject> results = jdbcTemplate.query(
    "SELECT x,y FROM ... ",
    (rs, n) -> {
        MyObject o = new MyObject();
        o.setX(rs.getString("x"));
        o.setY(rs.getBytes("y")); // <-- a BLOB
        return o;
    }
);

或者,如果您仅查询BLOB:

List<byte[]> b = jdbc.query("SELECT y FROM ...", (rs, n) -> rs.getBytes(1));

答案 3 :(得分:0)

另一种方法是使用java.sql.ResultSet getBytes()将BLOB列转换为String对象,

List<ModelClass> hulaList = jdbcTemplate.query(sql,
    new RowMapper<ModelClass>() {
        @Override
        public ModelClass mapRow(ResultSet rs, int rowNum) throws SQLException {
            ModelClass model = new ModelClass();
            model.setOperationName(rs.getString("OPERATION_NAME"));
            byte[] byteArr = rs.getBytes("REQUEST_MESSAGE");
            model.setRequestMessage(new String(byteArr));
            return model;
        }
});