使用 JPA 将 UUID 作为字符串存储在 mysql 中 [英] Storing UUID as string in mysql using JPA

查看:37
本文介绍了使用 JPA 将 UUID 作为字符串存储在 mysql 中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到了一篇关于在 Hibernate 和 MySql 中使用 UUID 的博客.现在的问题是,每当我查看数据库时,ID 的格式都是不可读的(二进制 16).如何将 UUID 存储为可读格式,例如 7feb24af-fc38-44de-bc38-04defc3804fe 而不是 ¡7ôáßEN¹º}ÅÑ?s

I came across a blog of using UUID with Hibernate and MySql. Now the problem is, whenever I take a look at the database the ID's will be non-readable format (binary-16). How can I store UUID as a readable format like 7feb24af-fc38-44de-bc38-04defc3804fe instead of ¡7ôáßEN¹º}ÅÑs

我正在使用此代码

@Id
@GeneratedValue( generator = "uuid2" )
@GenericGenerator( name = "uuid2", strategy = "uuid2" )
@Column( name = "id", columnDefinition = "BINARY(16)" )
private UUID id;

结果是¡7ôáßEN¹º}ÅÑ?s.但我希望它是可读的 UUID,所以我使用了以下对我没有帮助的代码

And the result is ¡7ôáßEN¹º}ÅÑs. But I want it as readable UUID so I used the following code which didn't help me

@Id
@GeneratedValue( generator = "uuid2" )
@GenericGenerator( name = "uuid2", strategy = "uuid2" )
@Column( name = "id", columnDefinition = "CHAR(32)" )
private UUID id;

如何在不改变java类型UUID的情况下将UUID保存为字符串而不是二进制(16)

How to save the UUID as a string instead of binary(16) without changing the java type UUID

推荐答案

只需使用@org.hibernate.annotations.Type(type="uuid-char")

数据类型分为三个级别:
- Java 类型
- Hibernate 的类型
- 数据库特定类型.

There is three levels of data types:
- Java types
- Hibernate's types
- Database Specific types.

Hibernate 数据类型表示是 Java 数据类型和独立于数据库的数据库类型之间的桥梁.

Hibernate data type presentation is a bridge between Java data type and Database types to be independent from database.

您可以查看此映射.正如您所见,java.util.UUID 可以映射到不同的类型(二进制或 char/varchar).uuid-binary 是 hibernate 的 UUIDBinaryType 的关键,默认情况下你会得到这个类型,它会映射到你的数据库的 BINARY.

You can check this mappings. As you can find there java.util.UUID can be mapped to diferent types (binary or char/varchar). uuid-binary is key to hibernate's UUIDBinaryType, you get this type by default and it will be mapped to BINARY of your database.

如果你想在你的 UUID 下获得 CHAR 类型,你应该向休眠解释你想要他的 UUIDCharType.为此,您可以使用 uuid-char 键,并且您可以检查 @Type 注释的 JavaDoc:Defines a Hibernate type mapping..所以,你使用注解来解释 hibernate 应该使用哪个网桥.

If you want to get CHAR type under your UUID, you should explain to hibernate that you want his UUIDCharType. To do that you use uuid-char key and as you can check in JavaDoc of @Type annotation: Defines a Hibernate type mapping.. So, you use annotation to explain hibernate which bridge it should use.

这篇关于使用 JPA 将 UUID 作为字符串存储在 mysql 中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆