gpt4 book ai didi

java - 除了 'rawtohex' 之外,还有其他方法可以将数据插入 H2 中的 blob 列吗?

转载 作者:行者123 更新时间:2023-11-30 02:08:22 24 4
gpt4 key购买 nike

我有一个连接到 Oracle 数据库的 Java 应用程序。其中一个表包含一个 blob 列,我们使用 utl_raw.cast_to_raw 填充该列。 ,像这样:

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]);
}
}

由于某种超出我所知的原因,我们在此应用程序中没有使用 Hibernate、JPA 或类似的东西。只需简单的 SQL 语句和 Spring JDBC 即可执行它们。 (...) 无论如何,上述方法效果很好。至少对于 Oracle 来说是这样。

我已经设置了一个包含最少数据的内存 H2 数据库,用于我们的 JUnit 测试。但是H2中没有utl_raw包。 Apparently, the way to go is使用rawtohex function反而。它有点作用...但是它使数据长度加倍。例如,如果我将字符串 "TEST" 保留在 blob 列中,稍后我检索其值,则它会变为 "T E S T"。作为字节数组,它将是 [0, 84, 0, 69, 0, 83, 0, 84]。 H2 文档指出这应该发生:

Converts a string to the hex representation. 4 hex characters per string character are used.

Weird 。我想这是支持 UTF-16 字符串的方式(?),但我使用的是 UTF-8。它实际上损坏了我的数据。

还有其他方法可以在 H2 中存储 blob 吗?我见过 this answer where they suggest using a PreparedStatement ,但随后我必须自己处理连接:

super.getConnection().prepareStatement(/* ... */).executeUpdate();
// release the statement and the connection, handle exceptions

当然,它并不比我们现在所拥有的丑陋得多,但是,我仍然非常不愿意仅仅为了使其与我们的 JUnit 测试设置兼容而更改工作生产代码。

另一个选项是像检索 UTF-16 字符串一样检索 blob,因此每个字符实际上会使用 4 个十六进制。但同样,我会只针对 H2 修复该问题,并针对 Oracle 打破该问题。

我还有其他选择吗?有什么方法可以告诉 H2 数据库在 rawtohex 中每个字符仅使用 1 个字节吗?或者也许another function我可以使用rawtohex来代替吗?

最佳答案

我不会在数据库(Oracle 或 H2)中进行转换。

H2's docs说使用 PreparedStatement.setBinaryStream 。这对 Oracle 也适用吗?根据您要转换的字符串的大小,其他方法可能会更高效。顺便说一句,将字符串转换为二进制对象有什么特殊原因吗?

如果您知道它总是相对较小的字符串(例如 < 1MB),那么尝试这样的操作可能非常安全:

String sql = "insert into table (id, name, data) values " +
"(sequence.nextval, ?, ?)";
PreparedStatement ps = super.getConnection().prepareStatement(sql);
InputStream stream = new ByteArrayInputStream(data.getBytes(StandardCharsets.UTF_8));
ps.setString(1, name);
ps.setBinaryStream(2, stream);
ps.executeUpdate();

关于java - 除了 'rawtohex' 之外,还有其他方法可以将数据插入 H2 中的 blob 列吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50802086/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com