Postgres + 休眠+ Java UUID
我想将 PostgreSQL 的本机 UUID 类型与 Java UUID 一起使用。 我使用 Hibernate 作为我的 JPA 提供程序和 ORM。 如果我尝试直接保存它,它只会在 Postgres 中保存为 bytea。
我怎样才能做到这一点?
I want to use PostgreSQL's native UUID type with a Java UUID. I am using Hibernate as my JPA provider and ORM. If I try to save it directly, it is just saved as a bytea in Postgres.
How can I do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
尝试使用最新开发版本的 JDBC 驱动程序(当前为 8.4dev-700),或等待下一个发行版本。 (编辑添加:8.4-701 已发布)
发行说明提到这个改变:
Try use the latest development version of the JDBC driver (Currently 8.4dev-700), or wait for the next release version. (Edited to add: 8.4-701 has been released)
The release notes mention this change:
这是我在 Hibernate 支持的 Postgresql UUID? 上的回答。 ..我知道这个问题很老了,但是如果有人偶然发现它,这会对他们有所帮助。
这可以通过在 UUID 中添加以下注释来解决:
至于为什么 Hibernate 不只是将其设为默认设置,我无法告诉你...
更新:似乎仍然有使用
createNativeQuery
方法打开具有 UUID 字段的对象时出现问题。 幸运的是,到目前为止,createQuery
方法对我来说效果很好。Here's a repost of my answer on Postgresql UUID supported by Hibernate? ... I know this question is old, but if someone stumbles across it, this will help them out.
This can be solved by adding the following annotation to the UUID:
As to why Hibernate doesn't just make this the default setting, I couldn't tell you...
UPDATE: There still seem to be issues using the
createNativeQuery
method to open objects that have UUID fields. Fortunately, thecreateQuery
method so far has worked fine for me.你可以尝试使用:
其中columnDefinition是本机SQL的片段
you could try with:
where columnDefinition is a fragment of native SQL
尝试这个
Try this
在非 JPA 使用中,我将创建一个 UserType 将 UUID 格式化为 PostgreSQL 接受的字符串,然后只需将 UserType 实现的名称指定为列类型。
In non-JPA usage I'd create a UserType to format the UUID as a string that PostgreSQL accepts, then just give the name of the UserType implementation as the column type.
也许您可以将 UUID 类型自动转换为字符串(uuid.toString() 应该给出规范的 36 个字符表示形式)? 数据库通常在字符串和本机类型之间可靠地转换事物。
Perhaps you can get UUID type to be auto-converted to a String (uuid.toString() should give the canonical 36-char representation)? DBs usually convert things reliably between Strings and native types.