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

Ser*_*kov 6 oracle uuid jdbc dbsetup

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

        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);
Run Code Online (Sandbox Code Playgroud)

但是,我得到一个例外:

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)
Run Code Online (Sandbox Code Playgroud)

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

有没有办法使JDBC将UUID插入RAW(16)列?

我正在使用Oracle JDBC 12.2.0.1.0。

Mar*_*ber 6

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

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

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()
Run Code Online (Sandbox Code Playgroud)

这里只是为了防止链接不起作用将UUID转换为字节数组的方法

  public static byte[] asBytes(UUID uuid) {
    ByteBuffer bb = ByteBuffer.wrap(new byte[16]);
    bb.putLong(uuid.getMostSignificantBits());
    bb.putLong(uuid.getLeastSignificantBits());
    return bb.array();
  }
Run Code Online (Sandbox Code Playgroud)

  • @Serge 不客气;无论如何,根据我的经验,只有在有两个很好的理由时,我才会使用/允许使用哈希码作为 PK,为什么不能使用 `sequence`,并且该哈希码对数字 PK 带来真正的优势。祝你好运! (2认同)

小智 5

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

我们所做的是将 UUID 作为字符串传递给使用以下命令的 SQL 语句hextoraw()

String sql = "insert into foo (id) values (hextoraw(?))";
PreparedStatement pstmt = connection.prepareStatement(sql);
UUID uid = UUID.randomUUID();
pstmt.setString(1, uid.toString().replaceAll("-", ""));
Run Code Online (Sandbox Code Playgroud)