Punter Vicky
Punter Vicky

Reputation: 16982

How to read Blob data into String Object using Spring JDBCTemplate

I am trying to use Spring JDBCTemplate to read blob data from a table.

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
}

How can I read blob into a Java String object?

Upvotes: 2

Views: 35638

Answers (4)

rustyx
rustyx

Reputation: 85276

Java 8+ syntax:

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

Or if you query only a BLOB:

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

Upvotes: 1

AGan
AGan

Reputation: 487

Another approach is by using java.sql.ResultSet getBytes() to convert BLOB column to String object,

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

Upvotes: 1

Punter Vicky
Punter Vicky

Reputation: 16982

This seemed to work fine -

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

Upvotes: 4

Aditya Garimella
Aditya Garimella

Reputation: 933

You can try retrieving the blob from database as below.

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

Upvotes: 3

Related Questions