简体   繁体   English

使用JPA将UUID存储为mysql中的字符串

[英]Storing UUID as string in mysql using JPA

I came across a blog of using UUID with Hibernate and MySql. 我遇到了一个使用UUID和Hibernate和MySql的博客。 Now the problem is, whenever I take a look at the database the ID's will be non-readable format (binary-16). 现在的问题是,每当我查看数据库时,ID都是不可读的格式(binary-16)。 How can I store UUID as a readable format like 7feb24af-fc38-44de-bc38-04defc3804fe instead of ¡7ôáßEN¹º}ÅÑ?s 如何将UUID存储为可读格式,如7feb24af-fc38-44de-bc38-04defc3804fe而不是¡7ôáßEN¹º}ÅÑ?s

I was using this code 我正在使用此代码

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

And the result is ¡7ôáßEN¹º}ÅÑ?s . 结果是¡7ááßEN¹º}ÅÑ?s But I want it as readable UUID so I used the following code which didn't help me 但我希望它作为可读UUID,所以我使用以下代码,但没有帮助我

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

How to save the UUID as a string instead of binary(16) without changing the java type UUID 如何在不更改java类型UUID的情况下将UUID保存为字符串而不是二进制(16)

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

There is three levels of data types: 有三种级别的数据类型:
- Java types - Java类型
- Hibernate's types - Hibernate的类型
- Database Specific types. - 数据库特定类型。

Hibernate data type presentation is a bridge between Java data type and Database types to be independent from database. Hibernate数据类型表示是Java数据类型和数据库类型之间的桥梁,它独立于数据库。

You can check this mappings . 您可以检查此映射 As you can find there java.util.UUID can be mapped to diferent types (binary or char/varchar). 正如您所见, java.util.UUID可以映射到不同的类型(二进制或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-binary是hibernate的UUIDBinaryType的关键,默认情况下你得到这个类型,它将被映射到你的数据库的BINARY

If you want to get CHAR type under your UUID, you should explain to hibernate that you want his UUIDCharType . 如果你想在你的UUID下获得CHAR类型,你应该向hibernate解释你想要他的UUIDCharType To do that you use uuid-char key and as you can check in JavaDoc of @Type annotation: Defines a Hibernate type mapping. 要做到这一点,你可以使用uuid-char键,因为你可以检查@Type注释的JavaDoc: Defines a Hibernate type mapping. . So, you use annotation to explain hibernate which bridge it should use. 所以,你使用注释来解释hibernate它应该使用哪个桥。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM