I have a Java application which connects to an Oracle database. One of the tables contains a blob column, which we populate using utl_raw.cast_to_raw
, like this:
public class MyDAO extends JdbcDaoSupport {
public void persist(String name, String data) {
String sql = "insert into table (id, name, data) values " +
"(sequence.nextval, ?, utl_raw.cast_to_raw(?))";
getJdbcTemplate().update(sql, [name, data]);
}
}
For some reason beyond my knowledge, we don't use Hibernate, JPA or anything like that in this application. Just plain SQL statements and Spring JDBC to execute them. (...) Anyway, the above method works fine. At least with Oracle.
I've set up an in-memory H2 database with minimal data, to use in our JUnit tests. But there is no utl_raw
package in H2. Apparently, the way to go is to use the rawtohex
function instead. It kind of works... but it doubles the data length. For example, if I persist the string "TEST"
in the blob column and later I retrieve its value, it becomes " T E S T"
. As a byte array, it would be [0, 84, 0, 69, 0, 83, 0, 84]
. The H2 documentation states that this is supposed to happen:
Converts a string to the hex representation. 4 hex characters per string character are used.
Weird. I guess it's that way to support UTF-16 strings (?), but I'm using UTF-8. It actually corrupts my data.
Is there any other way to store the blob in H2? I've seen this answer where they suggest using a PreparedStatement, but then I'd have to handle the connection myself:
super.getConnection().prepareStatement(/* ... */).executeUpdate();
// release the statement and the connection, handle exceptions
Sure, it's not much uglier than what we have right now, but still, I'm very reluctant to change working production code only to make it compatible with our JUnit test setup.
Another option would be to retrieve the blob as if it were an UTF-16 string, so it will actually use 4 hexs per character. But again, I would be fixing the problem just for H2, and breaking it for Oracle instead.
Do I have any other choice? Is there any way I can tell the H2 database to use just 1 byte per character in rawtohex
? Or perhaps another function I can use instead of rawtohex
?