I'm using Oracle database with ojdbc7
driver
I'm getting Clob from ResultSet using (Clob)rs.getObject("DATA")
and then I'm convert it to String in method:
private String clobToString(Clob data) {
StringBuilder sb = new StringBuilder();
try (Reader reader = data.getCharacterStream(); BufferedReader br = new BufferedReader(reader)){
String line;
while(null != (line = br.readLine())) {
sb.append(line);
}
} catch (Exception e) {
logger.error("Failed to read CLOB", e);
}
return sb.toString();
}
According to Oracle's Using Large Objects
Blob, Clob, and NClob Java objects remain valid for at least the duration of the transaction in which they are created. This could potentially result in an application running out of resources during a long running transaction. Applications may release Blob, Clob, and NClob resources by invoking their free method.
In the following excerpt, the method Clob.free is called to release the resources held for a previously created Clob object
Should I add more code to release in finally
:
finally {
try {
data.free();
} catch (SQLException e) {
logger.error("Failed to release Clob", e);
}
}
Or is it insignificant addition because Clob
isn't used outside method or is there a simple/native way of getting a String from large object from database?
The fact that the clob isn't used outside that method doesn't imply that calling free()
is unuseful: if you don't call it you are delaying the release of resources at least until the transaction ends (as Oracle's doc says).
This is also discussed in Do java.sql.Array/Blob/Clob types need to be "free()"ed? and Should JDBC Blob (not) be free()'d after use? and JDBC 4's java.sql.Clob.free() method and backwards compatibility
About simple/native way of getting a String from clob, see Most efficient solution for reading CLOB to String, and String to CLOB in Java?