Oracle JDBC:如何将UUID插入RAW(16)列

Oracle JDBC: How to insert UUID into RAW(16) column

我在Oracle中有RAW(16)PK列,并尝试使用JDBC插入到其中:

1
2
3
        PreparedStatement stmt = connection.prepareStatement("insert into COUNTRY (id, state, version, code, name, nationality, issuing_entity, country) values (?, ?, ?, ?, ?, ?, ?, ?)");
        UUID id = UUID.randomUUID();
        stmt.setObject(1, id, Types.BINARY);

但是,我遇到一个例外:

1
2
3
4
5
6
7
8
9
java.sql.SQLException: Invalid column type
at oracle.jdbc.driver.OraclePreparedStatement.setObjectCritical(OraclePreparedStatement.java:8494)
at oracle.jdbc.driver.OraclePreparedStatement.setObjectInternal(OraclePreparedStatement.java:7995)
at oracle.jdbc.driver.OraclePreparedStatement.setObject(OraclePreparedStatement.java:8559)
at oracle.jdbc.driver.OraclePreparedStatementWrapper.setObject(OraclePreparedStatementWrapper.java:225)
at com.zaxxer.hikari.pool.HikariProxyPreparedStatement.setObject(HikariProxyPreparedStatement.java)
at rw.gov.dgie.framework.test.AbstractTestCaseWithDB.tryToInsertCountry(AbstractTestCaseWithDB.java:78)
at rw.gov.dgie.framework.test.AbstractTestCaseWithDB.dbSetup(AbstractTestCaseWithDB.java:62)
at test.rw.gov.dgie.bms.terr.service.TestCountryService.init(TestCountryService.java:37)

当尝试使用DbSetup插入测试数据时,我遇到了相同的异常。

是否有一种方法可以使JDBC将UUID插入RAW(16)列?

我正在使用Oracle JDBC 12.2.0.1.0。


您必须将UUID转换为字节数组。请参见asBytes方法。

绑定之后,就像使用setBytes一样简单。

示例

1
2
3
4
5
6
def stmt = con.prepareStatement("insert into TAB_UUID (id, uuid) values (?,?)")
// bind
stmt.setInt(1,1)
def uuid = UUID.randomUUID()
stmt.setBytes(2,asBytes(uuid))
def rowCount = stmt.executeUpdate()

在此情况下,如果链接无法正常工作,则将UUID转换为字节数组的方法

1
2
3
4
5
6
  public static byte[] asBytes(UUID uuid) {
    ByteBuffer bb = ByteBuffer.wrap(new byte[16]);
    bb.putLong(uuid.getMostSignificantBits());
    bb.putLong(uuid.getLeastSignificantBits());
    return bb.array();
  }


Oracle没有真正的UUID数据类型,因此处理RAW(16)确实是PITA。

我们要做的是将UUID作为字符串传递给使用hextoraw()的SQL语句:

1
2
3
4
String sql ="insert into foo (id) values (hextoraw(?))";
PreparedStatement pstmt = connection.prepareStatement(sql);
UUID uid = UUID.randomUUID();
pstmt.setString(1, uid.toString().replaceAll("-",""));

1
2
3
getJdbcTemplate().update("INSERT INTO abc(abc_id, abc_uuid,"
                                       +"VALUES (?, ?)",
                                          abcId, uuidToBytes(abcUuid))

这是将UUID类型转换为字节的辅助方法。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
private byte[] uuidToBytes(final UUID uuid) {
        if (Objects.isNull(uuid)) {
            return null;
        }

        final byte[] uuidAsBytes = new byte[16];

        ByteBuffer.wrap(uuidAsBytes)
                  .order(ByteOrder.BIG_ENDIAN)
                  .putLong(uuid.getMostSignificantBits())
                  .putLong(uuid.getLeastSignificantBits());

        return uuidAsBytes;
    }