Tony
Tony

Reputation: 351

Store UUID as binary in Mysql database with Hibernate/JPA for improving the performance

Now, we define the id as String type with JPA annotation:

@Id
private String id;

Now we want to save UUID as binary in Mysql, I know JPA have one way to implement it like below:

@Id
@Column(columnDefinition = "BINARY(16)")
private UUID id;

But it is big effort to modify String to java.util.UUID type, because I need to modify huge code (a lots of test cases, other calls and so on, anyway we can't do this).

Then I try to use JPA Converter to convert String to bytes and save it, but I found JPA doesn't allow define converter on ID field.

So, please who could provide some possible ways for saving UUID as binary without changing the original String type.

Upvotes: 1

Views: 2970

Answers (1)

Bhushan Uniyal
Bhushan Uniyal

Reputation: 5703

You can use uuid2. It offers a broader type range to choose from:

  • java.lang.UUID
  • a 16 byte array
  • a hexadecimal String value

Your id will like:

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

Upvotes: 1

Related Questions