如何将 UUID 插入 RAW(16) 列 [英] How to insert UUID into RAW(16) column
问题描述
我在 Oracle 中有 RAW(16) PK 列,并尝试使用 JDBC 将其插入:
I have the RAW(16) PK column in Oracle, and trying to insert into it using 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);
但是,我遇到了一个例外:
However, I am getting an exception:
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 插入测试数据时遇到相同的异常.
I am getting the same exception when trying to use DbSetup for inserting test data.
有没有办法让 JDBC 将 UUID 插入到 RAW(16) 列中?
Is there a way to make JDBC insert UUIDs into RAW(16) column?
我使用的是 Oracle JDBC 12.2.0.1.0.
I am using Oracle JDBC 12.2.0.1.0.
推荐答案
您必须将 UUID 转换为字节数组.请参阅方法 asBytes 如何做吧.
You must convert the UUID to a byte array. See the method asBytes how to do it.
在它之后,绑定就像使用 setBytes
一样简单.
After it the binding is a s simple as using 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()
这里只是以防万一链接不起作用 UUID 到字节数组的转换方法
Here just for case the link doesn't work the conversion method UUID to byte array
public static byte[] asBytes(UUID uuid) {
ByteBuffer bb = ByteBuffer.wrap(new byte[16]);
bb.putLong(uuid.getMostSignificantBits());
bb.putLong(uuid.getLeastSignificantBits());
return bb.array();
}
这篇关于如何将 UUID 插入 RAW(16) 列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!