mysql jpa uuid,使用JPA在MySQL中将UUID存储为字符串

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

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. 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;

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

解决方案

just use

@org.hibernate.annotations.Type(type="uuid-char")

There is three levels of data types:

- Java types

- Hibernate's types

- Database Specific types.

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

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.

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值