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

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

问题描述

我遇到了一个在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.

休眠数据类型表示是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是休眠的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..因此,您可以使用注释来解释休眠模式,它应该使用哪个桥接.

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在MySQL中将UUID存储为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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